@galacean/cli 2.0.0-alpha.23 → 2.0.0-alpha.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.bundle.cjs +74 -12
- package/dist/preview-client/_static/{Accordion-75b7b34e.js → Accordion-f938dadf.js} +1 -1
- package/dist/preview-client/_static/{AmbientLightAsset-02786385.js → AmbientLightAsset-e34de607.js} +1 -1
- package/dist/preview-client/_static/{AnimationClipAsset-f96e0e56.js → AnimationClipAsset-b084da2a.js} +1 -1
- package/dist/preview-client/_static/{AnimatorControllerAsset-23cceb12.js → AnimatorControllerAsset-6cc04274.js} +1 -1
- package/dist/preview-client/_static/{AnimatorStore-48d2c14c.js → AnimatorStore-0bc90c37.js} +1 -1
- package/dist/preview-client/_static/{AssetViewer-1073ddb5.js → AssetViewer-d2c63b00.js} +1 -1
- package/dist/preview-client/_static/{AudioAsset-6218f2bb.js → AudioAsset-9c715952.js} +1 -1
- package/dist/preview-client/_static/{AudioComponent-16766db8.js → AudioComponent-80d06ef4.js} +1 -1
- package/dist/preview-client/_static/{Callout-312ada1c.js → Callout-48e71f13.js} +1 -1
- package/dist/preview-client/_static/{CameraComponent-c919c2dd.js → CameraComponent-9c9db3fb.js} +1 -1
- package/dist/preview-client/_static/{Component-6d1e73e5.js → Component-b95aa2af.js} +1 -1
- package/dist/preview-client/_static/{DirectLight-166a628d.js → DirectLight-b0490ef7.js} +1 -1
- package/dist/preview-client/_static/{FontAsset-8367aad9.js → FontAsset-6e9c0549.js} +1 -1
- package/dist/preview-client/_static/{FormItemArray-53c58844.js → FormItemArray-b2a3d249.js} +1 -1
- package/dist/preview-client/_static/{GlTFAsset-5c8e7813.js → GlTFAsset-83e8190e.js} +1 -1
- package/dist/preview-client/_static/{IconPlus-5fbc029e.js → IconPlus-172c6c17.js} +1 -1
- package/dist/preview-client/_static/{IconPointFilled-dbf63b5c.js → IconPointFilled-bad94cf1.js} +1 -1
- package/dist/preview-client/_static/{LightBaseComponent-545c5ee8.js → LightBaseComponent-b4854e8a.js} +1 -1
- package/dist/preview-client/_static/{LottieAnimationComponent-4db5a6c2.js → LottieAnimationComponent-efd5da2b.js} +1 -1
- package/dist/preview-client/_static/{MarkdownAsset-58491579.js → MarkdownAsset-b42846c0.js} +1 -1
- package/dist/preview-client/_static/{MaterialAsset-c83c7d3d.js → MaterialAsset-0b9d7eba.js} +1 -1
- package/dist/preview-client/_static/{MaterialInspector-237b6a5e.js → MaterialInspector-23ea0240.js} +1 -1
- package/dist/preview-client/_static/{Menu-a427d272.js → Menu-05c1f0a4.js} +1 -1
- package/dist/preview-client/_static/{MeshAsset-1c11d7ab.js → MeshAsset-85e99837.js} +1 -1
- package/dist/preview-client/_static/{MeshRendererBaseComponent-8fd1f0df.js → MeshRendererBaseComponent-5621d663.js} +1 -1
- package/dist/preview-client/_static/{MeshRendererComponent-082c1a1a.js → MeshRendererComponent-c3c3c683.js} +1 -1
- package/dist/preview-client/_static/{MeshThumbnail-d8ee2674.js → MeshThumbnail-b1283749.js} +1 -1
- package/dist/preview-client/_static/{ParticleRendererComponent-ff12cdb1.js → ParticleRendererComponent-94656239.js} +1 -1
- package/dist/preview-client/_static/{PhysicsMaterialAsset-7e86c718.js → PhysicsMaterialAsset-cb9afb6e.js} +1 -1
- package/dist/preview-client/_static/{PhysicsStore-66a9a461.js → PhysicsStore-0a751fa0.js} +1 -1
- package/dist/preview-client/_static/{PointLight-a9992e50.js → PointLight-a2bfed75.js} +1 -1
- package/dist/preview-client/_static/{PostProcessComponent-c17ac553.js → PostProcessComponent-040cf521.js} +1 -1
- package/dist/preview-client/_static/{PrefabAsset-a6750aec.js → PrefabAsset-265f6f48.js} +1 -1
- package/dist/preview-client/_static/{PrimitiveMesh-388f3f36.js → PrimitiveMesh-70c93e7e.js} +1 -1
- package/dist/preview-client/_static/{ReferencedMaterial-f7ea80fb.js → ReferencedMaterial-831d0583.js} +1 -1
- package/dist/preview-client/_static/{RenderTargetAsset-c48990a4.js → RenderTargetAsset-b810caf3.js} +1 -1
- package/dist/preview-client/_static/{SceneAsset-1e802e29.js → SceneAsset-d05b1a79.js} +1 -1
- package/dist/preview-client/_static/{ShaderAsset-256afb00.js → ShaderAsset-370b6f1c.js} +1 -1
- package/dist/preview-client/_static/{ShaderChunkAsset-a42443fc.js → ShaderChunkAsset-e3487bd1.js} +1 -1
- package/dist/preview-client/_static/{ShaderUIScriptAsset-5acb02f5.js → ShaderUIScriptAsset-ebf57ceb.js} +1 -1
- package/dist/preview-client/_static/{SkinnedMeshRendererComponent-934c055b.js → SkinnedMeshRendererComponent-ee33da25.js} +1 -1
- package/dist/preview-client/_static/{SpineAnimationComponent-b04ba1ee.js → SpineAnimationComponent-12e694e8.js} +1 -1
- package/dist/preview-client/_static/{SpineSkeletonDataAsset-fff17383.js → SpineSkeletonDataAsset-0dffbb4d.js} +1 -1
- package/dist/preview-client/_static/{SpotLight-617d8957.js → SpotLight-ada565f2.js} +1 -1
- package/dist/preview-client/_static/{SpriteBaseComponent-062cb4f8.js → SpriteBaseComponent-3156cb3b.js} +1 -1
- package/dist/preview-client/_static/{SpriteMaskComponent-43ae2b1f.js → SpriteMaskComponent-a32024e1.js} +1 -1
- package/dist/preview-client/_static/{SpriteRendererComponent-4f52910c.js → SpriteRendererComponent-489486e0.js} +1 -1
- package/dist/preview-client/_static/{TextBaseComponent-bd7ed8ee.js → TextBaseComponent-520dea39.js} +1 -1
- package/dist/preview-client/_static/{TextRendererComponent-8db74598.js → TextRendererComponent-6be5f80c.js} +1 -1
- package/dist/preview-client/_static/{TextureAsset-d88af413.js → TextureAsset-9cd94531.js} +1 -1
- package/dist/preview-client/_static/{Tooltip-3bc02b10.js → Tooltip-71e5a4e7.js} +1 -1
- package/dist/preview-client/_static/{TrailRendererComponent-42a58f1d.js → TrailRendererComponent-74bf88c0.js} +1 -1
- package/dist/preview-client/_static/{TransformBaseComponent-77478ccb.js → TransformBaseComponent-0d241199.js} +1 -1
- package/dist/preview-client/_static/{TransformComponent-0f395b08.js → TransformComponent-49d279f5.js} +1 -1
- package/dist/preview-client/_static/{XRReferenceImageAsset-d6d8e59c.js → XRReferenceImageAsset-79e78558.js} +1 -1
- package/dist/preview-client/_static/{audio-d14900e2.js → audio-5d0ddf55.js} +1 -1
- package/dist/preview-client/_static/{createOnModelChange-c010a049.js → createOnModelChange-e65da908.js} +1 -1
- package/dist/preview-client/_static/{createReactComponent-d9f8b1af.js → createReactComponent-cb70ea50.js} +1 -1
- package/dist/preview-client/_static/index-0fef73f8.js +1 -0
- package/dist/preview-client/_static/index-1e036622.js +1 -0
- package/dist/preview-client/_static/index-1fd4207a.js +1 -0
- package/dist/preview-client/_static/{index-9feced3c.js → index-46c87b46.js} +1 -1
- package/dist/preview-client/_static/index-6649d404.js +1 -0
- package/dist/preview-client/_static/{index-f165015e.js → index-788e8750.js} +1 -1
- package/dist/preview-client/_static/{index-75e7d483.js → index-7e414715.js} +1 -1
- package/dist/preview-client/_static/index-87ef1c72.js +1 -0
- package/dist/preview-client/_static/{index-f4d91eb4.js → index-b13216a9.js} +1 -1
- package/dist/preview-client/_static/{index-4e7bb453.js → index-b4bde36a.js} +1 -1
- package/dist/preview-client/_static/{index-071c0532.js → index-d00c8bc3.js} +1 -1
- package/dist/preview-client/_static/index-d9ee84ce.js +1 -0
- package/dist/preview-client/_static/{index-365736f7.js → index-debbe073.js} +1 -1
- package/dist/preview-client/_static/{index-3660a664.js → index-e44b357e.js} +4 -4
- package/dist/preview-client/_static/{index-eb74362c.js → index-ea7fe254.js} +1 -1
- package/dist/preview-client/_static/{index-8e169cc2.js → index-f7bd6fef.js} +1 -1
- package/dist/preview-client/_static/{ktx2-encoder-e9b1c83a.js → ktx2-encoder-522fc017.js} +1 -1
- package/dist/preview-client/_static/{module-4a37a616.js → module-5547be1c.js} +1 -1
- package/dist/preview-client/_static/{module-81a206c0.js → module-57b6e417.js} +1 -1
- package/dist/preview-client/_static/{module-1c91b4e1.js → module-5906e0d4.js} +1 -1
- package/dist/preview-client/_static/{postmen-c7605b45.js → postmen-443b3e5f.js} +1 -1
- package/dist/preview-client/_static/{shader-data-utils-6ef12596.js → shader-data-utils-000170ae.js} +1 -1
- package/dist/preview-client/index.html +1 -1
- package/package.json +1 -1
- package/dist/preview-client/_static/index-1c260f88.js +0 -1
- package/dist/preview-client/_static/index-44137d7e.js +0 -1
- package/dist/preview-client/_static/index-5ae70b23.js +0 -1
- package/dist/preview-client/_static/index-be42fc1e.js +0 -1
- package/dist/preview-client/_static/index-cfa0dccc.js +0 -1
- package/dist/preview-client/_static/index-f3d42be3.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var fo=Object.defineProperty;var po=(rt,_e,tt)=>_e in rt?fo(rt,_e,{enumerable:!0,configurable:!0,writable:!0,value:tt}):rt[_e]=tt;var Rt=(rt,_e,tt)=>(po(rt,typeof _e!="symbol"?_e+"":_e,tt),tt);function _mergeNamespaces(rt,_e){for(var tt=0;tt<_e.length;tt++){const et=_e[tt];if(typeof et!="string"&&!Array.isArray(et)){for(const nt in et)if(nt!=="default"&&!(nt in rt)){const it=Object.getOwnPropertyDescriptor(et,nt);it&&Object.defineProperty(rt,nt,it.get?it:{enumerable:!0,get:()=>et[nt]})}}}return Object.freeze(Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"}))}(function(){const _e=document.createElement("link").relList;if(_e&&_e.supports&&_e.supports("modulepreload"))return;for(const nt of document.querySelectorAll('link[rel="modulepreload"]'))et(nt);new MutationObserver(nt=>{for(const it of nt)if(it.type==="childList")for(const at of it.addedNodes)at.tagName==="LINK"&&at.rel==="modulepreload"&&et(at)}).observe(document,{childList:!0,subtree:!0});function tt(nt){const it={};return nt.integrity&&(it.integrity=nt.integrity),nt.referrerPolicy&&(it.referrerPolicy=nt.referrerPolicy),nt.crossOrigin==="use-credentials"?it.credentials="include":nt.crossOrigin==="anonymous"?it.credentials="omit":it.credentials="same-origin",it}function et(nt){if(nt.ep)return;nt.ep=!0;const it=tt(nt);fetch(nt.href,it)}})();const CLI_PREVIEW_READY_MESSAGE="render path prototype";function createDefaultPreviewReadyStatus(){return`preview initialized (${CLI_PREVIEW_READY_MESSAGE})`}function createPreviewReadyStatus(rt){return`preview initialized in ${rt} (${CLI_PREVIEW_READY_MESSAGE})`}const stageLabels={"boot-runtime":"booting runtime modules","register-assets":"registering asset types","register-components":"registering components","init-gltf-io":"initializing gltf io","resolve-project-id":"resolving project id","query-project":"querying project","init-project":"initializing project","init-engine":"creating engine","init-assets":"loading assets","init-scene":"loading scene","run-engine":"starting viewport","replay-bindings":"replaying bindings","resume-history":"finalizing runtime"};function createStartupStatusReporter(rt){const _e=rt.now??defaultNow,tt=_e();let et=createDefaultPreviewReadyStatus();return{reportStage:at=>{rt.setStatus(`${stageLabels[at]}... ${formatElapsed(_e()-tt)}`,"busy")},finish:()=>{et=createPreviewReadyStatus(formatElapsed(_e()-tt)),rt.setStatus(et,"idle")},getReadyStatus:()=>et}}function defaultNow(){return performance.now()}function formatElapsed(rt){const _e=Math.max(rt,0);return _e>=1e3?`${(_e/1e3).toFixed(1)}s`:`${_e.toFixed(0)}ms`}const scriptRel="modulepreload",assetsURL=function(rt){return"/"+rt},seen={},__vitePreload=function(_e,tt,et){if(!tt||tt.length===0)return _e();const nt=document.getElementsByTagName("link");return Promise.all(tt.map(it=>{if(it=assetsURL(it),it in seen)return;seen[it]=!0;const at=it.endsWith(".css"),ot=at?'[rel="stylesheet"]':"";if(!!et)for(let dt=nt.length-1;dt>=0;dt--){const ut=nt[dt];if(ut.href===it&&(!at||ut.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${it}"]${ot}`))return;const ct=document.createElement("link");if(ct.rel=at?"stylesheet":scriptRel,at||(ct.as="script",ct.crossOrigin=""),ct.href=it,document.head.appendChild(ct),at)return new Promise((dt,ut)=>{ct.addEventListener("load",dt),ct.addEventListener("error",()=>ut(new Error(`Unable to preload CSS for ${it}`)))})})).then(()=>_e()).catch(it=>{const at=new Event("vite:preloadError",{cancelable:!0});if(at.payload=it,window.dispatchEvent(at),!at.defaultPrevented)throw it})},FULL_ASSET_MODULE_KEYS=["all-assets"],FULL_COMPONENT_MODULE_KEYS=["all-components"],NON_RUNTIME_ASSET_TYPES=new Set(["Folder"]),ASSET_MODULE_KEYS_BY_TYPE={AmbientLight:"ambient-light",AnimationClip:"animation-clip",AnimatorController:"animator-controller",Audio:"audio",Font:"font",glTF:"gltf",Lottie:"lottie",LottieClip:"lottie",Markdown:"markdown",Material:"material",Mesh:"mesh",PhysicsMaterial:"physics-material",Prefab:"prefab",PrimitiveMesh:"primitive-mesh",RenderTarget:"render-target",Scene:"scene",script:"script",Shader:"shader",ShaderChunk:"shader",Spine:"spine",SpineAtlas:"spine",SpineSkeletonData:"spine",SpriteAtlas:"sprite-atlas",sprite:"sprite",StateMachineScript:"script",Texture:"texture",XRReferenceImage:"xr-reference-image"},COMPONENT_MODULE_KEYS_BY_TYPE={Animator:"animator",Audio:"audio-listener",AudioSource:"audio-source",Button:"ui",Camera:"camera",CharacterController:"physics",DirectLight:"direct-light",DynamicCollider:"physics",FixedJoint:"physics",HingeJoint:"physics",Image:"ui",LottieAnimation:"lottie-animation",MeshRenderer:"mesh-renderer",ParticleRenderer:"particle-renderer",PointLight:"point-light",PostProcess:"post-process",Script:"script",SkinnedMeshRenderer:"skinned-mesh-renderer",SpineAnimationRenderer:"spine-animation",SpotLight:"spot-light",SpringJoint:"physics",SpriteMask:"sprite-mask",SpriteRenderer:"sprite-renderer",StaticCollider:"physics",Text:"ui",TextRenderer:"text-renderer",TrailRenderer:"trail-renderer",Transform:"transform",UIGroup:"ui",UICanvas:"ui",UITransform:"ui","XR Anchor Manager":"xr","XR Image Manager":"xr","XR Origin":"xr","XR Plane Manager":"xr"},ASSET_MODULE_REGISTRY={"all-assets":{load:async()=>__vitePreload(()=>import("./index-f3d42be3.js"),["_static/index-f3d42be3.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-3bc02b10.js","_static/createReactComponent-d9f8b1af.js","_static/AssetViewer-1073ddb5.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-4a37a616.js","_static/module-81a206c0.js","_static/ShaderChunkAsset-a42443fc.js","_static/IconPlus-5fbc029e.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/assets/index.ts"},"ambient-light":{load:async()=>__vitePreload(()=>import("./AmbientLightAsset-02786385.js"),["_static/AmbientLightAsset-02786385.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-365736f7.js"]),warmupEntryPath:"plugins/main/src/assets/ambient/AmbientLightAsset.tsx"},"animation-clip":{load:async()=>__vitePreload(()=>import("./index-5ae70b23.js"),["_static/index-5ae70b23.js","_static/AnimationClipAsset-f96e0e56.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/module-4a37a616.js","_static/module-81a206c0.js"]),warmupEntryPath:"plugins/main/src/assets/animation-clip/index.tsx"},"animator-controller":{load:async()=>__vitePreload(()=>import("./AnimatorControllerAsset-23cceb12.js"),["_static/AnimatorControllerAsset-23cceb12.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js"]),warmupEntryPath:"plugins/main/src/assets/animator-controller/AnimatorControllerAsset.ts"},audio:{load:async()=>__vitePreload(()=>import("./AudioAsset-6218f2bb.js"),["_static/AudioAsset-6218f2bb.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/audio/AudioAsset.tsx"},font:{load:async()=>__vitePreload(()=>import("./FontAsset-8367aad9.js"),["_static/FontAsset-8367aad9.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/font/FontAsset.tsx"},gltf:{load:async()=>__vitePreload(()=>import("./GlTFAsset-5c8e7813.js").then(rt=>rt.b),["_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/ktx-parse.modern-6c9f771f.js","_static/meshopt_simplifier.module-cd99529d.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/shader-data-utils-6ef12596.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js"]),warmupEntryPath:"plugins/main/src/assets/gltf/GlTFAsset.tsx"},lottie:{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-a42443fc.js").then(rt=>rt.f),["_static/ShaderChunkAsset-a42443fc.js","_static/module-4a37a616.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/createReactComponent-d9f8b1af.js","_static/IconPlus-5fbc029e.js","_static/AssetViewer-1073ddb5.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-3bc02b10.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-81a206c0.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/assets/lottie/LottieAsset.tsx"},markdown:{load:async()=>__vitePreload(()=>import("./MarkdownAsset-58491579.js"),["_static/MarkdownAsset-58491579.js","_static/index-365736f7.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/assets/markdown/MarkdownAsset.ts"},material:{load:async()=>__vitePreload(()=>import("./MaterialAsset-c83c7d3d.js").then(rt=>rt.b),["_static/MaterialAsset-c83c7d3d.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/AssetViewer-1073ddb5.js","_static/shader-data-utils-6ef12596.js"]),warmupEntryPath:"plugins/main/src/assets/material/MaterialAsset.tsx"},mesh:{load:async()=>__vitePreload(()=>import("./MeshAsset-1c11d7ab.js"),["_static/MeshAsset-1c11d7ab.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AssetViewer-1073ddb5.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/mesh/MeshAsset.tsx"},"physics-material":{load:async()=>__vitePreload(()=>import("./PhysicsMaterialAsset-7e86c718.js"),["_static/PhysicsMaterialAsset-7e86c718.js","_static/index-365736f7.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/assets/physics/PhysicsMaterialAsset.ts"},prefab:{load:async()=>__vitePreload(()=>import("./PrefabAsset-a6750aec.js"),["_static/PrefabAsset-a6750aec.js","_static/TaskQueue-05c94a4d.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/prefab/PrefabAsset.ts"},"primitive-mesh":{load:async()=>__vitePreload(()=>import("./PrimitiveMesh-388f3f36.js"),["_static/PrimitiveMesh-388f3f36.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/MeshThumbnail-d8ee2674.js"]),warmupEntryPath:"plugins/main/src/assets/primitive-mesh/PrimitiveMesh.ts"},"render-target":{load:async()=>__vitePreload(()=>import("./RenderTargetAsset-c48990a4.js"),["_static/RenderTargetAsset-c48990a4.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/render-target/RenderTargetAsset.ts"},scene:{load:async()=>__vitePreload(()=>import("./SceneAsset-1e802e29.js"),["_static/SceneAsset-1e802e29.js","_static/index-365736f7.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/assets/scene/SceneAsset.tsx"},script:{load:async()=>__vitePreload(()=>import("./index-eb74362c.js"),["_static/index-eb74362c.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/index-365736f7.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/assets/script/index.ts"},shader:{load:async()=>__vitePreload(()=>import("./index-1c260f88.js"),["_static/index-1c260f88.js","_static/ShaderAsset-256afb00.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/meshopt_simplifier.module-cd99529d.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/shader-data-utils-6ef12596.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/index-75e7d483.js"]),warmupEntryPath:"plugins/main/src/assets/shader/index.ts"},spine:{load:async()=>__vitePreload(()=>import("./SpineSkeletonDataAsset-fff17383.js").then(rt=>rt.a),["_static/SpineSkeletonDataAsset-fff17383.js","_static/module-81a206c0.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/spine/SpineSkeletonDataAsset.ts"},"sprite-atlas":{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-a42443fc.js").then(rt=>rt.e),["_static/ShaderChunkAsset-a42443fc.js","_static/module-4a37a616.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/createReactComponent-d9f8b1af.js","_static/IconPlus-5fbc029e.js","_static/AssetViewer-1073ddb5.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-3bc02b10.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-81a206c0.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/assets/atlas/SpriteAtlasAsset.tsx"},sprite:{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-a42443fc.js").then(rt=>rt.d),["_static/ShaderChunkAsset-a42443fc.js","_static/module-4a37a616.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/createReactComponent-d9f8b1af.js","_static/IconPlus-5fbc029e.js","_static/AssetViewer-1073ddb5.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-3bc02b10.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-81a206c0.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/assets/sprite/SpriteAsset.ts"},texture:{load:async()=>__vitePreload(()=>import("./TextureAsset-d88af413.js").then(rt=>rt.d),["_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-3bc02b10.js","_static/createReactComponent-d9f8b1af.js","_static/AssetViewer-1073ddb5.js"]),warmupEntryPath:"plugins/main/src/assets/texture/TextureAsset.tsx"},"xr-reference-image":{load:async()=>__vitePreload(()=>import("./XRReferenceImageAsset-d6d8e59c.js"),["_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/AssetViewer-1073ddb5.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/xr/XRReferenceImageAsset.tsx"}},COMPONENT_MODULE_REGISTRY={"all-components":{load:async()=>__vitePreload(()=>import("./index-f165015e.js"),["_static/index-f165015e.js","_static/CameraComponent-c919c2dd.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/DirectLight-166a628d.js","_static/LightBaseComponent-545c5ee8.js","_static/PointLight-a9992e50.js","_static/SpotLight-617d8957.js","_static/MeshRendererComponent-082c1a1a.js","_static/createOnModelChange-c010a049.js","_static/ReferencedMaterial-f7ea80fb.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/MeshRendererBaseComponent-8fd1f0df.js","_static/SkinnedMeshRendererComponent-934c055b.js","_static/AnimatorStore-48d2c14c.js","_static/SpriteRendererComponent-4f52910c.js","_static/SpriteBaseComponent-062cb4f8.js","_static/SpriteMaskComponent-43ae2b1f.js","_static/PhysicsStore-66a9a461.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js","_static/index-071c0532.js","_static/create-script-property-context-model-0fe0258f.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-3bc02b10.js","_static/AssetViewer-1073ddb5.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-4a37a616.js","_static/module-81a206c0.js","_static/ShaderChunkAsset-a42443fc.js","_static/IconPlus-5fbc029e.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/TextRendererComponent-8db74598.js","_static/TextBaseComponent-bd7ed8ee.js","_static/LottieAnimationComponent-4db5a6c2.js","_static/SpineAnimationComponent-b04ba1ee.js","_static/ParticleRendererComponent-ff12cdb1.js","_static/index-8e169cc2.js","_static/Menu-a427d272.js","_static/TrailRendererComponent-42a58f1d.js","_static/index-f4d91eb4.js","_static/PostProcessComponent-c17ac553.js","_static/AudioComponent-16766db8.js","_static/TransformComponent-0f395b08.js","_static/TransformBaseComponent-77478ccb.js","_static/index-9feced3c.js","_static/Callout-312ada1c.js"]),warmupEntryPath:"plugins/main/src/components/index.ts"},animator:{load:async()=>__vitePreload(()=>import("./index-be42fc1e.js"),["_static/index-be42fc1e.js","_static/AnimatorStore-48d2c14c.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/animator/index.ts"},"audio-listener":{load:async()=>__vitePreload(()=>import("./audio-d14900e2.js"),["_static/audio-d14900e2.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/audio.ts"},"audio-source":{load:async()=>__vitePreload(()=>import("./AudioComponent-16766db8.js"),["_static/AudioComponent-16766db8.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/AudioComponent.ts"},camera:{load:async()=>__vitePreload(()=>import("./CameraComponent-c919c2dd.js"),["_static/CameraComponent-c919c2dd.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/CameraComponent.ts"},"direct-light":{load:async()=>__vitePreload(()=>import("./DirectLight-166a628d.js"),["_static/DirectLight-166a628d.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/LightBaseComponent-545c5ee8.js"]),warmupEntryPath:"plugins/main/src/components/light/DirectLight.ts"},"lottie-animation":{load:async()=>__vitePreload(()=>import("./LottieAnimationComponent-4db5a6c2.js"),["_static/LottieAnimationComponent-4db5a6c2.js","_static/module-4a37a616.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/LottieAnimationComponent.ts"},"mesh-renderer":{load:async()=>__vitePreload(()=>import("./MeshRendererComponent-082c1a1a.js"),["_static/MeshRendererComponent-082c1a1a.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/createOnModelChange-c010a049.js","_static/ReferencedMaterial-f7ea80fb.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/MeshRendererBaseComponent-8fd1f0df.js"]),warmupEntryPath:"plugins/main/src/components/mesh-renderer/MeshRendererComponent.ts"},"particle-renderer":{load:async()=>__vitePreload(()=>import("./ParticleRendererComponent-ff12cdb1.js"),["_static/ParticleRendererComponent-ff12cdb1.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/createOnModelChange-c010a049.js","_static/ReferencedMaterial-f7ea80fb.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-3bc02b10.js","_static/AssetViewer-1073ddb5.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-4a37a616.js","_static/module-81a206c0.js","_static/ShaderChunkAsset-a42443fc.js","_static/IconPlus-5fbc029e.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js","_static/index-8e169cc2.js","_static/Menu-a427d272.js"]),warmupEntryPath:"plugins/main/src/components/effects/ParticleRendererComponent.tsx"},physics:{load:async()=>__vitePreload(()=>import("./index-cfa0dccc.js"),["_static/index-cfa0dccc.js","_static/PhysicsStore-66a9a461.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/components/physics/index.ts"},"point-light":{load:async()=>__vitePreload(()=>import("./PointLight-a9992e50.js"),["_static/PointLight-a9992e50.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/LightBaseComponent-545c5ee8.js"]),warmupEntryPath:"plugins/main/src/components/light/PointLight.ts"},"post-process":{load:async()=>__vitePreload(()=>import("./index-44137d7e.js"),["_static/index-44137d7e.js","_static/PostProcessComponent-c17ac553.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/IconPlus-5fbc029e.js","_static/createReactComponent-d9f8b1af.js","_static/Menu-a427d272.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/components/postProcess/index.ts"},script:{load:async()=>__vitePreload(()=>import("./index-071c0532.js"),["_static/index-071c0532.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/create-script-property-context-model-0fe0258f.js","_static/TextureAsset-d88af413.js","_static/ktx2-encoder-e9b1c83a.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-3bc02b10.js","_static/createReactComponent-d9f8b1af.js","_static/AssetViewer-1073ddb5.js","_static/GlTFAsset-5c8e7813.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-c83c7d3d.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/shader-data-utils-6ef12596.js","_static/MeshAsset-1c11d7ab.js","_static/index-75e7d483.js","_static/MeshThumbnail-d8ee2674.js","_static/AnimatorControllerAsset-23cceb12.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-f96e0e56.js","_static/module-4a37a616.js","_static/module-81a206c0.js","_static/ShaderChunkAsset-a42443fc.js","_static/IconPlus-5fbc029e.js","_static/AmbientLightAsset-02786385.js","_static/SpineSkeletonDataAsset-fff17383.js","_static/FontAsset-8367aad9.js","_static/SceneAsset-1e802e29.js","_static/ShaderAsset-256afb00.js","_static/ShaderUIScriptAsset-5acb02f5.js","_static/PrimitiveMesh-388f3f36.js","_static/XRReferenceImageAsset-d6d8e59c.js","_static/module-1c91b4e1.js","_static/PrefabAsset-a6750aec.js","_static/PhysicsMaterialAsset-7e86c718.js","_static/RenderTargetAsset-c48990a4.js","_static/AudioAsset-6218f2bb.js","_static/index-eb74362c.js","_static/MarkdownAsset-58491579.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js"]),warmupEntryPath:"plugins/main/src/components/ScriptComponent/index.tsx"},"skinned-mesh-renderer":{load:async()=>__vitePreload(()=>import("./SkinnedMeshRendererComponent-934c055b.js"),["_static/SkinnedMeshRendererComponent-934c055b.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/createOnModelChange-c010a049.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js","_static/MeshRendererBaseComponent-8fd1f0df.js"]),warmupEntryPath:"plugins/main/src/components/skinned-mesh-renderer/SkinnedMeshRendererComponent.ts"},"spine-animation":{load:async()=>__vitePreload(()=>import("./SpineAnimationComponent-b04ba1ee.js"),["_static/SpineAnimationComponent-b04ba1ee.js","_static/module-81a206c0.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/SpineAnimationComponent.ts"},"spot-light":{load:async()=>__vitePreload(()=>import("./SpotLight-617d8957.js"),["_static/SpotLight-617d8957.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/LightBaseComponent-545c5ee8.js"]),warmupEntryPath:"plugins/main/src/components/light/SpotLight.ts"},"sprite-mask":{load:async()=>__vitePreload(()=>import("./SpriteMaskComponent-43ae2b1f.js"),["_static/SpriteMaskComponent-43ae2b1f.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js"]),warmupEntryPath:"plugins/main/src/components/SpriteMaskComponent.ts"},"sprite-renderer":{load:async()=>__vitePreload(()=>import("./SpriteRendererComponent-4f52910c.js"),["_static/SpriteRendererComponent-4f52910c.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/createOnModelChange-c010a049.js","_static/SpriteBaseComponent-062cb4f8.js"]),warmupEntryPath:"plugins/main/src/components/sprite/SpriteRendererComponent.ts"},"text-renderer":{load:async()=>__vitePreload(()=>import("./TextRendererComponent-8db74598.js"),["_static/TextRendererComponent-8db74598.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/TextBaseComponent-bd7ed8ee.js","_static/createReactComponent-d9f8b1af.js"]),warmupEntryPath:"plugins/main/src/components/text/TextRendererComponent.ts"},"trail-renderer":{load:async()=>__vitePreload(()=>import("./TrailRendererComponent-42a58f1d.js"),["_static/TrailRendererComponent-42a58f1d.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/index-8e169cc2.js","_static/Menu-a427d272.js","_static/createOnModelChange-c010a049.js","_static/ReferencedMaterial-f7ea80fb.js","_static/MaterialInspector-237b6a5e.js","_static/IconPointFilled-dbf63b5c.js","_static/createReactComponent-d9f8b1af.js"]),warmupEntryPath:"plugins/main/src/components/effects/TrailRendererComponent.tsx"},transform:{load:async()=>__vitePreload(()=>import("./TransformComponent-0f395b08.js"),["_static/TransformComponent-0f395b08.js","_static/index-365736f7.js","_static/Component-6d1e73e5.js","_static/postmen-c7605b45.js","_static/TransformBaseComponent-77478ccb.js"]),warmupEntryPath:"plugins/main/src/components/transform/TransformComponent.ts"},ui:{load:async()=>__vitePreload(()=>import("./index-9feced3c.js"),["_static/index-9feced3c.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/Component-6d1e73e5.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js","_static/SpriteBaseComponent-062cb4f8.js","_static/TextBaseComponent-bd7ed8ee.js","_static/createReactComponent-d9f8b1af.js","_static/TransformBaseComponent-77478ccb.js","_static/Callout-312ada1c.js"]),warmupEntryPath:"plugins/main/src/components/ui/index.ts"},xr:{load:async()=>__vitePreload(()=>import("./index-f4d91eb4.js").then(rt=>rt.i),["_static/index-f4d91eb4.js","_static/module-1c91b4e1.js","_static/index-365736f7.js","_static/postmen-c7605b45.js","_static/FormItemArray-53c58844.js","_static/Accordion-75b7b34e.js","_static/create-script-property-context-model-0fe0258f.js"]),warmupEntryPath:"plugins/main/src/components/xr/index.ts"}},GLTF_IO_MODULE_REGISTRATION={load:async()=>__vitePreload(()=>import("./glTFIO-45ff9a17.js").then(rt=>rt.j),["_static/glTFIO-45ff9a17.js","_static/ktx-parse.modern-6c9f771f.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/gltf/glTFIO.ts"};function createRuntimeBootstrapState(){return{loadedAssetModuleKeys:new Set,loadedComponentModuleKeys:new Set,gltfIOInitialized:!1}}async function runRuntimeBootstrapPlan({state:rt,plan:_e,onStage:tt,loadAssetModule:et,loadComponentModule:nt,loadGlTFIOModule:it}){const at=_e.assetModuleKeys.filter(st=>!rt.loadedAssetModuleKeys.has(st));at.length>0&&(tt==null||tt("register-assets"),await Promise.all(at.map(async st=>{await et(st),rt.loadedAssetModuleKeys.add(st)})));const ot=_e.componentModuleKeys.filter(st=>!rt.loadedComponentModuleKeys.has(st));if(ot.length>0&&(tt==null||tt("register-components"),await Promise.all(ot.map(async st=>{await nt(st),rt.loadedComponentModuleKeys.add(st)}))),_e.shouldInitGlTFIO&&!rt.gltfIOInitialized){tt==null||tt("init-gltf-io");const{initGlTFIO:st}=await it();await st(),rt.gltfIOInitialized=!0}}function bootstrapEditorRuntime(rt={}){const _e=()=>runRuntimeBootstrapPlan({state:bootstrapState,plan:rt.plan??FULL_RUNTIME_BOOTSTRAP_PLAN,onStage:rt.onStage,loadAssetModule:rt.loadAssetModule??defaultLoadAssetModule,loadComponentModule:rt.loadComponentModule??defaultLoadComponentModule,loadGlTFIOModule:rt.loadGlTFIOModule??defaultLoadGlTFIOModule}),tt=bootstrapQueue.then(_e,_e);return bootstrapQueue=tt.then(()=>{},()=>{}),tt}const FULL_RUNTIME_BOOTSTRAP_PLAN={mode:"full",assetTypes:[],componentTypes:[],unknownAssetTypes:[],unknownComponentTypes:[],assetModuleKeys:[...FULL_ASSET_MODULE_KEYS],componentModuleKeys:[...FULL_COMPONENT_MODULE_KEYS],shouldInitGlTFIO:!0};function defaultLoadAssetModule(rt){var tt;const _e=(tt=ASSET_MODULE_REGISTRY[rt])==null?void 0:tt.load;if(!_e)throw new Error(`unsupported asset runtime module: ${rt}`);return _e()}function defaultLoadComponentModule(rt){var tt;const _e=(tt=COMPONENT_MODULE_REGISTRY[rt])==null?void 0:tt.load;if(!_e)throw new Error(`unsupported component runtime module: ${rt}`);return _e()}async function defaultLoadGlTFIOModule(){return await GLTF_IO_MODULE_REGISTRATION.load()}const bootstrapState=createRuntimeBootstrapState();let bootstrapQueue=Promise.resolve();function attachSceneHotReload(rt){const _e=new EventSource("/events");let tt=!1;return _e.onmessage=async et=>{var it,at,ot,st,ct;if(tt)return;let nt=null;try{nt=JSON.parse(et.data)}catch{return}try{nt.type==="full-refresh"?((it=rt.onStatus)==null||it.call(rt,nt.reason==="project"?"project changed, rebuilding...":"scene changed, refreshing..."),await rt.runtime.reload(),(at=rt.onStatus)==null||at.call(rt,nt.reason==="project"?"project rebuilt":"scene refreshed","idle")):((ot=rt.onStatus)==null||ot.call(rt,`assets changed (${nt.changes.length}), refreshing...`),await rt.runtime.applyAssetBatchChange({changes:nt.changes}),(st=rt.onStatus)==null||st.call(rt,`assets refreshed (${nt.changes.length})`,"idle"))}catch(dt){if(tt)return;tt=!0,console.error(dt),(ct=rt.onStatus)==null||ct.call(rt,"refresh failed, reloading page...","busy"),setTimeout(()=>location.reload(),500)}},_e.onerror=()=>{var et;tt||(et=rt.onStatus)==null||et.call(rt,"hot reload disconnected, retrying...")},_e.onopen=()=>{var et;tt||(et=rt.onStatus)==null||et.call(rt,"hot reload connected","idle")},()=>{_e.close()}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(rt){return rt&&rt.__esModule&&Object.prototype.hasOwnProperty.call(rt,"default")?rt.default:rt}var browser={exports:{}};(function(rt){(_e=>{var tt=Object.defineProperty,et=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyNames,it=Object.prototype.hasOwnProperty,at=(Kt,Zt)=>{for(var an in Zt)tt(Kt,an,{get:Zt[an],enumerable:!0})},ot=(Kt,Zt,an,cn)=>{if(Zt&&typeof Zt=="object"||typeof Zt=="function")for(let gn of nt(Zt))!it.call(Kt,gn)&&gn!==an&&tt(Kt,gn,{get:()=>Zt[gn],enumerable:!(cn=et(Zt,gn))||cn.enumerable});return Kt},st=Kt=>ot(tt({},"__esModule",{value:!0}),Kt),ct=(Kt,Zt,an)=>new Promise((cn,gn)=>{var En=hn=>{try{xn(an.next(hn))}catch(Vn){gn(Vn)}},_n=hn=>{try{xn(an.throw(hn))}catch(Vn){gn(Vn)}},xn=hn=>hn.done?cn(hn.value):Promise.resolve(hn.value).then(En,_n);xn((an=an.apply(Kt,Zt)).next())}),dt={};at(dt,{analyzeMetafile:()=>Yr,analyzeMetafileSync:()=>Jr,build:()=>Sr,buildSync:()=>Kr,context:()=>vr,default:()=>jr,formatMessages:()=>Xr,formatMessagesSync:()=>qr,initialize:()=>_i,stop:()=>Zr,transform:()=>kr,transformSync:()=>Qr,version:()=>gr}),_e.exports=st(dt);function ut(Kt){let Zt=cn=>{if(cn===null)an.write8(0);else if(typeof cn=="boolean")an.write8(1),an.write8(+cn);else if(typeof cn=="number")an.write8(2),an.write32(cn|0);else if(typeof cn=="string")an.write8(3),an.write(pt(cn));else if(cn instanceof Uint8Array)an.write8(4),an.write(cn);else if(cn instanceof Array){an.write8(5),an.write32(cn.length);for(let gn of cn)Zt(gn)}else{let gn=Object.keys(cn);an.write8(6),an.write32(gn.length);for(let En of gn)an.write(pt(En)),Zt(cn[En])}},an=new ft;return an.write32(0),an.write32(Kt.id<<1|+!Kt.isRequest),Zt(Kt.value),yt(an.buf,an.len-4,0),an.buf.subarray(0,an.len)}function ht(Kt){let Zt=()=>{switch(an.read8()){case 0:return null;case 1:return!!an.read8();case 2:return an.read32();case 3:return mt(an.read());case 4:return an.read();case 5:{let _n=an.read32(),xn=[];for(let hn=0;hn<_n;hn++)xn.push(Zt());return xn}case 6:{let _n=an.read32(),xn={};for(let hn=0;hn<_n;hn++)xn[mt(an.read())]=Zt();return xn}default:throw new Error("Invalid packet")}},an=new ft(Kt),cn=an.read32(),gn=(cn&1)===0;cn>>>=1;let En=Zt();if(an.ptr!==Kt.length)throw new Error("Invalid packet");return{id:cn,isRequest:gn,value:En}}var ft=class{constructor(Kt=new Uint8Array(1024)){this.buf=Kt,this.len=0,this.ptr=0}_write(Kt){if(this.len+Kt>this.buf.length){let Zt=new Uint8Array((this.len+Kt)*2);Zt.set(this.buf),this.buf=Zt}return this.len+=Kt,this.len-Kt}write8(Kt){let Zt=this._write(1);this.buf[Zt]=Kt}write32(Kt){let Zt=this._write(4);yt(this.buf,Kt,Zt)}write(Kt){let Zt=this._write(4+Kt.length);yt(this.buf,Kt.length,Zt),this.buf.set(Kt,Zt+4)}_read(Kt){if(this.ptr+Kt>this.buf.length)throw new Error("Invalid packet");return this.ptr+=Kt,this.ptr-Kt}read8(){return this.buf[this._read(1)]}read32(){return _t(this.buf,this._read(4))}read(){let Kt=this.read32(),Zt=new Uint8Array(Kt),an=this._read(Zt.length);return Zt.set(this.buf.subarray(an,an+Kt)),Zt}},pt,mt,vt;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let Kt=new TextEncoder,Zt=new TextDecoder;pt=an=>Kt.encode(an),mt=an=>Zt.decode(an),vt='new TextEncoder().encode("")'}else if(typeof Buffer<"u")pt=Kt=>Buffer.from(Kt),mt=Kt=>{let{buffer:Zt,byteOffset:an,byteLength:cn}=Kt;return Buffer.from(Zt,an,cn).toString()},vt='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(pt("")instanceof Uint8Array))throw new Error(`Invariant violation: "${vt} instanceof Uint8Array" is incorrectly false
|
|
1
|
+
var fo=Object.defineProperty;var po=(rt,_e,tt)=>_e in rt?fo(rt,_e,{enumerable:!0,configurable:!0,writable:!0,value:tt}):rt[_e]=tt;var Rt=(rt,_e,tt)=>(po(rt,typeof _e!="symbol"?_e+"":_e,tt),tt);function _mergeNamespaces(rt,_e){for(var tt=0;tt<_e.length;tt++){const et=_e[tt];if(typeof et!="string"&&!Array.isArray(et)){for(const nt in et)if(nt!=="default"&&!(nt in rt)){const it=Object.getOwnPropertyDescriptor(et,nt);it&&Object.defineProperty(rt,nt,it.get?it:{enumerable:!0,get:()=>et[nt]})}}}return Object.freeze(Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"}))}(function(){const _e=document.createElement("link").relList;if(_e&&_e.supports&&_e.supports("modulepreload"))return;for(const nt of document.querySelectorAll('link[rel="modulepreload"]'))et(nt);new MutationObserver(nt=>{for(const it of nt)if(it.type==="childList")for(const at of it.addedNodes)at.tagName==="LINK"&&at.rel==="modulepreload"&&et(at)}).observe(document,{childList:!0,subtree:!0});function tt(nt){const it={};return nt.integrity&&(it.integrity=nt.integrity),nt.referrerPolicy&&(it.referrerPolicy=nt.referrerPolicy),nt.crossOrigin==="use-credentials"?it.credentials="include":nt.crossOrigin==="anonymous"?it.credentials="omit":it.credentials="same-origin",it}function et(nt){if(nt.ep)return;nt.ep=!0;const it=tt(nt);fetch(nt.href,it)}})();const CLI_PREVIEW_READY_MESSAGE="render path prototype";function createDefaultPreviewReadyStatus(){return`preview initialized (${CLI_PREVIEW_READY_MESSAGE})`}function createPreviewReadyStatus(rt){return`preview initialized in ${rt} (${CLI_PREVIEW_READY_MESSAGE})`}const stageLabels={"boot-runtime":"booting runtime modules","register-assets":"registering asset types","register-components":"registering components","init-gltf-io":"initializing gltf io","resolve-project-id":"resolving project id","query-project":"querying project","init-project":"initializing project","init-engine":"creating engine","init-assets":"loading assets","init-scene":"loading scene","run-engine":"starting viewport","replay-bindings":"replaying bindings","resume-history":"finalizing runtime"};function createStartupStatusReporter(rt){const _e=rt.now??defaultNow,tt=_e();let et=createDefaultPreviewReadyStatus();return{reportStage:at=>{rt.setStatus(`${stageLabels[at]}... ${formatElapsed(_e()-tt)}`,"busy")},finish:()=>{et=createPreviewReadyStatus(formatElapsed(_e()-tt)),rt.setStatus(et,"idle")},getReadyStatus:()=>et}}function defaultNow(){return performance.now()}function formatElapsed(rt){const _e=Math.max(rt,0);return _e>=1e3?`${(_e/1e3).toFixed(1)}s`:`${_e.toFixed(0)}ms`}const scriptRel="modulepreload",assetsURL=function(rt){return"/"+rt},seen={},__vitePreload=function(_e,tt,et){if(!tt||tt.length===0)return _e();const nt=document.getElementsByTagName("link");return Promise.all(tt.map(it=>{if(it=assetsURL(it),it in seen)return;seen[it]=!0;const at=it.endsWith(".css"),ot=at?'[rel="stylesheet"]':"";if(!!et)for(let dt=nt.length-1;dt>=0;dt--){const ut=nt[dt];if(ut.href===it&&(!at||ut.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${it}"]${ot}`))return;const ct=document.createElement("link");if(ct.rel=at?"stylesheet":scriptRel,at||(ct.as="script",ct.crossOrigin=""),ct.href=it,document.head.appendChild(ct),at)return new Promise((dt,ut)=>{ct.addEventListener("load",dt),ct.addEventListener("error",()=>ut(new Error(`Unable to preload CSS for ${it}`)))})})).then(()=>_e()).catch(it=>{const at=new Event("vite:preloadError",{cancelable:!0});if(at.payload=it,window.dispatchEvent(at),!at.defaultPrevented)throw it})},FULL_ASSET_MODULE_KEYS=["all-assets"],FULL_COMPONENT_MODULE_KEYS=["all-components"],NON_RUNTIME_ASSET_TYPES=new Set(["Folder"]),ASSET_MODULE_KEYS_BY_TYPE={AmbientLight:"ambient-light",AnimationClip:"animation-clip",AnimatorController:"animator-controller",Audio:"audio",Font:"font",glTF:"gltf",Lottie:"lottie",LottieClip:"lottie",Markdown:"markdown",Material:"material",Mesh:"mesh",PhysicsMaterial:"physics-material",Prefab:"prefab",PrimitiveMesh:"primitive-mesh",RenderTarget:"render-target",Scene:"scene",script:"script",Shader:"shader",ShaderChunk:"shader",Spine:"spine",SpineAtlas:"spine",SpineSkeletonData:"spine",SpriteAtlas:"sprite-atlas",sprite:"sprite",StateMachineScript:"script",Texture:"texture",XRReferenceImage:"xr-reference-image"},COMPONENT_MODULE_KEYS_BY_TYPE={Animator:"animator",Audio:"audio-listener",AudioSource:"audio-source",Button:"ui",Camera:"camera",CharacterController:"physics",DirectLight:"direct-light",DynamicCollider:"physics",FixedJoint:"physics",HingeJoint:"physics",Image:"ui",LottieAnimation:"lottie-animation",MeshRenderer:"mesh-renderer",ParticleRenderer:"particle-renderer",PointLight:"point-light",PostProcess:"post-process",Script:"script",SkinnedMeshRenderer:"skinned-mesh-renderer",SpineAnimationRenderer:"spine-animation",SpotLight:"spot-light",SpringJoint:"physics",SpriteMask:"sprite-mask",SpriteRenderer:"sprite-renderer",StaticCollider:"physics",Text:"ui",TextRenderer:"text-renderer",TrailRenderer:"trail-renderer",Transform:"transform",UIGroup:"ui",UICanvas:"ui",UITransform:"ui","XR Anchor Manager":"xr","XR Image Manager":"xr","XR Origin":"xr","XR Plane Manager":"xr"},ASSET_MODULE_REGISTRY={"all-assets":{load:async()=>__vitePreload(()=>import("./index-0fef73f8.js"),["_static/index-0fef73f8.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-71e5a4e7.js","_static/createReactComponent-cb70ea50.js","_static/AssetViewer-d2c63b00.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-b084da2a.js","_static/module-5547be1c.js","_static/module-57b6e417.js","_static/ShaderChunkAsset-e3487bd1.js","_static/IconPlus-172c6c17.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/assets/index.ts"},"ambient-light":{load:async()=>__vitePreload(()=>import("./AmbientLightAsset-e34de607.js"),["_static/AmbientLightAsset-e34de607.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-debbe073.js"]),warmupEntryPath:"plugins/main/src/assets/ambient/AmbientLightAsset.tsx"},"animation-clip":{load:async()=>__vitePreload(()=>import("./index-d9ee84ce.js"),["_static/index-d9ee84ce.js","_static/AnimationClipAsset-b084da2a.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/module-5547be1c.js","_static/module-57b6e417.js"]),warmupEntryPath:"plugins/main/src/assets/animation-clip/index.tsx"},"animator-controller":{load:async()=>__vitePreload(()=>import("./AnimatorControllerAsset-6cc04274.js"),["_static/AnimatorControllerAsset-6cc04274.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js"]),warmupEntryPath:"plugins/main/src/assets/animator-controller/AnimatorControllerAsset.ts"},audio:{load:async()=>__vitePreload(()=>import("./AudioAsset-9c715952.js"),["_static/AudioAsset-9c715952.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/audio/AudioAsset.tsx"},font:{load:async()=>__vitePreload(()=>import("./FontAsset-6e9c0549.js"),["_static/FontAsset-6e9c0549.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/font/FontAsset.tsx"},gltf:{load:async()=>__vitePreload(()=>import("./GlTFAsset-83e8190e.js").then(rt=>rt.b),["_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/ktx-parse.modern-6c9f771f.js","_static/meshopt_simplifier.module-cd99529d.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/shader-data-utils-000170ae.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js"]),warmupEntryPath:"plugins/main/src/assets/gltf/GlTFAsset.tsx"},lottie:{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-e3487bd1.js").then(rt=>rt.f),["_static/ShaderChunkAsset-e3487bd1.js","_static/module-5547be1c.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/createReactComponent-cb70ea50.js","_static/IconPlus-172c6c17.js","_static/AssetViewer-d2c63b00.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-71e5a4e7.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/AnimationClipAsset-b084da2a.js","_static/module-57b6e417.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/assets/lottie/LottieAsset.tsx"},markdown:{load:async()=>__vitePreload(()=>import("./MarkdownAsset-b42846c0.js"),["_static/MarkdownAsset-b42846c0.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/assets/markdown/MarkdownAsset.ts"},material:{load:async()=>__vitePreload(()=>import("./MaterialAsset-0b9d7eba.js").then(rt=>rt.b),["_static/MaterialAsset-0b9d7eba.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/AssetViewer-d2c63b00.js","_static/shader-data-utils-000170ae.js"]),warmupEntryPath:"plugins/main/src/assets/material/MaterialAsset.tsx"},mesh:{load:async()=>__vitePreload(()=>import("./MeshAsset-85e99837.js"),["_static/MeshAsset-85e99837.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AssetViewer-d2c63b00.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/mesh/MeshAsset.tsx"},"physics-material":{load:async()=>__vitePreload(()=>import("./PhysicsMaterialAsset-cb9afb6e.js"),["_static/PhysicsMaterialAsset-cb9afb6e.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/assets/physics/PhysicsMaterialAsset.ts"},prefab:{load:async()=>__vitePreload(()=>import("./PrefabAsset-265f6f48.js"),["_static/PrefabAsset-265f6f48.js","_static/TaskQueue-05c94a4d.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/prefab/PrefabAsset.ts"},"primitive-mesh":{load:async()=>__vitePreload(()=>import("./PrimitiveMesh-70c93e7e.js"),["_static/PrimitiveMesh-70c93e7e.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/MeshThumbnail-b1283749.js"]),warmupEntryPath:"plugins/main/src/assets/primitive-mesh/PrimitiveMesh.ts"},"render-target":{load:async()=>__vitePreload(()=>import("./RenderTargetAsset-b810caf3.js"),["_static/RenderTargetAsset-b810caf3.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/render-target/RenderTargetAsset.ts"},scene:{load:async()=>__vitePreload(()=>import("./SceneAsset-d05b1a79.js"),["_static/SceneAsset-d05b1a79.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/assets/scene/SceneAsset.tsx"},script:{load:async()=>__vitePreload(()=>import("./index-ea7fe254.js"),["_static/index-ea7fe254.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/assets/script/index.ts"},shader:{load:async()=>__vitePreload(()=>import("./index-6649d404.js"),["_static/index-6649d404.js","_static/ShaderAsset-370b6f1c.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/meshopt_simplifier.module-cd99529d.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/shader-data-utils-000170ae.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/index-7e414715.js"]),warmupEntryPath:"plugins/main/src/assets/shader/index.ts"},spine:{load:async()=>__vitePreload(()=>import("./SpineSkeletonDataAsset-0dffbb4d.js").then(rt=>rt.a),["_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/module-57b6e417.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/spine/SpineSkeletonDataAsset.ts"},"sprite-atlas":{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-e3487bd1.js").then(rt=>rt.e),["_static/ShaderChunkAsset-e3487bd1.js","_static/module-5547be1c.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/createReactComponent-cb70ea50.js","_static/IconPlus-172c6c17.js","_static/AssetViewer-d2c63b00.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-71e5a4e7.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/AnimationClipAsset-b084da2a.js","_static/module-57b6e417.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/assets/atlas/SpriteAtlasAsset.tsx"},sprite:{load:async()=>__vitePreload(()=>import("./ShaderChunkAsset-e3487bd1.js").then(rt=>rt.d),["_static/ShaderChunkAsset-e3487bd1.js","_static/module-5547be1c.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/createReactComponent-cb70ea50.js","_static/IconPlus-172c6c17.js","_static/AssetViewer-d2c63b00.js","_static/meshopt_simplifier.module-cd99529d.js","_static/bundlers-9b0d37fc.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/Tooltip-71e5a4e7.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/AnimationClipAsset-b084da2a.js","_static/module-57b6e417.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/assets/sprite/SpriteAsset.ts"},texture:{load:async()=>__vitePreload(()=>import("./TextureAsset-9cd94531.js").then(rt=>rt.d),["_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-71e5a4e7.js","_static/createReactComponent-cb70ea50.js","_static/AssetViewer-d2c63b00.js"]),warmupEntryPath:"plugins/main/src/assets/texture/TextureAsset.tsx"},"xr-reference-image":{load:async()=>__vitePreload(()=>import("./XRReferenceImageAsset-79e78558.js"),["_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/AssetViewer-d2c63b00.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/xr/XRReferenceImageAsset.tsx"}},COMPONENT_MODULE_REGISTRY={"all-components":{load:async()=>__vitePreload(()=>import("./index-788e8750.js"),["_static/index-788e8750.js","_static/CameraComponent-9c9db3fb.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/DirectLight-b0490ef7.js","_static/LightBaseComponent-b4854e8a.js","_static/PointLight-a2bfed75.js","_static/SpotLight-ada565f2.js","_static/MeshRendererComponent-c3c3c683.js","_static/createOnModelChange-e65da908.js","_static/ReferencedMaterial-831d0583.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/MeshRendererBaseComponent-5621d663.js","_static/SkinnedMeshRendererComponent-ee33da25.js","_static/AnimatorStore-0bc90c37.js","_static/SpriteRendererComponent-489486e0.js","_static/SpriteBaseComponent-3156cb3b.js","_static/SpriteMaskComponent-a32024e1.js","_static/PhysicsStore-0a751fa0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js","_static/index-d00c8bc3.js","_static/create-script-property-context-model-0fe0258f.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-71e5a4e7.js","_static/AssetViewer-d2c63b00.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-b084da2a.js","_static/module-5547be1c.js","_static/module-57b6e417.js","_static/ShaderChunkAsset-e3487bd1.js","_static/IconPlus-172c6c17.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/TextRendererComponent-6be5f80c.js","_static/TextBaseComponent-520dea39.js","_static/LottieAnimationComponent-efd5da2b.js","_static/SpineAnimationComponent-12e694e8.js","_static/ParticleRendererComponent-94656239.js","_static/index-f7bd6fef.js","_static/Menu-05c1f0a4.js","_static/TrailRendererComponent-74bf88c0.js","_static/index-b13216a9.js","_static/PostProcessComponent-040cf521.js","_static/AudioComponent-80d06ef4.js","_static/TransformComponent-49d279f5.js","_static/TransformBaseComponent-0d241199.js","_static/index-46c87b46.js","_static/Callout-48e71f13.js"]),warmupEntryPath:"plugins/main/src/components/index.ts"},animator:{load:async()=>__vitePreload(()=>import("./index-1fd4207a.js"),["_static/index-1fd4207a.js","_static/AnimatorStore-0bc90c37.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/animator/index.ts"},"audio-listener":{load:async()=>__vitePreload(()=>import("./audio-5d0ddf55.js"),["_static/audio-5d0ddf55.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/audio.ts"},"audio-source":{load:async()=>__vitePreload(()=>import("./AudioComponent-80d06ef4.js"),["_static/AudioComponent-80d06ef4.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/AudioComponent.ts"},camera:{load:async()=>__vitePreload(()=>import("./CameraComponent-9c9db3fb.js"),["_static/CameraComponent-9c9db3fb.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/CameraComponent.ts"},"direct-light":{load:async()=>__vitePreload(()=>import("./DirectLight-b0490ef7.js"),["_static/DirectLight-b0490ef7.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/LightBaseComponent-b4854e8a.js"]),warmupEntryPath:"plugins/main/src/components/light/DirectLight.ts"},"lottie-animation":{load:async()=>__vitePreload(()=>import("./LottieAnimationComponent-efd5da2b.js"),["_static/LottieAnimationComponent-efd5da2b.js","_static/module-5547be1c.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/LottieAnimationComponent.ts"},"mesh-renderer":{load:async()=>__vitePreload(()=>import("./MeshRendererComponent-c3c3c683.js"),["_static/MeshRendererComponent-c3c3c683.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/createOnModelChange-e65da908.js","_static/ReferencedMaterial-831d0583.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/MeshRendererBaseComponent-5621d663.js"]),warmupEntryPath:"plugins/main/src/components/mesh-renderer/MeshRendererComponent.ts"},"particle-renderer":{load:async()=>__vitePreload(()=>import("./ParticleRendererComponent-94656239.js"),["_static/ParticleRendererComponent-94656239.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/createOnModelChange-e65da908.js","_static/ReferencedMaterial-831d0583.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-71e5a4e7.js","_static/AssetViewer-d2c63b00.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-b084da2a.js","_static/module-5547be1c.js","_static/module-57b6e417.js","_static/ShaderChunkAsset-e3487bd1.js","_static/IconPlus-172c6c17.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js","_static/index-f7bd6fef.js","_static/Menu-05c1f0a4.js"]),warmupEntryPath:"plugins/main/src/components/effects/ParticleRendererComponent.tsx"},physics:{load:async()=>__vitePreload(()=>import("./index-87ef1c72.js"),["_static/index-87ef1c72.js","_static/PhysicsStore-0a751fa0.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/components/physics/index.ts"},"point-light":{load:async()=>__vitePreload(()=>import("./PointLight-a2bfed75.js"),["_static/PointLight-a2bfed75.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/LightBaseComponent-b4854e8a.js"]),warmupEntryPath:"plugins/main/src/components/light/PointLight.ts"},"post-process":{load:async()=>__vitePreload(()=>import("./index-1e036622.js"),["_static/index-1e036622.js","_static/PostProcessComponent-040cf521.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/IconPlus-172c6c17.js","_static/createReactComponent-cb70ea50.js","_static/Menu-05c1f0a4.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/components/postProcess/index.ts"},script:{load:async()=>__vitePreload(()=>import("./index-d00c8bc3.js"),["_static/index-d00c8bc3.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/create-script-property-context-model-0fe0258f.js","_static/TextureAsset-9cd94531.js","_static/ktx2-encoder-522fc017.js","_static/TaskQueue-05c94a4d.js","_static/ktx-parse.modern-6c9f771f.js","_static/encode-ac4bb64e.js","_static/meshopt_simplifier.module-cd99529d.js","_static/Tooltip-71e5a4e7.js","_static/createReactComponent-cb70ea50.js","_static/AssetViewer-d2c63b00.js","_static/GlTFAsset-83e8190e.js","_static/glTFIO-45ff9a17.js","_static/MaterialAsset-0b9d7eba.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/shader-data-utils-000170ae.js","_static/MeshAsset-85e99837.js","_static/index-7e414715.js","_static/MeshThumbnail-b1283749.js","_static/AnimatorControllerAsset-6cc04274.js","_static/bundlers-9b0d37fc.js","_static/AnimationClipAsset-b084da2a.js","_static/module-5547be1c.js","_static/module-57b6e417.js","_static/ShaderChunkAsset-e3487bd1.js","_static/IconPlus-172c6c17.js","_static/AmbientLightAsset-e34de607.js","_static/SpineSkeletonDataAsset-0dffbb4d.js","_static/FontAsset-6e9c0549.js","_static/SceneAsset-d05b1a79.js","_static/ShaderAsset-370b6f1c.js","_static/ShaderUIScriptAsset-ebf57ceb.js","_static/PrimitiveMesh-70c93e7e.js","_static/XRReferenceImageAsset-79e78558.js","_static/module-5906e0d4.js","_static/PrefabAsset-265f6f48.js","_static/PhysicsMaterialAsset-cb9afb6e.js","_static/RenderTargetAsset-b810caf3.js","_static/AudioAsset-9c715952.js","_static/index-ea7fe254.js","_static/MarkdownAsset-b42846c0.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js"]),warmupEntryPath:"plugins/main/src/components/ScriptComponent/index.tsx"},"skinned-mesh-renderer":{load:async()=>__vitePreload(()=>import("./SkinnedMeshRendererComponent-ee33da25.js"),["_static/SkinnedMeshRendererComponent-ee33da25.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/createOnModelChange-e65da908.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js","_static/MeshRendererBaseComponent-5621d663.js"]),warmupEntryPath:"plugins/main/src/components/skinned-mesh-renderer/SkinnedMeshRendererComponent.ts"},"spine-animation":{load:async()=>__vitePreload(()=>import("./SpineAnimationComponent-12e694e8.js"),["_static/SpineAnimationComponent-12e694e8.js","_static/module-57b6e417.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/SpineAnimationComponent.ts"},"spot-light":{load:async()=>__vitePreload(()=>import("./SpotLight-ada565f2.js"),["_static/SpotLight-ada565f2.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/LightBaseComponent-b4854e8a.js"]),warmupEntryPath:"plugins/main/src/components/light/SpotLight.ts"},"sprite-mask":{load:async()=>__vitePreload(()=>import("./SpriteMaskComponent-a32024e1.js"),["_static/SpriteMaskComponent-a32024e1.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js"]),warmupEntryPath:"plugins/main/src/components/SpriteMaskComponent.ts"},"sprite-renderer":{load:async()=>__vitePreload(()=>import("./SpriteRendererComponent-489486e0.js"),["_static/SpriteRendererComponent-489486e0.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/createOnModelChange-e65da908.js","_static/SpriteBaseComponent-3156cb3b.js"]),warmupEntryPath:"plugins/main/src/components/sprite/SpriteRendererComponent.ts"},"text-renderer":{load:async()=>__vitePreload(()=>import("./TextRendererComponent-6be5f80c.js"),["_static/TextRendererComponent-6be5f80c.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/TextBaseComponent-520dea39.js","_static/createReactComponent-cb70ea50.js"]),warmupEntryPath:"plugins/main/src/components/text/TextRendererComponent.ts"},"trail-renderer":{load:async()=>__vitePreload(()=>import("./TrailRendererComponent-74bf88c0.js"),["_static/TrailRendererComponent-74bf88c0.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/index-f7bd6fef.js","_static/Menu-05c1f0a4.js","_static/createOnModelChange-e65da908.js","_static/ReferencedMaterial-831d0583.js","_static/MaterialInspector-23ea0240.js","_static/IconPointFilled-bad94cf1.js","_static/createReactComponent-cb70ea50.js"]),warmupEntryPath:"plugins/main/src/components/effects/TrailRendererComponent.tsx"},transform:{load:async()=>__vitePreload(()=>import("./TransformComponent-49d279f5.js"),["_static/TransformComponent-49d279f5.js","_static/index-debbe073.js","_static/Component-b95aa2af.js","_static/postmen-443b3e5f.js","_static/TransformBaseComponent-0d241199.js"]),warmupEntryPath:"plugins/main/src/components/transform/TransformComponent.ts"},ui:{load:async()=>__vitePreload(()=>import("./index-46c87b46.js"),["_static/index-46c87b46.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/Component-b95aa2af.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js","_static/SpriteBaseComponent-3156cb3b.js","_static/TextBaseComponent-520dea39.js","_static/createReactComponent-cb70ea50.js","_static/TransformBaseComponent-0d241199.js","_static/Callout-48e71f13.js"]),warmupEntryPath:"plugins/main/src/components/ui/index.ts"},xr:{load:async()=>__vitePreload(()=>import("./index-b13216a9.js").then(rt=>rt.i),["_static/index-b13216a9.js","_static/module-5906e0d4.js","_static/index-debbe073.js","_static/postmen-443b3e5f.js","_static/FormItemArray-b2a3d249.js","_static/Accordion-f938dadf.js","_static/create-script-property-context-model-0fe0258f.js"]),warmupEntryPath:"plugins/main/src/components/xr/index.ts"}},GLTF_IO_MODULE_REGISTRATION={load:async()=>__vitePreload(()=>import("./glTFIO-45ff9a17.js").then(rt=>rt.j),["_static/glTFIO-45ff9a17.js","_static/ktx-parse.modern-6c9f771f.js","_static/meshopt_simplifier.module-cd99529d.js"]),warmupEntryPath:"plugins/main/src/assets/gltf/glTFIO.ts"};function createRuntimeBootstrapState(){return{loadedAssetModuleKeys:new Set,loadedComponentModuleKeys:new Set,gltfIOInitialized:!1}}async function runRuntimeBootstrapPlan({state:rt,plan:_e,onStage:tt,loadAssetModule:et,loadComponentModule:nt,loadGlTFIOModule:it}){const at=_e.assetModuleKeys.filter(st=>!rt.loadedAssetModuleKeys.has(st));at.length>0&&(tt==null||tt("register-assets"),await Promise.all(at.map(async st=>{await et(st),rt.loadedAssetModuleKeys.add(st)})));const ot=_e.componentModuleKeys.filter(st=>!rt.loadedComponentModuleKeys.has(st));if(ot.length>0&&(tt==null||tt("register-components"),await Promise.all(ot.map(async st=>{await nt(st),rt.loadedComponentModuleKeys.add(st)}))),_e.shouldInitGlTFIO&&!rt.gltfIOInitialized){tt==null||tt("init-gltf-io");const{initGlTFIO:st}=await it();await st(),rt.gltfIOInitialized=!0}}function bootstrapEditorRuntime(rt={}){const _e=()=>runRuntimeBootstrapPlan({state:bootstrapState,plan:rt.plan??FULL_RUNTIME_BOOTSTRAP_PLAN,onStage:rt.onStage,loadAssetModule:rt.loadAssetModule??defaultLoadAssetModule,loadComponentModule:rt.loadComponentModule??defaultLoadComponentModule,loadGlTFIOModule:rt.loadGlTFIOModule??defaultLoadGlTFIOModule}),tt=bootstrapQueue.then(_e,_e);return bootstrapQueue=tt.then(()=>{},()=>{}),tt}const FULL_RUNTIME_BOOTSTRAP_PLAN={mode:"full",assetTypes:[],componentTypes:[],unknownAssetTypes:[],unknownComponentTypes:[],assetModuleKeys:[...FULL_ASSET_MODULE_KEYS],componentModuleKeys:[...FULL_COMPONENT_MODULE_KEYS],shouldInitGlTFIO:!0};function defaultLoadAssetModule(rt){var tt;const _e=(tt=ASSET_MODULE_REGISTRY[rt])==null?void 0:tt.load;if(!_e)throw new Error(`unsupported asset runtime module: ${rt}`);return _e()}function defaultLoadComponentModule(rt){var tt;const _e=(tt=COMPONENT_MODULE_REGISTRY[rt])==null?void 0:tt.load;if(!_e)throw new Error(`unsupported component runtime module: ${rt}`);return _e()}async function defaultLoadGlTFIOModule(){return await GLTF_IO_MODULE_REGISTRATION.load()}const bootstrapState=createRuntimeBootstrapState();let bootstrapQueue=Promise.resolve();function attachSceneHotReload(rt){const _e=new EventSource("/events");let tt=!1;return _e.onmessage=async et=>{var it,at,ot,st,ct;if(tt)return;let nt=null;try{nt=JSON.parse(et.data)}catch{return}try{nt.type==="full-refresh"?((it=rt.onStatus)==null||it.call(rt,nt.reason==="project"?"project changed, rebuilding...":"scene changed, refreshing..."),await rt.runtime.reload(),(at=rt.onStatus)==null||at.call(rt,nt.reason==="project"?"project rebuilt":"scene refreshed","idle")):((ot=rt.onStatus)==null||ot.call(rt,`assets changed (${nt.changes.length}), refreshing...`),await rt.runtime.applyAssetBatchChange({changes:nt.changes}),(st=rt.onStatus)==null||st.call(rt,`assets refreshed (${nt.changes.length})`,"idle"))}catch(dt){if(tt)return;tt=!0,console.error(dt),(ct=rt.onStatus)==null||ct.call(rt,"refresh failed, reloading page...","busy"),setTimeout(()=>location.reload(),500)}},_e.onerror=()=>{var et;tt||(et=rt.onStatus)==null||et.call(rt,"hot reload disconnected, retrying...")},_e.onopen=()=>{var et;tt||(et=rt.onStatus)==null||et.call(rt,"hot reload connected","idle")},()=>{_e.close()}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(rt){return rt&&rt.__esModule&&Object.prototype.hasOwnProperty.call(rt,"default")?rt.default:rt}var browser={exports:{}};(function(rt){(_e=>{var tt=Object.defineProperty,et=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyNames,it=Object.prototype.hasOwnProperty,at=(Kt,Zt)=>{for(var an in Zt)tt(Kt,an,{get:Zt[an],enumerable:!0})},ot=(Kt,Zt,an,cn)=>{if(Zt&&typeof Zt=="object"||typeof Zt=="function")for(let gn of nt(Zt))!it.call(Kt,gn)&&gn!==an&&tt(Kt,gn,{get:()=>Zt[gn],enumerable:!(cn=et(Zt,gn))||cn.enumerable});return Kt},st=Kt=>ot(tt({},"__esModule",{value:!0}),Kt),ct=(Kt,Zt,an)=>new Promise((cn,gn)=>{var En=hn=>{try{xn(an.next(hn))}catch(Vn){gn(Vn)}},_n=hn=>{try{xn(an.throw(hn))}catch(Vn){gn(Vn)}},xn=hn=>hn.done?cn(hn.value):Promise.resolve(hn.value).then(En,_n);xn((an=an.apply(Kt,Zt)).next())}),dt={};at(dt,{analyzeMetafile:()=>Yr,analyzeMetafileSync:()=>Jr,build:()=>Sr,buildSync:()=>Kr,context:()=>vr,default:()=>jr,formatMessages:()=>Xr,formatMessagesSync:()=>qr,initialize:()=>_i,stop:()=>Zr,transform:()=>kr,transformSync:()=>Qr,version:()=>gr}),_e.exports=st(dt);function ut(Kt){let Zt=cn=>{if(cn===null)an.write8(0);else if(typeof cn=="boolean")an.write8(1),an.write8(+cn);else if(typeof cn=="number")an.write8(2),an.write32(cn|0);else if(typeof cn=="string")an.write8(3),an.write(pt(cn));else if(cn instanceof Uint8Array)an.write8(4),an.write(cn);else if(cn instanceof Array){an.write8(5),an.write32(cn.length);for(let gn of cn)Zt(gn)}else{let gn=Object.keys(cn);an.write8(6),an.write32(gn.length);for(let En of gn)an.write(pt(En)),Zt(cn[En])}},an=new ft;return an.write32(0),an.write32(Kt.id<<1|+!Kt.isRequest),Zt(Kt.value),yt(an.buf,an.len-4,0),an.buf.subarray(0,an.len)}function ht(Kt){let Zt=()=>{switch(an.read8()){case 0:return null;case 1:return!!an.read8();case 2:return an.read32();case 3:return mt(an.read());case 4:return an.read();case 5:{let _n=an.read32(),xn=[];for(let hn=0;hn<_n;hn++)xn.push(Zt());return xn}case 6:{let _n=an.read32(),xn={};for(let hn=0;hn<_n;hn++)xn[mt(an.read())]=Zt();return xn}default:throw new Error("Invalid packet")}},an=new ft(Kt),cn=an.read32(),gn=(cn&1)===0;cn>>>=1;let En=Zt();if(an.ptr!==Kt.length)throw new Error("Invalid packet");return{id:cn,isRequest:gn,value:En}}var ft=class{constructor(Kt=new Uint8Array(1024)){this.buf=Kt,this.len=0,this.ptr=0}_write(Kt){if(this.len+Kt>this.buf.length){let Zt=new Uint8Array((this.len+Kt)*2);Zt.set(this.buf),this.buf=Zt}return this.len+=Kt,this.len-Kt}write8(Kt){let Zt=this._write(1);this.buf[Zt]=Kt}write32(Kt){let Zt=this._write(4);yt(this.buf,Kt,Zt)}write(Kt){let Zt=this._write(4+Kt.length);yt(this.buf,Kt.length,Zt),this.buf.set(Kt,Zt+4)}_read(Kt){if(this.ptr+Kt>this.buf.length)throw new Error("Invalid packet");return this.ptr+=Kt,this.ptr-Kt}read8(){return this.buf[this._read(1)]}read32(){return _t(this.buf,this._read(4))}read(){let Kt=this.read32(),Zt=new Uint8Array(Kt),an=this._read(Zt.length);return Zt.set(this.buf.subarray(an,an+Kt)),Zt}},pt,mt,vt;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let Kt=new TextEncoder,Zt=new TextDecoder;pt=an=>Kt.encode(an),mt=an=>Zt.decode(an),vt='new TextEncoder().encode("")'}else if(typeof Buffer<"u")pt=Kt=>Buffer.from(Kt),mt=Kt=>{let{buffer:Zt,byteOffset:an,byteLength:cn}=Kt;return Buffer.from(Zt,an,cn).toString()},vt='Buffer.from("")';else throw new Error("No UTF-8 codec found");if(!(pt("")instanceof Uint8Array))throw new Error(`Invariant violation: "${vt} instanceof Uint8Array" is incorrectly false
|
|
2
2
|
|
|
3
3
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
4
4
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
@@ -707,7 +707,7 @@ Please switch to a supported browser to use this feature.`,"unsupported-confirm"
|
|
|
707
707
|
请切换到受支持的浏览器后再使用。`,"unsupported-confirm":"知道了","open-in-ide":"在 IDE 中打开",unbind:"取消关联","unbind-confirm-title":"取消关联本地工作区","unbind-confirm-description":"这将断开本地工作区关联并清除同步缓存。已同步到本地文件夹的文件不会被删除。","unbind-current-path":"已关联:{{0}}"},"sprite-atlas":{title:"精灵图集",adding:"添加中",success:"成功",error:"添加精灵失败"},"tree-shaking":{tip:"Tree Shaking 是减少项目文件大小的有效功能。在打包时可智能移除项目中不需要的资产",default:{title:"默认",desc:"关闭 Tree Shaking"},"current-scene":{title:"当前场景",desc:"仅对默认场景做 Tree Shaking"},"all-scene":{title:"所有场景",desc:"对所有场景做 Tree Shaking"},title:"Tree Shaking"},"primitive-mesh":{title:"原始网格",type:{label:"类型",info:"要创建的原始网格类型"},sphere:{radius:{label:"半径",info:"球体的半径"},step:{label:"步数",info:"构建球体所用的段数"}},capsule:{radius:{label:"半径",info:"胶囊体的半径"},height:{label:"高度",info:"胶囊体的高度"},"radial-segments":{label:"径向段数",info:"胶囊体周围的段数"},"height-segments":{label:"高度段数",info:"胶囊体高度上的段数"}},cone:{radius:{label:"底部半径",info:"圆锥底部的半径"},height:{label:"高度",info:"圆锥的高度"},"radial-segments":{label:"径向段数",info:"圆锥周围的段数"},"height-segments":{label:"高度段数",info:"圆锥高度上的段数"}},cuboid:{width:{label:"宽度",info:"立方体的宽度"},height:{label:"高度",info:"立方体的高度"},depth:{label:"深度",info:"立方体的深度"}},cylinder:{"radius-top":{label:"顶半径",info:"圆柱顶的半径"},"radius-bottom":{label:"底半径",info:"圆柱底的半径"},height:{label:"高度",info:"圆柱的高度"},"radial-segments":{label:"径向段数",info:"圆柱周围的段数"},"height-segments":{label:"高度段数",info:"圆柱高度上的段数"}},plane:{width:{label:"宽度",info:"平面的宽度"},height:{label:"高度",info:"平面的高度"},"horizontal-segments":{label:"水平段数",info:"平面宽度上的段数"},"vertical-segments":{label:"垂直段数",info:"平面高度上的段数"}},torus:{radius:{label:"半径",info:"从环中心到管中心的半径"},"tube-radius":{label:"管半径",info:"环管的半径"},"radial-segments":{label:"径向段数",info:"环周围的段数"},"tubular-segments":{label:"管段数",info:"管周围的段数"},arc:{label:"弧度",info:"环段的中心角度"}}},gltf:{title:"GlTF","basic-info":"基本信息",triangles:"三角形",drawcall:"绘制调用","compute-tangents":"计算切线","keep-mesh-data":"保留网格数据","refresh-tip":"刷新后生效",issues:"问题","remapped-materials":"重新映射的材质",compression:"压缩",quantize:"量化",meshopt:"网格优化"},"select-asset":"选择资产...",filter:{all:"全部"},folder:{title:"文件夹"},shader:{title:"着色器"},material:{title:"材质"},script:{title:"脚本"},font:{title:"字体"},"texture-cube":{title:"TextureCube"},"ambient-light":{title:"环境光"},"directional-light":{title:"平行光"},"point-light":{title:"点光源"},"spot-light":{title:"聚光灯"},sprite:{title:"精灵"},"xr-reference-image":{title:"XR参考图像"},"animator-controller":{title:"动画控制器"},"animation-clip":{title:"动画片段"},scene:{title:"场景"},"physics-material":{title:"物理材质"},"render-target":{title:"渲染目标"},"entity-script":{title:"实体脚本"},"state-machine-script":{title:"状态机脚本"},"shader-chunk":{title:"着色器片段"},"shader-ui-script":{title:"着色器UI脚本"},prefab:{title:"预制体"},audio:{title:"音频"},mesh:{title:"网格"},lottie:{title:"Lottie"},"spine-skeleton-data":{title:"Spine骨骼数据"},"spine-atlas":{title:"图集"},ktx2:{mode:{label:"模式",uastc:{label:"UASTC",desc:"UASTC 提供更好的质量但文件更大"},etc1s:{label:"ETC1S",desc:"ETC1S 提供更好的压缩率但质量较低"}},quality:"质量"}},transform$3={position:{title:"位置",info:"实体在3D空间中的位置"},rotation:{title:"旋转",info:"实体在3D空间中的旋转角度"},scale:{title:"缩放",info:"实体在3D空间中的缩放比例"},error:{"cant-disable":"无法禁用变换组件","cant-delete":"无法删除变换组件"}},light$1={color:"颜色","culling-mask":"剔除遮罩",point:{distance:{label:"距离",info:"点光源能照亮的最大距离"}},shadow:{title:"阴影",type:{label:"类型",info:"阴影类型",none:"无",hard:"硬阴影",softlow:"软阴影(低质量)",softhigh:"软阴影(高质量)"},bias:{label:"偏移",info:"阴影偏移,用于防止阴影痤疮"},"normal-bias":{label:"法线偏移",info:"阴影法线偏移,用于防止阴影痤疮"},"near-plane-offset":{label:"近平面偏移",info:"阴影近平面偏移"},strength:{label:"强度",info:"阴影强度"}},spot:{distance:{label:"距离",info:"聚光灯能照亮的最大距离"},angle:{label:"角度",info:"聚光灯的锥形角度"},penumbra:{label:"半影角度",info:"聚光灯的半影角度"}}},prefab$1={inspector:{"basic-info":"基本信息","dependent-assets":"依赖资产",url:"URL",missed:"缺失"},error:{"create-from-sub":"不能从预制体子实体创建预制体"},delete:{title:"删除预制体实例?",description:"预制体 '{{name}}' 已被移除,是否要删除所有实例?"},button:{no:"否",yes:"是"},replace:{title:"替换预制体",description:'确定要替换预制体 "{{name}}" 吗?所有预制体实例都将被替换',confirm:"仍然替换"}},community$1={title:"社区","all-projects":"全部项目","my-projects":"我的项目","all-projects-desc":"探索社区分享的项目","my-projects-desc":"您发布到社区的项目","search-placeholder":"搜索社区项目...","no-projects":"未找到社区项目","no-my-projects":"您还没有发布任何项目","publish-hint":"发布您的第一个项目与社区分享","load-more":"加载更多",loading:"加载中...","no-preview":"预览不可用",preview:"预览",share:"分享",withdraw:"撤回",tags:"标签",license:"许可证",stats:"统计",copyright:"额外版权声明",views:"浏览",likes:"点赞",downloads:"下载",publish:{title:"发布到社区","published-at":"发布于","publish-button":"发布",agreement:"点击发布即表示您同意我们的","community-guidelines":"社区准则","more-options":"更多选项"},"link-copied":"链接已复制到剪贴板","withdraw-success":"项目撤回成功","withdraw-error":"撤回项目失败","publish-success":"已提交审核",status:{pending:"待审核",approved:"已通过",rejected:"已拒绝"}},resourcePackage$1={export:"导出为资源包",import:"导入资源包",exporting:"正在导出资源包...",importing:"正在导入资源包...","export-success":"资源包导出成功","export-failed":"资源包导出失败","import-success":"资源包导入成功","import-failed":"资源包导入失败","no-assets-selected":"请先选择要导出的资产","cant-export-sub-asset":"无法导出子资产",assets:"个资产"},zh$1={service:service$1,"code-editor":{"back-to-editor":"返回场景编辑器",preview:"预览",devtools:{console:"控制台",inspector:"检查器"},file:{"not-saved":"文件未保存。","not-saved-description":"是否仍要放弃更改?所有未保存的更改都将丢失。",cancel:"取消",confirm:"确认",project:"项目"},"event-debug":{input:"输入",json:"JSON",clear:"清空",confirm:"确认",events:"事件",trigger:"触发","no-events":"未检测到来自预览的任何事件信号。"},"file-tree":{title:"资源",search:{placeholder:"搜索文件..."}},library:{title:"依赖",import:"导入",search:{placeholder:"库名称"},version:{latest:"最新",updating:"更新中..."}},menubar:{file:{title:"文件","new-file":"新建文件","open-file":"打开文件",save:"保存",close:"关闭"},edit:{title:"编辑",undo:"撤销",redo:"重做",find:{title:"查找...",find:"查找",replace:"替换"},cut:"剪切",copy:"复制",paste:"粘贴"},view:{title:"视图","show-minimap":"显示小地图","new-tab":"新建标签页","close-tab":"关闭标签页",share:"分享",print:"打印"},help:{title:"帮助",documentation:"文档","shader-syntax":"Shader 语法",about:"关于"}},monaco:{loading:"加载中..."},"preview-inspector":{title:"检查器"},"preview-toolbar":{"open-in-new-tab":"在新标签页中打开","toggle-orientation":"切换方向","toggle-lock":"切换锁定",refresh:"刷新",close:"关闭"}},shortcuts:shortcuts$1,project:project$1,member:member$1,setting:setting$1,snapshot:snapshot$1,export:{"copied-to-clipboard":"已复制到剪贴板",auto:"自动","playing-options":{title:"游玩选项","loading-ui":"加载界面","orbit-control":"轨道控制",enable:"启用",disabled:"禁用"},"main-scene":"主场景",default:"默认","current-scene":"当前场景","all-scene":"所有场景",fixed:"固定","required-external-components":"必需的外部组件",rendering:"渲染","webgl-mode":"WebGL模式",alpha:"使用 Alpha 通道","preserve-drawing-buffer":"保留绘图缓冲区",dpr:{label:"设备像素比模式",fixed:"固定",auto:"自动"},publish:"发 布",update:"更 新","publish-success":{title:"发布成功",description:"恭喜!您已经成功发布了您的第一个项目。现在您可以与他人分享了。","got-it":"知道了"},"publish-to-web":"公共URL","public-url-generated":"公共URL已生成","download-project-json":"下载Project.json","update-public-url":"更新公共URL","generate-public-url":"生成公共URL","platform-setting":"平台设置","copy-url":"复制URL",scenes:"场景",download:"下 载",orientation:"方向",portrait:"竖屏",landscape:"横屏","network-timeout":"网络超时",request:"请求","connect-socket":"连接Socket","upload-file":"上传文件","download-file":"下载文件","web-project":"Web 项目",vanilla:"Vanilla JS",react:"React",vue:"Vue",framework:"框架","runtime-options":"运行时设置","package-to-zip":"打包成zip","export-as-react-project":"导出为React项目","export-as-vue-project":"导出为Vue项目","public-url":"公共URL","shader-and-publish":"着色器和发布","public-url-publish":"发布到互联网","wechat-mini-game":"微信小游戏","publish-to-wechat":"发布到微信","tiktok-mini-game":"抖音小游戏","publish-to-tiktok":"发布到抖音","project-url":"获取项目 URL","subpackage-setting":"子包列表","subpackage-list":"子包列表","subpackage-add":"添加子包","subpackage-index":"子包","subpackage-empty":"列表为空","subpackage-folder":"子包目录","subpackage-holder":"选择一个目录作为子包","subpackage-info":"选中目录将作为一个子包。该目录中除了脚本以外的资产均会导出到子包","subpackage-conflict":"和现有子包冲突,冲突子包为:子包 "},plugin:plugin$1,hierarchy:hierarchy$1,inspector:inspector$1,menu:menu$1,viewport:viewport$2,effects:effects$1,trail:trail$1,texture:texture$1,ui:ui$2,xr:xr$1,homepage:homepage$1,user:user$1,layout:layout$1,sandbox:sandbox$1,entity:entity$1,component:component$1,"skinned-mesh-renderer":{title:"蒙皮网格渲染器","local-bounds":{title:"局部边界框",info:"蒙皮网格渲染器的局部空间边界框",min:{label:"最小值",info:"局部边界框的最小点"},max:{label:"最大值",info:"局部边界框的最大点"}},skin:{title:"蒙皮","root-bone":{label:"根骨骼",info:"蒙皮网格渲染器的根骨骼"},bones:{label:"骨骼",info:"骨骼数量"}}},"mesh-renderer":{material:{title:"材质",info:"网格渲染器使用的材质",thumbnail:"材质缩略图"},mesh:{title:"网格",info:"要渲染的网格"},"receive-shadows":{title:"接收阴影",info:"网格是否接收阴影"},"cast-shadows":{title:"投射阴影",info:"网格是否投射阴影"},priority:{title:"优先级",info:"渲染优先级"}},script:script$1,scene:scene$1,"post-process":{global:{title:"全局",info:"后处理是否全局,局部模式必须与碰撞器组件一起使用。"},"blend-distance":{title:"混合距离",info:"开始混合的外距离。"},priority:{title:"优先级",info:"当后处理有相等的影响力时,确定使用哪个后处理。"},layer:{title:"图层",info:"后处理所属的图层,可以与摄像机的后处理遮罩一起使用"},effects:{options:{half:"半",quarter:"四分之一",neutral:"中性",aces:"ACES(电影色彩编码系统)"},bloom:{title:"泛光","high-quality-filtering":{label:"高质量过滤",info:"启用高质量过滤"},scatter:{label:"散射",info:"设置泛光效果的半径"},"down-scale":{label:"下采样",info:"控制此效果开始处理的起始分辨率"},threshold:{label:"阈值",info:"过滤掉此亮度级别以下的像素。值在伽马空间中"},intensity:{label:"强度",info:"泛光效果的强度"},tint:{label:"色调",info:"泛光效果的色调"},"dirt-texture":{label:"污渍纹理",info:"添加污渍或灰尘到泛光效果的纹理"},"dirt-intensity":{label:"污渍强度",info:"污渍纹理的强度"}},"tone-mapping":{title:"色调映射",mode:{label:"模式",info:"色调映射模式,`Neutral`模式尤其适合只想最小化颜色色调和饱和度影响的情况下进行范围重新映射;`ACES`模式使用电影剪辑的ACES参考颜色空间,它产生电影般对比效果,但性能消耗更多"}},title:"后处理效果",add:"添加效果"}},camera:camera$1,physics:physics$1,shader:shader$1,sprite:sprite$1,"text-renderer":{text:{label:"文本",info:"要显示的文本内容"},color:{label:"颜色",info:"文本的颜色"},"font-size":{label:"字体大小",info:"文本字体的大小"},font:{label:"字体",info:"用于渲染文本的字体资产"},width:{label:"宽度",info:"文本渲染器的宽度"},height:{label:"高度",info:"文本渲染器的高度"},"line-spacing":{label:"行间距",info:"文本行间的间距"},"font-style":{label:"字体样式",info:"字体的样式(粗体、斜体)"},"horizontal-alignment":{label:"水平对齐",info:"文本的水平对齐"},"vertical-alignment":{label:"垂直对齐",info:"文本的垂直对齐"},"enable-wrapping":{label:"启用换行",info:"是否启用文本换行"},"overflow-mode":{label:"溢出模式",info:"如何处理超出容器的文本",overflow:"溢出",truncate:"截断"},"mask-interaction":{label:"遮罩交互",info:"此文本渲染器与精灵遮罩如何交互",none:"无","visible-inside":"遮罩内可见","visible-outside":"遮罩外可见"},"mask-layer":{label:"遮罩图层",info:"此文本渲染器所属的遮罩图层",everything:"所有",nothing:"无",layer0:"图层0",layer1:"图层1",layer2:"图层2",layer3:"图层3",layer4:"图层4",layer5:"图层5",layer6:"图层6",layer7:"图层7",layer8:"图层8"},priority:{label:"优先级",info:"文本渲染器的渲染优先级"}},lottie:lottie$1,spine:spine$1,animation:animation$1,asset:asset$2,transform:transform$3,light:light$1,prefab:prefab$1,"ai-panel":{"remaining-times":"剩余次数","image-to-3d":"图片生成3D","upload-description":"上传图片生成3D模型","ai-generated":"所有模型均由AI生成",retry:"重试",view:"预览",generate:"生成",upload:{error:"仅支持 PNG、JPG、JPEG 格式的文件","drag-drop":"拖拽或点击上传图片","supported-formats":"支持的格式:PNG、JPG、JPEG"},pagination:{previous:"上一页",next:"下一页","page-info":"第 {{current}} 页,共 {{total}} 页"},history:"历史记录","generate-error":"生成模型失败, 请稍后重试",use:"使用","add-success":"已成功添加到资产面板中","add-error":"添加失败,请稍后重试","fetch-error":"加载模型列表失败,请稍后重试",waiting:"排队中,剩余 {{queuePosition}} 人",executing:"执行中",result:"结果",thinking:"思考中","todo-update":"任务更新","todo-step":"{{count}} 个步骤","tool-calls":"{{count}} 次工具调用","searching-editor-tools":"搜索编辑器工具","searching-skills":"搜索技能",knowledge:"知识检索","searching-knowledge":"搜索知识","loading-knowledge":"加载知识","reading-knowledge":"读取知识","listing-knowledge":"列出知识","loading-skill":"加载技能","reading-skill-file":"读取技能文件","listing-skills":"列出技能","reading-file":"读取文件","listing-files":"列出文件","searching-files":"搜索文件","finding-files":"查找文件","editing-scene":"编辑场景","searching-assets":"搜索资产","execution-failed":"执行失败","tool-not-found":'AI 尝试调用不存在的工具 "{{toolId}}"。该工具应通过 editorDispatch 调用,请重试您的请求。'},community:community$1,resourcePackage:resourcePackage$1,"local-ide-config":{title:"在本地 IDE 中打开",description:"由于浏览器安全限制,编辑器无法自动获取你本地文件夹的真实路径。请手动输入你选择的工作区根路径,后续无需重复设置。","workspace-path-label":"工作区根路径","workspace-path-placeholder":"例如 /Users/you/galacean-workspace 或 C:\\Users\\you\\galacean-workspace","ide-label":"代码编辑器",hint:"保存后,双击脚本或着色器资产将直接在本地 IDE 中打开对应文件。如配置错误或 IDE 无法打开,可在「项目设置」中随时修改。",test:"测试",save:"保存","section-title":"本地路径","workspace-path-hint":"我们会在此路径下为项目创建子文件夹","status-configured":"{{0}} · {{1}}","status-not-configured":"未配置",configure:"配置","validation-empty":"请填写路径","validation-tilde":"不要使用 ~,请填写完整绝对路径,例如 /Users/<你的用户名>/...","validation-not-absolute":"必须是绝对路径(macOS 以 / 开头,Windows 以盘符开头)","validation-illegal-chars":'路径包含非法字符 < > " | ? *,请检查是否多输入了引号或特殊字符',"validation-embedded-url":"请只填写路径,不要带 vscode:// / file:// / https:// 等协议前缀","validation-embedded-newline":"路径中含有换行或制表符,请清理后再粘贴","validation-parent-segment":"路径不能含 .. 或 .,请填写完整真实路径","validation-no-binding":"请先关联本地工作区,再设置 IDE 路径","validation-tail-mismatch":"路径末尾必须是已绑定的工作区目录「{{0}}」"}},service={error:{10001:"アカウント認証に失敗しました",10002:"無効なパラメータ",10003:"メールがすでに使用されています",10006:"メールを送信できる回数が制限を超えました。しばらくしてからもう一度お試しください。",10007:"ログイン確認コードエラー",10008:"ログイン確認コードが期限切れです",10010:"招待の有効期限が切れています",10011:"現在のユーザーはこのプロジェクトに参加できません",10012:"ユーザーはこのプロジェクトに参加しました",10013:"招待はすでに存在します",11001:"使用済みのストレージスペースが制限を超えています",11002:"作成されたプロジェクトの数が制限を超えています",11003:"権限が不十分です",mesh:{label:"メッシュ",info:"レンダーモードがメッシュのときのみ有効"}}},shortcuts={title:"キーボードショートカット",category:{global:"グローバル",viewport:"ビューポート",hierarchy:"階層",assets:"アセット",inspector:"インスペクター","animation-clip":"アニメーションクリップ","animator-controller":"アニメーターコントローラー","animation-clip-property":"アニメーションクリッププロパティ","animator-controller-state-machine":"アニメーターコントローラーステートマシン"},all:{"play-project":"プロジェクトを再生",undo:"元に戻す",redo:"やり直す","entity-focus":"エンティティフォーカス"},viewport:{zoom:"ズーム",orbit:"軌道",pan:"パン",around:"周り","fly-up":"上昇","fly-down":"下降","fly-forward":"前進","fly-backward":"後退","fly-left":"左へ飛ぶ","fly-right":"右へ飛ぶ","navigation-tool":"ナビゲーションツール","gizmo-translate":"ギズモ翻訳","gizmo-rotate":"ギズモ回転","gizmo-scale":"ギズモスケール","gizmo-rect":"ギズモ矩形","entity-focus":"エンティティフォーカス","align-with-view":"ビューと整列"},hierarchy:{"add-entity":"エンティティを追加","copy-entity":"エンティティをコピー","paste-entity":"エンティティを貼り付け","search-entity":"エンティティを検索","remove-entity":"エンティティを削除","duplicated-entity":"エンティティを複製"},"animation-clip":{"delete-event":"イベントを削除","delete-keyframe":"キーフレームを削除"},"animation-clip-property":{"delete-property":"プロパティを削除"},"animator-controller-state-machine":{"delete-cell":"セルを削除"},assets:{"delete-asset":"アセットを削除","copy-asset":"アセットをコピー","duplicate-asset":"アセットを複製","search-asset":"アセットを検索","paste-asset":"アセットを貼り付け"}},project={name:"名前",banner:"バナー",thumbnail:"サムネイル",description:"説明","new-project":"新しいプロジェクト","create-with-ai":"AIで作成","3d-project":"3Dプロジェクト","2d-project":"2Dプロジェクト",cloning:"クローン作成中",cloned:"クローン作成完了","clone-failed":"クローン作成に失敗しました。","delete-project-title":"プロジェクトを削除","delete-project-desc":"このプロジェクトを削除してもよろしいですか",deleting:"削除中",deleted:"削除完了","delete-failed":"削除に失敗しました。",open:"開く",clone:"クローン",delete:"削除","project-settings":"プロジェクト設定",syncing:{status:"同期状態"},created:"作成日時:","engine-version":"エンジンバージョン","create-time":"作成時間",operation:"操作",projects:"プロジェクト",search:"検索","all-projects":"すべてのプロジェクト","load-more":"さらに読み込む",create:{contextmenu:{label:"新しいものを作成"}},saving:"プロジェクト保存中"},member={Developer:"開発者",Visiter:"訪問者",Administator:"管理者",Creator:"作成者",assignedMembers:"割り当てられたメンバー","share-project-title":"プロジェクトを共有",pendingInvitations:"保留中の招待","update-success":"更新成功","delete-success":"削除成功",yourself:"自分自身","share-link":"共有リンク",admin:{title:"管理者",desc:"編集、共有、プレビューが可能"},"generate-share-link":"共有リンクを生成","copy-share-link":"共有リンクをコピー","link-access":"リンクアクセス",developer:{title:"開発者",desc:"編集可能ですが、他の人と共有することはできません"},visiter:{title:"訪問者",desc:"プレビューのみ可能"},remove:"削除",creator:{title:"作成者"},search:{"via-username":"ユーザー名で検索","via-email":"メールで検索",invite:"招待","placeholder-mail":"メールでユーザーを検索...","placeholder-user":"名前でユーザーを検索...","invalid-email":"メールアドレスが無効です"},"already-added":"メンバーは既に追加されています"},setting={title:"設定",upgrade:{engine:{loading:"エンジンをアップグレード中...",success:"エンジンのアップグレードが完了しました",error:"エンジンのアップグレードに失敗しました"}},rendering:"レンダリング","update-engine-tip":"エンジンを更新するとページがリフレッシュされます。","physics-backend":"物理バックエンド",auto:"自動","xr-backend":"XRバックエンド","select-target-verions":"ターゲットバージョンを選択","model-import-options":"モデルインポートオプション","anim-framerate":"アニメーションフレームレート","compute-normals":"法線を計算","blendshape-normals":"ブレンドシェイプ法線","blendshape-tangents":"ブレンドシェイプ切線",basic:{title:"基本"},snapshots:{title:"スナップショット"},"plugin-manager":{title:"プラグインマネージャー"},"edit-member":"メンバーを編集",none:"なし",save:{title:"保存",success:"設定が正常に保存されました",error:"設定の保存に失敗しました"},preference:"環境設定"},snapshot={delete:{title:"削除",desc:"スナップショットを削除してもよろしいですか?",loading:"スナップショットを削除中...","delete.success":"削除成功!","delete.error":"スナップショットを削除に失敗しました。"},"sure-to-revert":"このバージョンに戻してもよろしいですか?",operation:"操作",add:{title:"スナップショットを追加",loading:"スナップショットを追加中...",success:"保存成功!",error:"スナップショットを追加に失敗しました。"},manage:"スナップショットを管理",revert:{title:"戻す",loading:"スナップショットを戻している...",success:"戻し完了!",error:"スナップショットを戻しに失敗しました。"}},plugin={select:{title:"プラグインフォルダを選択",desc:"ドラッグまたはクリックしてフォルダを選択"},detect:{title:"検出",desc:"プラグイン情報を自動的に検出します"},install:{title:"インストール",desc:"検出プロセスが成功したら、ボタンをクリックしてプラグインを読み込んでください",success:"プラグインが正常にインストールされました",button:"プラグインをインストール"},"non-detected":"未検出",directory:"プラグインディレクトリを選択",name:"プラグイン名","minum-version":"最低Galaceanバージョン",background:"背景","custom-ui":"カスタムUI","custom-component":"カスタムコンポーネント",clear:"クリア",recheck:"再チェック","latest-version":"最新バージョン","running-plugin":"実行中のプラグイン","add-plugin":"プラグインを追加","manage-plugins":"プラグインを管理","install-developing-plugin":"開発中のプラグインをインストール",title:"プラグイン",topics:"トピック",topic:{animation:"アニメーション",camera:"カメラ","asset-management":"アセット管理",material:"材料"},required:{warning:"プロジェクトにはこのプラグインが必要です。"},"developing-plugins":"開発中のプラグイン"},hierarchy={"copy-success":"パスがクリップボードに正常にコピーされました。","apply-to-prefab":"プレハブに適用",revert:"戻す","added-entity":"エンティティを追加","removed-entity":"エンティティを削除","create-prefab":"プレハブを作成","unpack-prefab":"プレハブを解包","copy-relative-path":"相対パスをコピー","copy-entity":"コピー","paste-entity":"貼り付け","duplicated-entity":"複製されたエンティティ","delete-entity":"削除","align-with-view":"ビューと整列",error:{"move-gltf":"glTFのエンティティを移動できません","move-sub-entity-of-prefab":"プレハブのサブエンティティを移動できません"},"search-node":"ノードを検索"},inspector={name:"名前","select-parameter":"パラメータを選択","add-statemachine-script":"ステートマシンスクリプトを追加",conditions:"条件","add-condition":"条件を追加","statemachine-script":"ステートマシンスクリプト",script:"スクリプト","material-remap-tip":"材料はglTF資産内に埋め込まれており、材料を編集するにはコピーと再マッピングが必要です。","duplicate-and-remap":"複製と再マッピング","batch-editing-alert":"バッチ編集はサポートされていません","batch-editing":"バッチ編集","apply-to-prefab":"プレハブに適用",revert:"戻す","modified-component":"変更されたコンポーネント","added-component":"追加されたコンポーネント","removed-component":"削除されたコンポーネント","remove-component":"削除",asset:"アセット","locate-asset":"アセットを特定","alert-disable-component":"コンポーネントを無効にできません","alert-remove-component":"コンポーネントを削除できません","add-component":"コンポーネントを追加","basic-information":"基本情報","modified-entity":"変更されたエンティティ"},menu={audio:"オーディオ",scripts:"スクリプト",undo:"元に戻す",redo:"やり直し","remove-entity":"エンティティを削除",entity:"エンティティ",camera:"カメラ",light:"ライト","3d-object":"3Dオブジェクト",cuboid:"直方体",sphere:"球体",plane:"平面",cylinder:"円柱",capsule:"カプセル",cone:"円錐","2d-object":"2Dオブジェクト","sprite-renderer":"スプライトレンダラー","sprite-mask":"スプライトマスク","text-renderer":"テキストレンダラー","lottie-animation":"Lottieアニメーション","spine-animation-renderer":"Spineアニメーションレンダラー",ui:{title:"UI",canvas:"キャンバス",image:"画像",text:"テキスト",button:"ボタン"},effects:"エフェクト",particle:"粒子",trail:"トレイル",xr:"XR","ar-origin":"AR原点","vr-origin":"VR原点","post-process":"ポストプロセス","global-post-process":"グローバルポストプロセス","box-post-process":"ボックスポストプロセス","sphere-post-process":"スフィアポストプロセス","new-project":"新しいプロジェクト","new-3d-project":"新しい3Dプロジェクト","new-2d-project":"新しい2Dプロジェクト",clone:"クローン","project-settings":"プロジェクト設定",learn:"学ぶ","report-bug":"バグを報告","latest-version":"最新","back-to-files":"ホームページに戻る",assets:"アセット",component:"コンポーネント",theme:{title:"テーマ",dark:"ダーク",light:"ライト"},text:{basic:"基本"},"direct-light":"指向性ライト","point-light":"ポイントライト","spot-light":"スポットライト"},viewport$1={setting:"カメラ設定",fov:"視野角",navigation:"ナビゲーション設定",smooth:"スムーズ",ease:"イーズ",acceleration:"加速",speed:"速度","dynamic-clipping":"動的クリッピング","near-clip-plane":"近クリップ面","far-clip-plane":"遠クリップ面",capture:"キャプチャ",focus:"フォーカス","gizmo-move":"移動","view-tool":"ビュー道具","gizmo-rotate":"回転","gizmo-scale":"スケール","gizmo-rect":"矩形","pivot-anchor":"ピボットアンカー","center-anchor":"中心アンカー","local-coordinate":"ローカル座標","global-coordinate":"グローバル座標","3d-icons":"3Dアイコン","switch-to-2d-mode":"2Dモードに切り替える","switch-to-3d-mode":"3Dモードに切り替える",play:"再生","switch-to-perspective":"透視に切り替える","switch-to-orthographic":"正射に切り替える",grid:"グリッド","auxiliary-element-settings":"補助要素設定","scene-camera-settings":"シーンカメラ設定","navigation-gizmo":"ナビゲーションギズモ",outline:"アウトライン",camera:"カメラ",light:"ライト","static-collider":"静的コライダー","dynamic-collider":"動的コライダー","character-controller":"キャラクターコントローラー","emission-shape":"発射形状","ui-canvas":"UIキャンバス","scan-qr-code":"QRコードをスキャン","scan-qr-code-in-mobile":"モバイルで開くためにQRコードをスキャン","refresh-qr-code":"QRコードを生成","qr-code-ttl":"QRコードは1時間利用可能","watch-mode":"ウォッチモード","force-reload":"強制リロード","open-in-new-tab":"新しいタブで開く","apply-aigc-model":"アセットとして適用",exit:"終了",update:{idle:"",success:"最後の更新成功",error:"最後の更新失敗",syncing:"保存中..."},"locate-camera":"このカメラをビューポートで特定","full-screen":"フルスクリーン"},effects={shape:{type:{label:"タイプ",info:"粒子放出の形状タイプ"},options:{box:"ボックス",circle:"サークル",cone:"コーン",hemisphere:"半球",sphere:"球"},"cone-base":"コーンベース",volume:"ボリューム",angle:"角度",radius:"半径",length:"長さ",size:"サイズ",arc:"アーク",loop:"ループ",random:"ランダム","random-direction-amount":"ランダム方向数","random-direction-amount-tip":"粒子の開始方向をランダム化します。",position:"位置",rotation:"回転",scale:"スケール","arc-mode":{label:"アークモード",info:"粒子放出のアークモード"},"arc-speed":{label:"アーク速度",info:"粒子放出のアーク速度"},"emit-type":{label:"放出タイプ",info:"粒子の放出タイプ"}},particle:{title:"粒子",restart:"粒子を再起動",pause:"粒子を一時停止",play:"粒子を再生",stop:"粒子を停止",speed:"速度",scope:{label:"範囲",selected:"選択済み",everything:"すべて"},bounding:"バウンディング"},burst:{add:"バーストを追加",item:"バースト",time:{label:"時間"},count:{label:"カウント"},cycles:{label:"サイクル",number:"数値",infinity:"無限"},interval:{label:"間隔"}},renderer:{mesh:{label:"メッシュ",info:"レンダーモードがメッシュのときのみ有効"},"velocity-scale":{label:"速度スケール",info:"粒子が速度に応じてどれだけ伸びるかを指定します"},"length-scale":{label:"長さスケール",info:"粒子が移動方向にどれだけ引き伸ばされるかを定義します。粒子の長さと幅との比率です"},duration:{label:"持続時間",info:"粒子ジェネレーターの持続時間(秒単位)"},start:{size:{label:"開始サイズ",info:"有効にすると、各軸のサイズを個別に制御できます"},rotation:{label:"開始回転",info:"有効にすると、各軸の回転を個別に制御できます"},delay:{label:"開始遅延",info:"開始遅延(秒単位)"},speed:{label:"開始速度",info:"粒子が放出されるときの初速度"},color:{label:"開始色",info:"粒子が放出されるときの初色"},lifetime:{label:"開始寿命",info:"粒子が放出されるときの初寿命"}},"gravity-modifier":{label:"重力修正",info:"Physics.gravityで定義された重力にこの粒子ジェネレーターが適用するスケール"},"scaling-mode":{label:"スケーリングモード",info:"粒子ジェネレーターが放出する粒子に変換コンポーネントをどのように適用するかを制御します",options:{world:"ワールド",local:"ローカル",shape:"シェイプ"}},"curve-mode":{options:{constant:"定数",curve:"曲線","two-constants":"二定数","two-curves":"二曲線"}},pivot:{label:"ピボット"},"render-mode":{label:"レンダーモード",options:{billboard:"ビルボード","stretch-billboard":"ストレッチビルボード","horizontal-billboard":"水平ビルボード","vertical-billboard":"垂直ビルボード",mesh:"メッシュ",none:"なし"}},"play-on-enabled":{label:"有効時に再生",info:"trueに設定すると、粒子ジェネレーターは有効時に自動的に再生を開始します"},"max-particles":{label:"最大粒子数",info:"最大粒子数"},"over-lifetime":{size:{label:"寿命中のサイズ"},rotation:{label:"寿命中の回転"},velocity:{label:"寿命中の速度"},color:{label:"寿命中の色"},frame:{label:"時間中のフレーム"}},"rate-over-time":{label:"時間中のレート",info:"粒子の放出レートを表します。デフォルト値は10です"},"space-mode":{label:"空間モード",info:"寿命中の速度の空間モード",options:{local:"ローカル",world:"ワールド"}},velocity:{x:{label:"速度X",info:"寿命中のX軸の速度"},y:{label:"速度Y",info:"寿命中のY軸の速度"},z:{label:"速度Z",info:"寿命中のZ軸の速度"}},"limit-velocity":{limit:{label:"速度制限"},dampen:{label:"ダンピング",info:"速度制限を超えた速度をどの程度減衰させるかを制御します。0は減衰なし、1は完全な減衰"},drag:{label:"ドラッグ",info:"粒子速度に適用されるドラッグの量を制御します"},"multiply-drag-by-size":{label:"サイズでドラッグを乗算",info:"粒子サイズに基づいてドラッグ量を調整します"},"multiply-drag-by-velocity":{label:"速度でドラッグを乗算",info:"粒子速度に基づいてドラッグ量を調整します"},space:{info:"寿命中の速度制限の空間モード"}},"texture-sheet":{label:"テクスチャシートアニメーション",type:{label:"テクスチャシートタイプ",info:"テクスチャシートアニメーションのタイプ",options:{"whole-sheet":"全シート","single-row":"単一行"}},"cycle-count":{label:"サイクルカウント",info:"テクスチャシートアニメーションのサイクル数"},tiling:{label:"タイル",info:"テクスチャシートのタイル"}},"flip-rotation":{label:"回転を反転",info:"一部の粒子を逆方向に回転させる"},simulation:{space:{label:"シミュレーションスペース",info:"粒子をシミュレートする空間を選択します。それはワールドスペースまたはローカルスペースにすることができます",options:{local:"ローカル",world:"ワールド",custom:"カスタム"}},speed:{label:"シミュレーション速度",info:"粒子ジェネレーターのデフォルトの再生速度を上書きする"}},"color-over-lifetime":{label:"寿命中の色",info:"粒子の色が寿命中にどのように変化するかを制御します"},sections:{rendering:"レンダリング",emission:"放射",shape:"形状","size-over-lifetime":"寿命中のサイズ","rotation-over-lifetime":"寿命中の回転","velocity-over-lifetime":"寿命中の速度","limit-velocity-over-lifetime":"寿命中の速度制限","color-over-lifetime":"寿命中の色","texture-sheet-animation":"テクスチャシートアニメーション",noise:"ノイズ"},noise:{preview:{label:"プレビュー"},strength:{label:"強度"},frequency:{label:"周波数"},"scroll-speed":{label:"スクロール速度"},"octave-count":{label:"オクターブ数"},"octave-intensity-multiplier":{label:"オクターブ強度乗数"},"octave-frequency-multiplier":{label:"オクターブ周波数乗数"}},loop:{label:"ループ",info:"粒子ジェネレーターがループするかどうか"},material:{label:"材料",info:"粒子レンダラーが使用する材料"},priority:{label:"レンダープライオリティ",info:"粒子レンダラーのレンダープライオリティ"},bursts:{label:"バースト",info:"粒子システムのバースト設定"}},curve:{constant:"定数","two-constant":"二定数",curve:"曲線","two-curve":"二曲線","3d-prefix":"3D","separate-axes":"軸分離",gradient:"グラデーション","two-gradient":"二グラデーション"}},trail={emitting:{label:"放出中",info:"トレイルが現在放出されているかどうか"},time:{label:"時間",info:"トレイルのフェードアウト時間(秒)"},"min-vertex-distance":{label:"最小頂点距離",info:"トレイル頂点間の最小距離"},"width-curve":{label:"幅カーブ",info:"トレイルの生存期間における幅倍率カーブ"},"color-gradient":{label:"カラーグラデーション",info:"トレイルの生存期間におけるカラーグラデーション"},"texture-mode":{label:"テクスチャモード",info:"テクスチャがトレイルに適用される方法",stretch:"ストレッチ",tile:"タイル"},"texture-scale":{label:"テクスチャスケール",info:"トレイルテクスチャの UV スケール"},material:{label:"マテリアル",info:"トレイルレンダラーが使用するマテリアル"},priority:{label:"レンダープライオリティ",info:"トレイルレンダラーのレンダープライオリティ"}},texture={"select-texture":"テクスチャを選択...",shape:{title:"シェイプ"},"filter-mode":{title:"テクスチャフィルターモード",point:"フィルターモードポイント",bilinear:"フィルターモードバイリニア",trilinear:"フィルターモードトリリニア"},"wrap-mode":{u:{title:"U軸ラップモード"},v:{title:"V軸ラップモード"},clamp:"ラップモードクランプ",repeat:"ラップモードリピート",mirror:"ラップモードミラー"},"aniso-level":{title:"テクスチャ異方性レベル"},width:{title:"テクスチャ幅"},height:{title:"テクスチャ高さ"},sRGB:{title:"sRGB"},mipmap:{title:"ミップマップ"},bundle:{"format-options":"形式",overwrite:"上書き","texture-compression":"圧縮",type:{ktx2:"KTX2",webp:"WebP",original:"オリジナル"}},dilate:{title:"色膨張",info:"透明または半透明のエッジピクセルを膨張させて黒い境界を避ける"}},ui$1={canvas:{warning:{label:"ヒント",info:"詳細","not-root-canvas":"このキャンバスはルートキャンバスではありません","not-root-canvas-reason-disabled":"(コンポーネントが無効です)","not-root-canvas-reason-not-closest":"(ルートノードに最も近いキャンバスではありません)"},"render-mode":{label:"レンダーモード",info:"UIキャンバスのレンダリングモード","screen-space-overlay":"スクリーンスペース - オーバーレイ","screen-space-camera":"スクリーンスペース - カメラ","world-space":"ワールドスペース"},resolution:{label:"参照解像度",info:"`ScreenSpaceCamera`と`ScreenSpaceOverlay`モードのUIキャンバスの参照解像度"},"resolution-per-unit":{label:"単位ごとの解像度",info:"このキャンバスのUI要素の参照解像度と単位の変換比。"},"render-camera":{label:"レンダーカメラ",info:"`ScreenSpaceCamera`モードでUIキャンバスをレンダリングするために使用されるカメラ。"},adaptation:"適応","adaptation-mode":{label:"適応モード",info:"`ScreenSpaceCamera`と`ScreenSpaceOverlay`モードのUIキャンバスの画面解像度適応モード。",width:"幅",height:"高さ",both:"両方",expand:"拡張",shrink:"縮小"},"sort-order":{label:"並べ替え順序",info:"`ScreenSpaceOverlay`モードでのUIキャンバスのレンダリング順序の優先度"},distance:{label:"平面距離",info:"`ScreenSpaceCamera`モードでUIキャンバスとカメラとの距離。"}},image:{material:{info:"画像のマテリアル",label:"マテリアル"},raycast:{title:"レイキャスト",enabled:{label:"レイキャストを有効にする",info:"この画像がレイキャストで選択されるかどうか"},padding:{label:"レイキャストパディング",info:"レイキャスト検出のためのカスタム境界",left:"左",down:"下",right:"右",up:"上"}}},button:{interactive:{label:"インタラクティブ",info:"ボタンがインタラクティブであるかどうか"},transitions:{label:"トランジション",info:"ボタンの状態が変わるとトリガーされるトランジションのリスト"}},transition:{target:{label:"ターゲット",info:"トランジションを適用するターゲットコンポーネント"},type:{label:"タイプ",info:"トランジションのタイプを選択",sprite:"スプライト",scale:"スケール",color:"色"},duration:{label:"持続時間",info:"トランジションの持続時間(秒単位)"},color:{normal:{label:"通常の色"},hover:{label:"ホバー色"},pressed:{label:"押された色"},disabled:{label:"無効色"}},scale:{normal:{label:"通常のスケール"},hover:{label:"ホバースケール"},pressed:{label:"押されたスケール"},disabled:{label:"無効スケール"}}},group:{alpha:{label:"アルファ",info:"グループのアルファ値"},interactive:{label:"インタラクティブ",info:"グループがインタラクティブであるかどうか"},"ignore-parent":{label:"親グループを無視",info:"グループが親グループの設定を無視するかどうか"}},transform:{size:{label:"サイズ",info:"UI要素のサイズ(ピクセル単位)"},pivot:{label:"ピボット",info:"UI要素の中心点(0,0は左下、1,1は右上)"},error:{"cant-disable":"Transformコンポーネントを無効にできません","cant-delete":"Transformコンポーネントを削除できません"},relativeLayout:"相対レイアウト",horizontalAlignment:{label:"水平配置"},alignLeft:{label:"左間隔"},alignRight:{label:"右間隔"},alignCenter:{label:"中央間隔"},verticalAlignment:{label:"垂直配置"},alignTop:{label:"上部間隔"},alignBottom:{label:"下部間隔"},alignMiddle:{label:"中間間隔"}}},xr={origin:{title:"XR原点",mode:{label:"セッションモード",info:"XRセッションのモード",none:"なし",ar:"AR",vr:"VR"},origin:{label:"原点",info:"仮想世界と現実世界の接続点(XRスペース)"},camera:{label:"カメラ",info:"XRスペース内のカメラ"},"left-camera":{label:"左カメラ",info:"XRスペース内の左目"},"right-camera":{label:"右カメラ",info:"XRスペース内の右目"}},anchor:{title:"XRアンカーマネージャー",list:{label:"アンカーリスト",info:"追跡するアンカー"},position:"アンカーの位置",rotation:"アンカーのクォータニオン",item:"アンカー {{index}}"},image:{title:"XRイメージマネージャー",list:{label:"イメージリスト",info:"追跡するイメージ"},select:"イメージを選択...",add:"イメージを追加",width:{label:"物理的な幅",info:"追跡されている実世界の画像の予想される物理的な幅(メートル単位)"}},plane:{title:"XR平面マネージャー","detection-mode":{label:"検出モード",info:"平面の検出モード"}},prefab:"オブジェクトが追跡されたとき、自動的にプレハブが取り付けられます。",toast:{"only-one-effect":"XR原点は1つのみ効果を発揮します"}},homepage={projects:"プロジェクト",templates:"エグザンプル",documentation:"ドキュメント",discussion:"ディスカッション","templates-all":"すべて",time:{"just-now":"ただ今","hours-ago":"時間前","days-ago":"日前","months-ago":"ヶ月前"},template:{disclaimer:"免責事項",open:"編集器で開く"},plan:{text:{plan:{beta:"ベータプラン"},"created-project":"作成されたプロジェクト","used-space":"使用済みスペース",unlimit:"無制限"}}},user={avatar:{title:"アバター",error:{"file-size":"アバターは正方形の画像で、幅と高さが少なくとも100px以上必要です。最大サイズは2MBです。"},tip:"アバターは正方形の画像で、幅と高さが少なくとも100px以上必要です。最大サイズは2MBです。",change:"変更"},"account-settings":"アカウント設定","update-avatar-success":"アバターの更新に成功","save-name-success":"名前の保存に成功","save-failed":"保存に失敗",logout:"ログアウト","account-detail":"アカウントの詳細","display-name":"表示名",security:"セキュリティ","access-token":"アクセストークン","access-token-tip":"アクセストークンはプロジェクトリソースへのアクセスに使用されます。安全に保管し、他の人と共有しないでください。","access-token-description":"アクセストークンエイリアス",revoke:"取り消し","copy-token-tip":"アクセストークンを適切に保存したことを確認してください。再度表示することはできません!",generate:"生成",email:"メール","connected-account":"接続されたアカウント",wechat:"Wechat",connected:"接続済み",connect:"接続",alipay:"Alipay","auth-code-error":"認証コードエラー","rebind-email":{title:"メールを再バインド",confirm:"確認","tip-0":"メールをリセットするには、まず自分自身を認証する必要があります。","tip-1":"新しいメールアドレスを入力してください。","tip-2":"新しいメールアドレスに確認コードを添えたメールを送信しました。"},"send-auth-code":"認証コードを送信","email-successfully-modified":"メールが正常に変更されました","email-modified-tip":"このダイアログを安全に閉じることができます。","send-code-error":"コード送信エラー",permission:{tip:{first:"申し訳ありませんが、このプロジェクトにアクセスできません",second:"オーナーに連絡してメンバーとして追加してもらってください"},dev:{title:"パーミッションリクエスト",desc:"開いているプロジェクトにはサードパーティのプラグイン開発が含まれています。プロジェクトを開く前にプラグインへのアクセスを許可してください。",button:"パーミッションを許可",tip:"この動作を防ぐために、ブラウザで少なくとも1つのGalaceanページタブを開いたままにしてください。"}},login:{error:"ログインに失敗しました。メールでgalacean_support@alipay.service.comに問い合わせてください",success:"ログイン成功",redirecting:"リダイレクト中..."},lock:{warning:{title:"現在このプロジェクトを編集できません",description:"このプロジェクトは現在{{name}}によって編集されています。同時に複数のユーザーが同じプロジェクトを編集することはサポートされていません。後で再試行してください。",ok:"リスクを理解しました。続行",confirm:"リスクを理解しました、続行"}},signin:{text:{welcome:"Galaceanへようこそ",purewelcome:"ようこそ、 ",verion:"イントラネットバージョン",sendemail:"メールにコードを送信しました",subwelcome:"以下にメールを入力して、一時パスコードを受け取ります。",security:"企業イントラネット環境が検出されました。情報セキュリティに注意してください。",verfify:"メールに送信した6桁のコードを入力してください。",policy:{policy1:"続行することで、",policy2:"サービス利用規約",policy3:"および",policy4:"プライバシーポリシー"},powered:"Galaceanエンジンによって提供"},btn:{signup:"サインアップ",login:"ログイン",logout:"ログアウト",continue:"続行",oauth:{ali:"Alipay社員チャンネル",other:"続行",resend:"コードを再送"}},input:{invitecode:"招待コード",email:"@example.com"},cannot:{signin:{value:"サインインに問題がありますか?",description:"galacean_support@service.alipay.comに連絡してください"}},"email-input":"メールを入力してください","email-valid":"有効なメールを入力してください","resend-code-after":"後でコードを再送します","policy-agree":"続行をクリックすることで、当社の",artist:"アーティスト"}},layout={"layout-name":"レイアウト名...",cancel:"キャンセル",add:"追加",panels:"パネル",sidebar:"サイドバー","move-to-left":"左に移動","move-to-right":"右に移動",panel:{name:{hierarchy:"階層",ai:"AI",assets:"アセット",inspector:"インスペクター",animationclip:"アニメーションクリップ",animatorcontroller:"アニメーターコントローラー"}},preset:{name:{default:"デフォルト","left-to-right":"左から右"}},reset:{title:"レイアウトをリセット",description:`レイアウトをリセットしてもよろしいですか?
|
|
708
708
|
この操作は現在のすべてのレイアウト設定をクリアします。`,confirm:"リセット"},action:{"add.name":"レイアウトを追加","delete.name":"レイアウトを削除","save.name":"レイアウトを保存"},"collapse-all":"すべて折りたたむ","inspector-back":"戻る","close-all-tab":"すべてのタブを閉じる",title:"レイアウト"},sandbox={mask:{loading:"読み込み中...",deps:{resolving:"解決中...",resolved:"解決済み。"}}},entity={"select-entity":"エンティティを選択...",name:"名前","is-active":"アクティブ",clear:"クリア","search-node":"ノードを検索...",layer:{title:"レイヤー",info:"カメラのカリングマスクまたはライトのカリングマスクを使用すると、特定のレイヤー内のエンティティのみをレンダリングまたは照明できます",everything:"すべて",nothing:"なし",layer0:"レイヤー0",layer1:"レイヤー1",layer2:"レイヤー2",layer3:"レイヤー3",layer4:"レイヤー4",layer5:"レイヤー5",layer6:"レイヤー6",layer7:"レイヤー7",layer8:"レイヤー8",layer9:"レイヤー9",layer10:"レイヤー10",layer11:"レイヤー11",layer12:"レイヤー12",layer13:"レイヤー13",layer14:"レイヤー14",layer15:"レイヤー15",layer16:"レイヤー16",layer17:"レイヤー17",layer18:"レイヤー18",layer19:"レイヤー19",layer20:"レイヤー20",layer21:"レイヤー21",layer22:"レイヤー22",layer23:"レイヤー23",layer24:"レイヤー24",layer25:"レイヤー25",layer26:"レイヤー26",layer27:"レイヤー27",layer28:"レイヤー28",layer29:"レイヤー29",layer30:"レイヤー30",layer31:"レイヤー31","select-all":"すべて選択","update-children":{title:"子エンティティのレイヤーを更新",description:"すべての子エンティティのレイヤーを更新しますか?",confirm:"更新",cancel:"キャンセル"},selected:"レイヤーが選択されています",none:"なし"}},component={transform:{title:"トランスフォーム"},prefab:{"cannot-modify":"プレハブを変更できません","mutually-exclusive":"相互排他的なコンポーネントは変更できません!"},delete:{title:"コンポーネントを削除","remove-dependent":"{{0}}を削除する前に{{1}}を削除する必要があります","remove-together":"{{0}}を一緒に削除"},add:{dependent:"{{0}}を追加する前に{{1}}を追加する必要があります",unique:"{{0}}は1つしか追加できません"},"ui-transform":{title:"UIトランスフォーム"},"ui-canvas":{title:"UIキャンバス"},"static-collider":{title:"静的コライダー"},"dynamic-collider":{title:"動的コライダー"},renderer:{mesh:{title:"メッシュレンダラー"},"skinned-mesh":{title:"スキンメッシュレンダラー"},sprite:{title:"スプライトレンダラー"}},"post-process":{title:"ポストプロセス"},animator:{title:"アニメーター"},"sprite-mask":{title:"スプライトマスク"},camera:{title:"カメラ"},light:{direct:{title:"指向性ライト"},point:{title:"ポイントライト"},spot:{title:"スポットライト"}},"lottie-animation":{title:"Lottieアニメーション"},"spine-animation":{title:"Spineアニメーション"},"ui-group":{title:"UIグループ"},"ui-button":{title:"ボタン"},"ui-text":{title:"テキスト"},"ui-image":{title:"画像"},audio:{title:"オーディオ"},script:{title:"スクリプト","parse-properties":"プロパティを解析","script-label":"スクリプト","properties-label":"プロパティ"},"text-renderer":{title:"テキストレンダラー"},physics:{character:{title:"キャラクターコントローラー"},"spring-joint":{title:"スプリングジョイント"},"fixed-joint":{title:"固定ジョイント"},"hinge-joint":{title:"ヒンジジョイント"}},group:{ui:"UI","2d":"2D","3d":"3D",basic:"基本",light:"ライト",effects:"エフェクト",xr:"XR",physics:"物理"},"particle-renderer":{title:"粒子レンダラー"},"trail-renderer":{title:"トレイルレンダラー"}},script={source:{code:"ソースコード"}},scene={"ambient-light":{title:"環境光",diffuse:{title:"拡散",mode:"モード",source:"ソース","source-info":"拡散反射がソリッドカラーかベイクされた球面調和数から来るかを指定します","source-background":"背景","source-solid-color":"ソリッドカラー","solid-color":"ソリッドカラー","solid-color-info":"拡散ソリッドカラー",intensity:"強度","intensity-info":"拡散強度"},specular:{title:"スペキュラー",mode:"モード",source:"ソース","source-background":"背景","source-custom":"カスタム","custom-texture":"カスタムテクスチャ","custom-texture-info":"スペキュラー反射用のカスタムHDRテクスチャ",intensity:"強度","intensity-info":"スペキュラー強度"},bake:{title:"ベイク",auto:{title:"自動ベイク",info:"背景が変更されたとき、またはベイク解像度が変更されたときに自動ベイクします"},resolution:{title:"解像度",info:"ベイクされたキューブテクスチャの解像度を制御します。この解像度はベイク製品のサイズに影響を与えます。シーンに明確な反射が必要ない場合は、より小さい解像度を選んでください",r16:"16",r32:"32",r64:"64",r128:"128",r256:"256",r512:"512",r1024:"1024"},button:{title:"ベイクボタン",info:"現在のシーン構成に基づいてベイクを開始します。ベイクされた製品には球面調和数と事前フィルタリングされた環境マップが含まれています"}}},ambientOcclusion:{title:"アンビエントオクルージョン",enable:"有効化","enable-info":"アンビエントオクルージョンを有効にするかどうかを制御します",quality:{title:"品質",info:"アンビエントオクルージョン効果の品質を制御します",low:"低",medium:"中",high:"高"},intensity:"強度","intensity-info":"アンビエントオクルージョン効果の強さを制御します",power:"コントラスト","power-info":"アンビエントオクルージョンのコントラストを制御します。値が大きいほど効果が灰色っぽくなります",radius:"半径","radius-info":"アンビエントオクルージョンの半径を制御します。値が大きいほど遮蔽範囲が広くなります",bias:"バイアス","bias-info":"自己遮蔽のアーティファクトを防ぐためのバイアスを制御します",bilateralThreshold:"バイラテラルしきい値","bilateralThreshold-info":"ぼかしエッジのしきい値を制御します。値が小さいとエッジがはっきりし、値が大きいとエッジが柔らかくなります",minHorizonAngle:"最小地平角","minHorizonAngle-info":"ポリゴン数の少ないジオメトリから発生するアーティファクトを減らすために最小地平角を制御します"},background:{title:"背景",mode:{title:"モード",info:"背景モードがソリッドカラー、テクスチャ、または空であるかを指定します",solidcolor:"ソリッドカラー",texture:"テクスチャ",sky:"空"},color:{title:"色",info:"背景のソリッドカラー"},texture:{title:"テクスチャ",info:"背景のテクスチャ"},"texture-fill-mode":{title:"フィルモード",info:"背景テクスチャのフィルモード",aspectfitheight:"アスペクトフィット高さ",aspectfitwidth:"アスペクトフィット幅",fill:"フィル"}},sky:{title:"空",material:{title:"素材",info:"背景用の空の素材"},mesh:{title:"メッシュ",info:"背景用の空のメッシュ"}},shadow:{title:"影","cast-shadows":{title:"影を投げる",info:"影を投げるかどうか"},"enable-transparent":{title:"透明な影を有効にする",info:"透明な影を投げるかどうか"},resolution:{title:"解像度",info:"シャドウマップの解像度",low:"低",medium:"中",high:"高",veryhigh:"非常に高い"},cascades:{title:"カスケード",info:"指向性ライトのシャドウ用に使用するカスケードの数",nocascades:"カスケードなし",twocascades:"二つのカスケード",fourcascades:"四つのカスケード"},"two-cascade-splits":{title:"二つのカスケードスプリット",info:"二つのカスケード分布のスプリット"},"four-cascade-splits":{title:"四つのカスケードスプリット",info:"四つのカスケード分布のスプリット"},distance:{title:"距離",info:"最大シャドウ距離"},"fade-border":{title:"フェードボーダー",info:"境界からの最後のシャドウフェード距離をパーセンテージで指定します。範囲は[0,1]です"}},fog:{title:"霧",enable:{title:"有効",info:"霧を有効にする"},mode:{title:"モード",info:"霧のモード",none:"なし",linear:"線形",exponential:"指数関数",exponentialsquared:"指数二乗"},color:{title:"色",info:"霧の色"},start:{title:"開始",info:"霧の開始"},end:{title:"終了",info:"霧の終了"},density:{title:"密度",info:"霧の密度"}}},camera={"is-orthographic":"オルソグラフィック","near-clip-plane":"近クリップ面","far-clip-plane":"遠クリップ面","field-of-view":"視野角","orthographic-size":"オルソグラフィックサイズ","enable-frustum-culling":"フラスタムカリングを有効にする","clear-flags":{title:"クリアフラグ",none:"クリアしない",color:"カラーをクリア",depth:"深度をクリア",stencil:"ステンシルをクリア",all:"すべてクリア",colordepth:"カラー&深度をクリア",colorstencil:"カラー&ステンシルをクリア",depthstencil:"深度&ステンシルをクリア"},"culling-mask":"カリングマスク","post-process-mask":"ポストプロセスマスク","depth-texture-mode":{title:"深度テクスチャモード",info:"`DepthTextureMode.PrePass`が使用されている場合、シェーダーで`camera_DepthTexture`を使用して深度テクスチャにアクセスできます",none:"なし",prepass:"プレパス"},"opaque-texture-enabled":{title:"不透明テクスチャ",info:"有効にすると、シェーダーで`camera_OpaqueTexture`を使用して不透明テクスチャにアクセスできます"},"opaque-texture-down-sampling":{title:"不透明テクスチャのダウンサンプリング",info:"不透明テクスチャのダウンサンプリング",none:"なし",twox:"2倍",fourx:"4倍",eightx:"8倍"},"msaa-samples":{title:"MSAAサンプル",info:"マルチサンプリングアンチギザギザ(MSAA)のサンプル数は、幾何学的なエッジのギザギザを低減します",none:"なし",twox:"2倍",fourx:"4倍",eightx:"8倍"},"enable-hdr":{title:"HDR",info:"HDRレンダリングを有効にし、シェーダー出力色を浮動小数点数で保存できるようにします。これにより、ポストプロセッシングや他の状況でより広い範囲の値を得ることができます"},"enable-post-process":{title:"ポストプロセス",info:"ポストプロセスを有効にします。具体的な構成はシーンパネルにあります"},"anti-aliasing":{title:"アンチエイリアシング",info:"カメラが最終画像にレンダリングするピクセルのギザギザを低減するスクリーン空間のアンチエイジング手法です",none:"なし",fxaa:"FXAA"},"is-alpha-output-required":{title:"アルファ出力が必要です",info:"出力でアルファチャンネルを保持するかどうかを決定します。trueに設定すると、アルファチャンネルは常に保持されます。falseに設定すると、エンジンが自動的に保持するかどうかを決定します。"},"render-target":{title:"レンダーターゲット"},viewport:{title:"ビューポート"},priority:{title:"優先度",info:"シーンに複数のカメラが存在する場合、どのカメラが使用されるかを決定します"}},physics={shape:{add:"形状を追加",type:{title:"タイプ",info:"コライダー形状のタイプを選択"},box:{title:"ボックス",size:{title:"サイズ",info:"ボックス形状のサイズ。"}},sphere:{title:"球体",radius:{title:"半径",info:"球体形状の半径。"}},capsule:{title:"カプセル",radius:{title:"半径",info:"カプセル形状の半径。"},height:{title:"高さ",info:"カプセル形状の高さ。"},"up-axis":{title:"上向き軸",info:"カプセル形状の上向き軸。"}},plane:{title:"平面"},"item-name":"コライダー形状 {{index}}"},collider:{title:"コライダー形状",info:"このコライダーの形状。",trigger:{title:"トリガー",info:"Trueの場合、TriggerShape。Falseの場合、SimulationShape。"},material:{title:"素材",info:"このコライダー形状の物理素材を選択。"},"local-position":{title:"ローカル位置",info:"このコライダー形状のローカル位置。"},rotation:{title:"ローカル回転",info:"このコライダー形状のローカル回転。"}},"dynamic-collider":{kinematic:{title:"キネマティック",info:"動的コライダーに物理が影響を与えるかどうかを制御。"},"collision-detection-mode":{title:"衝突検出モード",discrete:"ディスクリート",continuous:"連続","continuous-dynamic":"連続動的","continuous-speculative":"連続推測"},constraints:{title:"制約",info:"特定の剛体動的ロックフラグ。"},shapes:{title:"コライダー形状",info:"このコライダーの形状。"},mass:{title:"質量",info:"動的コライダーの質量。"},gravity:{title:"重力を使用",info:"有効にすると、動的コライダーは重力の影響を受けます。"},"linear-damping":{title:"線形減衰",info:"動的コライダーの線形減衰。"},"angular-damping":{title:"角度減衰",info:"動的コライダーの角度減衰。"},"automatic-center-of-mass":{title:"重心を自動的に計算",info:"有効にすると、重心は自動的に計算されます。"},"center-of-mass":{title:"重心",info:"変換の原点に対する重心。"},"automatic-inertia-tensor":{title:"慣性テンソルを自動的に計算",info:"有効にすると、慣性テンソルは自動的に計算されます。"},"inertia-tensor":{title:"慣性テンソル",info:"重心に対する質量の慣性テンソル。"},"linear-velocity":{title:"線形速度",info:"動的コライダーの線形速度ベクトル(秒あたりのワールド単位で測定)。"},"angular-velocity":{title:"角速度",info:"動的コライダーの角速度ベクトル(ラジアン毎秒)。"},"max-angular-velocity":{title:"最大角速度",info:"ラジアン毎秒で測定されたコライダーの最大角速度。"},"max-depenetration-velocity":{title:"最大脱浸透速度",info:"浸透状態から移動するときのコライダーの最大速度。"},"sleep-threshold":{title:"スリープしきい値",info:"質量正規化されたエネルギーしきい値。これを下回るとオブジェクトはスリープを開始します。"},"solver-iterations":{title:"ソルバー反復",info:"solverIterationsはコライダージョイントと衝突接触がどれだけ正確に解決されるかを決定します。"}},character:{title:"キャラクターコントローラー",info:"キャラクターコントローラー","step-offset":{title:"ステップオフセット",info:"ステップオフセット"},"up-direction":{title:"上方向",info:"上方向"},"slop-limit":{title:"スロープリミット",info:"スロープリミット"},"non-walkable-mode":{title:"歩行不能モード",info:"歩行不能な表面上でのキャラクターコントローラーの動作を制御します","prevent-climbing":"登れないようにする","prevent-climbing-and-force-sliding":"登れないようにして滑りを強制する"}},joint:{"connected-collider":{title:"接続されたコライダー",info:"接続されたコライダーが属するエンティティを選択します。"},anchor:{title:"アンカー"},"automatic-connected-anchor":{title:"接続アンカーを自動設定"},"connected-anchor":{title:"接続されたアンカー"},"break-force":{title:"破壊力"},"break-torque":{title:"破壊トルク"},"mass-scale":{title:"質量スケール"},"connected-mass-scale":{title:"接続された質量スケール"}},"hinge-joint":{axis:{title:"軸"},"use-limits":{title:"制限を使用"},"use-spring":{title:"スプリングを使用"},limits:{title:"制限"},"use-motor":{title:"モーターを使用"},motor:{title:"モーター"}},"spring-joint":{"connected-collider":{title:"接続されたコライダー",info:"接続されたコライダーが属するエンティティを選択します。"},anchor:{title:"アンカー"},"automatic-connected-anchor":{title:"接続アンカーを自動設定"},"connected-anchor":{title:"接続されたアンカー"},spring:{title:"スプリング"},damper:{title:"ダンパー"},"min-distance":{title:"最小距離"},"max-distance":{title:"最大距離"},tolerance:{title:"許容値"}},"joint-limits":{min:"最小",max:"最大",stiffness:"剛性",damping:"減衰","contact-distance":"接触距離"},"joint-motor":{"target-velocity":"目標速度","force-limit":"力の制限","gear-ratio":"ギア比","free-spin":"フリースピン"},"collider-constraints":{"freeze-position":{title:"位置を固定",info:"位置の動きを固定"},"freeze-rotation":{title:"回転を固定",info:"回転の動きを固定"}},"collider-picker":{placeholder:"コライダーが属するものを選択..."}},shader={compile:{error:"コンパイルエラー"},source:{code:"ソースコード"},material:{ior:"IOR","base-color":"基本色","base-texture":"基本テクスチャ",metallic:"金属感",roughness:"粗さ","roughness-metallic-texture":"粗さ金属感テクスチャ","pbr-specular-color":"色","pbr-specular-intensity":"強さ","pbr-specular-intensity-texture":"強度テクスチャ","pbr-specular-color-texture":"色の質感",glossiness:"光沢","specular-glossiness-texture":"スペキュラー光沢テクスチャ","anisotropy-info":"異方性情報",anisotropy:"異方性","anisotropy-rotation":"異方性回転","anisotropy-texture":"異方性テクスチャ","normal-texture":"法線テクスチャ","normal-intensity":"法線強度","emissive-color":"放射色","emissive-texture":"放射テクスチャ","specular-color":"スペキュラー色","specular-texture":"スペキュラーテクスチャ",shininess:"光沢度","occlusion-texture":"遮蔽テクスチャ","occlusion-intensity":"遮蔽強度","occlusion-texture-coord":"遮蔽テクスチャ座標",clearcoat:"クリアコート","clear-coat-texture":"クリアコートテクスチャ","clear-coat-roughness":"クリアコート粗さ","clear-coat-roughness-texture":"クリアコート粗さテクスチャ","clear-coat-normal-texture":"クリアコート法線テクスチャ",iridescence:"虹色","iridescence-ior":"虹色IOR","iridescence-range":"虹色範囲","iridescence-thickness-texture":"虹色厚さテクスチャ","iridescence-texture":"虹色テクスチャ","sheen-color":"光沢色","sheen-intensity":"光沢強度","sheen-roughness":"光沢粗さ","sheen-texture":"光沢テクスチャ","sheen-roughness-texture":"光沢粗さテクスチャ",transmission:"透過","transmission-texture":"透過テクスチャ","transmission-thickness":"透過厚さ","transmission-thickness-texture":"透過厚さテクスチャ","refraction-mode":"屈折モード","attenuation-color":"減衰色","attenuation-distance":"減衰距離","lightmap-texture":"ライトマップテクスチャ","lightmap-intensity":"ライトマップ強度","tint-color":"色合い",exposure:"露出",rotation:"回転","texture-cube":"Texture Cube","sun-mode":"太陽モード","sun-size":"太陽サイズ","sun-size-convergence":"太陽サイズ収束","atmosphere-thickness":"大気の厚さ","sky-tint":"空の色合い","ground-tint":"地面の色合い","is-transparent":"透明かどうか","alpha-cutoff":"アルファカットオフ","render-face":"レンダー面","blend-mode":"ブレンドモード","tiling-offset":"タイルオフセット","blend-mode-options":{normal:"通常ブレンドモード",additive:"加算ブレンドモード"},uv:{uv0:"UV0",uv1:"UV1"},group:{base:"基本","metal-roughness":"金属粗さ","specular-glossiness":"スペキュラー光沢",anisotropy:"異方性",normal:"法線",emissive:"放射","blinn-phong":"ブリン・フォン",occlusion:"遮蔽","clear-coat":"クリアコート",common:"共通",iridescence:"虹色",sheen:"光沢",transmission:"透過"}},chunk:{title:"シェーダーチャンク","include-path":"インクルードパス"},inspector:{"compile-error":"コンパイルエラー",properties:"プロパティ","included-ui-script":"含まれるUIScript",macro:"マクロ"}},sprite={texture:{info:"スプライトに使用されるテクスチャ",label:"テクスチャ"},width:{info:"3Dワールド内のスプライトの幅",label:"幅"},height:{info:"3Dワールド内のスプライトの高さ",label:"高さ"},region:{info:"スプライトの矩形領域を正規化された値で指定",label:"領域"},"quick-pivot":{info:"スプライトの中心点の位置を矩形領域内で指定(正規化)",label:"クイックピボット",center:"中心","top-left":"左上",top:"上","top-right":"右上",left:"左",right:"右","bottom-left":"左下",bottom:"下","bottom-right":"右下",custom:"カスタム"},pivot:{info:"スプライトのピボット点",label:"ピボット"},border:{info:"スプライトのボーダー(スライスモードとタイルモードの描画効果に影響)",label:"ボーダー",editor:{title:"ボーダーエディター",guides:"9スライスガイド",preview:"ストレッチプレビュー","source-size":"元サイズ","preview-size":"プレビューサイズ",left:"左",bottom:"下",right:"右",top:"上",cancel:"キャンセル",apply:"適用"}},belong:{info:"スプライトが属するスプライトアトラス",label:"所属"},mask:{sprite:{info:"マスキングに使用されるスプライト",label:"マスクスプライト"},"alpha-cutoff":{info:"マスキングのためのアルファしきい値",label:"アルファカットオフ"},"influence-layers":{info:"このマスクの影響を受けるレイヤー",label:"影響レイヤー",everything:"すべて",nothing:"なし",layer1:"レイヤー1",layer2:"レイヤー2",layer3:"レイヤー3",layer4:"レイヤー4",layer5:"レイヤー5",layer6:"レイヤー6",layer7:"レイヤー7",layer8:"レイヤー8"}},atlas:{"max-width":{info:"アトラステクスチャの最大幅",label:"最大幅"},"max-height":{info:"アトラステクスチャの最大高さ",label:"最大高さ"},padding:{info:"アトラス内のスプライト間のパディング",label:"パディング"},rotation:{info:"より良いパッキングのためにスプライトの回転を許可する",label:"回転を許可"},"tight-packing":{info:"メッシュの輪郭を使用して全体のテクスチャ矩形の代わりにフィットさせる。",label:"タイトパッキング"},mipmap:{label:"ミップマップを生成"},"filter-mode":{label:"フィルターモード",point:"ポイント",bilinear:"バイリニア",trilinear:"トリリニア"},"wrap-mode-u":{label:"U軸のラップモード"},"wrap-mode-v":{label:"V軸のラップモード"},"wrap-mode":{clamp:"クランプ",repeat:"リピート",mirror:"ミラー"},"aniso-level":{label:"異方性レベル"},"sprite-list":{label:"スプライトリスト"},"pack-error":{title:"アトラスパッケージエラー","no-sprite":"最初にスプライトを追加してください"},"add-object":{label:"リストに追加"},"pack-preview":{label:"パックしてプレビュー"},packing:"パッキング中",export:"エクスポート",list:"パッキング用オブジェクト","belong-to":"アトラスに追加","add-sprite":"スプライトの追加","select-sprite-atlas":"スプライトシートを選択..."},renderer:{material:{info:"スプライトレンダラーのマテリアル",label:"マテリアル"},sprite:{info:"レンダリングするスプライト",label:"スプライト"},width:{info:"スプライトレンダラーの幅",label:"幅"},height:{info:"スプライトレンダラーの高さ",label:"高さ"},flip:{label:"フリップ",info:"X軸またはY軸でスプライトを反転",x:"X",y:"Y"},"draw-mode":{label:"描画モード",info:"スプライトレンダラーの描画モード",simple:"シンプル",sliced:"スライス",tiled:"タイル"},color:{label:"色",info:"スプライトに適用される色の色調"},"mask-interaction":{label:"マスクとの相互作用",info:"このスプライトレンダラーがスプライトマスクとどのように相互作用するか",none:"なし","visible-inside":"マスク内で可視","visible-outside":"マスク外で可視"},"mask-layer":{label:"マスクレイヤー",info:"このスプライトレンダラーが属するマスクレイヤー",everything:"すべて",nothing:"なし",layer1:"レイヤー1",layer2:"レイヤー2",layer3:"レイヤー3",layer4:"レイヤー4",layer5:"レイヤー5",layer6:"レイヤー6",layer7:"レイヤー7",layer8:"レイヤー8"},priority:{label:"優先度",info:"スプライトレンダラーのレンダリング優先度"}},inspector:{title:"スプライト","texture-thumbnail":"テクスチャサムネイル",thumbnail:"スプライトサムネイル"}},lottie={resource:{label:"リソース",info:"Lottieアニメーションリソースファイル"},"auto-play":{label:"自動再生",info:"Lottieアニメーションが自動再生するかどうかを設定"},"is-looping":{label:"ループ",info:"Lottieアニメーションがループするかどうかを設定"},speed:{label:"速度",info:"Lottieアニメーションの再生速度を設定"},priority:{label:"優先度",info:"Lottieアニメーションのレンダリング優先度"},clip:{name:"クリップ名",start:"開始フレーム",end:"終了フレーム"},asset:{width:"幅",height:"高さ",duration:"持続時間","in-point":"インポイント","out-point":"アウトポイント",mipmap:"ミップマップ","color-dilate":"色膨張","filter-mode":{title:"テクスチャフィルターモード",point:"ポイント",bilinear:"バイリニア",trilinear:"トリリニア"},"wrap-mode":{u:"U軸ラップモード",v:"V軸ラップモード",clamp:"クランプ",repeat:"リピート",mirror:"ミラー"},"atlas-export":"アトラスエクスポート"},clips:{title:"クリップ",add:"クリップを追加",item:"クリップ {{index}}"}},spine={resource:{label:"リソース",info:"Spineスケルトンデータリソース"},loop:{label:"ループ",info:"初期アニメーションループ"},animation:{label:"初期アニメーション",info:"再生する初期アニメーション"},skin:{label:"スキン",info:"レンダリングに使用するスキン"},priority:{label:"レンダリング優先度",info:"レンダリングの優先度"},"premultiplied-alpha":{label:"プリマルチプライドアルファ",info:"プリマルチプライドアルファモードでレンダリングするかどうか"},"tint-black":{label:"濃色着色",info:"濃色の着色機能を有効化するか"},error:{"generate-skeleton-data":"Spineスケルトンデータの生成に失敗しました","no-atlas-file":".atlasファイルが見つかりません。Spineアセットに少なくとも1つの.atlasファイルをアップロードしてください。","missing-images":"アトラスに対応する画像ファイルが見つかりません。関連するすべての画像ファイルがアップロードされていることを確認してください","missing-attachments":"アップロードされたアトラスファイルに必要なすべてのアタッチメントが含まれていません","incompatible-version":'認識できないアタッチメントタイプ:"{{0}}"。スケルトンが互換性のないSpineバージョンからエクスポートされた可能性があります。'}},animation={layer:{name:"名前",weight:"重さ",blending:"ブレンディング",override:"オーバーライド",additive:"加算"},"remove-property":"プロパティを削除","recording-mode-tip":"録画モードを有効/無効にする","play-tip":"アニメーションクリップを再生/一時停止","replay-tip":"アニメーションクリップを再生","add-event":"イベントを追加","add-property":"プロパティを追加","remove-event":"イベントを削除","remove-keyframe":"キーフレームを削除","left-tangent":"左タンジェント",linear:"線形",constant:"定数",free:"自由","right-tangent":"右タンジェント","both-tangent":"両方のタンジェント","select-target-entity":"アニメーション化するターゲットエンティティを階層パネルから選択","no-parameters":"パラメータなし",layers:"レイヤー",parameters:"パラメータ","add-animator-state":"アニメーターステートを追加","select-controller":"編集するアニメーターコントローラーアセットをアセットパネルから選択",clip:{event:"イベント","param-type":{title:"パラメータタイプ",string:"文字列",number:"数値",null:"ヌル"},"function-name":"関数名",number:"数値",string:"文字列",asset:"アセット","tip-0":"{{0}}をアニメーション化するために、アニメーターに{{1}}を追加","tip-1":"{{0}}をアニメーション化するために、アニメーターコントローラーを作成","tip-2":"{{0}}をアニメーション化するために、","tip-3":"、アニメーターを作成して{{0}}を追加","tip-4":"アニメーターを作成","an-clip":"アニメーションクリップ",create:"作成","create-animator-controller":"アニメーターコントローラーを作成","add-target":"ターゲットを追加","current-frame":"現在のフレーム",error:{"sub-property-existed":"サブプロパティはすでに存在します","property-existed":"プロパティはすでに存在します","property-not-supported":"プロパティはサポートされていません","keyframe-parse-failed":"キーフレーム解析エラー、Galacean 開発者にお問い合わせください"},"select-entity-preview":"プレビューするエンティティを選択"},"animator-controller":{controller:{title:"コントローラー",info:"アニメーションステートマシンを制御するために使用されるアニメーターコントローラーリソース"},"culling-mode":{title:"カリングモード",info:"アニメーターコンポーネントのカリングモード",none:"なし",complete:"完了"},speed:{title:"速度",info:"アニメーションの再生速度"},delete:"削除",state:{name:"名前",clip:"アニメーションクリップ","wrap-mode":{title:"ラップモード",once:"一度",loop:"ループ"},speed:"速度","start-time":"開始時間","end-time":"終了時間",new:"新しい状態",validation:{"must-be-unique":"ステート名は一意である必要があります"}},transition:{solo:"ソロ",mute:"ミュート","has-exit-time":"終了時間あり","fixed-duration":"固定持続時間",duration:"持続時間","exit-time":"終了時間",offset:"オフセット"},editor:{open:"アニメーターコントローラーエディターを開く"}}},asset$1={markdown:{title:"Markdown",toolbar:{bold:"太字",italic:"斜体",strikethrough:"取り消し線","inline-code":"インラインコード",heading1:"見出し1",heading2:"見出し2",heading3:"見出し3","bullet-list":"箇条書き","ordered-list":"番号付きリスト","task-list":"タスクリスト",blockquote:"引用","code-block":"コードブロック","horizontal-rule":"水平線",table:"表を挿入"}},texture:{title:"テクスチャ","texture-compression":"圧縮"},menu:{Folder:"フォルダー",Material:"材料",AnimatorController:"アニメーターコントローラー",AnimationClip:"アニメーションクリップ",sprite:"スプライト",SpriteAtlas:"スプライトアトラス",Scene:"シーン",PrimitiveMesh:"プリミティブメッシュ",PhysicsMaterial:"物理素材",scripting:"スクリプティング","entity-script":"エンティティスクリプト","state-machine-script":"ステートマシンスクリプト",shader:"シェーダー","shader-chunk":"シェーダーチャンク","shader-ui-script":"シェーダーUIScript"},"copied-to-clipboard":"クリップボードにコピーされました",create:"作成",search:"アセットを検索...",explorer:{name:"名前",type:"タイプ",size:"サイズ","ascending-in-alphabet":"アルファベット順に昇順","descending-in-alphabet":"アルファベット順に降順","ascending-with-file-type":"ファイルタイプで昇順","descending-with-file-type":"ファイルタイプで降順"},upload:"アップロード","add-to-atlas":"アトラスに追加",duplicate:"重複",copy:"コピー",paste:"貼り付け","copy-file-url":"ファイルURLをコピー","copy-relative-path":"相対パスをコピー","copy-relative-path-success":"相対パスがクリップボードにコピーされました","copy-development-id":"開発IDをコピー","copy-development-id-success":"開発IDがクリップボードにコピーされました",download:"ダウンロード...",delete:"削除",root:"ルート","cant-download-sub-asset":"サブアセットをダウンロードできません。","export-success":"エクスポート成功","open-in-code-editor":"オンラインコードエディターで開く","moved-assets-to":"アセットを{{0}}フォルダーに移動しました","export-asset":"アセットをエクスポート","these-assets":"これらのアセット","this-asset":"このアセット","delete-asset":"アセットを削除",cancel:"キャンセル","sure-to-delete":"本当に{{0}}を削除してもよろしいですか?","upload-success":"アップロード成功",uploading:"アップロード中","overwrite-tip":"同じ名前のファイルを上書きしますか?","paste-error":"まずアセットを選択してください!","paste-assets-error":"アセットの貼り付けエラー","copy-none":"まずアセットを選択してください!","duplicate-folder-error":"フォルダーを複製することはできません!","delete-scene-error":"現在のシーンを削除できません","delete-internal-asset-error":"内部アセットを削除できません","upload-failed":"アップロード失敗","file-size-limit":"ファイルサイズ制限",title:"アセット","upload-to-cdn":"CDNにアップロード",original:"オリジナル",exporting:"エクスポート中...","local-workspace-sync":{"create-workspace":"ローカルワークスペースをリンク",sync:"ローカルワークスペースを同期","select-directory":"ローカルワークスペースをリンク",linked:"ローカルワークスペースをリンク済み",restoring:"ローカルワークスペースのリンクを復元中...","local-workspace":"ローカルワークスペース",connected:"{{0}} にリンクしました","permission-required":"アクセス権が必要です","permission-denied":"同期する前にローカルワークスペースへのアクセス権が必要です。",planning:"アセットを準備中",applying:"ファイルを書き込み中",progress:"{{0}}({{1}}/{{2}})","current-path":"現在: {{0}}",syncing:"ローカルワークスペースを同期中...",success:"アセットを {{0}} に同期しました",failed:"ローカルワークスペースの同期に失敗しました。",error:"同期エラー","conflict-title":"ファイルの競合を検出しました","conflict-description":"{{0}} 件のファイルがエディターとローカルワークスペース間で異なります。解決方法を選択してください:","conflict-confirm":"同期して上書き","conflict-use-editor":"エディター版を使用","conflict-use-local":"ローカル版を使用","conflict-more":"…ほか {{0}} 件","guide-title":"ローカルワークスペースをリンク","guide-description":"プロジェクトアセットをローカルフォルダに同期し、お好みの IDE やツールで編集できます。変更は自動検出され、双方向に同期されます。","guide-feature-1":"VS Code、WebStorm、または任意の IDE でスクリプトやシェーダーを編集","guide-feature-2":"ローカルファイルの変更を自動検出してエディターに同期","guide-feature-3":"上書き前にファイルの競合を自動検出して解決","guide-requirement":"Chrome 86+ または Edge 86+ が必要です。ブラウザは選択したフォルダへの読み書き権限を要求します。","guide-select-folder":"フォルダを選択","unsupported-title":"ブラウザがサポートされていません","unsupported-description":`ローカルワークスペース同期には File System Access API が必要です。この機能は Chrome 86+ または Edge 86+ でのみ利用可能です。
|
|
709
709
|
|
|
710
|
-
サポートされているブラウザに切り替えてください。`,"unsupported-confirm":"OK","open-in-ide":"IDEで開く",unbind:"ワークスペースのリンクを解除","unbind-confirm-title":"ローカルワークスペースのリンクを解除","unbind-confirm-description":"ローカルワークスペースのリンクを解除し、同期キャッシュをクリアします。既にローカルフォルダに同期されたファイルは削除されません。","unbind-current-path":"リンク先: {{0}}"},"sprite-atlas":{title:"スプライトアトラス",adding:"追加中",success:"成功",error:"スプライトの追加に失敗しました"},"tree-shaking":{tip:"ツリーシェイキングは、プロジェクトファイルのサイズを削減するための効果的な機能です。パッケージング中にプロジェクトから不要なアセットをインテリジェントに削除することができます。",default:{title:"デフォルト",desc:"ツリーシェイキングなし。"},"current-scene":{title:"現在のシーン",desc:"現在のシーンのみツリーシェイクします。"},"all-scene":{title:"すべてのシーン",desc:"すべてのシーンをツリーシェイクします。"},title:"ツリーシェイキング"},"primitive-mesh":{title:"プリミティブメッシュ",type:{label:"タイプ",info:"作成するプリミティブメッシュのタイプ"},sphere:{radius:{label:"半径",info:"球体の半径"},step:{label:"ステップ",info:"球体を構築するために使用されるセグメントの数"}},capsule:{radius:{label:"半径",info:"カプセルの半径"},height:{label:"高さ",info:"カプセルの高さ"},"radial-segments":{label:"ラジアルセグメント",info:"カプセルの円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"カプセルの高さに沿ったセグメント数"}},cone:{radius:{label:"半径",info:"円錐の底面の半径"},height:{label:"高さ",info:"円錐の高さ"},"radial-segments":{label:"ラジアルセグメント",info:"円錐の円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"円錐の高さに沿ったセグメント数"}},cuboid:{width:{label:"幅",info:"直方体の幅"},height:{label:"高さ",info:"直方体の高さ"},depth:{label:"深さ",info:"直方体の深さ"}},cylinder:{"radius-top":{label:"上部半径",info:"円柱の上部の半径"},"radius-bottom":{label:"底部半径",info:"円柱の底部の半径"},height:{label:"高さ",info:"円柱の高さ"},"radial-segments":{label:"ラジアルセグメント",info:"円柱の円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"円柱の高さに沿ったセグメント数"}},plane:{width:{label:"幅",info:"平面の幅"},height:{label:"高さ",info:"平面の高さ"},"horizontal-segments":{label:"水平セグメント",info:"平面の幅に沿ったセグメント数"},"vertical-segments":{label:"垂直セグメント",info:"平面の高さに沿ったセグメント数"}},torus:{radius:{label:"半径",info:"トーラスの中心からチューブの中心への半径"},"tube-radius":{label:"チューブ半径",info:"トーラスのチューブの半径"},"radial-segments":{label:"ラジアルセグメント",info:"トーラスの円周を囲むセグメント数"},"tubular-segments":{label:"チューブラーセグメント",info:"チューブを囲むセグメント数"},arc:{label:"アーク",info:"トーラスセクションの中心角"}}},gltf:{title:"GlTF","basic-info":"基本情報",triangles:"三角形",drawcall:"ドローコール","compute-tangents":"タンジェントを計算","keep-mesh-data":"メッシュデータを保持","refresh-tip":"リフレッシュ後に有効",issues:"問題","remapped-materials":"再マッピングされた材料",compression:"圧縮",quantize:"量子化",meshopt:"メッシュオプティマイズ"},"select-asset":"アセットを選択...",filter:{all:"すべて"},folder:{title:"フォルダー"},shader:{title:"シェーダー"},material:{title:"材料"},script:{title:"スクリプト"},font:{title:"フォント"},"texture-cube":{title:"TextureCube"},"ambient-light":{title:"環境光"},"directional-light":{title:"指向性ライト"},"point-light":{title:"ポイントライト"},"spot-light":{title:"スポットライト"},sprite:{title:"スプライト"},"xr-reference-image":{title:"XRリファレンスイメージ"},"animator-controller":{title:"アニメーターコントローラー"},"animation-clip":{title:"アニメーションクリップ"},scene:{title:"シーン"},"physics-material":{title:"物理素材"},"render-target":{title:"レンダーターゲット"},"entity-script":{title:"エンティティスクリプト"},"state-machine-script":{title:"ステートマシンスクリプト"},"shader-chunk":{title:"シェーダーチャンク"},"shader-ui-script":{title:"シェーダーUIScript"},prefab:{title:"プレハブ"},audio:{title:"オーディオ"},mesh:{title:"メッシュ"},lottie:{title:"Lottie"},"spine-skeleton-data":{title:"Spineスケルトンデータ"},"spine-atlas":{title:"アトラス"},ktx2:{mode:{label:"モード",uastc:{label:"UASTC",desc:"UASTCはより良い品質を提供しますが、ファイルサイズが大きくなります"},etc1s:{label:"ETC1S",desc:"ETC1Sはより良い圧縮を提供しますが、品質が低くなります"}},quality:"品質"}},transform$2={position:{title:"位置",info:"3D空間内のエンティティの位置"},rotation:{title:"回転",info:"3D空間内のエンティティの回転角度"},scale:{title:"スケール",info:"3D空間内のエンティティのスケールファクター"},error:{"cant-disable":"トランスフォームコンポーネントを無効にできません","cant-delete":"トランスフォームコンポーネントを削除できません"}},light={color:"色","culling-mask":"カリングマスク",point:{distance:{label:"距離",info:"ポイントライトが照らす最大距離"}},shadow:{title:"影",type:{label:"タイプ",info:"影のタイプ",none:"なし",hard:"ハード",softlow:"ソフト低",softhigh:"ソフト高"},bias:{label:"バイアス",info:"影のアクネを防ぐための影バイアス"},"normal-bias":{label:"ノーマルバイアス",info:"影のアクネを防ぐためのノーマルバイアス"},"near-plane-offset":{label:"近クリップ面オフセット",info:"影の近クリップ面のオフセット"},strength:{label:"強度",info:"影の強度"}},spot:{distance:{label:"距離",info:"スポットライトが照らす最大距離"},angle:{label:"角度",info:"スポットライトの円錐の角度"},penumbra:{label:"ペンブラス",info:"スポットライトのペンブラス角度"}}},prefab={inspector:{"basic-info":"基本情報","dependent-assets":"依存アセット",url:"URL",missed:"失敗"},error:{"create-from-sub":"プレハブサブエンティティからプレハブを作成できません。"},delete:{title:"プレハブインスタンスを削除しますか?",description:"プレハブ '{{name}}' が削除されました。すべてのインスタンスを削除しますか?"},button:{no:"いいえ",yes:"はい"},replace:{title:"プレハブを置き換える",description:'プレハブ "{{name}}" を置き換えてもよろしいですか?すべてのプレハブインスタンスが置き換えられます',confirm:"それでも置き換える"}},community={title:"コミュニティ","all-projects":"すべてのプロジェクト","my-projects":"マイプロジェクト","all-projects-desc":"コミュニティで共有されているプロジェクトを探索","my-projects-desc":"コミュニティに公開したプロジェクト","search-placeholder":"コミュニティプロジェクトを検索...","no-projects":"コミュニティプロジェクトが見つかりません","no-my-projects":"まだプロジェクトを公開していません","publish-hint":"最初のプロジェクトを公開してコミュニティと共有しましょう","load-more":"さらに読み込む",loading:"読み込み中...","no-preview":"プレビューが利用できません",preview:"プレビュー",share:"共有",withdraw:"撤回",tags:"タグ",license:"ライセンス",stats:"統計",copyright:"著作権",views:"閲覧数",likes:"いいね",downloads:"ダウンロード","publish-success":"レビュー待ちに提出しました",publish:{title:"コミュニティに公開","published-at":"公開日","publish-button":"公開",agreement:"公開をクリックすることで、","more-options":"その他のオプション","community-guidelines":"コミュニティガイドライン"}},resourcePackage={export:"リソースパッケージとしてエクスポート",import:"リソースパッケージをインポート",exporting:"リソースパッケージをエクスポート中...",importing:"リソースパッケージをインポート中...","export-success":"リソースパッケージのエクスポートに成功しました","export-failed":"リソースパッケージのエクスポートに失敗しました","import-success":"リソースパッケージのインポートに成功しました","import-failed":"リソースパッケージのインポートに失敗しました","no-assets-selected":"エクスポートするアセットを選択してください","cant-export-sub-asset":"サブアセットはエクスポートできません",assets:"個のアセット"},ja$1={service,"code-editor":{"back-to-editor":"シーンエディターに戻る",preview:"プレビュー",devtools:{console:"コンソール",inspector:"インスペクター"},file:{"not-saved":"ファイルは保存されていません。","not-saved-description":"変更を破棄してもよろしいですか?保存されていない変更はすべて失われます。",cancel:"キャンセル",confirm:"確認",project:"プロジェクト"},"event-debug":{input:"入力",json:"JSON",clear:"クリア",confirm:"確認",events:"イベント",trigger:"トリガー","no-events":"プレビューからイベント信号を検出できません。"},"file-tree":{title:"アセット",search:{placeholder:"ファイルを検索..."}},library:{title:"依存関係",import:"インポート",search:{placeholder:"ライブラリ名"},version:{latest:"最新",updating:"更新中..."}},menubar:{file:{title:"ファイル","new-file":"新しいファイル","open-file":"ファイルを開く",save:"保存",close:"閉じる"},edit:{title:"編集",undo:"元に戻す",redo:"やり直す",find:{title:"検索...",find:"検索",replace:"置換"},cut:"切り取り",copy:"コピー",paste:"貼り付け"},view:{title:"表示","show-minimap":"ミニマップを表示","new-tab":"新しいタブ","close-tab":"タブを閉じる",share:"共有",print:"印刷"},help:{title:"ヘルプ",documentation:"ドキュメント","shader-syntax":"Shader構文",about:"について"}},monaco:{loading:"読み込み中..."},"preview-inspector":{title:"インスペクター"},"preview-toolbar":{"open-in-new-tab":"新しいタブで開く","toggle-orientation":"向きを切り替える","toggle-lock":"ロックを切り替える",refresh:"更新",close:"閉じる"}},shortcuts,project,member,setting,snapshot,export:{"copied-to-clipboard":"クリップボードにコピーしました",auto:"自動","playing-options":{title:"プレイオプション","loading-ui":"ローディングUI","orbit-control":"軌道制御",enable:"有効",disabled:"無効"},"main-scene":"メインシーン",default:"デフォルト","current-scene":"現在のシーン","all-scene":"すべてのシーン",fixed:"固定","required-external-components":"必要な外部コンポーネント",rendering:"レンダリング","webgl-mode":"WebGLモード",alpha:"アルファを使用","preserve-drawing-buffer":"描画バッファを保存",dpr:{label:"デバイスピクセル比モード",fixed:"固定",auto:"自動"},update:"更新",publish:"公開","publish-success":{title:"公開成功",description:"おめでとうございます!初回プロジェクトの公開が完了しました。他の人と共有できるようになりました。","got-it":"了解"},"public-url-generated":"公開URLが生成されました","download-project-json":"Project.jsonをダウンロード","update-public-url":"公開URLを更新","generate-public-url":"公開URLを生成","platform-setting":"プラットフォーム設定","copy-url":"URLをコピー",scenes:"シーン",download:"ダウンロード",orientation:"向き",portrait:"縦向き",landscape:"横向き","network-timeout":"ネットワークタイムアウト",request:"リクエスト","connect-socket":"ソケットに接続","upload-file":"ファイルをアップロード","download-file":"ファイルをダウンロード","web-project":"Webプロジェクト",vanilla:"Vanilla JS",react:"React",vue:"Vue",framework:"フレームワーク","package-to-zip":"Zipにパッケージ","public-url-publish":"Webに公開","export-as-react-project":"Reactプロジェクトとしてエクスポート","export-as-vue-project":"Vueプロジェクトとしてエクスポート","public-url":"公開URL","shader-and-publish":"シェーダーと公開","wechat-mini-game":"Wechatミニゲーム","publish-to-wechat":"Wechatに公開","tiktok-mini-game":"TikTokミニゲーム","publish-to-tiktok":"TikTokに公開","project-url":"プロジェクトURLを取得","subpackage-setting":"サブパッケージリスト","subpackage-list":"サブパッケージリスト","subpackage-add":"サブパッケージを追加","subpackage-index":"サブパッケージ","subpackage-empty":"リストは空です","subpackage-folder":"サブパッケージディレクトリ","subpackage-holder":"サブパッケージとしてディレクトリを選択","subpackage-info":"選択したディレクトリはサブパッケージとして使用されます。このディレクトリ内のスクリプト以外のすべてのアセットはサブパッケージにエクスポートされます","subpackage-conflict":"既存のサブパッケージと競合します。競合するサブパッケージは次のとおりです: サブパッケージ "},plugin,hierarchy,inspector,menu,viewport:viewport$1,effects,trail,texture,ui:ui$1,xr,homepage,user,layout,sandbox,entity,component,"skinned-mesh-renderer":{title:"スキンメッシュレンダラー","local-bounds":{title:"ローカル境界",info:"スキンドスケルタルレンダラーのローカル空間境界ボックス",min:{label:"最小",info:"ローカル境界ボックスの最小点"},max:{label:"最大",info:"ローカル境界ボックスの最大点"}},skin:{title:"スキン","root-bone":{label:"ルートボーン",info:"スキンメッシュレンダラーのルートボーン"},bones:{label:"ボーン",info:"ボーンの数"}}},"mesh-renderer":{material:{title:"材料",info:"メッシュレンダラーが使用する材料",thumbnail:"材料サムネイル"},mesh:{title:"メッシュ",info:"レンダリングするメッシュ"},"receive-shadows":{title:"影を受け取る",info:"メッシュが影を受け取るかどうか"},"cast-shadows":{title:"影を投げる",info:"メッシュが影を投げるかどうか"},priority:{title:"優先度",info:"レンダリングの優先度"}},script,scene,"post-process":{global:{title:"グローバル",info:"ポストプロセスがグローバルであるかどうかを示します。ローカルモードはコライダーコンポーネントと一緒に使用する必要があります。"},"blend-distance":{title:"ブレンド距離",info:"ブレンドを開始する外部距離。"},priority:{title:"優先度",info:"ポストプロセスがシーンに等しい影響度を持つ場合、どのポストプロセスが使用されるかを決定します。"},layer:{title:"レイヤー",info:"ポストプロセスが属するレイヤーで、カメラのポストプロセスマスクと一緒に使用できます"},effects:{options:{half:"半分",quarter:"四分の一",neutral:"ニュートラル",aces:"ACES(アカデミーカラーエンコーディングシステム)"},bloom:{title:"ブルーム","high-quality-filtering":{label:"高品質フィルタリング",info:"高品質フィルタリングを有効にする"},scatter:{label:"スキャッター",info:"ブルームエフェクトの半径を設定します"},"down-scale":{label:"ダウンスケール",info:"このエフェクトが処理を開始する解像度を制御します"},threshold:{label:"しきい値",info:"この明るさレベル以下のピクセルをフィルタリングします。値はガンマ空間で指定されます"},intensity:{label:"強度",info:"ブルームエフェクトの強さ"},tint:{label:"色調",info:"ブルームエフェクトの色調"},"dirt-texture":{label:"汚れのテクスチャ",info:"ブルームエフェクトに汚れやほこりを追加する汚れのテクスチャ"},"dirt-intensity":{label:"汚れの強度",info:"汚れのテクスチャの強さ"}},"tone-mapping":{title:"トーンマッピング",mode:{label:"モード",info:"トーンマッピングモード、`Neutral`モードは、色相と彩度への影響を最小限に抑えながら範囲リマッピングだけを希望する状況に特に適しています。`ACES`モードは長編映画用のACES参照カラー空間を使用し、シネマティックでコントラストのある結果を生み出しますが、より多くのパフォーマンスが必要です"}},title:"ポストエフェクト",add:"エフェクトを追加"}},camera,physics,shader,sprite,"text-renderer":{text:{label:"テキスト",info:"表示するテキストコンテンツ"},color:{label:"色",info:"テキストの色"},"font-size":{label:"フォントサイズ",info:"テキストフォントのサイズ"},font:{label:"フォント",info:"テキストのレンダリングに使用するフォントアセット"},width:{label:"幅",info:"テキストレンダラーの幅"},height:{label:"高さ",info:"テキストレンダラーの高さ"},"line-spacing":{label:"行間隔",info:"テキストの行間隔"},"font-style":{label:"フォントスタイル",info:"フォントのスタイル(太字、イタリック)"},"horizontal-alignment":{label:"水平配置",info:"テキストの水平配置"},"vertical-alignment":{label:"垂直配置",info:"テキストの垂直配置"},"enable-wrapping":{label:"折り返しを有効にする",info:"テキストの折り返しを有効にするかどうか"},"overflow-mode":{label:"オーバーフローモード",info:"コンテナをオーバーフローするテキストをどのように処理するか",overflow:"オーバーフロー",truncate:"切り詰め"},"mask-interaction":{label:"マスクとの相互作用",info:"このテキストレンダラーがスプライトマスクとどのように相互作用するか",none:"なし","visible-inside":"マスク内で可視","visible-outside":"マスク外で可視"},"mask-layer":{label:"マスクレイヤー",info:"このテキストレンダラーが属するマスクレイヤー",everything:"すべて",nothing:"なし",layer0:"レイヤー0",layer1:"レイヤー1",layer2:"レイヤー2",layer3:"レイヤー3",layer4:"レイヤー4",layer5:"レイヤー5",layer6:"レイヤー6",layer7:"レイヤー7",layer8:"レイヤー8"},priority:{label:"優先度",info:"テキストレンダラーのレンダリング優先度"}},lottie,spine,animation,asset:asset$1,transform:transform$2,light,prefab,"ai-panel":{"remaining-times":"残りの回数","image-to-3d":"画像から3Dモデルを生成","upload-description":"画像をアップロードして3Dモデルを生成","ai-generated":"すべてのモデルはAIによって生成されました",retry:"再試行",view:"表示",generate:"生成",upload:{error:"PNG、JPG、JPEGファイルのみサポートされています。","drag-drop":"画像をドラッグまたはクリックしてアップロード","supported-formats":"サポートされているフォーマット:PNG、JPG、JPEG"},pagination:{previous:"前へ",next:"次へ","page-info":"ページ {{current}} / {{total}}"},history:"履歴","generate-error":"モデルの生成に失敗しました,しばらくしてから再試行してください",use:"使用","add-success":"資産パネルに正常に追加されました","add-error":"追加に失敗しました。しばらくしてから再試行してください","fetch-error":"モデルリストの読み込みに失敗しました。しばらくしてから再試行してください",waiting:"{{queuePosition}} 人待っています",executing:"実行中",result:"結果",thinking:"思考中","todo-update":"タスク更新","todo-step":"{{count}} ステップ","tool-calls":"{{count}} 件のツール呼び出し","searching-editor-tools":"エディタツールを検索中","searching-skills":"スキルを検索中",knowledge:"ナレッジ検索","searching-knowledge":"ナレッジを検索","loading-knowledge":"ナレッジを読み込み","reading-knowledge":"ナレッジを読み取り","listing-knowledge":"ナレッジ一覧","loading-skill":"スキルを読み込み中","reading-skill-file":"スキルファイルを読み取り中","listing-skills":"スキル一覧を取得中","reading-file":"ファイルを読み取り中","listing-files":"ファイル一覧を取得中","searching-files":"ファイルを検索中","finding-files":"ファイルを検索中","editing-scene":"シーンを編集中","searching-assets":"アセットを検索中","execution-failed":"実行に失敗しました","tool-not-found":'AIが存在しないツール"{{toolId}}"を呼び出そうとしました。このツールはeditorDispatch経由で呼び出す必要があります。もう一度お試しください。'},community,resourcePackage,"local-ide-config":{title:"ローカル IDE で開く",description:"ブラウザのセキュリティ制限により、エディターはローカルフォルダーのパスを自動取得できません。選択したワークスペースのルートパスを手動で入力してください。この設定は一度だけ必要です。","workspace-path-label":"ワークスペースのルートパス","workspace-path-placeholder":"例: /Users/you/galacean-workspace または C:\\Users\\you\\galacean-workspace","ide-label":"エディタ",hint:"保存後、スクリプトまたはシェーダーアセットをダブルクリックするとローカル IDE でファイルが開きます。設定が誤っている、または IDE が開かない場合は、「プロジェクト設定」からいつでも変更できます。",test:"テスト",save:"保存","section-title":"ローカルパス","workspace-path-hint":"このパスの下にプロジェクトフォルダを作成します","status-configured":"{{0}} · {{1}}","status-not-configured":"未設定",configure:"設定","validation-empty":"パスを入力してください","validation-tilde":"~ は使用しないでください。完全な絶対パスを入力してください。例: /Users/<ユーザー名>/...","validation-not-absolute":"絶対パスで入力してください(macOS は / で始まる、Windows はドライブレターで始まる)","validation-illegal-chars":'パスに不正な文字 < > " | ? * が含まれています — 引用符や特殊文字を入力していないか確認してください',"validation-embedded-url":"パスのみ入力してください。vscode:// / file:// / https:// などのプロトコルを含めないでください","validation-embedded-newline":"パスに改行やタブが含まれています — クリーンアップしてから再度貼り付けてください","validation-parent-segment":"パスに .. や . を含めないでください — 完全な実パスを入力してください","validation-no-binding":"先にローカルワークスペースをバインドしてから IDE パスを設定してください","validation-tail-mismatch":"パスの末尾はバインド済みのワークスペースディレクトリ「{{0}}」である必要があります"}},localStorageLanguage="__language__";instance.use(initReactI18next).init({resources:{en:{translation:en},zh:{translation:zh$1},ja:{translation:ja$1}},lng:typeof localStorage<"u"?localStorage.getItem(localStorageLanguage):void 0,fallbackLng:"en",interpolation:{escapeValue:!1}});const{t:t$7}=instance;let editorUiModulePromise=null;function loadEditorUiModule(){return editorUiModulePromise??(editorUiModulePromise=__vitePreload(()=>import("./index-4e7bb453.js"),["_static/index-4e7bb453.js","_static/index-8e169cc2.js","_static/Menu-a427d272.js","_static/Accordion-75b7b34e.js","_static/Callout-312ada1c.js","_static/Tooltip-3bc02b10.js"])),editorUiModulePromise}function runFireAndForgetEditorUi(rt){loadEditorUiModule().then(rt).catch(_e=>{console.error("[editorUiFeedback] failed to load editor UI module",_e)})}function showEditorUiAlert(rt){runFireAndForgetEditorUi(({showAlert:_e})=>{_e(rt)})}function showEditorUiToastSuccess(rt){runFireAndForgetEditorUi(({toast:_e})=>{_e.success(rt)})}function showEditorUiToastError(rt){runFireAndForgetEditorUi(({toast:_e})=>{_e.error(rt)})}async function runWithEditorUiToastPromise(rt,_e){const{toast:tt}=await loadEditorUiModule();return tt.promise(rt,_e)}function showComponentAlert(rt){showEditorUiAlert(rt)}function showComponentToastError(rt){showEditorUiToastError(rt)}var eventemitter3={exports:{}};(function(rt){var _e=Object.prototype.hasOwnProperty,tt="~";function et(){}Object.create&&(et.prototype=Object.create(null),new et().__proto__||(tt=!1));function nt(st,ct,dt){this.fn=st,this.context=ct,this.once=dt||!1}function it(st,ct,dt,ut,ht){if(typeof dt!="function")throw new TypeError("The listener must be a function");var ft=new nt(dt,ut||st,ht),pt=tt?tt+ct:ct;return st._events[pt]?st._events[pt].fn?st._events[pt]=[st._events[pt],ft]:st._events[pt].push(ft):(st._events[pt]=ft,st._eventsCount++),st}function at(st,ct){--st._eventsCount===0?st._events=new et:delete st._events[ct]}function ot(){this._events=new et,this._eventsCount=0}ot.prototype.eventNames=function(){var ct=[],dt,ut;if(this._eventsCount===0)return ct;for(ut in dt=this._events)_e.call(dt,ut)&&ct.push(tt?ut.slice(1):ut);return Object.getOwnPropertySymbols?ct.concat(Object.getOwnPropertySymbols(dt)):ct},ot.prototype.listeners=function(ct){var dt=tt?tt+ct:ct,ut=this._events[dt];if(!ut)return[];if(ut.fn)return[ut.fn];for(var ht=0,ft=ut.length,pt=new Array(ft);ht<ft;ht++)pt[ht]=ut[ht].fn;return pt},ot.prototype.listenerCount=function(ct){var dt=tt?tt+ct:ct,ut=this._events[dt];return ut?ut.fn?1:ut.length:0},ot.prototype.emit=function(ct,dt,ut,ht,ft,pt){var mt=tt?tt+ct:ct;if(!this._events[mt])return!1;var vt=this._events[mt],_t=arguments.length,yt,bt;if(vt.fn){switch(vt.once&&this.removeListener(ct,vt.fn,void 0,!0),_t){case 1:return vt.fn.call(vt.context),!0;case 2:return vt.fn.call(vt.context,dt),!0;case 3:return vt.fn.call(vt.context,dt,ut),!0;case 4:return vt.fn.call(vt.context,dt,ut,ht),!0;case 5:return vt.fn.call(vt.context,dt,ut,ht,ft),!0;case 6:return vt.fn.call(vt.context,dt,ut,ht,ft,pt),!0}for(bt=1,yt=new Array(_t-1);bt<_t;bt++)yt[bt-1]=arguments[bt];vt.fn.apply(vt.context,yt)}else{var Et=vt.length,St;for(bt=0;bt<Et;bt++)switch(vt[bt].once&&this.removeListener(ct,vt[bt].fn,void 0,!0),_t){case 1:vt[bt].fn.call(vt[bt].context);break;case 2:vt[bt].fn.call(vt[bt].context,dt);break;case 3:vt[bt].fn.call(vt[bt].context,dt,ut);break;case 4:vt[bt].fn.call(vt[bt].context,dt,ut,ht);break;default:if(!yt)for(St=1,yt=new Array(_t-1);St<_t;St++)yt[St-1]=arguments[St];vt[bt].fn.apply(vt[bt].context,yt)}}return!0},ot.prototype.on=function(ct,dt,ut){return it(this,ct,dt,ut,!1)},ot.prototype.once=function(ct,dt,ut){return it(this,ct,dt,ut,!0)},ot.prototype.removeListener=function(ct,dt,ut,ht){var ft=tt?tt+ct:ct;if(!this._events[ft])return this;if(!dt)return at(this,ft),this;var pt=this._events[ft];if(pt.fn)pt.fn===dt&&(!ht||pt.once)&&(!ut||pt.context===ut)&&at(this,ft);else{for(var mt=0,vt=[],_t=pt.length;mt<_t;mt++)(pt[mt].fn!==dt||ht&&!pt[mt].once||ut&&pt[mt].context!==ut)&&vt.push(pt[mt]);vt.length?this._events[ft]=vt.length===1?vt[0]:vt:at(this,ft)}return this},ot.prototype.removeAllListeners=function(ct){var dt;return ct?(dt=tt?tt+ct:ct,this._events[dt]&&at(this,dt)):(this._events=new et,this._eventsCount=0),this},ot.prototype.off=ot.prototype.removeListener,ot.prototype.addListener=ot.prototype.on,ot.prefixed=tt,ot.EventEmitter=ot,rt.exports=ot})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class MessageCenterImpl extends EventEmitter{dispatch(_e,...tt){this.emit(_e,...tt)}}const MessageCenter=new MessageCenterImpl;function hasProp$1(rt,_e){return Object.prototype.hasOwnProperty.call(rt,_e)}function addHiddenProp$1(rt,_e,tt){Object.defineProperty(rt,_e,{enumerable:!1,writable:!0,configurable:!0,value:tt})}function mergePropertyConfigs(rt,_e){for(const tt in _e)rt[tt]?rt[tt]={...rt[tt],..._e[tt]}:rt[tt]=_e[tt]}function collectDecoratorConfigs(rt,_e,tt=null){const et={},nt=[];let it=rt;for(;it&&it!==tt;)nt.push(it),it=Object.getPrototypeOf(it);for(let at=nt.length-1;at>=0;at--){const ot=nt[at][_e];ot&&mergePropertyConfigs(et,ot)}return et}const storedSerializeSymbol=Symbol("storedSerialize");function serialize(rt={}){return function(_e,tt){hasProp$1(_e,storedSerializeSymbol)||addHiddenProp$1(_e,storedSerializeSymbol,{}),rt.key=rt.key??tt,_e[storedSerializeSymbol][tt]=rt}}function getSerializeConfigs(rt){return collectDecoratorConfigs(rt,storedSerializeSymbol)}const storedPropertyProxySymbol=Symbol("storedPropertyProxy");function propertyProxy(rt={}){return function(_e,tt){addPropertyProxyConfig(_e,tt,rt)}}const addPropertyProxyConfig=(rt,_e,tt)=>{hasProp$1(rt,storedPropertyProxySymbol)||addHiddenProp$1(rt,storedPropertyProxySymbol,{}),tt.editorKey=_e,rt[storedPropertyProxySymbol][_e]=tt,tt.engineKey&&(rt[storedPropertyProxySymbol][tt.engineKey]=tt),tt.setPath&&(rt[storedPropertyProxySymbol][tt.setPath]=tt),tt.getPath&&(rt[storedPropertyProxySymbol][tt.getPath]=tt)};function getPropertyProxyConfigs(rt){return collectDecoratorConfigs(rt,storedPropertyProxySymbol)}function derivePropertySemantics(rt){var nt;const _e=getSerializeConfigs(rt),tt=getPropertyProxyConfigs(rt),et=new Map;for(const[it,at]of Object.entries(_e)){const ot=at.type??"props",st=at.key??it,ct=(nt=tt[it])==null?void 0:nt.engineKey;et.set(it,ct?{serializeType:ot,serializeKey:st,engineMethod:ct}:{serializeType:ot,serializeKey:st})}return et}function createComponentSemantics(rt){const _e=derivePropertySemantics(rt);let tt;const et=new Set;return _e.forEach((nt,it)=>{nt.engineMethod&&(tt??(tt={}),tt[it]=nt.engineMethod),nt.serializeType==="methods"&&et.add(it)}),{proxyMap:tt,methodKeys:et.size>0?et:void 0}}const registeredComponents={},registeredImportScriptProperty={},invDependentComponentsMap=new Map,customComponents={},componentSemantics=new Map;let registeredCache;function registerCustomEngineComponentDefinition(rt,_e){customComponents[rt]=_e}function getCustomEngineComponentDefinition(rt){return customComponents[rt]}function registerComponentConfig(rt,_e){if(registeredComponents[rt]=_e,registeredCache=void 0,componentSemantics.set(rt,createComponentSemantics(_e.class.prototype)),_e.dependentComponent){const tt=invDependentComponentsMap.get(_e.dependentComponent.type)||[];tt.push(rt),invDependentComponentsMap.set(_e.dependentComponent.type,tt)}}function getRegisteredComponentConfig(rt){return registeredComponents[rt]}function getComponentSemantics(rt){return componentSemantics.get(rt)}function getInvDependentComponentTypes(rt){return invDependentComponentsMap.get(rt)}function getAllRegisteredComponents(){return registeredComponents}function getRegisteredComponentList(){return registeredCache||(registeredCache=Object.values(registeredComponents)),registeredCache}function registerImportComponentPropertyConfig(rt,_e){registeredImportScriptProperty[rt]=_e}function getRegisteredImportComponentPropertyConfig(rt){return registeredImportScriptProperty[rt]}var EditorDependentMode=(rt=>(rt[rt.CheckOnly=0]="CheckOnly",rt[rt.AutoAdd=1]="AutoAdd",rt[rt.AutoDel=2]="AutoDel",rt))(EditorDependentMode||{});function hasComponentTypeInEntityModel(rt,_e){var tt;return rt.isStrippedEntity?!!((tt=rt.originalEntity)!=null&&tt.components.some(et=>et.type===_e)||rt.components.some(et=>et.type===_e)):rt.components.some(et=>et.type===_e)}function evaluateComponentAddToNormalizedEntityState(rt,_e,tt){const et=getRegisteredComponentConfig(tt);if(!et)return{allowed:!0,dependentComponents:[]};const{dependentComponent:nt,mutuallyComponent:it,unique:at}=et;if(it&&hasNormalizedEntityComponentType(rt,_e,it.type))return{allowed:!1,reason:"mutually-exclusive",componentClass:tt,relatedType:it.type};if(nt&&!hasNormalizedEntityComponentType(rt,_e,nt.type)){if(nt.dependentMode===EditorDependentMode.AutoAdd)return{allowed:!0,dependentComponents:[nt.type]};if(nt.dependentMode===EditorDependentMode.CheckOnly)return{allowed:!1,reason:"missing-dependent",componentClass:tt,relatedType:nt.type}}return at&&hasNormalizedEntityComponentType(rt,_e,tt)?{allowed:!1,reason:"unique",componentClass:tt,relatedType:tt}:{allowed:!0,dependentComponents:[]}}function evaluateComponentAddForEntityModel(rt,_e){const tt=getRegisteredComponentConfig(_e);if(!tt)return{allowed:!0,dependentComponents:[]};const{dependentComponent:et,mutuallyComponent:nt,unique:it}=tt;if(nt&&hasComponentTypeInEntityModel(rt,nt.type))return{allowed:!1,reason:"mutually-exclusive",componentClass:_e,relatedType:nt.type};if(et&&!hasComponentTypeInEntityModel(rt,et.type)){if(et.dependentMode===EditorDependentMode.AutoAdd)return{allowed:!0,dependentComponents:[et.type]};if(et.dependentMode===EditorDependentMode.CheckOnly)return{allowed:!1,reason:"missing-dependent",componentClass:_e,relatedType:et.type}}return it&&hasComponentTypeInEntityModel(rt,_e)?{allowed:!1,reason:"unique",componentClass:_e,relatedType:_e}:{allowed:!0,dependentComponents:[]}}function notifyRejectedComponentAdd(rt){if(rt.allowed)return;const _e=rt;if(_e.reason==="mutually-exclusive"){showComponentAlert({title:t$7("component.prefab.cannot-modify"),description:t$7("component.prefab.mutually-exclusive")});return}if(_e.reason==="missing-dependent"){showComponentToastError(t$7("component.add.dependent",[_e.relatedType,_e.componentClass]));return}showComponentToastError(t$7("component.add.unique",[_e.componentClass]))}function classifyPrefabEntityComponentOwnerRoute(rt,_e){const tt=rt.entities[_e];if(!(tt!=null&&tt.instance)||tt.instance.role==="added")return{kind:"ordinary"};const{bindingId:et}=tt.instance;if(!et)return{kind:"invalid-prefab",reason:`Entity "${_e}" has prefab instance link without bindingId`};const nt=getNormalizedSourceEntityId(rt,_e);return nt?{kind:"prefab-source",bindingId:et,sourceEntityId:nt}:{kind:"invalid-prefab",reason:`Entity "${_e}" has prefab instance link without resolvable sourceEntityId`}}function classifyPrefabComponentRoute(rt,_e,tt){const et=classifyPrefabEntityComponentOwnerRoute(rt,_e);if(et.kind!=="prefab-source")return et;const{bindingId:nt,sourceEntityId:it}=et,at=getNormalizedComponent(rt,_e,tt);return at!=null&&at.instance?at.instance.role==="added"?{kind:"prefab-added",bindingId:nt,sourceEntityId:it}:{kind:"prefab-source",bindingId:nt,sourceEntityId:it}:{kind:"invalid-prefab",reason:`Component "${tt}" on prefab instance entity "${_e}" has no instance link`}}class ComponentFacade{constructor(_e){Rt(this,"addCmd",new AddComponentCommand);Rt(this,"updateCmd",new UpdateComponentCommand);Rt(this,"removeCmd",new RemoveComponentCommand);Rt(this,"_logger");this.root=_e,this._logger=this.root.createLogger("ComponentFacade")}addComponent(_e,tt,et,nt){const it=typeof _e=="string"?{entityId:_e,type:tt,props:et,componentId:nt}:_e;return this.root.runInUndoGroup("component.add",()=>this._addComponentWithDependencies(it))}_addComponentWithDependencies(_e,tt=new Set){const{entityId:et,type:nt}=_e;this._logger.info("addComponent",{entityId:et,type:nt});const it=evaluateComponentAddToNormalizedEntityState(this.root.domainStore.getNormalizedState(),et,nt);if(tt.has(nt)||!it.allowed)return null;const at=new Set(tt);at.add(nt);for(const dt of it.dependentComponents)if(this._addComponentWithDependencies({entityId:et,type:dt},at)===null)return null;const ot=this.root.domainStore.getNormalizedState(),st=classifyPrefabEntityComponentOwnerRoute(ot,et);switch(st.kind){case"prefab-source":return this.root.prefabFacade.addComponentOverride(et,{type:nt,props:_e.props,componentId:_e.componentId});case"invalid-prefab":throw new Error(`ComponentFacade.addComponent: ${st.reason}`)}const{result:ct}=this.root.commandBus.execute(this.addCmd,_e,"component.add");return ct}updateComponent(_e,tt,et){const nt=classifyPrefabComponentRoute(this.root.domainStore.getNormalizedState(),_e,tt);switch(nt.kind){case"prefab-added":this.root.prefabFacade.updateAddedComponentOverride(_e,tt,et);return;case"prefab-source":this.root.prefabFacade.setComponentOverride(_e,tt,et);return;case"invalid-prefab":throw new Error(`ComponentFacade.updateComponent: ${nt.reason}`);case"ordinary":this.root.commandBus.execute(this.updateCmd,{entityId:_e,componentId:tt,props:et},"component.update");return}}setEnabled(_e,tt,et){this.updateComponent(_e,tt,{enabled:et})}removeComponent(_e,tt){this._logger.info("removeComponent",{entityId:_e,componentId:tt});const et=classifyPrefabComponentRoute(this.root.domainStore.getNormalizedState(),_e,tt);switch(et.kind){case"prefab-added":this.root.prefabFacade.revertOverride(et.bindingId,"addedComponents",{sourceEntityId:et.sourceEntityId,componentId:tt});return;case"prefab-source":this.root.prefabFacade.removeSourceComponent(_e,tt);return;case"invalid-prefab":throw new Error(`ComponentFacade.removeComponent: ${et.reason}`);case"ordinary":this.root.commandBus.execute(this.removeCmd,{entityId:_e,componentId:tt},"component.remove");return}}getComponent(_e,tt){const et=this.root.domainStore.getNormalizedState(),nt=getNormalizedComponent(et,_e,tt);if(!nt)return;const{id:it,entityId:at,...ot}=nt;return ot}getComponents(_e){const tt=this.root.domainStore.getNormalizedState(),et={};for(const nt of getNormalizedEntityComponents(tt,_e)){const{id:it,entityId:at,...ot}=nt;et[it]=ot}return et}}const SCENE_SETTING_DEFINITIONS={ambient:{ambientLight:{sceneKey:"ambientLight",valueKind:"assetRef",runtimeTarget:null},customAmbientLight:{sceneKey:"customAmbientLight",valueKind:"assetRef",runtimeTarget:null},diffuseMode:{sceneKey:"diffuseMode",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"diffuseMode",valueKind:"direct"}},diffuseSolidColor:{sceneKey:"diffuseSolidColor",sourceValueType:"color",runtimeTarget:{scope:"ambientLight",key:"diffuseSolidColor",valueKind:"structured"}},diffuseIntensity:{sceneKey:"diffuseIntensity",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"diffuseIntensity",valueKind:"direct"}},specularMode:{sceneKey:"specularMode",sourceValueType:"number",editorValueAliases:{Sky:0,Custom:1},runtimeTarget:{scope:"ambientLight",key:"specularMode",valueKind:"direct"}},customSpecularTexture:{sceneKey:"customSpecularTexture",valueKind:"assetRef",runtimeTarget:null},specularIntensity:{sceneKey:"specularIntensity",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"specularIntensity",valueKind:"direct"}},bakerResolution:{sceneKey:"bakerResolution",sourceValueType:"number",runtimeTarget:null}},background:{mode:{sceneKey:"backgroundMode",sourceValueType:"number",runtimeTarget:{scope:"background",key:"mode",valueKind:"direct"}},color:{sceneKey:"backgroundColor",sourceValueType:"color",runtimeTarget:{scope:"background",key:"solidColor",valueKind:"structured"}},texture:{sceneKey:"backgroundTexture",runtimeTarget:{scope:"background",key:"texture",valueKind:"assetRef"}},textureFillMode:{sceneKey:"textureFillMode",sourceValueType:"number",runtimeTarget:{scope:"background",key:"textureFillMode",valueKind:"direct"}},skyMaterial:{sceneKey:"skyMaterial",runtimeTarget:{scope:"background.sky",key:"material",valueKind:"assetRef"}},skyMesh:{sceneKey:"skyMesh",runtimeTarget:{scope:"background.sky",key:"mesh",valueKind:"assetRef"}}},shadow:{castShadows:{sceneKey:"castShadows",sourceValueType:"boolean",runtimeTarget:{scope:"scene",key:"castShadows",valueKind:"direct"}},enableTransparentShadow:{sceneKey:"enableTransparentShadow",sourceValueType:"boolean",runtimeTarget:{scope:"scene",key:"enableTransparentShadow",valueKind:"direct"}},shadowResolution:{sceneKey:"shadowResolution",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowResolution",valueKind:"direct"}},shadowCascades:{sceneKey:"shadowCascades",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowCascades",valueKind:"direct"}},shadowTwoCascadeSplits:{sceneKey:"shadowTwoCascadeSplits",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowTwoCascadeSplits",valueKind:"direct"}},shadowFourCascadeSplits:{sceneKey:"shadowFourCascadeSplits",sourceValueType:"vector3",runtimeTarget:{scope:"scene",key:"shadowFourCascadeSplits",valueKind:"structured"}},shadowDistance:{sceneKey:"shadowDistance",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowDistance",valueKind:"direct"}},shadowFadeBorder:{sceneKey:"shadowFadeBorder",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowFadeBorder",valueKind:"direct"}}},fog:{mode:{sceneKey:"fogMode",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogMode",valueKind:"direct"}},color:{sceneKey:"fogColor",sourceValueType:"color",runtimeTarget:{scope:"scene",key:"fogColor",valueKind:"structured"}},start:{sceneKey:"fogStart",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogStart",valueKind:"direct"}},end:{sceneKey:"fogEnd",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogEnd",valueKind:"direct"}},density:{sceneKey:"fogDensity",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogDensity",valueKind:"direct"}}},ambientOcclusion:{enabled:{sceneKey:"enabledAmbientOcclusion",sourceValueType:"boolean",runtimeTarget:{scope:"ambientOcclusion",key:"enabled",valueKind:"direct"}},quality:{sceneKey:"quality",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"quality",valueKind:"direct"}},intensity:{sceneKey:"intensity",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"intensity",valueKind:"direct"}},power:{sceneKey:"power",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"power",valueKind:"direct"}},radius:{sceneKey:"radius",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"radius",valueKind:"direct"}},bilateralThreshold:{sceneKey:"bilateralThreshold",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"bilateralThreshold",valueKind:"direct"}},bias:{sceneKey:"bias",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"bias",valueKind:"direct"}},minHorizonAngle:{sceneKey:"minHorizonAngle",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"minHorizonAngle",valueKind:"direct"}}}},TOP_LEVEL_SCENE_SETTING_DEFINITIONS={autoBake:{sceneKey:"autoBake",sourceValueType:"boolean",runtimeTarget:null}};function normalizeNumber(rt,_e){if(rt==null||typeof rt=="number"&&Number.isFinite(rt))return rt;if(typeof rt=="string"&&rt.trim()!==""){const tt=Number(rt);if(Number.isFinite(tt))return tt}throw new Error(`${_e} must be a number`)}function normalizeBoolean(rt,_e){if(rt==null||typeof rt=="boolean")return rt;if(rt==="true")return!0;if(rt==="false")return!1;throw new Error(`${_e} must be a boolean`)}function readNumericRecordValue(rt,_e,tt){return normalizeNumber(rt[_e],`${tt}.${_e}`)}function normalizeColor$1(rt,_e){if(rt==null)return rt;let tt;if(Array.isArray(rt))tt={r:rt[0],g:rt[1],b:rt[2],a:rt[3]};else if(typeof rt=="object"){const et=rt;"r"in et||"g"in et||"b"in et||"a"in et?tt={r:et.r,g:et.g,b:et.b,a:et.a}:"_r"in et||"_g"in et||"_b"in et||"_a"in et?tt={r:et._r,g:et._g,b:et._b,a:et._a}:tt={r:et.x,g:et.y,b:et.z,a:et.w},et._metaIntensity!==void 0&&(tt._metaIntensity=normalizeNumber(et._metaIntensity,`${_e}._metaIntensity`))}else throw new Error(`${_e} must be a color`);return{r:readNumericRecordValue(tt,"r",_e),g:readNumericRecordValue(tt,"g",_e),b:readNumericRecordValue(tt,"b",_e),a:readNumericRecordValue(tt,"a",_e),...tt._metaIntensity!==void 0?{_metaIntensity:tt._metaIntensity}:{}}}function normalizeVector3(rt,_e){if(rt==null)return rt;let tt;if(Array.isArray(rt))tt={x:rt[0],y:rt[1],z:rt[2]};else if(typeof rt=="object"){const et=rt;"x"in et||"y"in et||"z"in et?tt={x:et.x,y:et.y,z:et.z}:tt={x:et._x,y:et._y,z:et._z}}else throw new Error(`${_e} must be a vector3`);return[readNumericRecordValue(tt,"x",_e),readNumericRecordValue(tt,"y",_e),readNumericRecordValue(tt,"z",_e)]}function normalizeSceneSettingValue(rt,_e,tt){switch(rt.sourceValueType){case"number":return normalizeNumber(_e,tt);case"boolean":return normalizeBoolean(_e,tt);case"color":return normalizeColor$1(_e,tt);case"vector3":return normalizeVector3(_e,tt);default:return _e}}function applyEditorValueAlias(rt,_e){return typeof _e!="string"||!rt.editorValueAliases?_e:Object.prototype.hasOwnProperty.call(rt.editorValueAliases,_e)?rt.editorValueAliases[_e]:_e}function normalizeEditorSceneSettingValue(rt,_e,tt){return normalizeSceneSettingValue(rt,applyEditorValueAlias(rt,_e),tt)}function getSceneSettingDefinitionByPath(rt){var nt;if(!rt.includes("/")){const it=TOP_LEVEL_SCENE_SETTING_DEFINITIONS[rt];if(!it)throw new Error(`Unknown scene setting path: ${rt}`);return it}const[_e,tt]=rt.split("/"),et=(nt=SCENE_SETTING_DEFINITIONS[_e])==null?void 0:nt[tt];if(!et)throw new Error(`Unknown scene setting path: ${rt}`);return et}function normalizeEditorSceneSettingValueByPath(rt,_e){return normalizeEditorSceneSettingValue(getSceneSettingDefinitionByPath(rt),_e,`scene.${rt.replace("/",".")}`)}function upsertOp(rt,_e,tt){const et=_e.split("/").filter(Boolean);let nt=rt;for(const it of et){if(nt==null||typeof nt!="object"||!(it in nt))return{op:"add",path:`/${et.join("/")}`,value:tt};nt=nt[it]}return{op:"replace",path:`/${et.join("/")}`,value:tt}}class UpdateSceneSettingCommand{constructor(){Rt(this,"name","scene.updateSetting")}execute(_e,tt){const et=[],nt=_e.scene.settings,it=nt,at=normalizeSceneSettingPath(tt.path);nt||et.push({op:"add",path:"/scene/settings",value:{}});const ot=at.split("/"),st=ot[0];return ot.length>1&&!(it!=null&&it[st])&&et.push({op:"add",path:`/scene/settings/${st}`,value:{}}),et.push(upsertOp(_e,`scene/settings/${at}`,tt.value)),{operations:et,result:void 0,events:[{type:"SceneSettingUpdated",settingPath:at,value:tt.value}]}}}class BatchUpdateSceneSettingsCommand{constructor(){Rt(this,"name","scene.batchUpdateSettings")}execute(_e,tt){const et=[];let nt=_e.scene.settings,it=nt;const at=[];nt||(et.push({op:"add",path:"/scene/settings",value:{}}),nt={},it=nt);const ot=new Set;for(const st of tt.updates){const ct=normalizeSceneSettingPath(st.path),dt=ct.split("/"),ut=dt[0];dt.length>1&&!(it!=null&&it[ut])&&!ot.has(ut)&&(et.push({op:"add",path:`/scene/settings/${ut}`,value:{}}),ot.add(ut)),et.push(upsertOp(_e,`scene/settings/${ct}`,st.value)),at.push({type:"SceneSettingUpdated",settingPath:ct,value:st.value})}return{operations:et,result:void 0,events:at}}}class InitSceneSettingsCommand{constructor(){Rt(this,"name","scene.initSettings")}execute(_e,tt){const et=_e.scene.settings;return{operations:[et?{op:"replace",path:"/scene/settings",value:tt.settings,oldValue:et}:{op:"add",path:"/scene/settings",value:tt.settings}],result:void 0,events:flattenSceneSettingUpdateEvents(tt.settings)}}}class SceneFacade{constructor(_e,tt){Rt(this,"updateCmd",new UpdateSceneSettingCommand);Rt(this,"batchUpdateCmd",new BatchUpdateSceneSettingsCommand);Rt(this,"initCmd",new InitSceneSettingsCommand);this.domainStore=_e,this.commandBus=tt}updateSetting(_e,tt){const et=normalizeSceneSettingPath(_e);this.commandBus.execute(this.updateCmd,{path:et,value:normalizeEditorSceneSettingValueByPath(et,tt)})}batchUpdateSettings(_e){this.commandBus.execute(this.batchUpdateCmd,{updates:_e.map(tt=>{const et=normalizeSceneSettingPath(tt.path);return{path:et,value:normalizeEditorSceneSettingValueByPath(et,tt.value)}})})}getSetting(_e){const tt=_e.split("/");let et=this.domainStore.state.scene.settings;for(const nt of tt){if(et==null)return;et=et[nt]}return et}initSettings(_e){this.commandBus.execute(this.initCmd,{settings:_e})}initSettingsSystem(_e){const{operations:tt}=this.initCmd.execute(this.domainStore.state,{settings:_e});this.domainStore.applySystem(tt)}}class DebouncedDomainBatch{constructor(_e,tt=300,et="domain.batch"){Rt(this,"_timer",null);Rt(this,"_active",!1);this.store=_e,this.debounceMs=tt,this.commandName=et}apply(_e){_e.length&&this.run(()=>{this.store.apply(_e,this.commandName)})}run(_e){if(this._resetIfStale(),!this._active&&this.store.isBatchMode){_e();return}this._active||(this.store.beginBatch(),this._active=!0),_e(),this._clearTimer(),this._timer=setTimeout(()=>{this._commit()},this.debounceMs)}flush(){this._clearTimer(),this._resetIfStale(),this._active&&this.store.isBatchMode&&this.store.commitBatch(this.commandName),this._active=!1}dispose(){this._clearTimer(),this._resetIfStale(),this._active&&this.store.isBatchMode&&this.store.abortBatch(),this._active=!1}_commit(){this._timer=null,this._resetIfStale(),this._active&&this.store.isBatchMode&&(this.store.commitBatch(this.commandName),this._active=!1)}_resetIfStale(){this._active&&!this.store.isBatchMode&&(this._clearTimer(),this._active=!1)}_clearTimer(){this._timer!==null&&(clearTimeout(this._timer),this._timer=null)}}function resolveSceneChangePath(rt,_e){var et;const tt=((et=rt==null?void 0:rt.getDomainSettingPath)==null?void 0:et.call(rt,_e))??(_e.includes("/")?normalizeSceneSettingPath(_e):void 0);if(!tt)throw new Error(`resolveSceneChangePath: unknown scene setting property: ${_e}`);return tt}function resolveSceneChangeUpdate(rt,_e,tt){const et=resolveSceneChangePath(rt,_e),nt=tt===void 0?rt[_e]:tt;return{path:et,value:normalizeEditorSceneSettingValueByPath(et,nt)}}const TRANSFORM_PROPERTIES=new Set(["position","rotation","scale"]),TRANSFORM_COMPONENT_TYPES=new Set(["Transform","UITransform"]);function combineLayers(rt){let _e=0;for(const tt of rt)_e|=tt;return _e}const SCENE_ROOT_ID="__scene__";class InspectorFacade{constructor(_e){Rt(this,"_batch",null);Rt(this,"_batchEntityId",null);Rt(this,"_logger");this.root=_e,this._logger=this.root.createLogger("InspectorFacade")}async applyChange(_e){var et,nt;this._logger.info("applyChange",{objectType:_e.objectType,objectId:_e.objectId,property:_e.property});const tt=this.normalizeValue(_e.value);switch(_e.objectType){case"scene":{const it=resolveSceneChangePath(void 0,_e.property);this.root.sceneFacade.updateSetting(it,tt);return}case"entity":{this.applyEntityChange(_e.objectId,_e.property,tt);return}case"component":{const it=this.findComponentOwnerEntityId(_e.objectId);if(!it)throw new Error(`InspectorFacade.applyChange: component owner not found: ${_e.objectId}`);if(this.isTransformProperty(it,_e.objectId,_e.property)){if(this._batchEntityId&&this._batchEntityId!==it&&this.flushBatch(),this._batchEntityId=it,this.isPrefabSourceEntity(it)){const ot={[_e.property]:tt};this._getOrCreateBatch().run(()=>{this.root.entityFacade.setTransform(it,ot)});return}const at=this.buildTransformOps(it,_e.property,tt);this._getOrCreateBatch().apply(at),this.root.componentFacade.updateComponent(it,_e.objectId,{[_e.property]:tt});return}this.root.componentFacade.updateComponent(it,_e.objectId,{[_e.property]:tt});return}case"asset":{const it=(nt=(et=this.root.assetStore)==null?void 0:et.assets)==null?void 0:nt[_e.objectId],at={[_e.property]:tt};if(it!=null&&it.isSubAsset)await this.root.assetFacade.updateSubAssetProps(_e.objectId,at);else switch(_e.persistScope??"asset-main"){case"asset-main":await this.root.assetFacade.updateAssetProps(_e.objectId,at);break;case"asset-meta":await this.root.assetFacade.updateAssetMeta(_e.objectId,at);break;case"asset-both":await this.root.assetFacade.updateAssetProps(_e.objectId,at),await this.root.assetFacade.updateAssetMeta(_e.objectId,at);break}return}}}sceneChange(_e,tt){this.applyChange({objectType:"scene",objectId:SCENE_ROOT_ID,property:_e,value:tt,source:"inspector"})}entityChange(_e,tt,et){this.applyChange({objectType:"entity",objectId:_e,property:tt,value:et,source:"inspector"})}componentChange(_e,tt,et){this.applyChange({objectType:"component",objectId:_e,property:tt,value:et,source:"inspector"})}async assetChange(_e,tt,et,nt){await this.applyChange({objectType:"asset",objectId:_e,property:tt,value:et,source:"inspector",...nt?{persistScope:nt}:{}})}async assetChanges(_e,tt,et){for(const[nt,it]of Object.entries(tt))await this.assetChange(_e,nt,it,et)}getSceneRootId(){return SCENE_ROOT_ID}normalizeValue(_e){if(_e&&typeof _e=="object"&&"engineObjectType"in _e){const tt=_e.getCurrentRef;if(typeof tt=="function")return tt.call(_e)}return _e}applyEntityChange(_e,tt,et){if(tt==="name"&&typeof et=="string"){this.root.entityFacade.rename(_e,et);return}if(tt==="isActive"&&typeof et=="boolean"){this.root.entityFacade.setVisible(_e,et);return}if(tt==="layer"&&Array.isArray(et)){this.root.entityFacade.setLayer(_e,combineLayers(et));return}if(tt==="isLocked"&&typeof et=="boolean"){this.root.entityFacade.setLocked(_e,et);return}this.root.entityFacade.updateEntity(_e,{[tt]:et})}flushBatch(){var _e;(_e=this._batch)==null||_e.flush(),this._batchEntityId=null}disposeBatch(){var _e;(_e=this._batch)==null||_e.dispose(),this._batch=null,this._batchEntityId=null}_getOrCreateBatch(){return this._batch||(this._batch=new DebouncedDomainBatch(this.root.domainStore,300,"inspector.transform")),this._batch}isTransformProperty(_e,tt,et){var it;if(!TRANSFORM_PROPERTIES.has(et))return!1;const nt=this.root.domainStore.getNormalizedState();return nt.relations.componentOwner[tt]===_e&&TRANSFORM_COMPONENT_TYPES.has(((it=nt.components[tt])==null?void 0:it.type)??"")}isPrefabSourceEntity(_e){var et;const tt=this.root.domainStore.getNormalizedState().entities[_e];return!!((et=tt==null?void 0:tt.instance)!=null&&et.bindingId&&tt.instance.role!=="added")}buildTransformOps(_e,tt,et){return[{op:"replace",path:`/entities/${_e}/transform/${tt}/x`,value:et.x},{op:"replace",path:`/entities/${_e}/transform/${tt}/y`,value:et.y},{op:"replace",path:`/entities/${_e}/transform/${tt}/z`,value:et.z}]}findComponentOwnerEntityId(_e){return this.root.domainStore.getNormalizedState().relations.componentOwner[_e]??null}}function createEmptyPrefabOverrides$1(){return{entityProps:{},componentProps:{},removedEntities:{},removedComponents:{},addedEntities:{},addedComponents:{}}}function cloneTransform(rt){return{position:{...rt.position},rotation:{...rt.rotation},scale:{...rt.scale}}}function pushRemoveOnce(rt,_e,tt){_e.has(tt)||(_e.add(tt),rt.push({op:"remove",path:tt}))}function unlinkEntityInstance(rt,_e,tt,et,nt,it){var st,ct,dt,ut,ht;const at=rt.entities[_e];if(!at)return;const ot=encodeJsonPointerSegment(_e);((st=at.instance)==null?void 0:st.bindingId)===nt&&!((ct=it.preservedEntityIds)!=null&&ct.has(_e))&&pushRemoveOnce(tt,et,`/entities/${ot}/instance`);for(const[ft,pt]of Object.entries(at.components))((dt=pt.instance)==null?void 0:dt.bindingId)===nt&&!((ht=(ut=it.preservedComponentsByEntity)==null?void 0:ut.get(_e))!=null&&ht.has(ft))&&pushRemoveOnce(tt,et,`/entities/${ot}/components/${encodeJsonPointerSegment(ft)}/instance`)}function buildUnlinkInstanceOps(rt,_e,tt={}){const et=[],nt=new Set;for(const it of getSceneEntityIdsForPrefabBinding(_e))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);for(const it of Object.keys(_e.overrides.addedEntities))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);for(const it of Object.keys(rt.entities))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);return et}function findBindingByEntityId(rt,_e){const tt=rt.entities[_e];if(!tt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_e}" not found`);if(!tt.instance)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: entity "${_e}" has no instance link`);const et=rt.prefab.bindings[tt.instance.bindingId];if(!et)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${tt.instance.bindingId}" not found`);return{entity:tt,binding:et}}function normalizeTransform(rt){const _e=createDefaultTransform();return mergeTransform$1(_e,rt)}function mergeTransform$1(rt,_e){return{position:{...rt.position,..._e==null?void 0:_e.position},rotation:{...rt.rotation,..._e==null?void 0:_e.rotation},scale:{...rt.scale,..._e==null?void 0:_e.scale}}}function buildInstantiateSourceSnapshots(rt){const _e=new Map(rt.map(nt=>[nt.id,nt.sourceEntityId])),tt=new Map,et=new Map;for(const nt of rt)if(nt.parentId){const it=_e.get(nt.parentId);if(it){const at=tt.get(it)??[];et.set(nt.sourceEntityId,at.length),at.push(nt.sourceEntityId),tt.set(it,at)}}else et.set(nt.sourceEntityId,0);return Object.fromEntries(rt.map(nt=>{const it={};for(const ot of nt.components??[])it[ot.sourceComponentKey]={sceneComponentId:ot.id,type:ot.type,props:cloneState(ot.props??{})};const at={sceneEntityId:nt.id,parentSourceEntityId:nt.parentId?_e.get(nt.parentId)??null:null,childSourceEntityIds:[...tt.get(nt.sourceEntityId)??[]],childIndex:et.get(nt.sourceEntityId)??0,name:nt.name,isActive:!0,transform:normalizeTransform(nt.transform),components:it};return[nt.sourceEntityId,at]}))}class InstantiatePrefabCommand{constructor(){Rt(this,"name","prefab.instantiate")}execute(_e,tt){const{assetId:et,bindingId:nt,parentId:it,rootTransform:at,entities:ot}=tt,st=[],ct={},dt=ot.filter(At=>At.parentId===null);if(dt.length!==1)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: prefab instantiate requires exactly one root entity",{entityIds:ot.map(At=>At.id),rootCandidateIds:dt.map(At=>At.id)});const[ut]=dt,ht=ut.id,ft=ut.sourceEntityId;for(const At of ot)ct[At.sourceEntityId]=At.id;const pt=new Set,mt=new Map;let vt=0;for(const At of ot){const xt=At.id===ht,Ct=encodeJsonPointerSegment(At.id),Pt={};if(At.components)for(const It of At.components){const Ot={bindingId:nt,role:"linked",sourceComponentKey:It.sourceComponentKey};Pt[It.id]={type:It.type,props:It.props??{},instance:Ot}}const Tt=xt?it:At.parentId,wt={id:At.id,name:At.name,isActive:!0,parentId:Tt,children:[],transform:xt&&at?mergeTransform$1(normalizeTransform(At.transform),at):normalizeTransform(At.transform),components:Pt,instance:{bindingId:nt,assetId:et,assetKind:"Prefab",role:xt?"root":"linked",sourceEntityId:At.sourceEntityId}};if(st.push({op:"add",path:`/entities/${Ct}`,value:wt}),pt.add(At.id),At.parentId!==null){const It=_e.entities[At.parentId],Ot=pt.has(At.parentId),Nt=mt.get(At.parentId)??0;let Mt;It?Mt=It.children.length+Nt:Mt=Nt,st.push({op:"add",path:`/entities/${encodeJsonPointerSegment(At.parentId)}/children/${Mt}`,value:At.id}),mt.set(At.parentId,Nt+1)}else if(it!==null){const It=_e.entities[it],Ot=mt.get(it)??0,Nt=(It?It.children.length:0)+Ot;st.push({op:"add",path:`/entities/${encodeJsonPointerSegment(it)}/children/${Nt}`,value:At.id}),mt.set(it,Ot+1)}else{const It=_e.scene.rootEntityIds.length+vt;st.push({op:"add",path:`/scene/rootEntityIds/${It}`,value:At.id}),vt++}}const _t={id:nt,assetId:et,assetKind:"Prefab",instanceRootEntityId:ht,sourceRootEntityId:ft,sourceRevision:1,sourceToSceneEntity:ct,sourceEntitySnapshots:buildInstantiateSourceSnapshots(ot),overrides:createEmptyPrefabOverrides$1()},yt=encodeJsonPointerSegment(nt);st.push({op:"add",path:`/prefab/bindings/${yt}`,value:_t});const bt=encodeJsonPointerSegment(et),Et=_e.prefab.byAssetId[et];Et?st.push({op:"add",path:`/prefab/byAssetId/${bt}/${Et.length}`,value:nt}):st.push({op:"add",path:`/prefab/byAssetId/${bt}`,value:[nt]});const St={type:"PrefabBindingCreated",source:"instantiate",bindingId:nt,assetId:et,instanceRootEntityId:ht,sourceRootEntityId:ft,entityIds:ot.map(At=>At.id)};return{operations:st,result:nt,events:[St]}}}function sourceEntityIdToPathFromSnapshots(rt,_e){const tt=[];let et=rt[_e];const nt=new Set([_e]);for(;et&&et.parentSourceEntityId!=null;){tt.unshift(et.childIndex);const it=et.parentSourceEntityId;if(nt.has(it))return null;nt.add(it),et=rt[it]}return et?tt.join("/"):null}function sourceEntityIdToPath(rt,_e){return _e===rt.sourceRootEntityId?"":sourceEntityIdToPathFromSnapshots(rt.sourceEntitySnapshots??{},_e)}function sourcePathContains(rt,_e){return rt===_e?!0:rt===""?_e!=="":_e.startsWith(`${rt}/`)}function collectRemovedSourceEntityPaths(rt,_e=rt.sourceEntitySnapshots??{}){const tt=new Map;for(const et of Object.keys(rt.overrides.removedEntities??{})){const nt=et===rt.sourceRootEntityId?"":sourceEntityIdToPathFromSnapshots(_e,et);nt!==null&&tt.set(et,nt)}return tt}function sourceEntityIsCoveredByRemovedEntityInSnapshots(rt,_e,tt){const et=sourceEntityIdToPathFromSnapshots(rt,tt);if(et===null)return _e.has(tt);for(const nt of _e.values())if(sourcePathContains(nt,et))return!0;return!1}function sourceEntityIsCoveredByAnotherRemovedEntityInSnapshots(rt,_e,tt){const et=sourceEntityIdToPathFromSnapshots(rt,tt);if(et===null)return!1;for(const[nt,it]of _e)if(nt!==tt&&sourcePathContains(it,et))return!0;return!1}function sourceEntityIsCoveredByRemovedEntity(rt,_e){var et;const tt=sourceEntityIdToPath(rt,_e);if(tt===null)return!!((et=rt.overrides.removedEntities)!=null&&et[_e]);for(const nt of collectRemovedSourceEntityPaths(rt).values())if(sourcePathContains(nt,tt))return!0;return!1}function sourceEntityIsCoveredByAnotherRemovedEntity(rt,_e){const tt=sourceEntityIdToPath(rt,_e);if(tt===null)return!1;for(const[et,nt]of collectRemovedSourceEntityPaths(rt))if(et!==_e&&sourcePathContains(nt,tt))return!0;return!1}const VECTOR3_KEYS=["x","y","z"];function buildBindExistingSourceSnapshots(rt,_e,tt,et,nt){const it=new Map(_e.map(ct=>[ct.sceneEntityId,ct.sourceEntityId])),at=new Map(_e.map(ct=>[ct.sourceEntityId,ct.sceneEntityId])),ot=new Map,st=new Map;for(const ct of tt){const dt=ot.get(ct.sceneEntityId)??[];dt.push(ct),ot.set(ct.sceneEntityId,dt);const ut=it.get(ct.sceneEntityId);if(ut){const ht=st.get(ut)??new Map;ht.set(ct.sourceComponentKey,ct.sceneComponentId),st.set(ut,ht)}}return Object.fromEntries(et?Object.entries(et).map(([ct,dt])=>{var ht,ft,pt,mt,vt;const ut={};for(const[_t,yt]of Object.entries(dt.components))ut[_t]={sceneComponentId:((ht=st.get(ct))==null?void 0:ht.get(_t))??((pt=(ft=nt==null?void 0:nt[ct])==null?void 0:ft.components[_t])==null?void 0:pt.sceneComponentId)??yt.sceneComponentId??_t,type:yt.type,...yt.refId?{refId:yt.refId}:{},...yt.scriptKey?{scriptKey:yt.scriptKey}:{},props:cloneState(yt.props),...(mt=yt.calls)!=null&&mt.length?{calls:cloneState(yt.calls)}:{}};return[ct,{sceneEntityId:at.get(ct)??((vt=nt==null?void 0:nt[ct])==null?void 0:vt.sceneEntityId)??dt.sceneEntityId??ct,parentSourceEntityId:dt.parentSourceEntityId,childSourceEntityIds:[...dt.childSourceEntityIds],childIndex:dt.childIndex,...dt.instanceAssetKind?{instanceAssetKind:dt.instanceAssetKind}:{},name:dt.name,isActive:dt.isActive,...dt.layer!==void 0?{layer:dt.layer}:{},...dt.isLocked!==void 0?{isLocked:dt.isLocked}:{},transform:cloneTransform(dt.transform),components:ut}]}):_e.map(ct=>{var ft,pt,mt;const dt=rt.entities[ct.sceneEntityId],ut={};for(const vt of ot.get(ct.sceneEntityId)??[]){const _t=dt.components[vt.sceneComponentId];_t&&(ut[vt.sourceComponentKey]={sceneComponentId:vt.sceneComponentId,type:_t.type,..._t.refId?{refId:_t.refId}:{},..._t.scriptKey?{scriptKey:_t.scriptKey}:{},props:cloneState(_t.props),...(ft=_t.calls)!=null&&ft.length?{calls:cloneState(_t.calls)}:{}})}const ht={sceneEntityId:ct.sceneEntityId,parentSourceEntityId:dt.parentId?it.get(dt.parentId)??null:null,childSourceEntityIds:dt.children.map(vt=>it.get(vt)).filter(vt=>!!vt),childIndex:dt.parentId?Math.max(((pt=rt.entities[dt.parentId])==null?void 0:pt.children.indexOf(ct.sceneEntityId))??0,0):Math.max(rt.scene.rootEntityIds.indexOf(ct.sceneEntityId),0),...(mt=dt.instance)!=null&&mt.assetKind?{instanceAssetKind:dt.instance.assetKind}:{},name:dt.name,isActive:dt.isActive,...dt.layer!==void 0?{layer:dt.layer}:{},...dt.isLocked!==void 0?{isLocked:dt.isLocked}:{},transform:cloneTransform(dt.transform),components:ut};return[ct.sourceEntityId,ht]}))}function shouldPreserveNestedInstanceRootLink(rt,_e,tt){var ot;if(_e.role==="root")return!1;const et=(ot=tt==null?void 0:tt[_e.sourceEntityId])==null?void 0:ot.instanceAssetKind;if(!et)return!1;const nt=rt.entities[_e.sceneEntityId],it=nt==null?void 0:nt.instance;if(!it||it.role!=="root"||it.assetKind!==et)return!1;const at=rt.prefab.bindings[it.bindingId];return!!(at&&at.instanceRootEntityId===_e.sceneEntityId&&at.assetKind===et)}function resolveSceneEntityIdForSource(rt,_e){var tt,et,nt;return((tt=rt.sourceToSceneEntity)==null?void 0:tt[_e])??((nt=(et=rt.sourceEntitySnapshots)==null?void 0:et[_e])==null?void 0:nt.sceneEntityId)??(_e===rt.sourceRootEntityId?rt.instanceRootEntityId:void 0)}function buildSceneToSourceEntityLookup(rt,_e,tt,et){const nt=new Map;nt.set(et,tt);for(const[it,at]of Object.entries(rt))nt.set(at,it);for(const[it,at]of Object.entries(_e))nt.set(at.sceneEntityId,it);return nt}function resolveSourceComponentKeyForBaseline(rt,_e,tt,et,nt){var at,ot,st,ct,dt;if((at=_e[et])!=null&&at.components[nt])return nt;const it=(ct=(st=(ot=rt.sourceEntitySnapshots)==null?void 0:ot[tt])==null?void 0:st.components[nt])==null?void 0:ct.sceneComponentId;if(!it)return nt;for(const[ut,ht]of Object.entries(((dt=_e[et])==null?void 0:dt.components)??{}))if(ht.sceneComponentId===it)return ut;return nt}function mergeEntityOverrideProps$1(rt,_e){var et,nt,it,at;const tt={...rt??{},..._e};if(rt!=null&&rt.transform||_e.transform){tt.transform={...(rt==null?void 0:rt.transform)??{},..._e.transform??{}};for(const ot of["position","rotation","scale"])((et=rt==null?void 0:rt.transform)!=null&&et[ot]||(nt=_e.transform)!=null&&nt[ot])&&(tt.transform[ot]={...((it=rt==null?void 0:rt.transform)==null?void 0:it[ot])??{},...((at=_e.transform)==null?void 0:at[ot])??{}})}return tt}function sanitizeOverridesForSourceBaseline(rt,_e,tt,et,nt={}){var pt,mt,vt,_t,yt;const it=new Set(Object.keys(et)),at=new Set(Object.keys(tt)),ot=createEmptyPrefabOverrides$1(),st=collectRemovedSourceEntityPaths(_e,et),ct=buildSceneToSourceEntityLookup(tt,et,nt.sourceRootEntityId??_e.sourceRootEntityId,nt.instanceRootEntityId??_e.instanceRootEntityId),dt=bt=>{if(nt.sourceRootEntityId&&bt===_e.sourceRootEntityId)return nt.sourceRootEntityId;if(it.has(bt)||at.has(bt))return bt;const Et=resolveSceneEntityIdForSource(_e,bt);return Et?ct.get(Et)??bt:bt},ut=bt=>it.has(bt),ht=bt=>at.has(bt),ft=(bt,Et)=>{var St;return!!((St=et[bt])!=null&&St.components[Et])};for(const[bt,Et]of Object.entries(_e.overrides.entityProps)){const St=dt(bt),At=compactEntityPropsOverride(Et,et[St]);At&&ht(St)&&!sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St)&&(ot.entityProps[St]=mergeEntityOverrideProps$1(ot.entityProps[St],At))}for(const[bt,Et]of Object.entries(_e.overrides.componentProps)){const St=dt(bt);if(!ht(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At={};for(const[xt,Ct]of Object.entries(Et)){const Pt=resolveSourceComponentKeyForBaseline(_e,et,bt,St,xt),Tt=compactComponentPropsOverride(Ct,(mt=(pt=et[St])==null?void 0:pt.components[Pt])==null?void 0:mt.props);Tt&&ft(St,Pt)&&!((vt=_e.overrides.removedComponents[bt])!=null&&vt[xt])&&(At[Pt]={...At[Pt]??{},...Tt})}Object.keys(At).length>0&&(ot.componentProps[St]={...ot.componentProps[St]??{},...At})}for(const bt of Object.keys(_e.overrides.removedEntities)){const Et=dt(bt);ut(Et)&&!sourceEntityIsCoveredByAnotherRemovedEntityInSnapshots(et,st,Et)&&(ot.removedEntities[Et]=!0)}for(const[bt,Et]of Object.entries(_e.overrides.removedComponents)){const St=dt(bt);if(!ut(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At={};for(const xt of Object.keys(Et)){const Ct=resolveSourceComponentKeyForBaseline(_e,et,bt,St,xt);ft(St,Ct)&&(At[Ct]=!0)}Object.keys(At).length>0&&(ot.removedComponents[St]={...ot.removedComponents[St]??{},...At})}for(const[bt,Et]of Object.entries(_e.overrides.addedEntities)){const St=dt(Et.parentSourceEntityId);(rt.entities[bt]||nt.preserveMissingAddedEntities)&&ut(St)&&!sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St)&&(ot.addedEntities[bt]={...cloneState(Et),parentSourceEntityId:St})}for(const[bt,Et]of Object.entries(_e.overrides.addedComponents)){const St=dt(bt);if(!ht(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At=tt[St],xt=resolveSceneEntityIdForSource(_e,bt),Ct={};for(const[Pt,Tt]of Object.entries(Et)){const wt=!!((_t=rt.entities[At])!=null&&_t.components[Pt]),It=!!(xt&&((yt=rt.entities[xt])!=null&&yt.components[Pt]));(wt||It)&&(Ct[Pt]=cloneState(Tt))}Object.keys(Ct).length>0&&(ot.addedComponents[St]={...ot.addedComponents[St]??{},...Ct})}return ot}function compactEntityPropsOverride(rt,_e){const tt={};rt.name!==void 0&&!isEqual$2(rt.name,_e==null?void 0:_e.name)&&(tt.name=cloneState(rt.name)),rt.isActive!==void 0&&!isEqual$2(rt.isActive,_e==null?void 0:_e.isActive)&&(tt.isActive=cloneState(rt.isActive)),rt.layer!==void 0&&!isEqual$2(rt.layer,(_e==null?void 0:_e.layer)??0)&&(tt.layer=cloneState(rt.layer)),rt.isLocked!==void 0&&!isEqual$2(rt.isLocked,(_e==null?void 0:_e.isLocked)??!1)&&(tt.isLocked=cloneState(rt.isLocked));const et=compactTransformOverride(rt.transform,_e==null?void 0:_e.transform);return et&&(tt.transform=et),Object.keys(tt).length>0?tt:null}function compactTransformOverride(rt,_e){if(!rt)return;const tt={};for(const et of["position","rotation","scale"]){const nt=compactVector3Override(rt[et],_e==null?void 0:_e[et]);nt&&(tt[et]=nt)}return Object.keys(tt).length>0?tt:void 0}function compactVector3Override(rt,_e){if(!rt)return;const tt={};for(const et of VECTOR3_KEYS)rt[et]!==void 0&&!isEqual$2(rt[et],_e==null?void 0:_e[et])&&(tt[et]=cloneState(rt[et]));return Object.keys(tt).length>0?tt:void 0}function compactComponentPropsOverride(rt,_e){const tt={};for(const[et,nt]of Object.entries(rt))isEqual$2(nt,_e==null?void 0:_e[et])||(tt[et]=cloneState(nt));return Object.keys(tt).length>0?tt:null}function pushRemoveBindingIndexOps(rt,_e,tt){for(const et of tt)_e.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(et)}`});for(const[et,nt]of Object.entries(rt.prefab.byAssetId)){const it=nt.map((ot,st)=>tt.has(ot)?st:-1).filter(ot=>ot>=0);if(!it.length)continue;const at=encodeJsonPointerSegment(et);if(it.length===nt.length){_e.push({op:"remove",path:`/prefab/byAssetId/${at}`});continue}it.sort((ot,st)=>st-ot).forEach(ot=>_e.push({op:"remove",path:`/prefab/byAssetId/${at}/${ot}`}))}}function pushUnlinkRemovedBindingLinksOps(rt,_e,tt,et,nt){if(tt.size)for(const it of tt){const at=rt.prefab.bindings[it];at&&_e.push(...buildUnlinkInstanceOps(rt,at,{preservedEntityIds:et,preservedComponentsByEntity:nt}))}}function buildPreservedComponentsByEntity(rt){const _e=new Map;for(const tt of rt){const et=_e.get(tt.sceneEntityId)??new Set;et.add(tt.sceneComponentId),_e.set(tt.sceneEntityId,et)}return _e}class BindExistingPrefabInstanceCommand{constructor(){Rt(this,"name","prefab.bindExistingInstance")}execute(_e,tt){var St,At,xt;const{assetId:et,assetKind:nt="Prefab",bindingId:it,instanceRootEntityId:at,sourceRevision:ot=1,entityMappings:st,componentMappings:ct=[]}=tt;if(!st.length)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: entityMappings is empty");if(_e.prefab.bindings[it])throw new CommandError(CommandErrorCode.DUPLICATE_ID,`DUPLICATE_ID: binding "${it}" already exists`);const dt=st.find(Ct=>Ct.sceneEntityId===at&&Ct.role==="root")??st.find(Ct=>Ct.role==="root");if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: missing root mapping for instance root "${at}"`);const ut={},ht=new Set,ft=[],pt=new Set,mt=(At=(St=tt.sourceEntitySnapshots)==null?void 0:St[dt.sourceEntityId])==null?void 0:At.instanceAssetKind,vt=Ct=>nt==="Prefab"&&mt==="glTF"&&Ct.assetKind==="glTF";for(const[Ct,Pt]of Object.entries(_e.prefab.bindings))Pt.instanceRootEntityId===at&&!vt(Pt)&&pt.add(Ct);pushUnlinkRemovedBindingLinksOps(_e,ft,pt,new Set(st.map(Ct=>Ct.sceneEntityId)),buildPreservedComponentsByEntity(ct)),pushRemoveBindingIndexOps(_e,ft,pt);for(const Ct of st){const Pt=_e.entities[Ct.sceneEntityId];if(!Pt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${Ct.sceneEntityId}" not found`);if(ut[Ct.sourceEntityId]||ht.has(Ct.sceneEntityId))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: duplicate mapping source="${Ct.sourceEntityId}" scene="${Ct.sceneEntityId}"`);if(ut[Ct.sourceEntityId]=Ct.sceneEntityId,ht.add(Ct.sceneEntityId),!shouldPreserveNestedInstanceRootLink(_e,Ct,tt.sourceEntitySnapshots)){const Tt={bindingId:it,assetId:et,assetKind:nt,role:Ct.role,sourceEntityId:Ct.sourceEntityId};ft.push({op:Pt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(Ct.sceneEntityId)}/instance`,value:Tt})}}for(const Ct of ct){const Pt=_e.entities[Ct.sceneEntityId];if(!Pt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${Ct.sceneEntityId}" not found`);const Tt=Pt.components[Ct.sceneComponentId];if(!Tt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${Ct.sceneComponentId}" not found on entity "${Ct.sceneEntityId}"`);const wt={bindingId:it,role:"linked",sourceComponentKey:Ct.sourceComponentKey};ft.push({op:Tt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(Ct.sceneEntityId)}/components/${encodeJsonPointerSegment(Ct.sceneComponentId)}/instance`,value:wt})}const _t={id:it,assetId:et,assetKind:nt,instanceRootEntityId:at,sourceRootEntityId:dt.sourceEntityId,sourceRevision:ot,sourceToSceneEntity:ut,sourceEntitySnapshots:buildBindExistingSourceSnapshots(_e,st,ct,tt.sourceEntitySnapshots),overrides:createEmptyPrefabOverrides$1()};ft.push({op:"add",path:`/prefab/bindings/${encodeJsonPointerSegment(it)}`,value:_t});const yt=encodeJsonPointerSegment(et),bt=(xt=_e.prefab.byAssetId[et])==null?void 0:xt.filter(Ct=>!pt.has(Ct));bt!=null&&bt.length?bt.includes(it)||ft.push({op:"add",path:`/prefab/byAssetId/${yt}/${bt.length}`,value:it}):ft.push({op:"add",path:`/prefab/byAssetId/${yt}`,value:[it]});const Et={type:"PrefabBindingCreated",source:"bindExisting",bindingId:it,assetId:et,instanceRootEntityId:at,sourceRootEntityId:dt.sourceEntityId,entityIds:st.map(Ct=>Ct.sceneEntityId)};return{operations:ft,result:void 0,events:[Et]}}}class UpdatePrefabBindingSourceBaselineCommand{constructor(){Rt(this,"name","prefab.updateBindingSourceBaseline")}execute(_e,tt){const{assetId:et,bindingId:nt,instanceRootEntityId:it,sourceRevision:at,entityMappings:ot,componentMappings:st=[]}=tt,ct=_e.prefab.bindings[nt];if(!ct)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${nt}" not found`);if(ct.assetId!==et)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: binding "${nt}" belongs to asset "${ct.assetId}", not "${et}"`);if(tt.preserveMissingAddedEntities&&ct.assetKind!=="glTF")throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: preserveMissingAddedEntities is only allowed for glTF deferred baseline sync");if(!ot.length)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: entityMappings is empty");const dt=ot.find(_t=>_t.sceneEntityId===it&&_t.role==="root")??ot.find(_t=>_t.role==="root");if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: missing root mapping for instance root "${it}"`);const ut={},ht=new Set,ft=[];for(const _t of ot){const yt=_e.entities[_t.sceneEntityId];if(!yt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_t.sceneEntityId}" not found`);if(ut[_t.sourceEntityId]||ht.has(_t.sceneEntityId))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: duplicate mapping source="${_t.sourceEntityId}" scene="${_t.sceneEntityId}"`);ut[_t.sourceEntityId]=_t.sceneEntityId,ht.add(_t.sceneEntityId),shouldPreserveNestedInstanceRootLink(_e,_t,tt.sourceEntitySnapshots??ct.sourceEntitySnapshots)||ft.push({op:yt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(_t.sceneEntityId)}/instance`,value:{bindingId:nt,assetId:et,assetKind:ct.assetKind,role:_t.role,sourceEntityId:_t.sourceEntityId}})}for(const _t of st){const yt=_e.entities[_t.sceneEntityId];if(!yt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_t.sceneEntityId}" not found`);const bt=yt.components[_t.sceneComponentId];if(!bt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${_t.sceneComponentId}" not found on entity "${_t.sceneEntityId}"`);ft.push({op:bt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(_t.sceneEntityId)}/components/${encodeJsonPointerSegment(_t.sceneComponentId)}/instance`,value:{bindingId:nt,role:"linked",sourceComponentKey:_t.sourceComponentKey}})}const pt=buildBindExistingSourceSnapshots(_e,ot,st,tt.sourceEntitySnapshots,ct.sourceEntitySnapshots),mt=sanitizeOverridesForSourceBaseline(_e,ct,ut,pt,{preserveMissingAddedEntities:tt.preserveMissingAddedEntities,sourceRootEntityId:dt.sourceEntityId,instanceRootEntityId:it}),vt=encodeJsonPointerSegment(nt);return ct.sourceRootEntityId!==dt.sourceEntityId&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceRootEntityId`,value:dt.sourceEntityId}),at!==void 0&&ct.sourceRevision!==at&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceRevision`,value:at}),ct.instanceRootEntityId!==it&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/instanceRootEntityId`,value:it}),ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceToSceneEntity`,value:ut}),ft.push({op:ct.sourceEntitySnapshots?"replace":"add",path:`/prefab/bindings/${vt}/sourceEntitySnapshots`,value:pt}),ft.push({op:"replace",path:`/prefab/bindings/${vt}/overrides`,value:mt}),{operations:ft,result:void 0,events:[]}}}function removeBindingIdFromAssetIndex(rt,_e,tt,et){const nt=rt.prefab.byAssetId[tt];if(!nt)return;const it=nt.indexOf(et);if(it<0)return;const at=encodeJsonPointerSegment(tt);nt.length===1?_e.push({op:"remove",path:`/prefab/byAssetId/${at}`}):_e.push({op:"remove",path:`/prefab/byAssetId/${at}/${it}`})}function addBindingIdToAssetIndex(rt,_e,tt,et){const nt=rt.prefab.byAssetId[tt],it=encodeJsonPointerSegment(tt);if(!nt){_e.push({op:"add",path:`/prefab/byAssetId/${it}`,value:[et]});return}nt.includes(et)||_e.push({op:"add",path:`/prefab/byAssetId/${it}/${nt.length}`,value:et})}function createRetargetedInstanceLink(rt,_e){const tt={...rt,assetId:_e.assetId,assetKind:_e.assetKind};return _e.assetKey===void 0?delete tt.assetKey:tt.assetKey=_e.assetKey,tt}function buildRetargetRootInstanceOps(rt,_e,tt){var it;const et=[],nt=encodeJsonPointerSegment(_e.id);_e.assetId!==tt.assetId&&et.push({op:"replace",path:`/prefab/bindings/${nt}/assetId`,value:tt.assetId}),_e.assetKind!==tt.assetKind&&et.push({op:"replace",path:`/prefab/bindings/${nt}/assetKind`,value:tt.assetKind}),typeof tt.sourceRevision=="number"&&_e.sourceRevision!==tt.sourceRevision&&et.push({op:"replace",path:`/prefab/bindings/${nt}/sourceRevision`,value:tt.sourceRevision});for(const[at,ot]of Object.entries(rt.entities))((it=ot.instance)==null?void 0:it.bindingId)===_e.id&&et.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(at)}/instance`,value:createRetargetedInstanceLink(ot.instance,tt)});return _e.assetId!==tt.assetId&&(removeBindingIdFromAssetIndex(rt,et,_e.assetId,_e.id),addBindingIdToAssetIndex(rt,et,tt.assetId,_e.id)),et}class UnpackInstanceCommand{constructor(){Rt(this,"name","prefab.unpack")}execute(_e,tt){const{bindingId:et,replacementRootInstance:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);if(nt)return{operations:buildRetargetRootInstanceOps(_e,it,nt),result:void 0,events:[]};const at=buildUnlinkInstanceOps(_e,it),ot=encodeJsonPointerSegment(et);at.push({op:"remove",path:`/prefab/bindings/${ot}`}),removeBindingIdFromAssetIndex(_e,at,it.assetId,et);const st={type:"PrefabBindingRemoved",reason:"unpack",bindingId:et,assetId:it.assetId,instanceRootEntityId:it.instanceRootEntityId};return{operations:at,result:void 0,events:[st]}}}class UnpackByAssetCommand{constructor(){Rt(this,"name","prefab.unpackByAsset")}execute(_e,tt){const{assetId:et}=tt,nt=_e.prefab.byAssetId[et];if(!nt||nt.length===0)return{operations:[],result:void 0,events:[]};const it=[],at=[];for(const st of nt){const ct=_e.prefab.bindings[st];if(!ct)continue;it.push(...buildUnlinkInstanceOps(_e,ct));const dt=encodeJsonPointerSegment(st);it.push({op:"remove",path:`/prefab/bindings/${dt}`}),at.push({type:"PrefabBindingRemoved",reason:"unpackByAsset",bindingId:st,assetId:ct.assetId,instanceRootEntityId:ct.instanceRootEntityId})}const ot=encodeJsonPointerSegment(et);return it.push({op:"remove",path:`/prefab/byAssetId/${ot}`}),{operations:it,result:void 0,events:at}}}function requireSourceComponentKey(rt,_e,tt){var nt;const et=(nt=rt.instance)==null?void 0:nt.sourceComponentKey;if(!et)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab source component "${tt}" on entity "${_e}" is missing sourceComponentKey`);return et}function mergeTransformOverride(rt,_e){if(!(!rt&&!_e))return{...rt!=null&&rt.position||_e!=null&&_e.position?{position:{...(rt==null?void 0:rt.position)??{},...(_e==null?void 0:_e.position)??{}}}:{},...rt!=null&&rt.rotation||_e!=null&&_e.rotation?{rotation:{...(rt==null?void 0:rt.rotation)??{},...(_e==null?void 0:_e.rotation)??{}}}:{},...rt!=null&&rt.scale||_e!=null&&_e.scale?{scale:{...(rt==null?void 0:rt.scale)??{},...(_e==null?void 0:_e.scale)??{}}}:{}}}function mergeEntityOverrideProps(rt,_e){const tt={...rt??{},..._e},et=mergeTransformOverride(rt==null?void 0:rt.transform,_e.transform);return et?tt.transform=et:delete tt.transform,tt}function compactDomainValuePatch(rt,_e){if(_e===void 0)return;if(!isPlainRecord(rt)||!isPlainRecord(_e))return isEqual$2(rt,_e)?void 0:cloneState(_e);const tt={};for(const[et,nt]of Object.entries(_e)){const it=compactDomainValuePatch(rt[et],nt);it!==void 0&&(tt[et]=it)}return Object.keys(tt).length?tt:void 0}function compactDomainRecordPatch(rt,_e){const tt=compactDomainValuePatch(rt??{},_e);return isPlainRecord(tt)&&Object.keys(tt).length?tt:void 0}function compactTransformAgainstSnapshot(rt,_e){if(!_e)return;const tt={};for(const et of["position","rotation","scale"]){const nt=_e[et];if(!nt)continue;const it=compactDomainRecordPatch(rt[et],nt);it&&(tt[et]=it)}return Object.keys(tt).length?tt:void 0}function compactEntityOverrideAgainstSnapshot(rt,_e){if(!rt)return cloneState(_e);const tt={};_e.name!==void 0&&!isEqual$2(_e.name,rt.name)&&(tt.name=cloneState(_e.name)),_e.isActive!==void 0&&!isEqual$2(_e.isActive,rt.isActive)&&(tt.isActive=cloneState(_e.isActive)),_e.layer!==void 0&&!isEqual$2(_e.layer,rt.layer??0)&&(tt.layer=cloneState(_e.layer)),_e.isLocked!==void 0&&!isEqual$2(_e.isLocked,rt.isLocked??!1)&&(tt.isLocked=cloneState(_e.isLocked));const et=compactTransformAgainstSnapshot(rt.transform,_e.transform);return et&&(tt.transform=et),Object.keys(tt).length?tt:void 0}function compactComponentOverrideAgainstSnapshot(rt,_e){return rt?compactDomainRecordPatch(rt.props??{},_e):cloneState(_e)}function createAddedComponentOverrideState(rt,_e,tt){var et;return{componentId:rt,ownerSourceEntityId:_e,type:tt.type,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:cloneState(tt.props),...(et=tt.calls)!=null&&et.length?{calls:cloneState(tt.calls)}:{}}}function isDomainAncestorOrSelf(rt,_e,tt){var it;const et=new Set;let nt=tt;for(;nt&&!et.has(nt);){if(nt===_e)return!0;et.add(nt),nt=((it=rt.entities[nt])==null?void 0:it.parentId)??null}return!1}function resolveAddedEntityParentSceneEntityId(rt,_e,tt,et){var ct,dt;const nt=getSceneEntityIdForPrefabSource(_e,tt);if(nt&&rt.entities[nt])return nt;if(!et||!rt.entities[et])throw new CommandError(CommandErrorCode.PARENT_NOT_FOUND,`PARENT_NOT_FOUND: prefab source parent "${tt}" is not bound in instance "${_e.id}"`,{bindingId:_e.id,parentSourceEntityId:tt});if(!isDomainAncestorOrSelf(rt,_e.instanceRootEntityId,et))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${et}" is outside prefab instance "${_e.id}"`,{bindingId:_e.id,parentSceneEntityId:et});const it=rt.entities[et],at=(ct=it==null?void 0:it.instance)==null?void 0:ct.bindingId,ot=at?rt.prefab.bindings[at]:void 0,st=ot?getSourceEntityIdForPrefabScene(ot,et,(dt=it==null?void 0:it.instance)==null?void 0:dt.sourceEntityId):null;if(!ot||ot.id===_e.id||ot.assetKind!=="Prefab"&&ot.assetKind!=="glTF"||st!==tt||!isDomainAncestorOrSelf(rt,_e.instanceRootEntityId,ot.instanceRootEntityId))throw new CommandError(CommandErrorCode.PARENT_NOT_FOUND,`PARENT_NOT_FOUND: prefab source parent "${tt}" is not bound in instance "${_e.id}"`,{bindingId:_e.id,parentSourceEntityId:tt,parentSceneEntityId:et});return et}function requirePrefabSourceEntityId(rt,_e,tt){var nt,it,at,ot;if(((nt=rt.instance)==null?void 0:nt.role)==="added")throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${_e}" has no sourceEntityId for prefab override`,{entityId:_e,role:rt.instance.role,bindingId:rt.instance.bindingId});const et=getSourceEntityIdForPrefabScene(tt,_e,(it=rt.instance)==null?void 0:it.sourceEntityId);if(et)return et;throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${_e}" has no sourceEntityId for prefab override`,{entityId:_e,role:(at=rt.instance)==null?void 0:at.role,bindingId:(ot=rt.instance)==null?void 0:ot.bindingId})}function pushTransformReplaceOps(rt,_e,tt){rt.push({op:"replace",path:`/entities/${_e}/transform/position`,value:tt.position}),rt.push({op:"replace",path:`/entities/${_e}/transform/rotation`,value:tt.rotation}),rt.push({op:"replace",path:`/entities/${_e}/transform/scale`,value:tt.scale})}class SetEntityOverrideCommand{constructor(){Rt(this,"name","prefab.setEntityOverride")}execute(_e,tt){var _t,yt,bt,Et;const{entityId:et,overrides:nt}=tt,{entity:it,binding:at}=findBindingByEntityId(_e,et),ot=[],st=encodeJsonPointerSegment(et),ct=requirePrefabSourceEntityId(it,et,at),dt=encodeJsonPointerSegment(ct),ut=encodeJsonPointerSegment(at.id);if(nt.name!==void 0&&ot.push({op:"replace",path:`/entities/${st}/name`,value:nt.name}),nt.isActive!==void 0&&ot.push({op:"replace",path:`/entities/${st}/isActive`,value:nt.isActive}),nt.isLocked!==void 0){const St=((_t=_e.entities[et])==null?void 0:_t.isLocked)!==void 0?"replace":"add";ot.push({op:St,path:`/entities/${st}/isLocked`,value:nt.isLocked})}if(nt.layer!==void 0){const St=((yt=_e.entities[et])==null?void 0:yt.layer)!==void 0?"replace":"add";ot.push({op:St,path:`/entities/${st}/layer`,value:nt.layer})}if(nt.transform!==void 0){const St=nt.transform,At=(bt=_e.entities[et])==null?void 0:bt.transform;St.position&&ot.push({op:"replace",path:`/entities/${st}/transform/position`,value:{...At==null?void 0:At.position,...St.position}}),St.rotation&&ot.push({op:"replace",path:`/entities/${st}/transform/rotation`,value:{...At==null?void 0:At.rotation,...St.rotation}}),St.scale&&ot.push({op:"replace",path:`/entities/${st}/transform/scale`,value:{...At==null?void 0:At.scale,...St.scale}})}const ht=at.overrides.entityProps[ct],ft=mergeEntityOverrideProps(ht,nt),pt=compactEntityOverrideAgainstSnapshot((Et=at.sourceEntitySnapshots)==null?void 0:Et[ct],ft);let mt=null;pt?(ot.push({op:ht?"replace":"add",path:`/prefab/bindings/${ut}/overrides/entityProps/${dt}`,value:pt}),mt="set"):ht&&(ot.push({op:"remove",path:`/prefab/bindings/${ut}/overrides/entityProps/${dt}`}),mt="remove");const vt=[{type:"EntityUpdated",entityId:et,changes:cloneState(nt)}];return mt&&vt.push({type:"PrefabOverrideChanged",action:mt,bindingId:at.id,assetId:at.assetId,bucket:"entityProps",entityId:et,sourceEntityId:ct}),{operations:ot,result:void 0,events:vt}}}class SetComponentOverrideCommand{constructor(){Rt(this,"name","prefab.setComponentOverride")}execute(_e,tt){var xt,Ct;const{entityId:et,componentId:nt,overrides:it}=tt,{entity:at,binding:ot}=findBindingByEntityId(_e,et),st=[],ct=encodeJsonPointerSegment(et),dt=encodeJsonPointerSegment(nt),ut=requirePrefabSourceEntityId(at,et,ot),ht=encodeJsonPointerSegment(ut),ft=encodeJsonPointerSegment(ot.id),pt=at.components[nt];if(!pt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);for(const[Pt,Tt]of Object.entries(it)){const wt=Object.prototype.hasOwnProperty.call(pt.props,Pt);st.push({op:wt?"replace":"add",path:`/entities/${ct}/components/${dt}/props/${encodeJsonPointerSegment(Pt)}`,value:Tt})}const mt=requireSourceComponentKey(pt,et,nt),vt=encodeJsonPointerSegment(mt),_t=ot.overrides.componentProps[ut],yt=_t==null?void 0:_t[mt],bt={...yt??{},...it},Et=compactComponentOverrideAgainstSnapshot((Ct=(xt=ot.sourceEntitySnapshots)==null?void 0:xt[ut])==null?void 0:Ct.components[mt],bt);let St=null;if(Et)_t?st.push({op:yt?"replace":"add",path:`/prefab/bindings/${ft}/overrides/componentProps/${ht}/${vt}`,value:Et}):st.push({op:"add",path:`/prefab/bindings/${ft}/overrides/componentProps/${ht}`,value:{[mt]:Et}}),St="set";else if(yt){const Pt=Object.keys(_t??{});st.push({op:"remove",path:Pt.length===1?`/prefab/bindings/${ft}/overrides/componentProps/${ht}`:`/prefab/bindings/${ft}/overrides/componentProps/${ht}/${vt}`}),St="remove"}const At=[{type:"ComponentUpdated",entityId:et,componentId:nt,changes:cloneState(it)}];return St&&At.push({type:"PrefabOverrideChanged",action:St,bindingId:ot.id,assetId:ot.assetId,bucket:"componentProps",entityId:et,sourceEntityId:ut,componentId:mt}),{operations:st,result:void 0,events:At}}}class AddEntityOverrideCommand{constructor(){Rt(this,"name","prefab.addEntityOverride")}execute(_e,tt){const{bindingId:et,entityId:nt,name:it,parentSourceEntityId:at,index:ot}=tt,st=_e.prefab.bindings[et];if(!st)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const ct=[],dt=encodeJsonPointerSegment(nt),ut=encodeJsonPointerSegment(et),ht=resolveAddedEntityParentSceneEntityId(_e,st,at,tt.parentSceneEntityId),ft={};if(tt.components)for(const[Et,St]of Object.entries(tt.components))ft[Et]={type:St.type,props:St.props,instance:{bindingId:et,role:"added"}};const pt={id:nt,name:it,isActive:!0,parentId:ht,children:[],transform:tt.transform??createDefaultTransform(),components:ft,instance:{bindingId:et,assetId:st.assetId,assetKind:st.assetKind,role:"added"}};ct.push({op:"add",path:`/entities/${dt}`,value:pt});const{siblings:mt,arrayPath:vt}=getSiblingsInfo(_e,ht),_t=Math.min(Math.max(ot,0),mt.length);ct.push({op:"add",path:`${vt}/${_t}`,value:nt});const yt={entityId:nt,parentSourceEntityId:at,index:_t};ct.push({op:"add",path:`/prefab/bindings/${ut}/overrides/addedEntities/${dt}`,value:yt});const bt=[{type:"EntityCreated",entityId:nt,parentId:ht??null,index:_t,entity:cloneState(pt)},{type:"PrefabOverrideChanged",action:"add",bindingId:et,assetId:st.assetId,bucket:"addedEntities",entityId:nt,sourceEntityId:at}];return{operations:ct,result:void 0,events:bt}}}class AddExistingEntityOverrideCommand{constructor(){Rt(this,"name","prefab.addExistingEntityOverride")}execute(_e,tt){var Ot,Nt;const{bindingId:et,entityId:nt,parentSourceEntityId:it}=tt,at=_e.prefab.bindings[et];if(!at)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const ot=_e.entities[nt];if(!ot)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${nt}" not found`);const st=collectSubtree(_e,nt),ct=new Set(st);for(const Mt of st){const Lt=_e.entities[Mt],$t=((Ot=Lt==null?void 0:Lt.instance)==null?void 0:Ot.bindingId)===et&&Lt.instance.role==="added",Dt=isNestedInstanceSubtreeEntity(_e,Lt,et,ct);if(Lt!=null&&Lt.instance&&!$t&&!Dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${Mt}" already has an instance link`,{entityId:Mt,bindingId:Lt.instance.bindingId,role:Lt.instance.role})}const dt=resolveAddedEntityParentSceneEntityId(_e,at,it,tt.parentSceneEntityId);if(nt===dt||wouldCreateCycle(_e,nt,dt))throw new CommandError(CommandErrorCode.CYCLE_DETECTED,`Cannot add entity "${nt}" to prefab override parent "${dt}"`);const ut=[],ht=encodeJsonPointerSegment(nt),ft=encodeJsonPointerSegment(et),pt=ot.parentId,{siblings:mt,arrayPath:vt}=getSiblingsInfo(_e,pt),_t=mt.indexOf(nt),yt=pt===dt,bt=yt?null:getLocalTransformPreservingWorld(_e,nt,dt),{siblings:Et,arrayPath:St}=getSiblingsInfo(_e,dt),At=Math.max(0,Et.length-(yt&&_t>=0?1:0)),xt=yt&&_t>=0&&_t<tt.index?tt.index-1:tt.index,Ct=Math.min(Math.max(xt,0),At);_t>=0&&(!yt||_t!==Ct)&&ut.push({op:"remove",path:`${vt}/${_t}`}),yt||(ut.push({op:"replace",path:`/entities/${ht}/parentId`,value:dt}),bt&&!transformsClose(ot.transform,bt)&&pushTransformReplaceOps(ut,ht,bt)),(_t===-1||!yt||_t!==Ct)&&ut.push({op:"add",path:`${St}/${Ct}`,value:nt});const Pt={bindingId:et,assetId:at.assetId,assetKind:at.assetKind,role:"added"};for(const Mt of st){const Lt=_e.entities[Mt];if(!Lt||isNestedInstanceSubtreeEntity(_e,Lt,et,ct))continue;const $t=encodeJsonPointerSegment(Mt),Dt=((Nt=Lt.instance)==null?void 0:Nt.bindingId)===et&&Lt.instance.role==="added";ut.push({op:Dt?"replace":"add",path:`/entities/${$t}/instance`,value:Pt});for(const[Bt,Gt]of Object.entries(Lt.components)){const zt=encodeJsonPointerSegment(Bt);ut.push({op:Gt.instance?"replace":"add",path:`/entities/${$t}/components/${zt}/instance`,value:{bindingId:et,role:"added"}})}}const Tt={entityId:nt,parentSourceEntityId:it,index:Ct},wt=at.overrides.addedEntities[nt];ut.push({op:wt?"replace":"add",path:`/prefab/bindings/${ft}/overrides/addedEntities/${ht}`,value:Tt});const It=[{type:"PrefabOverrideChanged",action:"add",bindingId:et,assetId:at.assetId,bucket:"addedEntities",entityId:nt,sourceEntityId:it}];return{operations:ut,result:void 0,events:It}}}function isNestedInstanceSubtreeEntity(rt,_e,tt,et){const nt=_e==null?void 0:_e.instance;if(!nt||nt.bindingId===tt)return!1;const it=rt.prefab.bindings[nt.bindingId];return!!(it&&et.has(it.instanceRootEntityId))}class RemoveSourceEntityOverrideCommand{constructor(){Rt(this,"name","prefab.removeSourceEntityOverride")}execute(_e,tt){var mt,vt,_t,yt;const{entityId:et}=tt,{entity:nt,binding:it}=findBindingByEntityId(_e,et),at=[],ot=encodeJsonPointerSegment(it.id),st=[],ct=bt=>{st.push(bt);const Et=_e.entities[bt];if(Et)for(const St of Et.children)ct(St)};if(ct(et),nt.parentId){const bt=_e.entities[nt.parentId];if(bt){const Et=bt.children.indexOf(et);Et>=0&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(nt.parentId)}/children/${Et}`})}}else{const bt=_e.scene.rootEntityIds.indexOf(et);bt>=0&&at.push({op:"remove",path:`/scene/rootEntityIds/${bt}`})}const dt=Object.fromEntries(st.map(bt=>[bt,cloneState(_e.entities[bt])])),ut=new Set;for(const bt of st){const Et=encodeJsonPointerSegment(bt);at.push({op:"remove",path:`/entities/${Et}`});const St=getSourceEntityIdForPrefabScene(it,bt,(vt=(mt=_e.entities[bt])==null?void 0:mt.instance)==null?void 0:vt.sourceEntityId);if(St){ut.add(St);const At=encodeJsonPointerSegment(St);at.push({op:"add",path:`/prefab/bindings/${ot}/overrides/removedEntities/${At}`,value:!0}),((_t=it.sourceToSceneEntity)==null?void 0:_t[St])!=null&&at.push({op:"remove",path:`/prefab/bindings/${ot}/sourceToSceneEntity/${At}`})}}const ht=(bt,Et)=>{it.overrides[bt][Et]!==void 0&&at.push({op:"remove",path:`/prefab/bindings/${ot}/overrides/${bt}/${encodeJsonPointerSegment(Et)}`})};for(const bt of ut)ht("entityProps",bt),ht("componentProps",bt),ht("removedComponents",bt),ht("addedComponents",bt);const ft=new Set(st);for(const[bt,Et]of Object.entries(it.overrides.addedEntities))!ut.has(Et.parentSourceEntityId)&&!ft.has(bt)||at.push({op:"remove",path:`/prefab/bindings/${ot}/overrides/addedEntities/${encodeJsonPointerSegment(bt)}`});const pt=[{type:"EntityDeleted",entityId:et,snapshot:dt[et],subtreeIds:cloneState(st),subtree:dt},{type:"PrefabOverrideChanged",action:"add",bindingId:it.id,assetId:it.assetId,bucket:"removedEntities",entityId:et,sourceEntityId:(yt=nt.instance)==null?void 0:yt.sourceEntityId}];return{operations:at,result:void 0,events:pt}}}class AddComponentOverrideCommand{constructor(){Rt(this,"name","prefab.addComponentOverride")}execute(_e,tt){var bt;const{entityId:et,componentId:nt,type:it,props:at}=tt,{entity:ot,binding:st}=findBindingByEntityId(_e,et),ct=[],dt=encodeJsonPointerSegment(et),ut=encodeJsonPointerSegment(nt),ht=encodeJsonPointerSegment(st.id),ft=requirePrefabSourceEntityId(ot,et,st),pt=encodeJsonPointerSegment(ft),mt={type:it,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:at,...(bt=tt.calls)!=null&&bt.length?{calls:cloneState(tt.calls)}:{},instance:{bindingId:st.id,role:"added"}};ct.push({op:"add",path:`/entities/${dt}/components/${ut}`,value:mt});const vt=createAddedComponentOverrideState(nt,ft,mt);st.overrides.addedComponents[ft]?ct.push({op:"add",path:`/prefab/bindings/${ht}/overrides/addedComponents/${pt}/${ut}`,value:vt}):ct.push({op:"add",path:`/prefab/bindings/${ht}/overrides/addedComponents/${pt}`,value:{[nt]:vt}});const yt=[{type:"ComponentAdded",entityId:et,componentId:nt,component:cloneState(mt)},{type:"PrefabOverrideChanged",action:"add",bindingId:st.id,assetId:st.assetId,bucket:"addedComponents",entityId:et,sourceEntityId:ft,componentId:nt}];return{operations:ct,result:void 0,events:yt}}}class UpdateAddedComponentOverrideCommand{constructor(){Rt(this,"name","prefab.updateAddedComponentOverride")}execute(_e,tt){var yt,bt;const{entityId:et,componentId:nt,overrides:it}=tt,{entity:at,binding:ot}=findBindingByEntityId(_e,et),st=requirePrefabSourceEntityId(at,et,ot),ct=at.components[nt];if(!ct)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);if(((yt=ct.instance)==null?void 0:yt.role)!=="added")throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: component "${nt}" on entity "${et}" is not a prefab added component`);const dt=(bt=ot.overrides.addedComponents[st])==null?void 0:bt[nt];if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab added component "${nt}" on source entity "${st}" is missing addedComponents override`);const ut=[],ht={},ft={...ct.props},pt=encodeJsonPointerSegment(et),mt=encodeJsonPointerSegment(nt);for(const[Et,St]of Object.entries(it)){if(isEqual$2(ct.props[Et],St))continue;const At=encodeJsonPointerSegment(Et),xt=Object.prototype.hasOwnProperty.call(ct.props,Et);ut.push({op:xt?"replace":"add",path:`/entities/${pt}/components/${mt}/props/${At}`,value:cloneState(St)}),ft[Et]=cloneState(St),ht[Et]=cloneState(St)}const vt=createAddedComponentOverrideState(nt,st,{...ct,props:ft});isEqual$2(dt,vt)||ut.push({op:"replace",path:`/prefab/bindings/${encodeJsonPointerSegment(ot.id)}/overrides/addedComponents/${encodeJsonPointerSegment(st)}/${mt}`,value:vt});const _t=[];return Object.keys(ht).length>0&&_t.push({type:"ComponentUpdated",entityId:et,componentId:nt,changes:ht}),ut.length>0&&_t.push({type:"PrefabOverrideChanged",action:"set",bindingId:ot.id,assetId:ot.assetId,bucket:"addedComponents",entityId:et,sourceEntityId:st,componentId:nt}),{operations:ut,result:void 0,events:_t}}}class RemoveSourceComponentOverrideCommand{constructor(){Rt(this,"name","prefab.removeSourceComponentOverride")}execute(_e,tt){const{entityId:et,componentId:nt}=tt,{entity:it,binding:at}=findBindingByEntityId(_e,et),ot=[],st=encodeJsonPointerSegment(et),ct=encodeJsonPointerSegment(nt),dt=encodeJsonPointerSegment(at.id),ut=requirePrefabSourceEntityId(it,et,at),ht=encodeJsonPointerSegment(ut),ft=it.components[nt];if(!ft)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);ot.push({op:"remove",path:`/entities/${st}/components/${ct}`});const pt=requireSourceComponentKey(ft,et,nt),mt=encodeJsonPointerSegment(pt);at.overrides.removedComponents[ut]?ot.push({op:"add",path:`/prefab/bindings/${dt}/overrides/removedComponents/${ht}/${mt}`,value:!0}):ot.push({op:"add",path:`/prefab/bindings/${dt}/overrides/removedComponents/${ht}`,value:{[pt]:!0}});const _t=[{type:"ComponentRemoved",entityId:et,componentId:nt,snapshot:cloneState(ft)},{type:"PrefabOverrideChanged",action:"add",bindingId:at.id,assetId:at.assetId,bucket:"removedComponents",entityId:et,sourceEntityId:ut,componentId:pt}];return{operations:ot,result:void 0,events:_t}}}function toComponentStateSnapshot(rt){if(!rt)return;const{id:_e,entityId:tt,...et}=rt;return et}function removeNestedOverrideContainerIfEmpty(rt,_e,tt,et,nt){Object.keys(_e.overrides[et][nt]??{}).length===1&&rt.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(tt)}/overrides/${et}/${encodeJsonPointerSegment(nt)}`})}function pushAcceptedAddedEntityPromotionOps(rt,_e,tt,et,nt,it,at){var ht,ft,pt,mt,vt;const ot=encodeJsonPointerSegment(et),st=collectSubtree(_e,nt),ct=new Map,dt=resolveSourceInsertionIndexForAddedEntity(_e,tt,it,nt,at);for(const _t of st)ct.set(_t,_t);tt.sourceEntitySnapshots||rt.push({op:"add",path:`/prefab/bindings/${ot}/sourceEntitySnapshots`,value:{}});const ut=(ht=tt.sourceEntitySnapshots)==null?void 0:ht[it];if(ut){const _t=[...ut.childSourceEntityIds??[]];_t.includes(nt)||_t.splice(Math.min(Math.max(dt,0),_t.length),0,nt),rt.push({op:"replace",path:`/prefab/bindings/${ot}/sourceEntitySnapshots/${encodeJsonPointerSegment(it)}/childSourceEntityIds`,value:_t})}for(const _t of st){const yt=_e.entities[_t];if(!yt)continue;const bt=ct.get(_t)??_t,Et=encodeJsonPointerSegment(_t),St=`/prefab/bindings/${ot}/sourceToSceneEntity/${encodeJsonPointerSegment(bt)}`;rt.push({op:((ft=tt.sourceToSceneEntity)==null?void 0:ft[bt])===void 0?"add":"replace",path:St,value:_t});const At={};for(const[Ot,Nt]of Object.entries(yt.components))At[Ot]={sceneComponentId:Ot,type:Nt.type,...Nt.refId?{refId:Nt.refId}:{},...Nt.scriptKey?{scriptKey:Nt.scriptKey}:{},props:cloneState(Nt.props),...(pt=Nt.calls)!=null&&pt.length?{calls:cloneState(Nt.calls)}:{}};const xt=_t===nt?it:ct.get(yt.parentId??""),Ct=yt.parentId?((mt=_e.entities[yt.parentId])==null?void 0:mt.children)??[]:_e.scene.rootEntityIds,Pt=_t===nt?dt:Math.max(Ct.indexOf(_t),0),Tt=yt.children.map(Ot=>ct.get(Ot)).filter(Ot=>!!Ot),wt={sceneEntityId:_t,parentSourceEntityId:xt??null,childSourceEntityIds:Tt,childIndex:Pt,name:yt.name,isActive:yt.isActive,...yt.layer!==void 0?{layer:yt.layer}:{},...yt.isLocked!==void 0?{isLocked:yt.isLocked}:{},transform:cloneTransform(yt.transform),components:At},It=`/prefab/bindings/${ot}/sourceEntitySnapshots/${encodeJsonPointerSegment(bt)}`;rt.push({op:((vt=tt.sourceEntitySnapshots)==null?void 0:vt[bt])===void 0?"add":"replace",path:It,value:wt}),rt.push({op:yt.instance?"replace":"add",path:`/entities/${Et}/instance`,value:{bindingId:et,assetId:tt.assetId,assetKind:tt.assetKind,role:"linked",sourceEntityId:bt}});for(const[Ot,Nt]of Object.entries(yt.components)){const Mt=encodeJsonPointerSegment(Ot);rt.push({op:Nt.instance?"replace":"add",path:`/entities/${Et}/components/${Mt}/instance`,value:{bindingId:et,role:"linked",sourceComponentKey:Ot}})}}}function resolveSourceInsertionIndexForAddedEntity(rt,_e,tt,et,nt){var dt,ut,ht;const it=getSceneEntityIdForPrefabSource(_e,tt),at=it?((dt=rt.entities[it])==null?void 0:dt.children)??[]:rt.scene.rootEntityIds,ot=new Set(((ht=(ut=_e.sourceEntitySnapshots)==null?void 0:ut[tt])==null?void 0:ht.childSourceEntityIds)??[]);if(!ot.size)return 0;let st=0;const ct=at.includes(et)?at.indexOf(et):Math.min(Math.max(nt,0),at.length);for(let ft=0;ft<ct;ft+=1){const pt=at[ft],mt=getNormalizedSourceEntityIdFromBinding(rt,_e,pt);mt&&ot.has(mt)&&(st+=1)}return st}function getNormalizedSourceEntityIdFromBinding(rt,_e,tt){var nt;const et=rt.entities[tt];return(nt=et==null?void 0:et.instance)!=null&&nt.sourceEntityId?et.instance.sourceEntityId:getSourceEntityIdForPrefabScene(_e,tt)}function requireOverrideId(rt,_e){const tt=rt[_e];if(typeof tt=="string"&&tt.length>0)return tt;throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab.${rt.type} requires ${_e}`)}class RevertOverrideCommand{constructor(){Rt(this,"name","prefab.revertOverride")}execute(_e,tt){var ut,ht,ft,pt,mt,vt,_t;const{bindingId:et,type:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const at=[],ot=[],st=encodeJsonPointerSegment(et),ct=it.sourceEntitySnapshots??{},dt=normalizeDomainState(_e);switch(nt){case"entityProps":{const yt=tt.sourceEntityId,bt=encodeJsonPointerSegment(yt),Et=ct[yt],St=getSceneEntityIdForPrefabSource(it,yt),At=it.overrides.entityProps[yt];if(Et&&St&&At){const xt=encodeJsonPointerSegment(St),Ct={};At.name!==void 0&&(at.push({op:"replace",path:`/entities/${xt}/name`,value:Et.name}),Ct.name=Et.name),At.isActive!==void 0&&(at.push({op:"replace",path:`/entities/${xt}/isActive`,value:Et.isActive}),Ct.isActive=Et.isActive),At.layer!==void 0&&(Et.layer!==void 0?(at.push({op:"replace",path:`/entities/${xt}/layer`,value:Et.layer}),Ct.layer=Et.layer):((ut=_e.entities[St])==null?void 0:ut.layer)!==void 0&&at.push({op:"remove",path:`/entities/${xt}/layer`})),(ht=At.transform)!=null&&ht.position&&(at.push({op:"replace",path:`/entities/${xt}/transform/position`,value:cloneState(Et.transform.position)}),(Ct.transform??(Ct.transform={})).position=cloneState(Et.transform.position)),(ft=At.transform)!=null&&ft.rotation&&(at.push({op:"replace",path:`/entities/${xt}/transform/rotation`,value:cloneState(Et.transform.rotation)}),(Ct.transform??(Ct.transform={})).rotation=cloneState(Et.transform.rotation)),(pt=At.transform)!=null&&pt.scale&&(at.push({op:"replace",path:`/entities/${xt}/transform/scale`,value:cloneState(Et.transform.scale)}),(Ct.transform??(Ct.transform={})).scale=cloneState(Et.transform.scale)),Object.keys(Ct).length>0&&ot.push({type:"EntityUpdated",entityId:St??void 0,changes:Ct})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/entityProps/${bt}`}),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"entityProps",entityId:St??void 0,sourceEntityId:yt});break}case"addedEntities":{const yt=tt.entityId,bt=[],Et=Ct=>{bt.push(Ct);const Pt=_e.entities[Ct];if(Pt)for(const Tt of Pt.children)Et(Tt)};Et(yt);const St=_e.entities[yt],At=Object.fromEntries(bt.map(Ct=>[Ct,cloneState(_e.entities[Ct])]));if(St!=null&&St.parentId){const Ct=_e.entities[St.parentId],Pt=(Ct==null?void 0:Ct.children.indexOf(yt))??-1;Pt>=0&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(St.parentId)}/children/${Pt}`})}for(const Ct of bt){const Pt=encodeJsonPointerSegment(Ct);at.push({op:"remove",path:`/entities/${Pt}`}),it.overrides.addedEntities[Ct]&&at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedEntities/${Pt}`})}At[yt]&&ot.push({type:"EntityDeleted",entityId:yt,snapshot:At[yt],subtreeIds:cloneState(bt),subtree:At});const xt=it.overrides.addedEntities[yt];ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"addedEntities",entityId:yt,sourceEntityId:xt==null?void 0:xt.parentSourceEntityId});break}case"removedEntities":{const yt=tt.sourceEntityId,bt=ct[yt];if(!bt){at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(yt)}`});break}const Et=[],St=xt=>{var Ct,Pt;Et.push(xt);for(const Tt of((Ct=ct[xt])==null?void 0:Ct.childSourceEntityIds)??[])(it.overrides.removedEntities[Tt]||((Pt=ct[Tt])==null?void 0:Pt.parentSourceEntityId)===xt)&&St(Tt)};St(yt);const At=bt.parentSourceEntityId;if(At){const xt=getSceneEntityIdForPrefabSource(it,At);if(xt){const Ct=_e.entities[xt],Pt=Math.min(bt.childIndex,(Ct==null?void 0:Ct.children.length)??0);at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(xt)}/children/${Pt}`,value:bt.sceneEntityId})}}else{const xt=Math.min(bt.childIndex,_e.scene.rootEntityIds.length);at.push({op:"add",path:`/scene/rootEntityIds/${xt}`,value:bt.sceneEntityId})}for(const xt of Et){const Ct=ct[xt];if(!Ct)continue;const Pt=Ct.sceneEntityId,Tt=Ct.parentSourceEntityId?((mt=ct[Ct.parentSourceEntityId])==null?void 0:mt.sceneEntityId)??null:null,wt=Ct.childSourceEntityIds.map(Nt=>{var Mt;return(Mt=ct[Nt])==null?void 0:Mt.sceneEntityId}).filter(Nt=>!!Nt),It=Object.fromEntries(Object.entries(Ct.components).map(([Nt,Mt])=>{const Lt={type:Mt.type,props:cloneState(Mt.props),instance:{bindingId:et,role:"linked",sourceComponentKey:Nt}};return[Mt.sceneComponentId,Lt]})),Ot={id:Pt,name:Ct.name,isActive:Ct.isActive,parentId:Tt,children:wt,transform:cloneTransform(Ct.transform),components:It,...Ct.layer!==void 0?{layer:Ct.layer}:{},instance:{bindingId:et,assetId:it.assetId,assetKind:it.assetKind,role:xt===it.sourceRootEntityId?"root":"linked",sourceEntityId:xt}};at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(Pt)}`,value:Ot}),ot.push({type:"EntityCreated",entityId:Pt??void 0,parentId:Tt,index:Ct.childIndex,entity:cloneState(Ot)}),at.push({op:"add",path:`/prefab/bindings/${st}/sourceToSceneEntity/${encodeJsonPointerSegment(xt)}`,value:Pt}),it.overrides.removedEntities[xt]&&at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(xt)}`})}ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"removedEntities",entityId:bt.sceneEntityId,sourceEntityId:yt});break}case"componentProps":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=it.overrides.componentProps[yt],xt=At==null?void 0:At[bt],Ct=(vt=ct[yt])==null?void 0:vt.components[bt],Pt=getSceneEntityIdForPrefabSource(it,yt),Tt=Ct==null?void 0:Ct.sceneComponentId,wt=Pt&&Tt?getNormalizedComponent(dt,Pt,Tt):void 0;if(xt&&Pt&&Tt&&wt&&Ct){const It=encodeJsonPointerSegment(Pt),Ot=encodeJsonPointerSegment(Tt),Nt={};for(const Mt of Object.keys(xt)){const Lt=encodeJsonPointerSegment(Mt);Mt in Ct.props?(at.push({op:"replace",path:`/entities/${It}/components/${Ot}/props/${Lt}`,value:cloneState(Ct.props[Mt])}),Nt[Mt]=cloneState(Ct.props[Mt])):Mt in wt.props&&at.push({op:"remove",path:`/entities/${It}/components/${Ot}/props/${Lt}`})}Object.keys(Nt).length>0&&ot.push({type:"ComponentUpdated",entityId:Pt??void 0,componentId:Tt,changes:Nt})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/componentProps/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"componentProps",yt),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"componentProps",entityId:Pt??void 0,sourceEntityId:yt,componentId:bt});break}case"addedComponents":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=getSceneEntityIdForPrefabSource(it,yt),xt=At?toComponentStateSnapshot(getNormalizedComponent(dt,At,bt)):void 0;At&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(At)}/components/${St}`}),at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedComponents/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"addedComponents",yt),At&&xt&&ot.push({type:"ComponentRemoved",entityId:At??void 0,componentId:bt,snapshot:cloneState(xt)}),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"addedComponents",entityId:At??void 0,sourceEntityId:yt,componentId:bt});break}case"removedComponents":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=getSceneEntityIdForPrefabSource(it,yt),xt=(_t=ct[yt])==null?void 0:_t.components[bt];if(At&&xt){const Ct={type:xt.type,props:cloneState(xt.props),instance:{bindingId:et,role:"linked",sourceComponentKey:bt}};at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(xt.sceneComponentId)}`,value:Ct}),ot.push({type:"ComponentAdded",entityId:At??void 0,componentId:xt.sceneComponentId,component:cloneState(Ct)})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedComponents/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"removedComponents",yt),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"removedComponents",entityId:At??void 0,sourceEntityId:yt,componentId:bt});break}}return{operations:at,result:void 0,events:ot}}}class AcceptOverrideCommand{constructor(){Rt(this,"name","prefab.acceptOverride")}execute(_e,tt){var ct,dt,ut;const{bindingId:et,type:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const at=[],ot=[],st=encodeJsonPointerSegment(et);switch(nt){case"entityProps":{const ht=requireOverrideId(tt,"sourceEntityId");if(!it.overrides.entityProps[ht])break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/entityProps/${encodeJsonPointerSegment(ht)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"entityProps",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht});break}case"componentProps":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((ct=it.overrides.componentProps[ht])!=null&&ct[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/componentProps/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"componentProps",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"componentProps",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}case"removedEntities":{const ht=requireOverrideId(tt,"sourceEntityId");if(!it.overrides.removedEntities[ht])break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(ht)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"removedEntities",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht});break}case"removedComponents":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((dt=it.overrides.removedComponents[ht])!=null&&dt[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedComponents/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"removedComponents",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"removedComponents",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}case"addedEntities":{const ht=requireOverrideId(tt,"entityId"),ft=it.overrides.addedEntities[ht];if(!ft)break;const pt=collectSubtree(_e,ht);pushAcceptedAddedEntityPromotionOps(at,_e,it,et,ht,ft.parentSourceEntityId,ft.index);for(const mt of pt){const vt=it.overrides.addedEntities[mt];vt&&(at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedEntities/${encodeJsonPointerSegment(mt)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"addedEntities",entityId:mt,sourceEntityId:vt.parentSourceEntityId}))}break}case"addedComponents":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((ut=it.overrides.addedComponents[ht])!=null&&ut[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedComponents/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"addedComponents",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"addedComponents",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}}return{operations:at,result:void 0,events:ot}}}class RebaseInstancesCommand{constructor(){Rt(this,"name","prefab.rebaseInstances")}execute(_e,tt){const{assetId:et,newRevision:nt}=tt,it=_e.prefab.byAssetId[et];if(!it||it.length===0)return{operations:[],result:void 0,events:[]};const at=[],ot=[];for(const st of it){const ct=_e.prefab.bindings[st];if(!ct)continue;const dt=encodeJsonPointerSegment(st);at.push({op:"replace",path:`/prefab/bindings/${dt}/sourceRevision`,value:nt}),ot.push({type:"PrefabBindingRebased",bindingId:st,assetId:et,previousRevision:ct.sourceRevision,sourceRevision:nt})}return{operations:at,result:void 0,events:ot}}}class PrefabFacade{constructor(_e){Rt(this,"instantiateCmd",new InstantiatePrefabCommand);Rt(this,"bindExistingInstanceCmd",new BindExistingPrefabInstanceCommand);Rt(this,"updateBindingSourceBaselineCmd",new UpdatePrefabBindingSourceBaselineCommand);Rt(this,"unpackCmd",new UnpackInstanceCommand);Rt(this,"unpackByAssetCmd",new UnpackByAssetCommand);Rt(this,"setEntityOverrideCmd",new SetEntityOverrideCommand);Rt(this,"setComponentOverrideCmd",new SetComponentOverrideCommand);Rt(this,"addEntityOverrideCmd",new AddEntityOverrideCommand);Rt(this,"addExistingEntityOverrideCmd",new AddExistingEntityOverrideCommand);Rt(this,"removeSourceEntityOverrideCmd",new RemoveSourceEntityOverrideCommand);Rt(this,"addComponentOverrideCmd",new AddComponentOverrideCommand);Rt(this,"updateAddedComponentOverrideCmd",new UpdateAddedComponentOverrideCommand);Rt(this,"removeSourceComponentOverrideCmd",new RemoveSourceComponentOverrideCommand);Rt(this,"revertOverrideCmd",new RevertOverrideCommand);Rt(this,"acceptOverrideCmd",new AcceptOverrideCommand);Rt(this,"rebaseInstancesCmd",new RebaseInstancesCommand);Rt(this,"_logger");this.root=_e,this._logger=_e.createLogger("PrefabFacade")}persistScene(){var _e,tt;(_e=this.root.domainStore)!=null&&_e.isHistoryPaused||(tt=this.root.projectStore)==null||tt.persistSceneDebounced("PrefabFacade")}get state(){return this.root.domainStore.state}getPrefabStateForSerialization(){var nt,it,at;const _e=this.root.domainStore.state.prefab;if(!_e||Object.keys(_e.bindings).length===0)return null;const tt=this.root.domainStore.state.entities,et={bindings:{},byAssetId:{}};for(const[ot,st]of Object.entries(_e.bindings)){const ct=tt[st.instanceRootEntityId];((nt=ct==null?void 0:ct.instance)==null?void 0:nt.bindingId)===ot&&(et.bindings[ot]=structuredClone(st))}for(const ot of Object.values(et.bindings))for(const st of Object.keys(ot.overrides.addedEntities??{}))tt[st]||delete ot.overrides.addedEntities[st];for(const[ot,st]of Object.entries(et.bindings)){const ct=(it=et.byAssetId)[at=st.assetId]??(it[at]=[]);ct.includes(ot)||ct.push(ot)}return Object.keys(et.bindings).length===0?null:et}instantiate(_e){var st;const tt=_e.bindingId??`binding-${v4().slice(0,8)}`,et=_e.assetId,nt=_e.parentId??null,it=this.buildInstantiateEntities(_e.sourceEntities,tt,et),at=((st=it[0])==null?void 0:st.id)??"",ot={assetId:et,bindingId:tt,parentId:nt,rootTransform:_e.rootTransform,entities:it};return this.root.commandBus.execute(this.instantiateCmd,ot,"prefab.instantiate"),this.persistScene(),{bindingId:tt,rootEntityId:at}}instantiateFromSchema(_e){const tt=_e.schemas.map(et=>({sourceEntityId:et.sourceEntityId,name:et.name,parentSourceId:et.parentSourceId??null,transform:et.transform,components:et.components}));return this.instantiate({assetId:_e.assetId,parentId:_e.parentId??null,bindingId:_e.bindingId,rootTransform:_e.rootTransform,sourceEntities:tt})}bindExistingInstance(_e){const tt=_e.bindingId??`binding-${v4().slice(0,8)}`,et={assetId:_e.assetId,assetKind:_e.assetKind,bindingId:tt,instanceRootEntityId:_e.instanceRootEntityId,sourceRevision:_e.sourceRevision,entityMappings:_e.entityMappings,componentMappings:_e.componentMappings,sourceEntitySnapshots:_e.sourceEntitySnapshots};if(_e.undoable)this.root.commandBus.execute(this.bindExistingInstanceCmd,et,"prefab.bindExistingInstance");else{const nt=this.bindExistingInstanceCmd.execute(this.root.domainStore.state,et);this.root.domainStore.applySystem(nt.operations)}return this.persistScene(),tt}updateBindingSourceBaseline(_e){const tt=this.updateBindingSourceBaselineCmd.execute(this.root.domainStore.state,_e);this.root.domainStore.applySystem(tt.operations)}unpack(_e,tt){this.root.commandBus.execute(this.unpackCmd,{bindingId:_e,replacementRootInstance:tt==null?void 0:tt.replacementRootInstance},"prefab.unpack"),this.persistScene()}unpackByAsset(_e){this.root.commandBus.execute(this.unpackByAssetCmd,{assetId:_e},"prefab.unpackByAsset"),this.persistScene()}setEntityOverride(_e,tt){this.root.commandBus.execute(this.setEntityOverrideCmd,{entityId:_e,overrides:tt},"prefab.setEntityOverride"),this.persistScene()}setComponentOverride(_e,tt,et){this.root.commandBus.execute(this.setComponentOverrideCmd,{entityId:_e,componentId:tt,overrides:et},"prefab.setComponentOverride"),this.persistScene()}addEntityOverride(_e,tt){const et=tt.entityId??`entity-${v4().slice(0,8)}`;return this.root.commandBus.execute(this.addEntityOverrideCmd,{bindingId:_e,entityId:et,name:tt.name,parentSourceEntityId:tt.parentSourceEntityId,parentSceneEntityId:tt.parentSceneEntityId,index:tt.index??0,transform:tt.transform,components:tt.components},"prefab.addEntityOverride"),this.persistScene(),et}addExistingEntityOverride(_e,tt,et){this.root.commandBus.execute(this.addExistingEntityOverrideCmd,{bindingId:_e,entityId:tt.entityId,parentSourceEntityId:tt.parentSourceEntityId,parentSceneEntityId:tt.parentSceneEntityId,index:tt.index??0},"prefab.addExistingEntityOverride"),(et==null?void 0:et.persist)!==!1&&this.persistScene()}removeSourceEntityForSceneEntity(_e){this.root.commandBus.execute(this.removeSourceEntityOverrideCmd,{entityId:_e},"prefab.removeSourceEntityOverride"),this.persistScene()}addComponentOverride(_e,tt){const et=tt.componentId??`comp-${v4().slice(0,8)}`;return this.root.commandBus.execute(this.addComponentOverrideCmd,{entityId:_e,componentId:et,type:tt.type,refId:tt.refId,scriptKey:tt.scriptKey,props:tt.props??{},calls:tt.calls},"prefab.addComponentOverride"),this.persistScene(),et}updateAddedComponentOverride(_e,tt,et){this.root.commandBus.execute(this.updateAddedComponentOverrideCmd,{entityId:_e,componentId:tt,overrides:et},"prefab.updateAddedComponentOverride"),this.persistScene()}removeSourceComponent(_e,tt){this.root.commandBus.execute(this.removeSourceComponentOverrideCmd,{entityId:_e,componentId:tt},"prefab.removeSourceComponentOverride"),this.persistScene()}revertOverride(_e,tt,et){this.root.commandBus.execute(this.revertOverrideCmd,{bindingId:_e,type:tt,...et},"prefab.revertOverride"),this.persistScene()}acceptOverride(_e,tt,et){this.root.commandBus.execute(this.acceptOverrideCmd,{bindingId:_e,type:tt,...et},"prefab.acceptOverride"),this.persistScene()}updatePrefabContent(_e,tt){const et=this.rebaseInstancesCmd.execute(this.root.domainStore.state,{assetId:_e,newRevision:tt});this.root.domainStore.applySystem(et.operations),this.persistScene()}buildInstantiateEntities(_e,tt,et){const nt=new Map;for(const it of _e)nt.set(it.sourceEntityId,`entity-${v4().slice(0,8)}`);return _e.map(it=>{var ct;const at=nt.get(it.sourceEntityId),ot=it.parentSourceId!==null?nt.get(it.parentSourceId)??null:null,st=(ct=it.components)==null?void 0:ct.map(dt=>({id:`comp-${v4().slice(0,8)}`,type:dt.type,props:dt.props??{},sourceComponentKey:dt.sourceComponentKey}));return{id:at,name:it.name,parentId:ot,sourceEntityId:it.sourceEntityId,transform:it.transform,components:st}})}}function collectCreateByAddResumeCandidates(rt){if(rt.commandName!=="redo:asset.create")return[];const _e=[],tt=new Set;for(const et of rt.operations){if(et.op!=="add")continue;const nt=et.path.match(/^\/assets\/([^/]+)$/);if(!nt)continue;const it=nt[1];if(tt.has(it))continue;const at=rt.assets[it];at&&at.status==="uploading"&&(typeof at.stagingRef!="string"||!at.stagingRef.startsWith("local/")||at.serverId||at.url||(tt.add(it),_e.push(it)))}return _e}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/**
|
|
710
|
+
サポートされているブラウザに切り替えてください。`,"unsupported-confirm":"OK","open-in-ide":"IDEで開く",unbind:"ワークスペースのリンクを解除","unbind-confirm-title":"ローカルワークスペースのリンクを解除","unbind-confirm-description":"ローカルワークスペースのリンクを解除し、同期キャッシュをクリアします。既にローカルフォルダに同期されたファイルは削除されません。","unbind-current-path":"リンク先: {{0}}"},"sprite-atlas":{title:"スプライトアトラス",adding:"追加中",success:"成功",error:"スプライトの追加に失敗しました"},"tree-shaking":{tip:"ツリーシェイキングは、プロジェクトファイルのサイズを削減するための効果的な機能です。パッケージング中にプロジェクトから不要なアセットをインテリジェントに削除することができます。",default:{title:"デフォルト",desc:"ツリーシェイキングなし。"},"current-scene":{title:"現在のシーン",desc:"現在のシーンのみツリーシェイクします。"},"all-scene":{title:"すべてのシーン",desc:"すべてのシーンをツリーシェイクします。"},title:"ツリーシェイキング"},"primitive-mesh":{title:"プリミティブメッシュ",type:{label:"タイプ",info:"作成するプリミティブメッシュのタイプ"},sphere:{radius:{label:"半径",info:"球体の半径"},step:{label:"ステップ",info:"球体を構築するために使用されるセグメントの数"}},capsule:{radius:{label:"半径",info:"カプセルの半径"},height:{label:"高さ",info:"カプセルの高さ"},"radial-segments":{label:"ラジアルセグメント",info:"カプセルの円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"カプセルの高さに沿ったセグメント数"}},cone:{radius:{label:"半径",info:"円錐の底面の半径"},height:{label:"高さ",info:"円錐の高さ"},"radial-segments":{label:"ラジアルセグメント",info:"円錐の円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"円錐の高さに沿ったセグメント数"}},cuboid:{width:{label:"幅",info:"直方体の幅"},height:{label:"高さ",info:"直方体の高さ"},depth:{label:"深さ",info:"直方体の深さ"}},cylinder:{"radius-top":{label:"上部半径",info:"円柱の上部の半径"},"radius-bottom":{label:"底部半径",info:"円柱の底部の半径"},height:{label:"高さ",info:"円柱の高さ"},"radial-segments":{label:"ラジアルセグメント",info:"円柱の円周を囲むセグメント数"},"height-segments":{label:"高さセグメント",info:"円柱の高さに沿ったセグメント数"}},plane:{width:{label:"幅",info:"平面の幅"},height:{label:"高さ",info:"平面の高さ"},"horizontal-segments":{label:"水平セグメント",info:"平面の幅に沿ったセグメント数"},"vertical-segments":{label:"垂直セグメント",info:"平面の高さに沿ったセグメント数"}},torus:{radius:{label:"半径",info:"トーラスの中心からチューブの中心への半径"},"tube-radius":{label:"チューブ半径",info:"トーラスのチューブの半径"},"radial-segments":{label:"ラジアルセグメント",info:"トーラスの円周を囲むセグメント数"},"tubular-segments":{label:"チューブラーセグメント",info:"チューブを囲むセグメント数"},arc:{label:"アーク",info:"トーラスセクションの中心角"}}},gltf:{title:"GlTF","basic-info":"基本情報",triangles:"三角形",drawcall:"ドローコール","compute-tangents":"タンジェントを計算","keep-mesh-data":"メッシュデータを保持","refresh-tip":"リフレッシュ後に有効",issues:"問題","remapped-materials":"再マッピングされた材料",compression:"圧縮",quantize:"量子化",meshopt:"メッシュオプティマイズ"},"select-asset":"アセットを選択...",filter:{all:"すべて"},folder:{title:"フォルダー"},shader:{title:"シェーダー"},material:{title:"材料"},script:{title:"スクリプト"},font:{title:"フォント"},"texture-cube":{title:"TextureCube"},"ambient-light":{title:"環境光"},"directional-light":{title:"指向性ライト"},"point-light":{title:"ポイントライト"},"spot-light":{title:"スポットライト"},sprite:{title:"スプライト"},"xr-reference-image":{title:"XRリファレンスイメージ"},"animator-controller":{title:"アニメーターコントローラー"},"animation-clip":{title:"アニメーションクリップ"},scene:{title:"シーン"},"physics-material":{title:"物理素材"},"render-target":{title:"レンダーターゲット"},"entity-script":{title:"エンティティスクリプト"},"state-machine-script":{title:"ステートマシンスクリプト"},"shader-chunk":{title:"シェーダーチャンク"},"shader-ui-script":{title:"シェーダーUIScript"},prefab:{title:"プレハブ"},audio:{title:"オーディオ"},mesh:{title:"メッシュ"},lottie:{title:"Lottie"},"spine-skeleton-data":{title:"Spineスケルトンデータ"},"spine-atlas":{title:"アトラス"},ktx2:{mode:{label:"モード",uastc:{label:"UASTC",desc:"UASTCはより良い品質を提供しますが、ファイルサイズが大きくなります"},etc1s:{label:"ETC1S",desc:"ETC1Sはより良い圧縮を提供しますが、品質が低くなります"}},quality:"品質"}},transform$2={position:{title:"位置",info:"3D空間内のエンティティの位置"},rotation:{title:"回転",info:"3D空間内のエンティティの回転角度"},scale:{title:"スケール",info:"3D空間内のエンティティのスケールファクター"},error:{"cant-disable":"トランスフォームコンポーネントを無効にできません","cant-delete":"トランスフォームコンポーネントを削除できません"}},light={color:"色","culling-mask":"カリングマスク",point:{distance:{label:"距離",info:"ポイントライトが照らす最大距離"}},shadow:{title:"影",type:{label:"タイプ",info:"影のタイプ",none:"なし",hard:"ハード",softlow:"ソフト低",softhigh:"ソフト高"},bias:{label:"バイアス",info:"影のアクネを防ぐための影バイアス"},"normal-bias":{label:"ノーマルバイアス",info:"影のアクネを防ぐためのノーマルバイアス"},"near-plane-offset":{label:"近クリップ面オフセット",info:"影の近クリップ面のオフセット"},strength:{label:"強度",info:"影の強度"}},spot:{distance:{label:"距離",info:"スポットライトが照らす最大距離"},angle:{label:"角度",info:"スポットライトの円錐の角度"},penumbra:{label:"ペンブラス",info:"スポットライトのペンブラス角度"}}},prefab={inspector:{"basic-info":"基本情報","dependent-assets":"依存アセット",url:"URL",missed:"失敗"},error:{"create-from-sub":"プレハブサブエンティティからプレハブを作成できません。"},delete:{title:"プレハブインスタンスを削除しますか?",description:"プレハブ '{{name}}' が削除されました。すべてのインスタンスを削除しますか?"},button:{no:"いいえ",yes:"はい"},replace:{title:"プレハブを置き換える",description:'プレハブ "{{name}}" を置き換えてもよろしいですか?すべてのプレハブインスタンスが置き換えられます',confirm:"それでも置き換える"}},community={title:"コミュニティ","all-projects":"すべてのプロジェクト","my-projects":"マイプロジェクト","all-projects-desc":"コミュニティで共有されているプロジェクトを探索","my-projects-desc":"コミュニティに公開したプロジェクト","search-placeholder":"コミュニティプロジェクトを検索...","no-projects":"コミュニティプロジェクトが見つかりません","no-my-projects":"まだプロジェクトを公開していません","publish-hint":"最初のプロジェクトを公開してコミュニティと共有しましょう","load-more":"さらに読み込む",loading:"読み込み中...","no-preview":"プレビューが利用できません",preview:"プレビュー",share:"共有",withdraw:"撤回",tags:"タグ",license:"ライセンス",stats:"統計",copyright:"著作権",views:"閲覧数",likes:"いいね",downloads:"ダウンロード","publish-success":"レビュー待ちに提出しました",publish:{title:"コミュニティに公開","published-at":"公開日","publish-button":"公開",agreement:"公開をクリックすることで、","more-options":"その他のオプション","community-guidelines":"コミュニティガイドライン"}},resourcePackage={export:"リソースパッケージとしてエクスポート",import:"リソースパッケージをインポート",exporting:"リソースパッケージをエクスポート中...",importing:"リソースパッケージをインポート中...","export-success":"リソースパッケージのエクスポートに成功しました","export-failed":"リソースパッケージのエクスポートに失敗しました","import-success":"リソースパッケージのインポートに成功しました","import-failed":"リソースパッケージのインポートに失敗しました","no-assets-selected":"エクスポートするアセットを選択してください","cant-export-sub-asset":"サブアセットはエクスポートできません",assets:"個のアセット"},ja$1={service,"code-editor":{"back-to-editor":"シーンエディターに戻る",preview:"プレビュー",devtools:{console:"コンソール",inspector:"インスペクター"},file:{"not-saved":"ファイルは保存されていません。","not-saved-description":"変更を破棄してもよろしいですか?保存されていない変更はすべて失われます。",cancel:"キャンセル",confirm:"確認",project:"プロジェクト"},"event-debug":{input:"入力",json:"JSON",clear:"クリア",confirm:"確認",events:"イベント",trigger:"トリガー","no-events":"プレビューからイベント信号を検出できません。"},"file-tree":{title:"アセット",search:{placeholder:"ファイルを検索..."}},library:{title:"依存関係",import:"インポート",search:{placeholder:"ライブラリ名"},version:{latest:"最新",updating:"更新中..."}},menubar:{file:{title:"ファイル","new-file":"新しいファイル","open-file":"ファイルを開く",save:"保存",close:"閉じる"},edit:{title:"編集",undo:"元に戻す",redo:"やり直す",find:{title:"検索...",find:"検索",replace:"置換"},cut:"切り取り",copy:"コピー",paste:"貼り付け"},view:{title:"表示","show-minimap":"ミニマップを表示","new-tab":"新しいタブ","close-tab":"タブを閉じる",share:"共有",print:"印刷"},help:{title:"ヘルプ",documentation:"ドキュメント","shader-syntax":"Shader構文",about:"について"}},monaco:{loading:"読み込み中..."},"preview-inspector":{title:"インスペクター"},"preview-toolbar":{"open-in-new-tab":"新しいタブで開く","toggle-orientation":"向きを切り替える","toggle-lock":"ロックを切り替える",refresh:"更新",close:"閉じる"}},shortcuts,project,member,setting,snapshot,export:{"copied-to-clipboard":"クリップボードにコピーしました",auto:"自動","playing-options":{title:"プレイオプション","loading-ui":"ローディングUI","orbit-control":"軌道制御",enable:"有効",disabled:"無効"},"main-scene":"メインシーン",default:"デフォルト","current-scene":"現在のシーン","all-scene":"すべてのシーン",fixed:"固定","required-external-components":"必要な外部コンポーネント",rendering:"レンダリング","webgl-mode":"WebGLモード",alpha:"アルファを使用","preserve-drawing-buffer":"描画バッファを保存",dpr:{label:"デバイスピクセル比モード",fixed:"固定",auto:"自動"},update:"更新",publish:"公開","publish-success":{title:"公開成功",description:"おめでとうございます!初回プロジェクトの公開が完了しました。他の人と共有できるようになりました。","got-it":"了解"},"public-url-generated":"公開URLが生成されました","download-project-json":"Project.jsonをダウンロード","update-public-url":"公開URLを更新","generate-public-url":"公開URLを生成","platform-setting":"プラットフォーム設定","copy-url":"URLをコピー",scenes:"シーン",download:"ダウンロード",orientation:"向き",portrait:"縦向き",landscape:"横向き","network-timeout":"ネットワークタイムアウト",request:"リクエスト","connect-socket":"ソケットに接続","upload-file":"ファイルをアップロード","download-file":"ファイルをダウンロード","web-project":"Webプロジェクト",vanilla:"Vanilla JS",react:"React",vue:"Vue",framework:"フレームワーク","package-to-zip":"Zipにパッケージ","public-url-publish":"Webに公開","export-as-react-project":"Reactプロジェクトとしてエクスポート","export-as-vue-project":"Vueプロジェクトとしてエクスポート","public-url":"公開URL","shader-and-publish":"シェーダーと公開","wechat-mini-game":"Wechatミニゲーム","publish-to-wechat":"Wechatに公開","tiktok-mini-game":"TikTokミニゲーム","publish-to-tiktok":"TikTokに公開","project-url":"プロジェクトURLを取得","subpackage-setting":"サブパッケージリスト","subpackage-list":"サブパッケージリスト","subpackage-add":"サブパッケージを追加","subpackage-index":"サブパッケージ","subpackage-empty":"リストは空です","subpackage-folder":"サブパッケージディレクトリ","subpackage-holder":"サブパッケージとしてディレクトリを選択","subpackage-info":"選択したディレクトリはサブパッケージとして使用されます。このディレクトリ内のスクリプト以外のすべてのアセットはサブパッケージにエクスポートされます","subpackage-conflict":"既存のサブパッケージと競合します。競合するサブパッケージは次のとおりです: サブパッケージ "},plugin,hierarchy,inspector,menu,viewport:viewport$1,effects,trail,texture,ui:ui$1,xr,homepage,user,layout,sandbox,entity,component,"skinned-mesh-renderer":{title:"スキンメッシュレンダラー","local-bounds":{title:"ローカル境界",info:"スキンドスケルタルレンダラーのローカル空間境界ボックス",min:{label:"最小",info:"ローカル境界ボックスの最小点"},max:{label:"最大",info:"ローカル境界ボックスの最大点"}},skin:{title:"スキン","root-bone":{label:"ルートボーン",info:"スキンメッシュレンダラーのルートボーン"},bones:{label:"ボーン",info:"ボーンの数"}}},"mesh-renderer":{material:{title:"材料",info:"メッシュレンダラーが使用する材料",thumbnail:"材料サムネイル"},mesh:{title:"メッシュ",info:"レンダリングするメッシュ"},"receive-shadows":{title:"影を受け取る",info:"メッシュが影を受け取るかどうか"},"cast-shadows":{title:"影を投げる",info:"メッシュが影を投げるかどうか"},priority:{title:"優先度",info:"レンダリングの優先度"}},script,scene,"post-process":{global:{title:"グローバル",info:"ポストプロセスがグローバルであるかどうかを示します。ローカルモードはコライダーコンポーネントと一緒に使用する必要があります。"},"blend-distance":{title:"ブレンド距離",info:"ブレンドを開始する外部距離。"},priority:{title:"優先度",info:"ポストプロセスがシーンに等しい影響度を持つ場合、どのポストプロセスが使用されるかを決定します。"},layer:{title:"レイヤー",info:"ポストプロセスが属するレイヤーで、カメラのポストプロセスマスクと一緒に使用できます"},effects:{options:{half:"半分",quarter:"四分の一",neutral:"ニュートラル",aces:"ACES(アカデミーカラーエンコーディングシステム)"},bloom:{title:"ブルーム","high-quality-filtering":{label:"高品質フィルタリング",info:"高品質フィルタリングを有効にする"},scatter:{label:"スキャッター",info:"ブルームエフェクトの半径を設定します"},"down-scale":{label:"ダウンスケール",info:"このエフェクトが処理を開始する解像度を制御します"},threshold:{label:"しきい値",info:"この明るさレベル以下のピクセルをフィルタリングします。値はガンマ空間で指定されます"},intensity:{label:"強度",info:"ブルームエフェクトの強さ"},tint:{label:"色調",info:"ブルームエフェクトの色調"},"dirt-texture":{label:"汚れのテクスチャ",info:"ブルームエフェクトに汚れやほこりを追加する汚れのテクスチャ"},"dirt-intensity":{label:"汚れの強度",info:"汚れのテクスチャの強さ"}},"tone-mapping":{title:"トーンマッピング",mode:{label:"モード",info:"トーンマッピングモード、`Neutral`モードは、色相と彩度への影響を最小限に抑えながら範囲リマッピングだけを希望する状況に特に適しています。`ACES`モードは長編映画用のACES参照カラー空間を使用し、シネマティックでコントラストのある結果を生み出しますが、より多くのパフォーマンスが必要です"}},title:"ポストエフェクト",add:"エフェクトを追加"}},camera,physics,shader,sprite,"text-renderer":{text:{label:"テキスト",info:"表示するテキストコンテンツ"},color:{label:"色",info:"テキストの色"},"font-size":{label:"フォントサイズ",info:"テキストフォントのサイズ"},font:{label:"フォント",info:"テキストのレンダリングに使用するフォントアセット"},width:{label:"幅",info:"テキストレンダラーの幅"},height:{label:"高さ",info:"テキストレンダラーの高さ"},"line-spacing":{label:"行間隔",info:"テキストの行間隔"},"font-style":{label:"フォントスタイル",info:"フォントのスタイル(太字、イタリック)"},"horizontal-alignment":{label:"水平配置",info:"テキストの水平配置"},"vertical-alignment":{label:"垂直配置",info:"テキストの垂直配置"},"enable-wrapping":{label:"折り返しを有効にする",info:"テキストの折り返しを有効にするかどうか"},"overflow-mode":{label:"オーバーフローモード",info:"コンテナをオーバーフローするテキストをどのように処理するか",overflow:"オーバーフロー",truncate:"切り詰め"},"mask-interaction":{label:"マスクとの相互作用",info:"このテキストレンダラーがスプライトマスクとどのように相互作用するか",none:"なし","visible-inside":"マスク内で可視","visible-outside":"マスク外で可視"},"mask-layer":{label:"マスクレイヤー",info:"このテキストレンダラーが属するマスクレイヤー",everything:"すべて",nothing:"なし",layer0:"レイヤー0",layer1:"レイヤー1",layer2:"レイヤー2",layer3:"レイヤー3",layer4:"レイヤー4",layer5:"レイヤー5",layer6:"レイヤー6",layer7:"レイヤー7",layer8:"レイヤー8"},priority:{label:"優先度",info:"テキストレンダラーのレンダリング優先度"}},lottie,spine,animation,asset:asset$1,transform:transform$2,light,prefab,"ai-panel":{"remaining-times":"残りの回数","image-to-3d":"画像から3Dモデルを生成","upload-description":"画像をアップロードして3Dモデルを生成","ai-generated":"すべてのモデルはAIによって生成されました",retry:"再試行",view:"表示",generate:"生成",upload:{error:"PNG、JPG、JPEGファイルのみサポートされています。","drag-drop":"画像をドラッグまたはクリックしてアップロード","supported-formats":"サポートされているフォーマット:PNG、JPG、JPEG"},pagination:{previous:"前へ",next:"次へ","page-info":"ページ {{current}} / {{total}}"},history:"履歴","generate-error":"モデルの生成に失敗しました,しばらくしてから再試行してください",use:"使用","add-success":"資産パネルに正常に追加されました","add-error":"追加に失敗しました。しばらくしてから再試行してください","fetch-error":"モデルリストの読み込みに失敗しました。しばらくしてから再試行してください",waiting:"{{queuePosition}} 人待っています",executing:"実行中",result:"結果",thinking:"思考中","todo-update":"タスク更新","todo-step":"{{count}} ステップ","tool-calls":"{{count}} 件のツール呼び出し","searching-editor-tools":"エディタツールを検索中","searching-skills":"スキルを検索中",knowledge:"ナレッジ検索","searching-knowledge":"ナレッジを検索","loading-knowledge":"ナレッジを読み込み","reading-knowledge":"ナレッジを読み取り","listing-knowledge":"ナレッジ一覧","loading-skill":"スキルを読み込み中","reading-skill-file":"スキルファイルを読み取り中","listing-skills":"スキル一覧を取得中","reading-file":"ファイルを読み取り中","listing-files":"ファイル一覧を取得中","searching-files":"ファイルを検索中","finding-files":"ファイルを検索中","editing-scene":"シーンを編集中","searching-assets":"アセットを検索中","execution-failed":"実行に失敗しました","tool-not-found":'AIが存在しないツール"{{toolId}}"を呼び出そうとしました。このツールはeditorDispatch経由で呼び出す必要があります。もう一度お試しください。'},community,resourcePackage,"local-ide-config":{title:"ローカル IDE で開く",description:"ブラウザのセキュリティ制限により、エディターはローカルフォルダーのパスを自動取得できません。選択したワークスペースのルートパスを手動で入力してください。この設定は一度だけ必要です。","workspace-path-label":"ワークスペースのルートパス","workspace-path-placeholder":"例: /Users/you/galacean-workspace または C:\\Users\\you\\galacean-workspace","ide-label":"エディタ",hint:"保存後、スクリプトまたはシェーダーアセットをダブルクリックするとローカル IDE でファイルが開きます。設定が誤っている、または IDE が開かない場合は、「プロジェクト設定」からいつでも変更できます。",test:"テスト",save:"保存","section-title":"ローカルパス","workspace-path-hint":"このパスの下にプロジェクトフォルダを作成します","status-configured":"{{0}} · {{1}}","status-not-configured":"未設定",configure:"設定","validation-empty":"パスを入力してください","validation-tilde":"~ は使用しないでください。完全な絶対パスを入力してください。例: /Users/<ユーザー名>/...","validation-not-absolute":"絶対パスで入力してください(macOS は / で始まる、Windows はドライブレターで始まる)","validation-illegal-chars":'パスに不正な文字 < > " | ? * が含まれています — 引用符や特殊文字を入力していないか確認してください',"validation-embedded-url":"パスのみ入力してください。vscode:// / file:// / https:// などのプロトコルを含めないでください","validation-embedded-newline":"パスに改行やタブが含まれています — クリーンアップしてから再度貼り付けてください","validation-parent-segment":"パスに .. や . を含めないでください — 完全な実パスを入力してください","validation-no-binding":"先にローカルワークスペースをバインドしてから IDE パスを設定してください","validation-tail-mismatch":"パスの末尾はバインド済みのワークスペースディレクトリ「{{0}}」である必要があります"}},localStorageLanguage="__language__";instance.use(initReactI18next).init({resources:{en:{translation:en},zh:{translation:zh$1},ja:{translation:ja$1}},lng:typeof localStorage<"u"?localStorage.getItem(localStorageLanguage):void 0,fallbackLng:"en",interpolation:{escapeValue:!1}});const{t:t$7}=instance;let editorUiModulePromise=null;function loadEditorUiModule(){return editorUiModulePromise??(editorUiModulePromise=__vitePreload(()=>import("./index-b4bde36a.js"),["_static/index-b4bde36a.js","_static/index-f7bd6fef.js","_static/Menu-05c1f0a4.js","_static/Accordion-f938dadf.js","_static/Callout-48e71f13.js","_static/Tooltip-71e5a4e7.js"])),editorUiModulePromise}function runFireAndForgetEditorUi(rt){loadEditorUiModule().then(rt).catch(_e=>{console.error("[editorUiFeedback] failed to load editor UI module",_e)})}function showEditorUiAlert(rt){runFireAndForgetEditorUi(({showAlert:_e})=>{_e(rt)})}function showEditorUiToastSuccess(rt){runFireAndForgetEditorUi(({toast:_e})=>{_e.success(rt)})}function showEditorUiToastError(rt){runFireAndForgetEditorUi(({toast:_e})=>{_e.error(rt)})}async function runWithEditorUiToastPromise(rt,_e){const{toast:tt}=await loadEditorUiModule();return tt.promise(rt,_e)}function showComponentAlert(rt){showEditorUiAlert(rt)}function showComponentToastError(rt){showEditorUiToastError(rt)}var eventemitter3={exports:{}};(function(rt){var _e=Object.prototype.hasOwnProperty,tt="~";function et(){}Object.create&&(et.prototype=Object.create(null),new et().__proto__||(tt=!1));function nt(st,ct,dt){this.fn=st,this.context=ct,this.once=dt||!1}function it(st,ct,dt,ut,ht){if(typeof dt!="function")throw new TypeError("The listener must be a function");var ft=new nt(dt,ut||st,ht),pt=tt?tt+ct:ct;return st._events[pt]?st._events[pt].fn?st._events[pt]=[st._events[pt],ft]:st._events[pt].push(ft):(st._events[pt]=ft,st._eventsCount++),st}function at(st,ct){--st._eventsCount===0?st._events=new et:delete st._events[ct]}function ot(){this._events=new et,this._eventsCount=0}ot.prototype.eventNames=function(){var ct=[],dt,ut;if(this._eventsCount===0)return ct;for(ut in dt=this._events)_e.call(dt,ut)&&ct.push(tt?ut.slice(1):ut);return Object.getOwnPropertySymbols?ct.concat(Object.getOwnPropertySymbols(dt)):ct},ot.prototype.listeners=function(ct){var dt=tt?tt+ct:ct,ut=this._events[dt];if(!ut)return[];if(ut.fn)return[ut.fn];for(var ht=0,ft=ut.length,pt=new Array(ft);ht<ft;ht++)pt[ht]=ut[ht].fn;return pt},ot.prototype.listenerCount=function(ct){var dt=tt?tt+ct:ct,ut=this._events[dt];return ut?ut.fn?1:ut.length:0},ot.prototype.emit=function(ct,dt,ut,ht,ft,pt){var mt=tt?tt+ct:ct;if(!this._events[mt])return!1;var vt=this._events[mt],_t=arguments.length,yt,bt;if(vt.fn){switch(vt.once&&this.removeListener(ct,vt.fn,void 0,!0),_t){case 1:return vt.fn.call(vt.context),!0;case 2:return vt.fn.call(vt.context,dt),!0;case 3:return vt.fn.call(vt.context,dt,ut),!0;case 4:return vt.fn.call(vt.context,dt,ut,ht),!0;case 5:return vt.fn.call(vt.context,dt,ut,ht,ft),!0;case 6:return vt.fn.call(vt.context,dt,ut,ht,ft,pt),!0}for(bt=1,yt=new Array(_t-1);bt<_t;bt++)yt[bt-1]=arguments[bt];vt.fn.apply(vt.context,yt)}else{var Et=vt.length,St;for(bt=0;bt<Et;bt++)switch(vt[bt].once&&this.removeListener(ct,vt[bt].fn,void 0,!0),_t){case 1:vt[bt].fn.call(vt[bt].context);break;case 2:vt[bt].fn.call(vt[bt].context,dt);break;case 3:vt[bt].fn.call(vt[bt].context,dt,ut);break;case 4:vt[bt].fn.call(vt[bt].context,dt,ut,ht);break;default:if(!yt)for(St=1,yt=new Array(_t-1);St<_t;St++)yt[St-1]=arguments[St];vt[bt].fn.apply(vt[bt].context,yt)}}return!0},ot.prototype.on=function(ct,dt,ut){return it(this,ct,dt,ut,!1)},ot.prototype.once=function(ct,dt,ut){return it(this,ct,dt,ut,!0)},ot.prototype.removeListener=function(ct,dt,ut,ht){var ft=tt?tt+ct:ct;if(!this._events[ft])return this;if(!dt)return at(this,ft),this;var pt=this._events[ft];if(pt.fn)pt.fn===dt&&(!ht||pt.once)&&(!ut||pt.context===ut)&&at(this,ft);else{for(var mt=0,vt=[],_t=pt.length;mt<_t;mt++)(pt[mt].fn!==dt||ht&&!pt[mt].once||ut&&pt[mt].context!==ut)&&vt.push(pt[mt]);vt.length?this._events[ft]=vt.length===1?vt[0]:vt:at(this,ft)}return this},ot.prototype.removeAllListeners=function(ct){var dt;return ct?(dt=tt?tt+ct:ct,this._events[dt]&&at(this,dt)):(this._events=new et,this._eventsCount=0),this},ot.prototype.off=ot.prototype.removeListener,ot.prototype.addListener=ot.prototype.on,ot.prefixed=tt,ot.EventEmitter=ot,rt.exports=ot})(eventemitter3);var eventemitter3Exports=eventemitter3.exports;const EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);class MessageCenterImpl extends EventEmitter{dispatch(_e,...tt){this.emit(_e,...tt)}}const MessageCenter=new MessageCenterImpl;function hasProp$1(rt,_e){return Object.prototype.hasOwnProperty.call(rt,_e)}function addHiddenProp$1(rt,_e,tt){Object.defineProperty(rt,_e,{enumerable:!1,writable:!0,configurable:!0,value:tt})}function mergePropertyConfigs(rt,_e){for(const tt in _e)rt[tt]?rt[tt]={...rt[tt],..._e[tt]}:rt[tt]=_e[tt]}function collectDecoratorConfigs(rt,_e,tt=null){const et={},nt=[];let it=rt;for(;it&&it!==tt;)nt.push(it),it=Object.getPrototypeOf(it);for(let at=nt.length-1;at>=0;at--){const ot=nt[at][_e];ot&&mergePropertyConfigs(et,ot)}return et}const storedSerializeSymbol=Symbol("storedSerialize");function serialize(rt={}){return function(_e,tt){hasProp$1(_e,storedSerializeSymbol)||addHiddenProp$1(_e,storedSerializeSymbol,{}),rt.key=rt.key??tt,_e[storedSerializeSymbol][tt]=rt}}function getSerializeConfigs(rt){return collectDecoratorConfigs(rt,storedSerializeSymbol)}const storedPropertyProxySymbol=Symbol("storedPropertyProxy");function propertyProxy(rt={}){return function(_e,tt){addPropertyProxyConfig(_e,tt,rt)}}const addPropertyProxyConfig=(rt,_e,tt)=>{hasProp$1(rt,storedPropertyProxySymbol)||addHiddenProp$1(rt,storedPropertyProxySymbol,{}),tt.editorKey=_e,rt[storedPropertyProxySymbol][_e]=tt,tt.engineKey&&(rt[storedPropertyProxySymbol][tt.engineKey]=tt),tt.setPath&&(rt[storedPropertyProxySymbol][tt.setPath]=tt),tt.getPath&&(rt[storedPropertyProxySymbol][tt.getPath]=tt)};function getPropertyProxyConfigs(rt){return collectDecoratorConfigs(rt,storedPropertyProxySymbol)}function derivePropertySemantics(rt){var nt;const _e=getSerializeConfigs(rt),tt=getPropertyProxyConfigs(rt),et=new Map;for(const[it,at]of Object.entries(_e)){const ot=at.type??"props",st=at.key??it,ct=(nt=tt[it])==null?void 0:nt.engineKey;et.set(it,ct?{serializeType:ot,serializeKey:st,engineMethod:ct}:{serializeType:ot,serializeKey:st})}return et}function createComponentSemantics(rt){const _e=derivePropertySemantics(rt);let tt;const et=new Set;return _e.forEach((nt,it)=>{nt.engineMethod&&(tt??(tt={}),tt[it]=nt.engineMethod),nt.serializeType==="methods"&&et.add(it)}),{proxyMap:tt,methodKeys:et.size>0?et:void 0}}const registeredComponents={},registeredImportScriptProperty={},invDependentComponentsMap=new Map,customComponents={},componentSemantics=new Map;let registeredCache;function registerCustomEngineComponentDefinition(rt,_e){customComponents[rt]=_e}function getCustomEngineComponentDefinition(rt){return customComponents[rt]}function registerComponentConfig(rt,_e){if(registeredComponents[rt]=_e,registeredCache=void 0,componentSemantics.set(rt,createComponentSemantics(_e.class.prototype)),_e.dependentComponent){const tt=invDependentComponentsMap.get(_e.dependentComponent.type)||[];tt.push(rt),invDependentComponentsMap.set(_e.dependentComponent.type,tt)}}function getRegisteredComponentConfig(rt){return registeredComponents[rt]}function getComponentSemantics(rt){return componentSemantics.get(rt)}function getInvDependentComponentTypes(rt){return invDependentComponentsMap.get(rt)}function getAllRegisteredComponents(){return registeredComponents}function getRegisteredComponentList(){return registeredCache||(registeredCache=Object.values(registeredComponents)),registeredCache}function registerImportComponentPropertyConfig(rt,_e){registeredImportScriptProperty[rt]=_e}function getRegisteredImportComponentPropertyConfig(rt){return registeredImportScriptProperty[rt]}var EditorDependentMode=(rt=>(rt[rt.CheckOnly=0]="CheckOnly",rt[rt.AutoAdd=1]="AutoAdd",rt[rt.AutoDel=2]="AutoDel",rt))(EditorDependentMode||{});function hasComponentTypeInEntityModel(rt,_e){var tt;return rt.isStrippedEntity?!!((tt=rt.originalEntity)!=null&&tt.components.some(et=>et.type===_e)||rt.components.some(et=>et.type===_e)):rt.components.some(et=>et.type===_e)}function evaluateComponentAddToNormalizedEntityState(rt,_e,tt){const et=getRegisteredComponentConfig(tt);if(!et)return{allowed:!0,dependentComponents:[]};const{dependentComponent:nt,mutuallyComponent:it,unique:at}=et;if(it&&hasNormalizedEntityComponentType(rt,_e,it.type))return{allowed:!1,reason:"mutually-exclusive",componentClass:tt,relatedType:it.type};if(nt&&!hasNormalizedEntityComponentType(rt,_e,nt.type)){if(nt.dependentMode===EditorDependentMode.AutoAdd)return{allowed:!0,dependentComponents:[nt.type]};if(nt.dependentMode===EditorDependentMode.CheckOnly)return{allowed:!1,reason:"missing-dependent",componentClass:tt,relatedType:nt.type}}return at&&hasNormalizedEntityComponentType(rt,_e,tt)?{allowed:!1,reason:"unique",componentClass:tt,relatedType:tt}:{allowed:!0,dependentComponents:[]}}function evaluateComponentAddForEntityModel(rt,_e){const tt=getRegisteredComponentConfig(_e);if(!tt)return{allowed:!0,dependentComponents:[]};const{dependentComponent:et,mutuallyComponent:nt,unique:it}=tt;if(nt&&hasComponentTypeInEntityModel(rt,nt.type))return{allowed:!1,reason:"mutually-exclusive",componentClass:_e,relatedType:nt.type};if(et&&!hasComponentTypeInEntityModel(rt,et.type)){if(et.dependentMode===EditorDependentMode.AutoAdd)return{allowed:!0,dependentComponents:[et.type]};if(et.dependentMode===EditorDependentMode.CheckOnly)return{allowed:!1,reason:"missing-dependent",componentClass:_e,relatedType:et.type}}return it&&hasComponentTypeInEntityModel(rt,_e)?{allowed:!1,reason:"unique",componentClass:_e,relatedType:_e}:{allowed:!0,dependentComponents:[]}}function notifyRejectedComponentAdd(rt){if(rt.allowed)return;const _e=rt;if(_e.reason==="mutually-exclusive"){showComponentAlert({title:t$7("component.prefab.cannot-modify"),description:t$7("component.prefab.mutually-exclusive")});return}if(_e.reason==="missing-dependent"){showComponentToastError(t$7("component.add.dependent",[_e.relatedType,_e.componentClass]));return}showComponentToastError(t$7("component.add.unique",[_e.componentClass]))}function classifyPrefabEntityComponentOwnerRoute(rt,_e){const tt=rt.entities[_e];if(!(tt!=null&&tt.instance)||tt.instance.role==="added")return{kind:"ordinary"};const{bindingId:et}=tt.instance;if(!et)return{kind:"invalid-prefab",reason:`Entity "${_e}" has prefab instance link without bindingId`};const nt=getNormalizedSourceEntityId(rt,_e);return nt?{kind:"prefab-source",bindingId:et,sourceEntityId:nt}:{kind:"invalid-prefab",reason:`Entity "${_e}" has prefab instance link without resolvable sourceEntityId`}}function classifyPrefabComponentRoute(rt,_e,tt){const et=classifyPrefabEntityComponentOwnerRoute(rt,_e);if(et.kind!=="prefab-source")return et;const{bindingId:nt,sourceEntityId:it}=et,at=getNormalizedComponent(rt,_e,tt);return at!=null&&at.instance?at.instance.role==="added"?{kind:"prefab-added",bindingId:nt,sourceEntityId:it}:{kind:"prefab-source",bindingId:nt,sourceEntityId:it}:{kind:"invalid-prefab",reason:`Component "${tt}" on prefab instance entity "${_e}" has no instance link`}}class ComponentFacade{constructor(_e){Rt(this,"addCmd",new AddComponentCommand);Rt(this,"updateCmd",new UpdateComponentCommand);Rt(this,"removeCmd",new RemoveComponentCommand);Rt(this,"_logger");this.root=_e,this._logger=this.root.createLogger("ComponentFacade")}addComponent(_e,tt,et,nt){const it=typeof _e=="string"?{entityId:_e,type:tt,props:et,componentId:nt}:_e;return this.root.runInUndoGroup("component.add",()=>this._addComponentWithDependencies(it))}_addComponentWithDependencies(_e,tt=new Set){const{entityId:et,type:nt}=_e;this._logger.info("addComponent",{entityId:et,type:nt});const it=evaluateComponentAddToNormalizedEntityState(this.root.domainStore.getNormalizedState(),et,nt);if(tt.has(nt)||!it.allowed)return null;const at=new Set(tt);at.add(nt);for(const dt of it.dependentComponents)if(this._addComponentWithDependencies({entityId:et,type:dt},at)===null)return null;const ot=this.root.domainStore.getNormalizedState(),st=classifyPrefabEntityComponentOwnerRoute(ot,et);switch(st.kind){case"prefab-source":return this.root.prefabFacade.addComponentOverride(et,{type:nt,props:_e.props,componentId:_e.componentId});case"invalid-prefab":throw new Error(`ComponentFacade.addComponent: ${st.reason}`)}const{result:ct}=this.root.commandBus.execute(this.addCmd,_e,"component.add");return ct}updateComponent(_e,tt,et){const nt=classifyPrefabComponentRoute(this.root.domainStore.getNormalizedState(),_e,tt);switch(nt.kind){case"prefab-added":this.root.prefabFacade.updateAddedComponentOverride(_e,tt,et);return;case"prefab-source":this.root.prefabFacade.setComponentOverride(_e,tt,et);return;case"invalid-prefab":throw new Error(`ComponentFacade.updateComponent: ${nt.reason}`);case"ordinary":this.root.commandBus.execute(this.updateCmd,{entityId:_e,componentId:tt,props:et},"component.update");return}}setEnabled(_e,tt,et){this.updateComponent(_e,tt,{enabled:et})}removeComponent(_e,tt){this._logger.info("removeComponent",{entityId:_e,componentId:tt});const et=classifyPrefabComponentRoute(this.root.domainStore.getNormalizedState(),_e,tt);switch(et.kind){case"prefab-added":this.root.prefabFacade.revertOverride(et.bindingId,"addedComponents",{sourceEntityId:et.sourceEntityId,componentId:tt});return;case"prefab-source":this.root.prefabFacade.removeSourceComponent(_e,tt);return;case"invalid-prefab":throw new Error(`ComponentFacade.removeComponent: ${et.reason}`);case"ordinary":this.root.commandBus.execute(this.removeCmd,{entityId:_e,componentId:tt},"component.remove");return}}getComponent(_e,tt){const et=this.root.domainStore.getNormalizedState(),nt=getNormalizedComponent(et,_e,tt);if(!nt)return;const{id:it,entityId:at,...ot}=nt;return ot}getComponents(_e){const tt=this.root.domainStore.getNormalizedState(),et={};for(const nt of getNormalizedEntityComponents(tt,_e)){const{id:it,entityId:at,...ot}=nt;et[it]=ot}return et}}const SCENE_SETTING_DEFINITIONS={ambient:{ambientLight:{sceneKey:"ambientLight",valueKind:"assetRef",runtimeTarget:null},customAmbientLight:{sceneKey:"customAmbientLight",valueKind:"assetRef",runtimeTarget:null},diffuseMode:{sceneKey:"diffuseMode",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"diffuseMode",valueKind:"direct"}},diffuseSolidColor:{sceneKey:"diffuseSolidColor",sourceValueType:"color",runtimeTarget:{scope:"ambientLight",key:"diffuseSolidColor",valueKind:"structured"}},diffuseIntensity:{sceneKey:"diffuseIntensity",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"diffuseIntensity",valueKind:"direct"}},specularMode:{sceneKey:"specularMode",sourceValueType:"number",editorValueAliases:{Sky:0,Custom:1},runtimeTarget:{scope:"ambientLight",key:"specularMode",valueKind:"direct"}},customSpecularTexture:{sceneKey:"customSpecularTexture",valueKind:"assetRef",runtimeTarget:null},specularIntensity:{sceneKey:"specularIntensity",sourceValueType:"number",runtimeTarget:{scope:"ambientLight",key:"specularIntensity",valueKind:"direct"}},bakerResolution:{sceneKey:"bakerResolution",sourceValueType:"number",runtimeTarget:null}},background:{mode:{sceneKey:"backgroundMode",sourceValueType:"number",runtimeTarget:{scope:"background",key:"mode",valueKind:"direct"}},color:{sceneKey:"backgroundColor",sourceValueType:"color",runtimeTarget:{scope:"background",key:"solidColor",valueKind:"structured"}},texture:{sceneKey:"backgroundTexture",runtimeTarget:{scope:"background",key:"texture",valueKind:"assetRef"}},textureFillMode:{sceneKey:"textureFillMode",sourceValueType:"number",runtimeTarget:{scope:"background",key:"textureFillMode",valueKind:"direct"}},skyMaterial:{sceneKey:"skyMaterial",runtimeTarget:{scope:"background.sky",key:"material",valueKind:"assetRef"}},skyMesh:{sceneKey:"skyMesh",runtimeTarget:{scope:"background.sky",key:"mesh",valueKind:"assetRef"}}},shadow:{castShadows:{sceneKey:"castShadows",sourceValueType:"boolean",runtimeTarget:{scope:"scene",key:"castShadows",valueKind:"direct"}},enableTransparentShadow:{sceneKey:"enableTransparentShadow",sourceValueType:"boolean",runtimeTarget:{scope:"scene",key:"enableTransparentShadow",valueKind:"direct"}},shadowResolution:{sceneKey:"shadowResolution",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowResolution",valueKind:"direct"}},shadowCascades:{sceneKey:"shadowCascades",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowCascades",valueKind:"direct"}},shadowTwoCascadeSplits:{sceneKey:"shadowTwoCascadeSplits",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowTwoCascadeSplits",valueKind:"direct"}},shadowFourCascadeSplits:{sceneKey:"shadowFourCascadeSplits",sourceValueType:"vector3",runtimeTarget:{scope:"scene",key:"shadowFourCascadeSplits",valueKind:"structured"}},shadowDistance:{sceneKey:"shadowDistance",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowDistance",valueKind:"direct"}},shadowFadeBorder:{sceneKey:"shadowFadeBorder",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"shadowFadeBorder",valueKind:"direct"}}},fog:{mode:{sceneKey:"fogMode",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogMode",valueKind:"direct"}},color:{sceneKey:"fogColor",sourceValueType:"color",runtimeTarget:{scope:"scene",key:"fogColor",valueKind:"structured"}},start:{sceneKey:"fogStart",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogStart",valueKind:"direct"}},end:{sceneKey:"fogEnd",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogEnd",valueKind:"direct"}},density:{sceneKey:"fogDensity",sourceValueType:"number",runtimeTarget:{scope:"scene",key:"fogDensity",valueKind:"direct"}}},ambientOcclusion:{enabled:{sceneKey:"enabledAmbientOcclusion",sourceValueType:"boolean",runtimeTarget:{scope:"ambientOcclusion",key:"enabled",valueKind:"direct"}},quality:{sceneKey:"quality",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"quality",valueKind:"direct"}},intensity:{sceneKey:"intensity",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"intensity",valueKind:"direct"}},power:{sceneKey:"power",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"power",valueKind:"direct"}},radius:{sceneKey:"radius",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"radius",valueKind:"direct"}},bilateralThreshold:{sceneKey:"bilateralThreshold",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"bilateralThreshold",valueKind:"direct"}},bias:{sceneKey:"bias",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"bias",valueKind:"direct"}},minHorizonAngle:{sceneKey:"minHorizonAngle",sourceValueType:"number",runtimeTarget:{scope:"ambientOcclusion",key:"minHorizonAngle",valueKind:"direct"}}}},TOP_LEVEL_SCENE_SETTING_DEFINITIONS={autoBake:{sceneKey:"autoBake",sourceValueType:"boolean",runtimeTarget:null}};function normalizeNumber(rt,_e){if(rt==null||typeof rt=="number"&&Number.isFinite(rt))return rt;if(typeof rt=="string"&&rt.trim()!==""){const tt=Number(rt);if(Number.isFinite(tt))return tt}throw new Error(`${_e} must be a number`)}function normalizeBoolean(rt,_e){if(rt==null||typeof rt=="boolean")return rt;if(rt==="true")return!0;if(rt==="false")return!1;throw new Error(`${_e} must be a boolean`)}function readNumericRecordValue(rt,_e,tt){return normalizeNumber(rt[_e],`${tt}.${_e}`)}function normalizeColor$1(rt,_e){if(rt==null)return rt;let tt;if(Array.isArray(rt))tt={r:rt[0],g:rt[1],b:rt[2],a:rt[3]};else if(typeof rt=="object"){const et=rt;"r"in et||"g"in et||"b"in et||"a"in et?tt={r:et.r,g:et.g,b:et.b,a:et.a}:"_r"in et||"_g"in et||"_b"in et||"_a"in et?tt={r:et._r,g:et._g,b:et._b,a:et._a}:tt={r:et.x,g:et.y,b:et.z,a:et.w},et._metaIntensity!==void 0&&(tt._metaIntensity=normalizeNumber(et._metaIntensity,`${_e}._metaIntensity`))}else throw new Error(`${_e} must be a color`);return{r:readNumericRecordValue(tt,"r",_e),g:readNumericRecordValue(tt,"g",_e),b:readNumericRecordValue(tt,"b",_e),a:readNumericRecordValue(tt,"a",_e),...tt._metaIntensity!==void 0?{_metaIntensity:tt._metaIntensity}:{}}}function normalizeVector3(rt,_e){if(rt==null)return rt;let tt;if(Array.isArray(rt))tt={x:rt[0],y:rt[1],z:rt[2]};else if(typeof rt=="object"){const et=rt;"x"in et||"y"in et||"z"in et?tt={x:et.x,y:et.y,z:et.z}:tt={x:et._x,y:et._y,z:et._z}}else throw new Error(`${_e} must be a vector3`);return[readNumericRecordValue(tt,"x",_e),readNumericRecordValue(tt,"y",_e),readNumericRecordValue(tt,"z",_e)]}function normalizeSceneSettingValue(rt,_e,tt){switch(rt.sourceValueType){case"number":return normalizeNumber(_e,tt);case"boolean":return normalizeBoolean(_e,tt);case"color":return normalizeColor$1(_e,tt);case"vector3":return normalizeVector3(_e,tt);default:return _e}}function applyEditorValueAlias(rt,_e){return typeof _e!="string"||!rt.editorValueAliases?_e:Object.prototype.hasOwnProperty.call(rt.editorValueAliases,_e)?rt.editorValueAliases[_e]:_e}function normalizeEditorSceneSettingValue(rt,_e,tt){return normalizeSceneSettingValue(rt,applyEditorValueAlias(rt,_e),tt)}function getSceneSettingDefinitionByPath(rt){var nt;if(!rt.includes("/")){const it=TOP_LEVEL_SCENE_SETTING_DEFINITIONS[rt];if(!it)throw new Error(`Unknown scene setting path: ${rt}`);return it}const[_e,tt]=rt.split("/"),et=(nt=SCENE_SETTING_DEFINITIONS[_e])==null?void 0:nt[tt];if(!et)throw new Error(`Unknown scene setting path: ${rt}`);return et}function normalizeEditorSceneSettingValueByPath(rt,_e){return normalizeEditorSceneSettingValue(getSceneSettingDefinitionByPath(rt),_e,`scene.${rt.replace("/",".")}`)}function upsertOp(rt,_e,tt){const et=_e.split("/").filter(Boolean);let nt=rt;for(const it of et){if(nt==null||typeof nt!="object"||!(it in nt))return{op:"add",path:`/${et.join("/")}`,value:tt};nt=nt[it]}return{op:"replace",path:`/${et.join("/")}`,value:tt}}class UpdateSceneSettingCommand{constructor(){Rt(this,"name","scene.updateSetting")}execute(_e,tt){const et=[],nt=_e.scene.settings,it=nt,at=normalizeSceneSettingPath(tt.path);nt||et.push({op:"add",path:"/scene/settings",value:{}});const ot=at.split("/"),st=ot[0];return ot.length>1&&!(it!=null&&it[st])&&et.push({op:"add",path:`/scene/settings/${st}`,value:{}}),et.push(upsertOp(_e,`scene/settings/${at}`,tt.value)),{operations:et,result:void 0,events:[{type:"SceneSettingUpdated",settingPath:at,value:tt.value}]}}}class BatchUpdateSceneSettingsCommand{constructor(){Rt(this,"name","scene.batchUpdateSettings")}execute(_e,tt){const et=[];let nt=_e.scene.settings,it=nt;const at=[];nt||(et.push({op:"add",path:"/scene/settings",value:{}}),nt={},it=nt);const ot=new Set;for(const st of tt.updates){const ct=normalizeSceneSettingPath(st.path),dt=ct.split("/"),ut=dt[0];dt.length>1&&!(it!=null&&it[ut])&&!ot.has(ut)&&(et.push({op:"add",path:`/scene/settings/${ut}`,value:{}}),ot.add(ut)),et.push(upsertOp(_e,`scene/settings/${ct}`,st.value)),at.push({type:"SceneSettingUpdated",settingPath:ct,value:st.value})}return{operations:et,result:void 0,events:at}}}class InitSceneSettingsCommand{constructor(){Rt(this,"name","scene.initSettings")}execute(_e,tt){const et=_e.scene.settings;return{operations:[et?{op:"replace",path:"/scene/settings",value:tt.settings,oldValue:et}:{op:"add",path:"/scene/settings",value:tt.settings}],result:void 0,events:flattenSceneSettingUpdateEvents(tt.settings)}}}class SceneFacade{constructor(_e,tt){Rt(this,"updateCmd",new UpdateSceneSettingCommand);Rt(this,"batchUpdateCmd",new BatchUpdateSceneSettingsCommand);Rt(this,"initCmd",new InitSceneSettingsCommand);this.domainStore=_e,this.commandBus=tt}updateSetting(_e,tt){const et=normalizeSceneSettingPath(_e);this.commandBus.execute(this.updateCmd,{path:et,value:normalizeEditorSceneSettingValueByPath(et,tt)})}batchUpdateSettings(_e){this.commandBus.execute(this.batchUpdateCmd,{updates:_e.map(tt=>{const et=normalizeSceneSettingPath(tt.path);return{path:et,value:normalizeEditorSceneSettingValueByPath(et,tt.value)}})})}getSetting(_e){const tt=_e.split("/");let et=this.domainStore.state.scene.settings;for(const nt of tt){if(et==null)return;et=et[nt]}return et}initSettings(_e){this.commandBus.execute(this.initCmd,{settings:_e})}initSettingsSystem(_e){const{operations:tt}=this.initCmd.execute(this.domainStore.state,{settings:_e});this.domainStore.applySystem(tt)}}class DebouncedDomainBatch{constructor(_e,tt=300,et="domain.batch"){Rt(this,"_timer",null);Rt(this,"_active",!1);this.store=_e,this.debounceMs=tt,this.commandName=et}apply(_e){_e.length&&this.run(()=>{this.store.apply(_e,this.commandName)})}run(_e){if(this._resetIfStale(),!this._active&&this.store.isBatchMode){_e();return}this._active||(this.store.beginBatch(),this._active=!0),_e(),this._clearTimer(),this._timer=setTimeout(()=>{this._commit()},this.debounceMs)}flush(){this._clearTimer(),this._resetIfStale(),this._active&&this.store.isBatchMode&&this.store.commitBatch(this.commandName),this._active=!1}dispose(){this._clearTimer(),this._resetIfStale(),this._active&&this.store.isBatchMode&&this.store.abortBatch(),this._active=!1}_commit(){this._timer=null,this._resetIfStale(),this._active&&this.store.isBatchMode&&(this.store.commitBatch(this.commandName),this._active=!1)}_resetIfStale(){this._active&&!this.store.isBatchMode&&(this._clearTimer(),this._active=!1)}_clearTimer(){this._timer!==null&&(clearTimeout(this._timer),this._timer=null)}}function resolveSceneChangePath(rt,_e){var et;const tt=((et=rt==null?void 0:rt.getDomainSettingPath)==null?void 0:et.call(rt,_e))??(_e.includes("/")?normalizeSceneSettingPath(_e):void 0);if(!tt)throw new Error(`resolveSceneChangePath: unknown scene setting property: ${_e}`);return tt}function resolveSceneChangeUpdate(rt,_e,tt){const et=resolveSceneChangePath(rt,_e),nt=tt===void 0?rt[_e]:tt;return{path:et,value:normalizeEditorSceneSettingValueByPath(et,nt)}}const TRANSFORM_PROPERTIES=new Set(["position","rotation","scale"]),TRANSFORM_COMPONENT_TYPES=new Set(["Transform","UITransform"]);function combineLayers(rt){let _e=0;for(const tt of rt)_e|=tt;return _e}const SCENE_ROOT_ID="__scene__";class InspectorFacade{constructor(_e){Rt(this,"_batch",null);Rt(this,"_batchEntityId",null);Rt(this,"_logger");this.root=_e,this._logger=this.root.createLogger("InspectorFacade")}async applyChange(_e){var et,nt;this._logger.info("applyChange",{objectType:_e.objectType,objectId:_e.objectId,property:_e.property});const tt=this.normalizeValue(_e.value);switch(_e.objectType){case"scene":{const it=resolveSceneChangePath(void 0,_e.property);this.root.sceneFacade.updateSetting(it,tt);return}case"entity":{this.applyEntityChange(_e.objectId,_e.property,tt);return}case"component":{const it=this.findComponentOwnerEntityId(_e.objectId);if(!it)throw new Error(`InspectorFacade.applyChange: component owner not found: ${_e.objectId}`);if(this.isTransformProperty(it,_e.objectId,_e.property)){if(this._batchEntityId&&this._batchEntityId!==it&&this.flushBatch(),this._batchEntityId=it,this.isPrefabSourceEntity(it)){const ot={[_e.property]:tt};this._getOrCreateBatch().run(()=>{this.root.entityFacade.setTransform(it,ot)});return}const at=this.buildTransformOps(it,_e.property,tt);this._getOrCreateBatch().apply(at),this.root.componentFacade.updateComponent(it,_e.objectId,{[_e.property]:tt});return}this.root.componentFacade.updateComponent(it,_e.objectId,{[_e.property]:tt});return}case"asset":{const it=(nt=(et=this.root.assetStore)==null?void 0:et.assets)==null?void 0:nt[_e.objectId],at={[_e.property]:tt};if(it!=null&&it.isSubAsset)await this.root.assetFacade.updateSubAssetProps(_e.objectId,at);else switch(_e.persistScope??"asset-main"){case"asset-main":await this.root.assetFacade.updateAssetProps(_e.objectId,at);break;case"asset-meta":await this.root.assetFacade.updateAssetMeta(_e.objectId,at);break;case"asset-both":await this.root.assetFacade.updateAssetProps(_e.objectId,at),await this.root.assetFacade.updateAssetMeta(_e.objectId,at);break}return}}}sceneChange(_e,tt){this.applyChange({objectType:"scene",objectId:SCENE_ROOT_ID,property:_e,value:tt,source:"inspector"})}entityChange(_e,tt,et){this.applyChange({objectType:"entity",objectId:_e,property:tt,value:et,source:"inspector"})}componentChange(_e,tt,et){this.applyChange({objectType:"component",objectId:_e,property:tt,value:et,source:"inspector"})}async assetChange(_e,tt,et,nt){await this.applyChange({objectType:"asset",objectId:_e,property:tt,value:et,source:"inspector",...nt?{persistScope:nt}:{}})}async assetChanges(_e,tt,et){for(const[nt,it]of Object.entries(tt))await this.assetChange(_e,nt,it,et)}getSceneRootId(){return SCENE_ROOT_ID}normalizeValue(_e){if(_e&&typeof _e=="object"&&"engineObjectType"in _e){const tt=_e.getCurrentRef;if(typeof tt=="function")return tt.call(_e)}return _e}applyEntityChange(_e,tt,et){if(tt==="name"&&typeof et=="string"){this.root.entityFacade.rename(_e,et);return}if(tt==="isActive"&&typeof et=="boolean"){this.root.entityFacade.setVisible(_e,et);return}if(tt==="layer"&&Array.isArray(et)){this.root.entityFacade.setLayer(_e,combineLayers(et));return}if(tt==="isLocked"&&typeof et=="boolean"){this.root.entityFacade.setLocked(_e,et);return}this.root.entityFacade.updateEntity(_e,{[tt]:et})}flushBatch(){var _e;(_e=this._batch)==null||_e.flush(),this._batchEntityId=null}disposeBatch(){var _e;(_e=this._batch)==null||_e.dispose(),this._batch=null,this._batchEntityId=null}_getOrCreateBatch(){return this._batch||(this._batch=new DebouncedDomainBatch(this.root.domainStore,300,"inspector.transform")),this._batch}isTransformProperty(_e,tt,et){var it;if(!TRANSFORM_PROPERTIES.has(et))return!1;const nt=this.root.domainStore.getNormalizedState();return nt.relations.componentOwner[tt]===_e&&TRANSFORM_COMPONENT_TYPES.has(((it=nt.components[tt])==null?void 0:it.type)??"")}isPrefabSourceEntity(_e){var et;const tt=this.root.domainStore.getNormalizedState().entities[_e];return!!((et=tt==null?void 0:tt.instance)!=null&&et.bindingId&&tt.instance.role!=="added")}buildTransformOps(_e,tt,et){return[{op:"replace",path:`/entities/${_e}/transform/${tt}/x`,value:et.x},{op:"replace",path:`/entities/${_e}/transform/${tt}/y`,value:et.y},{op:"replace",path:`/entities/${_e}/transform/${tt}/z`,value:et.z}]}findComponentOwnerEntityId(_e){return this.root.domainStore.getNormalizedState().relations.componentOwner[_e]??null}}function createEmptyPrefabOverrides$1(){return{entityProps:{},componentProps:{},removedEntities:{},removedComponents:{},addedEntities:{},addedComponents:{}}}function cloneTransform(rt){return{position:{...rt.position},rotation:{...rt.rotation},scale:{...rt.scale}}}function pushRemoveOnce(rt,_e,tt){_e.has(tt)||(_e.add(tt),rt.push({op:"remove",path:tt}))}function unlinkEntityInstance(rt,_e,tt,et,nt,it){var st,ct,dt,ut,ht;const at=rt.entities[_e];if(!at)return;const ot=encodeJsonPointerSegment(_e);((st=at.instance)==null?void 0:st.bindingId)===nt&&!((ct=it.preservedEntityIds)!=null&&ct.has(_e))&&pushRemoveOnce(tt,et,`/entities/${ot}/instance`);for(const[ft,pt]of Object.entries(at.components))((dt=pt.instance)==null?void 0:dt.bindingId)===nt&&!((ht=(ut=it.preservedComponentsByEntity)==null?void 0:ut.get(_e))!=null&&ht.has(ft))&&pushRemoveOnce(tt,et,`/entities/${ot}/components/${encodeJsonPointerSegment(ft)}/instance`)}function buildUnlinkInstanceOps(rt,_e,tt={}){const et=[],nt=new Set;for(const it of getSceneEntityIdsForPrefabBinding(_e))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);for(const it of Object.keys(_e.overrides.addedEntities))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);for(const it of Object.keys(rt.entities))unlinkEntityInstance(rt,it,et,nt,_e.id,tt);return et}function findBindingByEntityId(rt,_e){const tt=rt.entities[_e];if(!tt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_e}" not found`);if(!tt.instance)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: entity "${_e}" has no instance link`);const et=rt.prefab.bindings[tt.instance.bindingId];if(!et)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${tt.instance.bindingId}" not found`);return{entity:tt,binding:et}}function normalizeTransform(rt){const _e=createDefaultTransform();return mergeTransform$1(_e,rt)}function mergeTransform$1(rt,_e){return{position:{...rt.position,..._e==null?void 0:_e.position},rotation:{...rt.rotation,..._e==null?void 0:_e.rotation},scale:{...rt.scale,..._e==null?void 0:_e.scale}}}function buildInstantiateSourceSnapshots(rt){const _e=new Map(rt.map(nt=>[nt.id,nt.sourceEntityId])),tt=new Map,et=new Map;for(const nt of rt)if(nt.parentId){const it=_e.get(nt.parentId);if(it){const at=tt.get(it)??[];et.set(nt.sourceEntityId,at.length),at.push(nt.sourceEntityId),tt.set(it,at)}}else et.set(nt.sourceEntityId,0);return Object.fromEntries(rt.map(nt=>{const it={};for(const ot of nt.components??[])it[ot.sourceComponentKey]={sceneComponentId:ot.id,type:ot.type,props:cloneState(ot.props??{})};const at={sceneEntityId:nt.id,parentSourceEntityId:nt.parentId?_e.get(nt.parentId)??null:null,childSourceEntityIds:[...tt.get(nt.sourceEntityId)??[]],childIndex:et.get(nt.sourceEntityId)??0,name:nt.name,isActive:!0,transform:normalizeTransform(nt.transform),components:it};return[nt.sourceEntityId,at]}))}class InstantiatePrefabCommand{constructor(){Rt(this,"name","prefab.instantiate")}execute(_e,tt){const{assetId:et,bindingId:nt,parentId:it,rootTransform:at,entities:ot}=tt,st=[],ct={},dt=ot.filter(At=>At.parentId===null);if(dt.length!==1)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: prefab instantiate requires exactly one root entity",{entityIds:ot.map(At=>At.id),rootCandidateIds:dt.map(At=>At.id)});const[ut]=dt,ht=ut.id,ft=ut.sourceEntityId;for(const At of ot)ct[At.sourceEntityId]=At.id;const pt=new Set,mt=new Map;let vt=0;for(const At of ot){const xt=At.id===ht,Ct=encodeJsonPointerSegment(At.id),Pt={};if(At.components)for(const It of At.components){const Ot={bindingId:nt,role:"linked",sourceComponentKey:It.sourceComponentKey};Pt[It.id]={type:It.type,props:It.props??{},instance:Ot}}const Tt=xt?it:At.parentId,wt={id:At.id,name:At.name,isActive:!0,parentId:Tt,children:[],transform:xt&&at?mergeTransform$1(normalizeTransform(At.transform),at):normalizeTransform(At.transform),components:Pt,instance:{bindingId:nt,assetId:et,assetKind:"Prefab",role:xt?"root":"linked",sourceEntityId:At.sourceEntityId}};if(st.push({op:"add",path:`/entities/${Ct}`,value:wt}),pt.add(At.id),At.parentId!==null){const It=_e.entities[At.parentId],Ot=pt.has(At.parentId),Nt=mt.get(At.parentId)??0;let Mt;It?Mt=It.children.length+Nt:Mt=Nt,st.push({op:"add",path:`/entities/${encodeJsonPointerSegment(At.parentId)}/children/${Mt}`,value:At.id}),mt.set(At.parentId,Nt+1)}else if(it!==null){const It=_e.entities[it],Ot=mt.get(it)??0,Nt=(It?It.children.length:0)+Ot;st.push({op:"add",path:`/entities/${encodeJsonPointerSegment(it)}/children/${Nt}`,value:At.id}),mt.set(it,Ot+1)}else{const It=_e.scene.rootEntityIds.length+vt;st.push({op:"add",path:`/scene/rootEntityIds/${It}`,value:At.id}),vt++}}const _t={id:nt,assetId:et,assetKind:"Prefab",instanceRootEntityId:ht,sourceRootEntityId:ft,sourceRevision:1,sourceToSceneEntity:ct,sourceEntitySnapshots:buildInstantiateSourceSnapshots(ot),overrides:createEmptyPrefabOverrides$1()},yt=encodeJsonPointerSegment(nt);st.push({op:"add",path:`/prefab/bindings/${yt}`,value:_t});const bt=encodeJsonPointerSegment(et),Et=_e.prefab.byAssetId[et];Et?st.push({op:"add",path:`/prefab/byAssetId/${bt}/${Et.length}`,value:nt}):st.push({op:"add",path:`/prefab/byAssetId/${bt}`,value:[nt]});const St={type:"PrefabBindingCreated",source:"instantiate",bindingId:nt,assetId:et,instanceRootEntityId:ht,sourceRootEntityId:ft,entityIds:ot.map(At=>At.id)};return{operations:st,result:nt,events:[St]}}}function sourceEntityIdToPathFromSnapshots(rt,_e){const tt=[];let et=rt[_e];const nt=new Set([_e]);for(;et&&et.parentSourceEntityId!=null;){tt.unshift(et.childIndex);const it=et.parentSourceEntityId;if(nt.has(it))return null;nt.add(it),et=rt[it]}return et?tt.join("/"):null}function sourceEntityIdToPath(rt,_e){return _e===rt.sourceRootEntityId?"":sourceEntityIdToPathFromSnapshots(rt.sourceEntitySnapshots??{},_e)}function sourcePathContains(rt,_e){return rt===_e?!0:rt===""?_e!=="":_e.startsWith(`${rt}/`)}function collectRemovedSourceEntityPaths(rt,_e=rt.sourceEntitySnapshots??{}){const tt=new Map;for(const et of Object.keys(rt.overrides.removedEntities??{})){const nt=et===rt.sourceRootEntityId?"":sourceEntityIdToPathFromSnapshots(_e,et);nt!==null&&tt.set(et,nt)}return tt}function sourceEntityIsCoveredByRemovedEntityInSnapshots(rt,_e,tt){const et=sourceEntityIdToPathFromSnapshots(rt,tt);if(et===null)return _e.has(tt);for(const nt of _e.values())if(sourcePathContains(nt,et))return!0;return!1}function sourceEntityIsCoveredByAnotherRemovedEntityInSnapshots(rt,_e,tt){const et=sourceEntityIdToPathFromSnapshots(rt,tt);if(et===null)return!1;for(const[nt,it]of _e)if(nt!==tt&&sourcePathContains(it,et))return!0;return!1}function sourceEntityIsCoveredByRemovedEntity(rt,_e){var et;const tt=sourceEntityIdToPath(rt,_e);if(tt===null)return!!((et=rt.overrides.removedEntities)!=null&&et[_e]);for(const nt of collectRemovedSourceEntityPaths(rt).values())if(sourcePathContains(nt,tt))return!0;return!1}function sourceEntityIsCoveredByAnotherRemovedEntity(rt,_e){const tt=sourceEntityIdToPath(rt,_e);if(tt===null)return!1;for(const[et,nt]of collectRemovedSourceEntityPaths(rt))if(et!==_e&&sourcePathContains(nt,tt))return!0;return!1}const VECTOR3_KEYS=["x","y","z"];function buildBindExistingSourceSnapshots(rt,_e,tt,et,nt){const it=new Map(_e.map(ct=>[ct.sceneEntityId,ct.sourceEntityId])),at=new Map(_e.map(ct=>[ct.sourceEntityId,ct.sceneEntityId])),ot=new Map,st=new Map;for(const ct of tt){const dt=ot.get(ct.sceneEntityId)??[];dt.push(ct),ot.set(ct.sceneEntityId,dt);const ut=it.get(ct.sceneEntityId);if(ut){const ht=st.get(ut)??new Map;ht.set(ct.sourceComponentKey,ct.sceneComponentId),st.set(ut,ht)}}return Object.fromEntries(et?Object.entries(et).map(([ct,dt])=>{var ht,ft,pt,mt,vt;const ut={};for(const[_t,yt]of Object.entries(dt.components))ut[_t]={sceneComponentId:((ht=st.get(ct))==null?void 0:ht.get(_t))??((pt=(ft=nt==null?void 0:nt[ct])==null?void 0:ft.components[_t])==null?void 0:pt.sceneComponentId)??yt.sceneComponentId??_t,type:yt.type,...yt.refId?{refId:yt.refId}:{},...yt.scriptKey?{scriptKey:yt.scriptKey}:{},props:cloneState(yt.props),...(mt=yt.calls)!=null&&mt.length?{calls:cloneState(yt.calls)}:{}};return[ct,{sceneEntityId:at.get(ct)??((vt=nt==null?void 0:nt[ct])==null?void 0:vt.sceneEntityId)??dt.sceneEntityId??ct,parentSourceEntityId:dt.parentSourceEntityId,childSourceEntityIds:[...dt.childSourceEntityIds],childIndex:dt.childIndex,...dt.instanceAssetKind?{instanceAssetKind:dt.instanceAssetKind}:{},name:dt.name,isActive:dt.isActive,...dt.layer!==void 0?{layer:dt.layer}:{},...dt.isLocked!==void 0?{isLocked:dt.isLocked}:{},transform:cloneTransform(dt.transform),components:ut}]}):_e.map(ct=>{var ft,pt,mt;const dt=rt.entities[ct.sceneEntityId],ut={};for(const vt of ot.get(ct.sceneEntityId)??[]){const _t=dt.components[vt.sceneComponentId];_t&&(ut[vt.sourceComponentKey]={sceneComponentId:vt.sceneComponentId,type:_t.type,..._t.refId?{refId:_t.refId}:{},..._t.scriptKey?{scriptKey:_t.scriptKey}:{},props:cloneState(_t.props),...(ft=_t.calls)!=null&&ft.length?{calls:cloneState(_t.calls)}:{}})}const ht={sceneEntityId:ct.sceneEntityId,parentSourceEntityId:dt.parentId?it.get(dt.parentId)??null:null,childSourceEntityIds:dt.children.map(vt=>it.get(vt)).filter(vt=>!!vt),childIndex:dt.parentId?Math.max(((pt=rt.entities[dt.parentId])==null?void 0:pt.children.indexOf(ct.sceneEntityId))??0,0):Math.max(rt.scene.rootEntityIds.indexOf(ct.sceneEntityId),0),...(mt=dt.instance)!=null&&mt.assetKind?{instanceAssetKind:dt.instance.assetKind}:{},name:dt.name,isActive:dt.isActive,...dt.layer!==void 0?{layer:dt.layer}:{},...dt.isLocked!==void 0?{isLocked:dt.isLocked}:{},transform:cloneTransform(dt.transform),components:ut};return[ct.sourceEntityId,ht]}))}function shouldPreserveNestedInstanceRootLink(rt,_e,tt){var ot;if(_e.role==="root")return!1;const et=(ot=tt==null?void 0:tt[_e.sourceEntityId])==null?void 0:ot.instanceAssetKind;if(!et)return!1;const nt=rt.entities[_e.sceneEntityId],it=nt==null?void 0:nt.instance;if(!it||it.role!=="root"||it.assetKind!==et)return!1;const at=rt.prefab.bindings[it.bindingId];return!!(at&&at.instanceRootEntityId===_e.sceneEntityId&&at.assetKind===et)}function resolveSceneEntityIdForSource(rt,_e){var tt,et,nt;return((tt=rt.sourceToSceneEntity)==null?void 0:tt[_e])??((nt=(et=rt.sourceEntitySnapshots)==null?void 0:et[_e])==null?void 0:nt.sceneEntityId)??(_e===rt.sourceRootEntityId?rt.instanceRootEntityId:void 0)}function buildSceneToSourceEntityLookup(rt,_e,tt,et){const nt=new Map;nt.set(et,tt);for(const[it,at]of Object.entries(rt))nt.set(at,it);for(const[it,at]of Object.entries(_e))nt.set(at.sceneEntityId,it);return nt}function resolveSourceComponentKeyForBaseline(rt,_e,tt,et,nt){var at,ot,st,ct,dt;if((at=_e[et])!=null&&at.components[nt])return nt;const it=(ct=(st=(ot=rt.sourceEntitySnapshots)==null?void 0:ot[tt])==null?void 0:st.components[nt])==null?void 0:ct.sceneComponentId;if(!it)return nt;for(const[ut,ht]of Object.entries(((dt=_e[et])==null?void 0:dt.components)??{}))if(ht.sceneComponentId===it)return ut;return nt}function mergeEntityOverrideProps$1(rt,_e){var et,nt,it,at;const tt={...rt??{},..._e};if(rt!=null&&rt.transform||_e.transform){tt.transform={...(rt==null?void 0:rt.transform)??{},..._e.transform??{}};for(const ot of["position","rotation","scale"])((et=rt==null?void 0:rt.transform)!=null&&et[ot]||(nt=_e.transform)!=null&&nt[ot])&&(tt.transform[ot]={...((it=rt==null?void 0:rt.transform)==null?void 0:it[ot])??{},...((at=_e.transform)==null?void 0:at[ot])??{}})}return tt}function sanitizeOverridesForSourceBaseline(rt,_e,tt,et,nt={}){var pt,mt,vt,_t,yt;const it=new Set(Object.keys(et)),at=new Set(Object.keys(tt)),ot=createEmptyPrefabOverrides$1(),st=collectRemovedSourceEntityPaths(_e,et),ct=buildSceneToSourceEntityLookup(tt,et,nt.sourceRootEntityId??_e.sourceRootEntityId,nt.instanceRootEntityId??_e.instanceRootEntityId),dt=bt=>{if(nt.sourceRootEntityId&&bt===_e.sourceRootEntityId)return nt.sourceRootEntityId;if(it.has(bt)||at.has(bt))return bt;const Et=resolveSceneEntityIdForSource(_e,bt);return Et?ct.get(Et)??bt:bt},ut=bt=>it.has(bt),ht=bt=>at.has(bt),ft=(bt,Et)=>{var St;return!!((St=et[bt])!=null&&St.components[Et])};for(const[bt,Et]of Object.entries(_e.overrides.entityProps)){const St=dt(bt),At=compactEntityPropsOverride(Et,et[St]);At&&ht(St)&&!sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St)&&(ot.entityProps[St]=mergeEntityOverrideProps$1(ot.entityProps[St],At))}for(const[bt,Et]of Object.entries(_e.overrides.componentProps)){const St=dt(bt);if(!ht(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At={};for(const[xt,Ct]of Object.entries(Et)){const Pt=resolveSourceComponentKeyForBaseline(_e,et,bt,St,xt),Tt=compactComponentPropsOverride(Ct,(mt=(pt=et[St])==null?void 0:pt.components[Pt])==null?void 0:mt.props);Tt&&ft(St,Pt)&&!((vt=_e.overrides.removedComponents[bt])!=null&&vt[xt])&&(At[Pt]={...At[Pt]??{},...Tt})}Object.keys(At).length>0&&(ot.componentProps[St]={...ot.componentProps[St]??{},...At})}for(const bt of Object.keys(_e.overrides.removedEntities)){const Et=dt(bt);ut(Et)&&!sourceEntityIsCoveredByAnotherRemovedEntityInSnapshots(et,st,Et)&&(ot.removedEntities[Et]=!0)}for(const[bt,Et]of Object.entries(_e.overrides.removedComponents)){const St=dt(bt);if(!ut(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At={};for(const xt of Object.keys(Et)){const Ct=resolveSourceComponentKeyForBaseline(_e,et,bt,St,xt);ft(St,Ct)&&(At[Ct]=!0)}Object.keys(At).length>0&&(ot.removedComponents[St]={...ot.removedComponents[St]??{},...At})}for(const[bt,Et]of Object.entries(_e.overrides.addedEntities)){const St=dt(Et.parentSourceEntityId);(rt.entities[bt]||nt.preserveMissingAddedEntities)&&ut(St)&&!sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St)&&(ot.addedEntities[bt]={...cloneState(Et),parentSourceEntityId:St})}for(const[bt,Et]of Object.entries(_e.overrides.addedComponents)){const St=dt(bt);if(!ht(St)||sourceEntityIsCoveredByRemovedEntityInSnapshots(et,st,St))continue;const At=tt[St],xt=resolveSceneEntityIdForSource(_e,bt),Ct={};for(const[Pt,Tt]of Object.entries(Et)){const wt=!!((_t=rt.entities[At])!=null&&_t.components[Pt]),It=!!(xt&&((yt=rt.entities[xt])!=null&&yt.components[Pt]));(wt||It)&&(Ct[Pt]=cloneState(Tt))}Object.keys(Ct).length>0&&(ot.addedComponents[St]={...ot.addedComponents[St]??{},...Ct})}return ot}function compactEntityPropsOverride(rt,_e){const tt={};rt.name!==void 0&&!isEqual$2(rt.name,_e==null?void 0:_e.name)&&(tt.name=cloneState(rt.name)),rt.isActive!==void 0&&!isEqual$2(rt.isActive,_e==null?void 0:_e.isActive)&&(tt.isActive=cloneState(rt.isActive)),rt.layer!==void 0&&!isEqual$2(rt.layer,(_e==null?void 0:_e.layer)??0)&&(tt.layer=cloneState(rt.layer)),rt.isLocked!==void 0&&!isEqual$2(rt.isLocked,(_e==null?void 0:_e.isLocked)??!1)&&(tt.isLocked=cloneState(rt.isLocked));const et=compactTransformOverride(rt.transform,_e==null?void 0:_e.transform);return et&&(tt.transform=et),Object.keys(tt).length>0?tt:null}function compactTransformOverride(rt,_e){if(!rt)return;const tt={};for(const et of["position","rotation","scale"]){const nt=compactVector3Override(rt[et],_e==null?void 0:_e[et]);nt&&(tt[et]=nt)}return Object.keys(tt).length>0?tt:void 0}function compactVector3Override(rt,_e){if(!rt)return;const tt={};for(const et of VECTOR3_KEYS)rt[et]!==void 0&&!isEqual$2(rt[et],_e==null?void 0:_e[et])&&(tt[et]=cloneState(rt[et]));return Object.keys(tt).length>0?tt:void 0}function compactComponentPropsOverride(rt,_e){const tt={};for(const[et,nt]of Object.entries(rt))isEqual$2(nt,_e==null?void 0:_e[et])||(tt[et]=cloneState(nt));return Object.keys(tt).length>0?tt:null}function pushRemoveBindingIndexOps(rt,_e,tt){for(const et of tt)_e.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(et)}`});for(const[et,nt]of Object.entries(rt.prefab.byAssetId)){const it=nt.map((ot,st)=>tt.has(ot)?st:-1).filter(ot=>ot>=0);if(!it.length)continue;const at=encodeJsonPointerSegment(et);if(it.length===nt.length){_e.push({op:"remove",path:`/prefab/byAssetId/${at}`});continue}it.sort((ot,st)=>st-ot).forEach(ot=>_e.push({op:"remove",path:`/prefab/byAssetId/${at}/${ot}`}))}}function pushUnlinkRemovedBindingLinksOps(rt,_e,tt,et,nt){if(tt.size)for(const it of tt){const at=rt.prefab.bindings[it];at&&_e.push(...buildUnlinkInstanceOps(rt,at,{preservedEntityIds:et,preservedComponentsByEntity:nt}))}}function buildPreservedComponentsByEntity(rt){const _e=new Map;for(const tt of rt){const et=_e.get(tt.sceneEntityId)??new Set;et.add(tt.sceneComponentId),_e.set(tt.sceneEntityId,et)}return _e}class BindExistingPrefabInstanceCommand{constructor(){Rt(this,"name","prefab.bindExistingInstance")}execute(_e,tt){var St,At,xt;const{assetId:et,assetKind:nt="Prefab",bindingId:it,instanceRootEntityId:at,sourceRevision:ot=1,entityMappings:st,componentMappings:ct=[]}=tt;if(!st.length)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: entityMappings is empty");if(_e.prefab.bindings[it])throw new CommandError(CommandErrorCode.DUPLICATE_ID,`DUPLICATE_ID: binding "${it}" already exists`);const dt=st.find(Ct=>Ct.sceneEntityId===at&&Ct.role==="root")??st.find(Ct=>Ct.role==="root");if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: missing root mapping for instance root "${at}"`);const ut={},ht=new Set,ft=[],pt=new Set,mt=(At=(St=tt.sourceEntitySnapshots)==null?void 0:St[dt.sourceEntityId])==null?void 0:At.instanceAssetKind,vt=Ct=>nt==="Prefab"&&mt==="glTF"&&Ct.assetKind==="glTF";for(const[Ct,Pt]of Object.entries(_e.prefab.bindings))Pt.instanceRootEntityId===at&&!vt(Pt)&&pt.add(Ct);pushUnlinkRemovedBindingLinksOps(_e,ft,pt,new Set(st.map(Ct=>Ct.sceneEntityId)),buildPreservedComponentsByEntity(ct)),pushRemoveBindingIndexOps(_e,ft,pt);for(const Ct of st){const Pt=_e.entities[Ct.sceneEntityId];if(!Pt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${Ct.sceneEntityId}" not found`);if(ut[Ct.sourceEntityId]||ht.has(Ct.sceneEntityId))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: duplicate mapping source="${Ct.sourceEntityId}" scene="${Ct.sceneEntityId}"`);if(ut[Ct.sourceEntityId]=Ct.sceneEntityId,ht.add(Ct.sceneEntityId),!shouldPreserveNestedInstanceRootLink(_e,Ct,tt.sourceEntitySnapshots)){const Tt={bindingId:it,assetId:et,assetKind:nt,role:Ct.role,sourceEntityId:Ct.sourceEntityId};ft.push({op:Pt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(Ct.sceneEntityId)}/instance`,value:Tt})}}for(const Ct of ct){const Pt=_e.entities[Ct.sceneEntityId];if(!Pt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${Ct.sceneEntityId}" not found`);const Tt=Pt.components[Ct.sceneComponentId];if(!Tt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${Ct.sceneComponentId}" not found on entity "${Ct.sceneEntityId}"`);const wt={bindingId:it,role:"linked",sourceComponentKey:Ct.sourceComponentKey};ft.push({op:Tt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(Ct.sceneEntityId)}/components/${encodeJsonPointerSegment(Ct.sceneComponentId)}/instance`,value:wt})}const _t={id:it,assetId:et,assetKind:nt,instanceRootEntityId:at,sourceRootEntityId:dt.sourceEntityId,sourceRevision:ot,sourceToSceneEntity:ut,sourceEntitySnapshots:buildBindExistingSourceSnapshots(_e,st,ct,tt.sourceEntitySnapshots),overrides:createEmptyPrefabOverrides$1()};ft.push({op:"add",path:`/prefab/bindings/${encodeJsonPointerSegment(it)}`,value:_t});const yt=encodeJsonPointerSegment(et),bt=(xt=_e.prefab.byAssetId[et])==null?void 0:xt.filter(Ct=>!pt.has(Ct));bt!=null&&bt.length?bt.includes(it)||ft.push({op:"add",path:`/prefab/byAssetId/${yt}/${bt.length}`,value:it}):ft.push({op:"add",path:`/prefab/byAssetId/${yt}`,value:[it]});const Et={type:"PrefabBindingCreated",source:"bindExisting",bindingId:it,assetId:et,instanceRootEntityId:at,sourceRootEntityId:dt.sourceEntityId,entityIds:st.map(Ct=>Ct.sceneEntityId)};return{operations:ft,result:void 0,events:[Et]}}}class UpdatePrefabBindingSourceBaselineCommand{constructor(){Rt(this,"name","prefab.updateBindingSourceBaseline")}execute(_e,tt){const{assetId:et,bindingId:nt,instanceRootEntityId:it,sourceRevision:at,entityMappings:ot,componentMappings:st=[]}=tt,ct=_e.prefab.bindings[nt];if(!ct)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${nt}" not found`);if(ct.assetId!==et)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: binding "${nt}" belongs to asset "${ct.assetId}", not "${et}"`);if(tt.preserveMissingAddedEntities&&ct.assetKind!=="glTF")throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: preserveMissingAddedEntities is only allowed for glTF deferred baseline sync");if(!ot.length)throw new CommandError(CommandErrorCode.INVALID_OPERATION,"INVALID_OPERATION: entityMappings is empty");const dt=ot.find(_t=>_t.sceneEntityId===it&&_t.role==="root")??ot.find(_t=>_t.role==="root");if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: missing root mapping for instance root "${it}"`);const ut={},ht=new Set,ft=[];for(const _t of ot){const yt=_e.entities[_t.sceneEntityId];if(!yt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_t.sceneEntityId}" not found`);if(ut[_t.sourceEntityId]||ht.has(_t.sceneEntityId))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: duplicate mapping source="${_t.sourceEntityId}" scene="${_t.sceneEntityId}"`);ut[_t.sourceEntityId]=_t.sceneEntityId,ht.add(_t.sceneEntityId),shouldPreserveNestedInstanceRootLink(_e,_t,tt.sourceEntitySnapshots??ct.sourceEntitySnapshots)||ft.push({op:yt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(_t.sceneEntityId)}/instance`,value:{bindingId:nt,assetId:et,assetKind:ct.assetKind,role:_t.role,sourceEntityId:_t.sourceEntityId}})}for(const _t of st){const yt=_e.entities[_t.sceneEntityId];if(!yt)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${_t.sceneEntityId}" not found`);const bt=yt.components[_t.sceneComponentId];if(!bt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${_t.sceneComponentId}" not found on entity "${_t.sceneEntityId}"`);ft.push({op:bt.instance?"replace":"add",path:`/entities/${encodeJsonPointerSegment(_t.sceneEntityId)}/components/${encodeJsonPointerSegment(_t.sceneComponentId)}/instance`,value:{bindingId:nt,role:"linked",sourceComponentKey:_t.sourceComponentKey}})}const pt=buildBindExistingSourceSnapshots(_e,ot,st,tt.sourceEntitySnapshots,ct.sourceEntitySnapshots),mt=sanitizeOverridesForSourceBaseline(_e,ct,ut,pt,{preserveMissingAddedEntities:tt.preserveMissingAddedEntities,sourceRootEntityId:dt.sourceEntityId,instanceRootEntityId:it}),vt=encodeJsonPointerSegment(nt);return ct.sourceRootEntityId!==dt.sourceEntityId&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceRootEntityId`,value:dt.sourceEntityId}),at!==void 0&&ct.sourceRevision!==at&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceRevision`,value:at}),ct.instanceRootEntityId!==it&&ft.push({op:"replace",path:`/prefab/bindings/${vt}/instanceRootEntityId`,value:it}),ft.push({op:"replace",path:`/prefab/bindings/${vt}/sourceToSceneEntity`,value:ut}),ft.push({op:ct.sourceEntitySnapshots?"replace":"add",path:`/prefab/bindings/${vt}/sourceEntitySnapshots`,value:pt}),ft.push({op:"replace",path:`/prefab/bindings/${vt}/overrides`,value:mt}),{operations:ft,result:void 0,events:[]}}}function removeBindingIdFromAssetIndex(rt,_e,tt,et){const nt=rt.prefab.byAssetId[tt];if(!nt)return;const it=nt.indexOf(et);if(it<0)return;const at=encodeJsonPointerSegment(tt);nt.length===1?_e.push({op:"remove",path:`/prefab/byAssetId/${at}`}):_e.push({op:"remove",path:`/prefab/byAssetId/${at}/${it}`})}function addBindingIdToAssetIndex(rt,_e,tt,et){const nt=rt.prefab.byAssetId[tt],it=encodeJsonPointerSegment(tt);if(!nt){_e.push({op:"add",path:`/prefab/byAssetId/${it}`,value:[et]});return}nt.includes(et)||_e.push({op:"add",path:`/prefab/byAssetId/${it}/${nt.length}`,value:et})}function createRetargetedInstanceLink(rt,_e){const tt={...rt,assetId:_e.assetId,assetKind:_e.assetKind};return _e.assetKey===void 0?delete tt.assetKey:tt.assetKey=_e.assetKey,tt}function buildRetargetRootInstanceOps(rt,_e,tt){var it;const et=[],nt=encodeJsonPointerSegment(_e.id);_e.assetId!==tt.assetId&&et.push({op:"replace",path:`/prefab/bindings/${nt}/assetId`,value:tt.assetId}),_e.assetKind!==tt.assetKind&&et.push({op:"replace",path:`/prefab/bindings/${nt}/assetKind`,value:tt.assetKind}),typeof tt.sourceRevision=="number"&&_e.sourceRevision!==tt.sourceRevision&&et.push({op:"replace",path:`/prefab/bindings/${nt}/sourceRevision`,value:tt.sourceRevision});for(const[at,ot]of Object.entries(rt.entities))((it=ot.instance)==null?void 0:it.bindingId)===_e.id&&et.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(at)}/instance`,value:createRetargetedInstanceLink(ot.instance,tt)});return _e.assetId!==tt.assetId&&(removeBindingIdFromAssetIndex(rt,et,_e.assetId,_e.id),addBindingIdToAssetIndex(rt,et,tt.assetId,_e.id)),et}class UnpackInstanceCommand{constructor(){Rt(this,"name","prefab.unpack")}execute(_e,tt){const{bindingId:et,replacementRootInstance:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);if(nt)return{operations:buildRetargetRootInstanceOps(_e,it,nt),result:void 0,events:[]};const at=buildUnlinkInstanceOps(_e,it),ot=encodeJsonPointerSegment(et);at.push({op:"remove",path:`/prefab/bindings/${ot}`}),removeBindingIdFromAssetIndex(_e,at,it.assetId,et);const st={type:"PrefabBindingRemoved",reason:"unpack",bindingId:et,assetId:it.assetId,instanceRootEntityId:it.instanceRootEntityId};return{operations:at,result:void 0,events:[st]}}}class UnpackByAssetCommand{constructor(){Rt(this,"name","prefab.unpackByAsset")}execute(_e,tt){const{assetId:et}=tt,nt=_e.prefab.byAssetId[et];if(!nt||nt.length===0)return{operations:[],result:void 0,events:[]};const it=[],at=[];for(const st of nt){const ct=_e.prefab.bindings[st];if(!ct)continue;it.push(...buildUnlinkInstanceOps(_e,ct));const dt=encodeJsonPointerSegment(st);it.push({op:"remove",path:`/prefab/bindings/${dt}`}),at.push({type:"PrefabBindingRemoved",reason:"unpackByAsset",bindingId:st,assetId:ct.assetId,instanceRootEntityId:ct.instanceRootEntityId})}const ot=encodeJsonPointerSegment(et);return it.push({op:"remove",path:`/prefab/byAssetId/${ot}`}),{operations:it,result:void 0,events:at}}}function requireSourceComponentKey(rt,_e,tt){var nt;const et=(nt=rt.instance)==null?void 0:nt.sourceComponentKey;if(!et)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab source component "${tt}" on entity "${_e}" is missing sourceComponentKey`);return et}function mergeTransformOverride(rt,_e){if(!(!rt&&!_e))return{...rt!=null&&rt.position||_e!=null&&_e.position?{position:{...(rt==null?void 0:rt.position)??{},...(_e==null?void 0:_e.position)??{}}}:{},...rt!=null&&rt.rotation||_e!=null&&_e.rotation?{rotation:{...(rt==null?void 0:rt.rotation)??{},...(_e==null?void 0:_e.rotation)??{}}}:{},...rt!=null&&rt.scale||_e!=null&&_e.scale?{scale:{...(rt==null?void 0:rt.scale)??{},...(_e==null?void 0:_e.scale)??{}}}:{}}}function mergeEntityOverrideProps(rt,_e){const tt={...rt??{},..._e},et=mergeTransformOverride(rt==null?void 0:rt.transform,_e.transform);return et?tt.transform=et:delete tt.transform,tt}function compactDomainValuePatch(rt,_e){if(_e===void 0)return;if(!isPlainRecord(rt)||!isPlainRecord(_e))return isEqual$2(rt,_e)?void 0:cloneState(_e);const tt={};for(const[et,nt]of Object.entries(_e)){const it=compactDomainValuePatch(rt[et],nt);it!==void 0&&(tt[et]=it)}return Object.keys(tt).length?tt:void 0}function compactDomainRecordPatch(rt,_e){const tt=compactDomainValuePatch(rt??{},_e);return isPlainRecord(tt)&&Object.keys(tt).length?tt:void 0}function compactTransformAgainstSnapshot(rt,_e){if(!_e)return;const tt={};for(const et of["position","rotation","scale"]){const nt=_e[et];if(!nt)continue;const it=compactDomainRecordPatch(rt[et],nt);it&&(tt[et]=it)}return Object.keys(tt).length?tt:void 0}function compactEntityOverrideAgainstSnapshot(rt,_e){if(!rt)return cloneState(_e);const tt={};_e.name!==void 0&&!isEqual$2(_e.name,rt.name)&&(tt.name=cloneState(_e.name)),_e.isActive!==void 0&&!isEqual$2(_e.isActive,rt.isActive)&&(tt.isActive=cloneState(_e.isActive)),_e.layer!==void 0&&!isEqual$2(_e.layer,rt.layer??0)&&(tt.layer=cloneState(_e.layer)),_e.isLocked!==void 0&&!isEqual$2(_e.isLocked,rt.isLocked??!1)&&(tt.isLocked=cloneState(_e.isLocked));const et=compactTransformAgainstSnapshot(rt.transform,_e.transform);return et&&(tt.transform=et),Object.keys(tt).length?tt:void 0}function compactComponentOverrideAgainstSnapshot(rt,_e){return rt?compactDomainRecordPatch(rt.props??{},_e):cloneState(_e)}function createAddedComponentOverrideState(rt,_e,tt){var et;return{componentId:rt,ownerSourceEntityId:_e,type:tt.type,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:cloneState(tt.props),...(et=tt.calls)!=null&&et.length?{calls:cloneState(tt.calls)}:{}}}function isDomainAncestorOrSelf(rt,_e,tt){var it;const et=new Set;let nt=tt;for(;nt&&!et.has(nt);){if(nt===_e)return!0;et.add(nt),nt=((it=rt.entities[nt])==null?void 0:it.parentId)??null}return!1}function resolveAddedEntityParentSceneEntityId(rt,_e,tt,et){var ct,dt;const nt=getSceneEntityIdForPrefabSource(_e,tt);if(nt&&rt.entities[nt])return nt;if(!et||!rt.entities[et])throw new CommandError(CommandErrorCode.PARENT_NOT_FOUND,`PARENT_NOT_FOUND: prefab source parent "${tt}" is not bound in instance "${_e.id}"`,{bindingId:_e.id,parentSourceEntityId:tt});if(!isDomainAncestorOrSelf(rt,_e.instanceRootEntityId,et))throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${et}" is outside prefab instance "${_e.id}"`,{bindingId:_e.id,parentSceneEntityId:et});const it=rt.entities[et],at=(ct=it==null?void 0:it.instance)==null?void 0:ct.bindingId,ot=at?rt.prefab.bindings[at]:void 0,st=ot?getSourceEntityIdForPrefabScene(ot,et,(dt=it==null?void 0:it.instance)==null?void 0:dt.sourceEntityId):null;if(!ot||ot.id===_e.id||ot.assetKind!=="Prefab"&&ot.assetKind!=="glTF"||st!==tt||!isDomainAncestorOrSelf(rt,_e.instanceRootEntityId,ot.instanceRootEntityId))throw new CommandError(CommandErrorCode.PARENT_NOT_FOUND,`PARENT_NOT_FOUND: prefab source parent "${tt}" is not bound in instance "${_e.id}"`,{bindingId:_e.id,parentSourceEntityId:tt,parentSceneEntityId:et});return et}function requirePrefabSourceEntityId(rt,_e,tt){var nt,it,at,ot;if(((nt=rt.instance)==null?void 0:nt.role)==="added")throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${_e}" has no sourceEntityId for prefab override`,{entityId:_e,role:rt.instance.role,bindingId:rt.instance.bindingId});const et=getSourceEntityIdForPrefabScene(tt,_e,(it=rt.instance)==null?void 0:it.sourceEntityId);if(et)return et;throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${_e}" has no sourceEntityId for prefab override`,{entityId:_e,role:(at=rt.instance)==null?void 0:at.role,bindingId:(ot=rt.instance)==null?void 0:ot.bindingId})}function pushTransformReplaceOps(rt,_e,tt){rt.push({op:"replace",path:`/entities/${_e}/transform/position`,value:tt.position}),rt.push({op:"replace",path:`/entities/${_e}/transform/rotation`,value:tt.rotation}),rt.push({op:"replace",path:`/entities/${_e}/transform/scale`,value:tt.scale})}class SetEntityOverrideCommand{constructor(){Rt(this,"name","prefab.setEntityOverride")}execute(_e,tt){var _t,yt,bt,Et;const{entityId:et,overrides:nt}=tt,{entity:it,binding:at}=findBindingByEntityId(_e,et),ot=[],st=encodeJsonPointerSegment(et),ct=requirePrefabSourceEntityId(it,et,at),dt=encodeJsonPointerSegment(ct),ut=encodeJsonPointerSegment(at.id);if(nt.name!==void 0&&ot.push({op:"replace",path:`/entities/${st}/name`,value:nt.name}),nt.isActive!==void 0&&ot.push({op:"replace",path:`/entities/${st}/isActive`,value:nt.isActive}),nt.isLocked!==void 0){const St=((_t=_e.entities[et])==null?void 0:_t.isLocked)!==void 0?"replace":"add";ot.push({op:St,path:`/entities/${st}/isLocked`,value:nt.isLocked})}if(nt.layer!==void 0){const St=((yt=_e.entities[et])==null?void 0:yt.layer)!==void 0?"replace":"add";ot.push({op:St,path:`/entities/${st}/layer`,value:nt.layer})}if(nt.transform!==void 0){const St=nt.transform,At=(bt=_e.entities[et])==null?void 0:bt.transform;St.position&&ot.push({op:"replace",path:`/entities/${st}/transform/position`,value:{...At==null?void 0:At.position,...St.position}}),St.rotation&&ot.push({op:"replace",path:`/entities/${st}/transform/rotation`,value:{...At==null?void 0:At.rotation,...St.rotation}}),St.scale&&ot.push({op:"replace",path:`/entities/${st}/transform/scale`,value:{...At==null?void 0:At.scale,...St.scale}})}const ht=at.overrides.entityProps[ct],ft=mergeEntityOverrideProps(ht,nt),pt=compactEntityOverrideAgainstSnapshot((Et=at.sourceEntitySnapshots)==null?void 0:Et[ct],ft);let mt=null;pt?(ot.push({op:ht?"replace":"add",path:`/prefab/bindings/${ut}/overrides/entityProps/${dt}`,value:pt}),mt="set"):ht&&(ot.push({op:"remove",path:`/prefab/bindings/${ut}/overrides/entityProps/${dt}`}),mt="remove");const vt=[{type:"EntityUpdated",entityId:et,changes:cloneState(nt)}];return mt&&vt.push({type:"PrefabOverrideChanged",action:mt,bindingId:at.id,assetId:at.assetId,bucket:"entityProps",entityId:et,sourceEntityId:ct}),{operations:ot,result:void 0,events:vt}}}class SetComponentOverrideCommand{constructor(){Rt(this,"name","prefab.setComponentOverride")}execute(_e,tt){var xt,Ct;const{entityId:et,componentId:nt,overrides:it}=tt,{entity:at,binding:ot}=findBindingByEntityId(_e,et),st=[],ct=encodeJsonPointerSegment(et),dt=encodeJsonPointerSegment(nt),ut=requirePrefabSourceEntityId(at,et,ot),ht=encodeJsonPointerSegment(ut),ft=encodeJsonPointerSegment(ot.id),pt=at.components[nt];if(!pt)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);for(const[Pt,Tt]of Object.entries(it)){const wt=Object.prototype.hasOwnProperty.call(pt.props,Pt);st.push({op:wt?"replace":"add",path:`/entities/${ct}/components/${dt}/props/${encodeJsonPointerSegment(Pt)}`,value:Tt})}const mt=requireSourceComponentKey(pt,et,nt),vt=encodeJsonPointerSegment(mt),_t=ot.overrides.componentProps[ut],yt=_t==null?void 0:_t[mt],bt={...yt??{},...it},Et=compactComponentOverrideAgainstSnapshot((Ct=(xt=ot.sourceEntitySnapshots)==null?void 0:xt[ut])==null?void 0:Ct.components[mt],bt);let St=null;if(Et)_t?st.push({op:yt?"replace":"add",path:`/prefab/bindings/${ft}/overrides/componentProps/${ht}/${vt}`,value:Et}):st.push({op:"add",path:`/prefab/bindings/${ft}/overrides/componentProps/${ht}`,value:{[mt]:Et}}),St="set";else if(yt){const Pt=Object.keys(_t??{});st.push({op:"remove",path:Pt.length===1?`/prefab/bindings/${ft}/overrides/componentProps/${ht}`:`/prefab/bindings/${ft}/overrides/componentProps/${ht}/${vt}`}),St="remove"}const At=[{type:"ComponentUpdated",entityId:et,componentId:nt,changes:cloneState(it)}];return St&&At.push({type:"PrefabOverrideChanged",action:St,bindingId:ot.id,assetId:ot.assetId,bucket:"componentProps",entityId:et,sourceEntityId:ut,componentId:mt}),{operations:st,result:void 0,events:At}}}class AddEntityOverrideCommand{constructor(){Rt(this,"name","prefab.addEntityOverride")}execute(_e,tt){const{bindingId:et,entityId:nt,name:it,parentSourceEntityId:at,index:ot}=tt,st=_e.prefab.bindings[et];if(!st)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const ct=[],dt=encodeJsonPointerSegment(nt),ut=encodeJsonPointerSegment(et),ht=resolveAddedEntityParentSceneEntityId(_e,st,at,tt.parentSceneEntityId),ft={};if(tt.components)for(const[Et,St]of Object.entries(tt.components))ft[Et]={type:St.type,props:St.props,instance:{bindingId:et,role:"added"}};const pt={id:nt,name:it,isActive:!0,parentId:ht,children:[],transform:tt.transform??createDefaultTransform(),components:ft,instance:{bindingId:et,assetId:st.assetId,assetKind:st.assetKind,role:"added"}};ct.push({op:"add",path:`/entities/${dt}`,value:pt});const{siblings:mt,arrayPath:vt}=getSiblingsInfo(_e,ht),_t=Math.min(Math.max(ot,0),mt.length);ct.push({op:"add",path:`${vt}/${_t}`,value:nt});const yt={entityId:nt,parentSourceEntityId:at,index:_t};ct.push({op:"add",path:`/prefab/bindings/${ut}/overrides/addedEntities/${dt}`,value:yt});const bt=[{type:"EntityCreated",entityId:nt,parentId:ht??null,index:_t,entity:cloneState(pt)},{type:"PrefabOverrideChanged",action:"add",bindingId:et,assetId:st.assetId,bucket:"addedEntities",entityId:nt,sourceEntityId:at}];return{operations:ct,result:void 0,events:bt}}}class AddExistingEntityOverrideCommand{constructor(){Rt(this,"name","prefab.addExistingEntityOverride")}execute(_e,tt){var Ot,Nt;const{bindingId:et,entityId:nt,parentSourceEntityId:it}=tt,at=_e.prefab.bindings[et];if(!at)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const ot=_e.entities[nt];if(!ot)throw new CommandError(CommandErrorCode.ENTITY_NOT_FOUND,`ENTITY_NOT_FOUND: entity "${nt}" not found`);const st=collectSubtree(_e,nt),ct=new Set(st);for(const Mt of st){const Lt=_e.entities[Mt],$t=((Ot=Lt==null?void 0:Lt.instance)==null?void 0:Ot.bindingId)===et&&Lt.instance.role==="added",Dt=isNestedInstanceSubtreeEntity(_e,Lt,et,ct);if(Lt!=null&&Lt.instance&&!$t&&!Dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: entity "${Mt}" already has an instance link`,{entityId:Mt,bindingId:Lt.instance.bindingId,role:Lt.instance.role})}const dt=resolveAddedEntityParentSceneEntityId(_e,at,it,tt.parentSceneEntityId);if(nt===dt||wouldCreateCycle(_e,nt,dt))throw new CommandError(CommandErrorCode.CYCLE_DETECTED,`Cannot add entity "${nt}" to prefab override parent "${dt}"`);const ut=[],ht=encodeJsonPointerSegment(nt),ft=encodeJsonPointerSegment(et),pt=ot.parentId,{siblings:mt,arrayPath:vt}=getSiblingsInfo(_e,pt),_t=mt.indexOf(nt),yt=pt===dt,bt=yt?null:getLocalTransformPreservingWorld(_e,nt,dt),{siblings:Et,arrayPath:St}=getSiblingsInfo(_e,dt),At=Math.max(0,Et.length-(yt&&_t>=0?1:0)),xt=yt&&_t>=0&&_t<tt.index?tt.index-1:tt.index,Ct=Math.min(Math.max(xt,0),At);_t>=0&&(!yt||_t!==Ct)&&ut.push({op:"remove",path:`${vt}/${_t}`}),yt||(ut.push({op:"replace",path:`/entities/${ht}/parentId`,value:dt}),bt&&!transformsClose(ot.transform,bt)&&pushTransformReplaceOps(ut,ht,bt)),(_t===-1||!yt||_t!==Ct)&&ut.push({op:"add",path:`${St}/${Ct}`,value:nt});const Pt={bindingId:et,assetId:at.assetId,assetKind:at.assetKind,role:"added"};for(const Mt of st){const Lt=_e.entities[Mt];if(!Lt||isNestedInstanceSubtreeEntity(_e,Lt,et,ct))continue;const $t=encodeJsonPointerSegment(Mt),Dt=((Nt=Lt.instance)==null?void 0:Nt.bindingId)===et&&Lt.instance.role==="added";ut.push({op:Dt?"replace":"add",path:`/entities/${$t}/instance`,value:Pt});for(const[Bt,Gt]of Object.entries(Lt.components)){const zt=encodeJsonPointerSegment(Bt);ut.push({op:Gt.instance?"replace":"add",path:`/entities/${$t}/components/${zt}/instance`,value:{bindingId:et,role:"added"}})}}const Tt={entityId:nt,parentSourceEntityId:it,index:Ct},wt=at.overrides.addedEntities[nt];ut.push({op:wt?"replace":"add",path:`/prefab/bindings/${ft}/overrides/addedEntities/${ht}`,value:Tt});const It=[{type:"PrefabOverrideChanged",action:"add",bindingId:et,assetId:at.assetId,bucket:"addedEntities",entityId:nt,sourceEntityId:it}];return{operations:ut,result:void 0,events:It}}}function isNestedInstanceSubtreeEntity(rt,_e,tt,et){const nt=_e==null?void 0:_e.instance;if(!nt||nt.bindingId===tt)return!1;const it=rt.prefab.bindings[nt.bindingId];return!!(it&&et.has(it.instanceRootEntityId))}class RemoveSourceEntityOverrideCommand{constructor(){Rt(this,"name","prefab.removeSourceEntityOverride")}execute(_e,tt){var mt,vt,_t,yt;const{entityId:et}=tt,{entity:nt,binding:it}=findBindingByEntityId(_e,et),at=[],ot=encodeJsonPointerSegment(it.id),st=[],ct=bt=>{st.push(bt);const Et=_e.entities[bt];if(Et)for(const St of Et.children)ct(St)};if(ct(et),nt.parentId){const bt=_e.entities[nt.parentId];if(bt){const Et=bt.children.indexOf(et);Et>=0&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(nt.parentId)}/children/${Et}`})}}else{const bt=_e.scene.rootEntityIds.indexOf(et);bt>=0&&at.push({op:"remove",path:`/scene/rootEntityIds/${bt}`})}const dt=Object.fromEntries(st.map(bt=>[bt,cloneState(_e.entities[bt])])),ut=new Set;for(const bt of st){const Et=encodeJsonPointerSegment(bt);at.push({op:"remove",path:`/entities/${Et}`});const St=getSourceEntityIdForPrefabScene(it,bt,(vt=(mt=_e.entities[bt])==null?void 0:mt.instance)==null?void 0:vt.sourceEntityId);if(St){ut.add(St);const At=encodeJsonPointerSegment(St);at.push({op:"add",path:`/prefab/bindings/${ot}/overrides/removedEntities/${At}`,value:!0}),((_t=it.sourceToSceneEntity)==null?void 0:_t[St])!=null&&at.push({op:"remove",path:`/prefab/bindings/${ot}/sourceToSceneEntity/${At}`})}}const ht=(bt,Et)=>{it.overrides[bt][Et]!==void 0&&at.push({op:"remove",path:`/prefab/bindings/${ot}/overrides/${bt}/${encodeJsonPointerSegment(Et)}`})};for(const bt of ut)ht("entityProps",bt),ht("componentProps",bt),ht("removedComponents",bt),ht("addedComponents",bt);const ft=new Set(st);for(const[bt,Et]of Object.entries(it.overrides.addedEntities))!ut.has(Et.parentSourceEntityId)&&!ft.has(bt)||at.push({op:"remove",path:`/prefab/bindings/${ot}/overrides/addedEntities/${encodeJsonPointerSegment(bt)}`});const pt=[{type:"EntityDeleted",entityId:et,snapshot:dt[et],subtreeIds:cloneState(st),subtree:dt},{type:"PrefabOverrideChanged",action:"add",bindingId:it.id,assetId:it.assetId,bucket:"removedEntities",entityId:et,sourceEntityId:(yt=nt.instance)==null?void 0:yt.sourceEntityId}];return{operations:at,result:void 0,events:pt}}}class AddComponentOverrideCommand{constructor(){Rt(this,"name","prefab.addComponentOverride")}execute(_e,tt){var bt;const{entityId:et,componentId:nt,type:it,props:at}=tt,{entity:ot,binding:st}=findBindingByEntityId(_e,et),ct=[],dt=encodeJsonPointerSegment(et),ut=encodeJsonPointerSegment(nt),ht=encodeJsonPointerSegment(st.id),ft=requirePrefabSourceEntityId(ot,et,st),pt=encodeJsonPointerSegment(ft),mt={type:it,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:at,...(bt=tt.calls)!=null&&bt.length?{calls:cloneState(tt.calls)}:{},instance:{bindingId:st.id,role:"added"}};ct.push({op:"add",path:`/entities/${dt}/components/${ut}`,value:mt});const vt=createAddedComponentOverrideState(nt,ft,mt);st.overrides.addedComponents[ft]?ct.push({op:"add",path:`/prefab/bindings/${ht}/overrides/addedComponents/${pt}/${ut}`,value:vt}):ct.push({op:"add",path:`/prefab/bindings/${ht}/overrides/addedComponents/${pt}`,value:{[nt]:vt}});const yt=[{type:"ComponentAdded",entityId:et,componentId:nt,component:cloneState(mt)},{type:"PrefabOverrideChanged",action:"add",bindingId:st.id,assetId:st.assetId,bucket:"addedComponents",entityId:et,sourceEntityId:ft,componentId:nt}];return{operations:ct,result:void 0,events:yt}}}class UpdateAddedComponentOverrideCommand{constructor(){Rt(this,"name","prefab.updateAddedComponentOverride")}execute(_e,tt){var yt,bt;const{entityId:et,componentId:nt,overrides:it}=tt,{entity:at,binding:ot}=findBindingByEntityId(_e,et),st=requirePrefabSourceEntityId(at,et,ot),ct=at.components[nt];if(!ct)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);if(((yt=ct.instance)==null?void 0:yt.role)!=="added")throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: component "${nt}" on entity "${et}" is not a prefab added component`);const dt=(bt=ot.overrides.addedComponents[st])==null?void 0:bt[nt];if(!dt)throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab added component "${nt}" on source entity "${st}" is missing addedComponents override`);const ut=[],ht={},ft={...ct.props},pt=encodeJsonPointerSegment(et),mt=encodeJsonPointerSegment(nt);for(const[Et,St]of Object.entries(it)){if(isEqual$2(ct.props[Et],St))continue;const At=encodeJsonPointerSegment(Et),xt=Object.prototype.hasOwnProperty.call(ct.props,Et);ut.push({op:xt?"replace":"add",path:`/entities/${pt}/components/${mt}/props/${At}`,value:cloneState(St)}),ft[Et]=cloneState(St),ht[Et]=cloneState(St)}const vt=createAddedComponentOverrideState(nt,st,{...ct,props:ft});isEqual$2(dt,vt)||ut.push({op:"replace",path:`/prefab/bindings/${encodeJsonPointerSegment(ot.id)}/overrides/addedComponents/${encodeJsonPointerSegment(st)}/${mt}`,value:vt});const _t=[];return Object.keys(ht).length>0&&_t.push({type:"ComponentUpdated",entityId:et,componentId:nt,changes:ht}),ut.length>0&&_t.push({type:"PrefabOverrideChanged",action:"set",bindingId:ot.id,assetId:ot.assetId,bucket:"addedComponents",entityId:et,sourceEntityId:st,componentId:nt}),{operations:ut,result:void 0,events:_t}}}class RemoveSourceComponentOverrideCommand{constructor(){Rt(this,"name","prefab.removeSourceComponentOverride")}execute(_e,tt){const{entityId:et,componentId:nt}=tt,{entity:it,binding:at}=findBindingByEntityId(_e,et),ot=[],st=encodeJsonPointerSegment(et),ct=encodeJsonPointerSegment(nt),dt=encodeJsonPointerSegment(at.id),ut=requirePrefabSourceEntityId(it,et,at),ht=encodeJsonPointerSegment(ut),ft=it.components[nt];if(!ft)throw new CommandError(CommandErrorCode.COMPONENT_NOT_FOUND,`COMPONENT_NOT_FOUND: component "${nt}" not found on entity "${et}"`);ot.push({op:"remove",path:`/entities/${st}/components/${ct}`});const pt=requireSourceComponentKey(ft,et,nt),mt=encodeJsonPointerSegment(pt);at.overrides.removedComponents[ut]?ot.push({op:"add",path:`/prefab/bindings/${dt}/overrides/removedComponents/${ht}/${mt}`,value:!0}):ot.push({op:"add",path:`/prefab/bindings/${dt}/overrides/removedComponents/${ht}`,value:{[pt]:!0}});const _t=[{type:"ComponentRemoved",entityId:et,componentId:nt,snapshot:cloneState(ft)},{type:"PrefabOverrideChanged",action:"add",bindingId:at.id,assetId:at.assetId,bucket:"removedComponents",entityId:et,sourceEntityId:ut,componentId:pt}];return{operations:ot,result:void 0,events:_t}}}function toComponentStateSnapshot(rt){if(!rt)return;const{id:_e,entityId:tt,...et}=rt;return et}function removeNestedOverrideContainerIfEmpty(rt,_e,tt,et,nt){Object.keys(_e.overrides[et][nt]??{}).length===1&&rt.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(tt)}/overrides/${et}/${encodeJsonPointerSegment(nt)}`})}function pushAcceptedAddedEntityPromotionOps(rt,_e,tt,et,nt,it,at){var ht,ft,pt,mt,vt;const ot=encodeJsonPointerSegment(et),st=collectSubtree(_e,nt),ct=new Map,dt=resolveSourceInsertionIndexForAddedEntity(_e,tt,it,nt,at);for(const _t of st)ct.set(_t,_t);tt.sourceEntitySnapshots||rt.push({op:"add",path:`/prefab/bindings/${ot}/sourceEntitySnapshots`,value:{}});const ut=(ht=tt.sourceEntitySnapshots)==null?void 0:ht[it];if(ut){const _t=[...ut.childSourceEntityIds??[]];_t.includes(nt)||_t.splice(Math.min(Math.max(dt,0),_t.length),0,nt),rt.push({op:"replace",path:`/prefab/bindings/${ot}/sourceEntitySnapshots/${encodeJsonPointerSegment(it)}/childSourceEntityIds`,value:_t})}for(const _t of st){const yt=_e.entities[_t];if(!yt)continue;const bt=ct.get(_t)??_t,Et=encodeJsonPointerSegment(_t),St=`/prefab/bindings/${ot}/sourceToSceneEntity/${encodeJsonPointerSegment(bt)}`;rt.push({op:((ft=tt.sourceToSceneEntity)==null?void 0:ft[bt])===void 0?"add":"replace",path:St,value:_t});const At={};for(const[Ot,Nt]of Object.entries(yt.components))At[Ot]={sceneComponentId:Ot,type:Nt.type,...Nt.refId?{refId:Nt.refId}:{},...Nt.scriptKey?{scriptKey:Nt.scriptKey}:{},props:cloneState(Nt.props),...(pt=Nt.calls)!=null&&pt.length?{calls:cloneState(Nt.calls)}:{}};const xt=_t===nt?it:ct.get(yt.parentId??""),Ct=yt.parentId?((mt=_e.entities[yt.parentId])==null?void 0:mt.children)??[]:_e.scene.rootEntityIds,Pt=_t===nt?dt:Math.max(Ct.indexOf(_t),0),Tt=yt.children.map(Ot=>ct.get(Ot)).filter(Ot=>!!Ot),wt={sceneEntityId:_t,parentSourceEntityId:xt??null,childSourceEntityIds:Tt,childIndex:Pt,name:yt.name,isActive:yt.isActive,...yt.layer!==void 0?{layer:yt.layer}:{},...yt.isLocked!==void 0?{isLocked:yt.isLocked}:{},transform:cloneTransform(yt.transform),components:At},It=`/prefab/bindings/${ot}/sourceEntitySnapshots/${encodeJsonPointerSegment(bt)}`;rt.push({op:((vt=tt.sourceEntitySnapshots)==null?void 0:vt[bt])===void 0?"add":"replace",path:It,value:wt}),rt.push({op:yt.instance?"replace":"add",path:`/entities/${Et}/instance`,value:{bindingId:et,assetId:tt.assetId,assetKind:tt.assetKind,role:"linked",sourceEntityId:bt}});for(const[Ot,Nt]of Object.entries(yt.components)){const Mt=encodeJsonPointerSegment(Ot);rt.push({op:Nt.instance?"replace":"add",path:`/entities/${Et}/components/${Mt}/instance`,value:{bindingId:et,role:"linked",sourceComponentKey:Ot}})}}}function resolveSourceInsertionIndexForAddedEntity(rt,_e,tt,et,nt){var dt,ut,ht;const it=getSceneEntityIdForPrefabSource(_e,tt),at=it?((dt=rt.entities[it])==null?void 0:dt.children)??[]:rt.scene.rootEntityIds,ot=new Set(((ht=(ut=_e.sourceEntitySnapshots)==null?void 0:ut[tt])==null?void 0:ht.childSourceEntityIds)??[]);if(!ot.size)return 0;let st=0;const ct=at.includes(et)?at.indexOf(et):Math.min(Math.max(nt,0),at.length);for(let ft=0;ft<ct;ft+=1){const pt=at[ft],mt=getNormalizedSourceEntityIdFromBinding(rt,_e,pt);mt&&ot.has(mt)&&(st+=1)}return st}function getNormalizedSourceEntityIdFromBinding(rt,_e,tt){var nt;const et=rt.entities[tt];return(nt=et==null?void 0:et.instance)!=null&&nt.sourceEntityId?et.instance.sourceEntityId:getSourceEntityIdForPrefabScene(_e,tt)}function requireOverrideId(rt,_e){const tt=rt[_e];if(typeof tt=="string"&&tt.length>0)return tt;throw new CommandError(CommandErrorCode.INVALID_OPERATION,`INVALID_OPERATION: prefab.${rt.type} requires ${_e}`)}class RevertOverrideCommand{constructor(){Rt(this,"name","prefab.revertOverride")}execute(_e,tt){var ut,ht,ft,pt,mt,vt,_t;const{bindingId:et,type:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const at=[],ot=[],st=encodeJsonPointerSegment(et),ct=it.sourceEntitySnapshots??{},dt=normalizeDomainState(_e);switch(nt){case"entityProps":{const yt=tt.sourceEntityId,bt=encodeJsonPointerSegment(yt),Et=ct[yt],St=getSceneEntityIdForPrefabSource(it,yt),At=it.overrides.entityProps[yt];if(Et&&St&&At){const xt=encodeJsonPointerSegment(St),Ct={};At.name!==void 0&&(at.push({op:"replace",path:`/entities/${xt}/name`,value:Et.name}),Ct.name=Et.name),At.isActive!==void 0&&(at.push({op:"replace",path:`/entities/${xt}/isActive`,value:Et.isActive}),Ct.isActive=Et.isActive),At.layer!==void 0&&(Et.layer!==void 0?(at.push({op:"replace",path:`/entities/${xt}/layer`,value:Et.layer}),Ct.layer=Et.layer):((ut=_e.entities[St])==null?void 0:ut.layer)!==void 0&&at.push({op:"remove",path:`/entities/${xt}/layer`})),(ht=At.transform)!=null&&ht.position&&(at.push({op:"replace",path:`/entities/${xt}/transform/position`,value:cloneState(Et.transform.position)}),(Ct.transform??(Ct.transform={})).position=cloneState(Et.transform.position)),(ft=At.transform)!=null&&ft.rotation&&(at.push({op:"replace",path:`/entities/${xt}/transform/rotation`,value:cloneState(Et.transform.rotation)}),(Ct.transform??(Ct.transform={})).rotation=cloneState(Et.transform.rotation)),(pt=At.transform)!=null&&pt.scale&&(at.push({op:"replace",path:`/entities/${xt}/transform/scale`,value:cloneState(Et.transform.scale)}),(Ct.transform??(Ct.transform={})).scale=cloneState(Et.transform.scale)),Object.keys(Ct).length>0&&ot.push({type:"EntityUpdated",entityId:St??void 0,changes:Ct})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/entityProps/${bt}`}),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"entityProps",entityId:St??void 0,sourceEntityId:yt});break}case"addedEntities":{const yt=tt.entityId,bt=[],Et=Ct=>{bt.push(Ct);const Pt=_e.entities[Ct];if(Pt)for(const Tt of Pt.children)Et(Tt)};Et(yt);const St=_e.entities[yt],At=Object.fromEntries(bt.map(Ct=>[Ct,cloneState(_e.entities[Ct])]));if(St!=null&&St.parentId){const Ct=_e.entities[St.parentId],Pt=(Ct==null?void 0:Ct.children.indexOf(yt))??-1;Pt>=0&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(St.parentId)}/children/${Pt}`})}for(const Ct of bt){const Pt=encodeJsonPointerSegment(Ct);at.push({op:"remove",path:`/entities/${Pt}`}),it.overrides.addedEntities[Ct]&&at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedEntities/${Pt}`})}At[yt]&&ot.push({type:"EntityDeleted",entityId:yt,snapshot:At[yt],subtreeIds:cloneState(bt),subtree:At});const xt=it.overrides.addedEntities[yt];ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"addedEntities",entityId:yt,sourceEntityId:xt==null?void 0:xt.parentSourceEntityId});break}case"removedEntities":{const yt=tt.sourceEntityId,bt=ct[yt];if(!bt){at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(yt)}`});break}const Et=[],St=xt=>{var Ct,Pt;Et.push(xt);for(const Tt of((Ct=ct[xt])==null?void 0:Ct.childSourceEntityIds)??[])(it.overrides.removedEntities[Tt]||((Pt=ct[Tt])==null?void 0:Pt.parentSourceEntityId)===xt)&&St(Tt)};St(yt);const At=bt.parentSourceEntityId;if(At){const xt=getSceneEntityIdForPrefabSource(it,At);if(xt){const Ct=_e.entities[xt],Pt=Math.min(bt.childIndex,(Ct==null?void 0:Ct.children.length)??0);at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(xt)}/children/${Pt}`,value:bt.sceneEntityId})}}else{const xt=Math.min(bt.childIndex,_e.scene.rootEntityIds.length);at.push({op:"add",path:`/scene/rootEntityIds/${xt}`,value:bt.sceneEntityId})}for(const xt of Et){const Ct=ct[xt];if(!Ct)continue;const Pt=Ct.sceneEntityId,Tt=Ct.parentSourceEntityId?((mt=ct[Ct.parentSourceEntityId])==null?void 0:mt.sceneEntityId)??null:null,wt=Ct.childSourceEntityIds.map(Nt=>{var Mt;return(Mt=ct[Nt])==null?void 0:Mt.sceneEntityId}).filter(Nt=>!!Nt),It=Object.fromEntries(Object.entries(Ct.components).map(([Nt,Mt])=>{const Lt={type:Mt.type,props:cloneState(Mt.props),instance:{bindingId:et,role:"linked",sourceComponentKey:Nt}};return[Mt.sceneComponentId,Lt]})),Ot={id:Pt,name:Ct.name,isActive:Ct.isActive,parentId:Tt,children:wt,transform:cloneTransform(Ct.transform),components:It,...Ct.layer!==void 0?{layer:Ct.layer}:{},instance:{bindingId:et,assetId:it.assetId,assetKind:it.assetKind,role:xt===it.sourceRootEntityId?"root":"linked",sourceEntityId:xt}};at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(Pt)}`,value:Ot}),ot.push({type:"EntityCreated",entityId:Pt??void 0,parentId:Tt,index:Ct.childIndex,entity:cloneState(Ot)}),at.push({op:"add",path:`/prefab/bindings/${st}/sourceToSceneEntity/${encodeJsonPointerSegment(xt)}`,value:Pt}),it.overrides.removedEntities[xt]&&at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(xt)}`})}ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"removedEntities",entityId:bt.sceneEntityId,sourceEntityId:yt});break}case"componentProps":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=it.overrides.componentProps[yt],xt=At==null?void 0:At[bt],Ct=(vt=ct[yt])==null?void 0:vt.components[bt],Pt=getSceneEntityIdForPrefabSource(it,yt),Tt=Ct==null?void 0:Ct.sceneComponentId,wt=Pt&&Tt?getNormalizedComponent(dt,Pt,Tt):void 0;if(xt&&Pt&&Tt&&wt&&Ct){const It=encodeJsonPointerSegment(Pt),Ot=encodeJsonPointerSegment(Tt),Nt={};for(const Mt of Object.keys(xt)){const Lt=encodeJsonPointerSegment(Mt);Mt in Ct.props?(at.push({op:"replace",path:`/entities/${It}/components/${Ot}/props/${Lt}`,value:cloneState(Ct.props[Mt])}),Nt[Mt]=cloneState(Ct.props[Mt])):Mt in wt.props&&at.push({op:"remove",path:`/entities/${It}/components/${Ot}/props/${Lt}`})}Object.keys(Nt).length>0&&ot.push({type:"ComponentUpdated",entityId:Pt??void 0,componentId:Tt,changes:Nt})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/componentProps/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"componentProps",yt),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"componentProps",entityId:Pt??void 0,sourceEntityId:yt,componentId:bt});break}case"addedComponents":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=getSceneEntityIdForPrefabSource(it,yt),xt=At?toComponentStateSnapshot(getNormalizedComponent(dt,At,bt)):void 0;At&&at.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(At)}/components/${St}`}),at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedComponents/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"addedComponents",yt),At&&xt&&ot.push({type:"ComponentRemoved",entityId:At??void 0,componentId:bt,snapshot:cloneState(xt)}),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"addedComponents",entityId:At??void 0,sourceEntityId:yt,componentId:bt});break}case"removedComponents":{const yt=tt.sourceEntityId,bt=tt.componentId,Et=encodeJsonPointerSegment(yt),St=encodeJsonPointerSegment(bt),At=getSceneEntityIdForPrefabSource(it,yt),xt=(_t=ct[yt])==null?void 0:_t.components[bt];if(At&&xt){const Ct={type:xt.type,props:cloneState(xt.props),instance:{bindingId:et,role:"linked",sourceComponentKey:bt}};at.push({op:"add",path:`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(xt.sceneComponentId)}`,value:Ct}),ot.push({type:"ComponentAdded",entityId:At??void 0,componentId:xt.sceneComponentId,component:cloneState(Ct)})}at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedComponents/${Et}/${St}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"removedComponents",yt),ot.push({type:"PrefabOverrideChanged",action:"revert",bindingId:et,assetId:it.assetId,bucket:"removedComponents",entityId:At??void 0,sourceEntityId:yt,componentId:bt});break}}return{operations:at,result:void 0,events:ot}}}class AcceptOverrideCommand{constructor(){Rt(this,"name","prefab.acceptOverride")}execute(_e,tt){var ct,dt,ut;const{bindingId:et,type:nt}=tt,it=_e.prefab.bindings[et];if(!it)throw new CommandError(CommandErrorCode.BINDING_NOT_FOUND,`BINDING_NOT_FOUND: binding "${et}" not found`);const at=[],ot=[],st=encodeJsonPointerSegment(et);switch(nt){case"entityProps":{const ht=requireOverrideId(tt,"sourceEntityId");if(!it.overrides.entityProps[ht])break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/entityProps/${encodeJsonPointerSegment(ht)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"entityProps",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht});break}case"componentProps":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((ct=it.overrides.componentProps[ht])!=null&&ct[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/componentProps/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"componentProps",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"componentProps",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}case"removedEntities":{const ht=requireOverrideId(tt,"sourceEntityId");if(!it.overrides.removedEntities[ht])break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedEntities/${encodeJsonPointerSegment(ht)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"removedEntities",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht});break}case"removedComponents":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((dt=it.overrides.removedComponents[ht])!=null&&dt[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/removedComponents/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"removedComponents",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"removedComponents",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}case"addedEntities":{const ht=requireOverrideId(tt,"entityId"),ft=it.overrides.addedEntities[ht];if(!ft)break;const pt=collectSubtree(_e,ht);pushAcceptedAddedEntityPromotionOps(at,_e,it,et,ht,ft.parentSourceEntityId,ft.index);for(const mt of pt){const vt=it.overrides.addedEntities[mt];vt&&(at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedEntities/${encodeJsonPointerSegment(mt)}`}),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"addedEntities",entityId:mt,sourceEntityId:vt.parentSourceEntityId}))}break}case"addedComponents":{const ht=requireOverrideId(tt,"sourceEntityId"),ft=requireOverrideId(tt,"componentId");if(!((ut=it.overrides.addedComponents[ht])!=null&&ut[ft]))break;at.push({op:"remove",path:`/prefab/bindings/${st}/overrides/addedComponents/${encodeJsonPointerSegment(ht)}/${encodeJsonPointerSegment(ft)}`}),removeNestedOverrideContainerIfEmpty(at,it,et,"addedComponents",ht),ot.push({type:"PrefabOverrideChanged",action:"remove",bindingId:et,assetId:it.assetId,bucket:"addedComponents",entityId:getSceneEntityIdForPrefabSource(it,ht)??void 0,sourceEntityId:ht,componentId:ft});break}}return{operations:at,result:void 0,events:ot}}}class RebaseInstancesCommand{constructor(){Rt(this,"name","prefab.rebaseInstances")}execute(_e,tt){const{assetId:et,newRevision:nt}=tt,it=_e.prefab.byAssetId[et];if(!it||it.length===0)return{operations:[],result:void 0,events:[]};const at=[],ot=[];for(const st of it){const ct=_e.prefab.bindings[st];if(!ct)continue;const dt=encodeJsonPointerSegment(st);at.push({op:"replace",path:`/prefab/bindings/${dt}/sourceRevision`,value:nt}),ot.push({type:"PrefabBindingRebased",bindingId:st,assetId:et,previousRevision:ct.sourceRevision,sourceRevision:nt})}return{operations:at,result:void 0,events:ot}}}class PrefabFacade{constructor(_e){Rt(this,"instantiateCmd",new InstantiatePrefabCommand);Rt(this,"bindExistingInstanceCmd",new BindExistingPrefabInstanceCommand);Rt(this,"updateBindingSourceBaselineCmd",new UpdatePrefabBindingSourceBaselineCommand);Rt(this,"unpackCmd",new UnpackInstanceCommand);Rt(this,"unpackByAssetCmd",new UnpackByAssetCommand);Rt(this,"setEntityOverrideCmd",new SetEntityOverrideCommand);Rt(this,"setComponentOverrideCmd",new SetComponentOverrideCommand);Rt(this,"addEntityOverrideCmd",new AddEntityOverrideCommand);Rt(this,"addExistingEntityOverrideCmd",new AddExistingEntityOverrideCommand);Rt(this,"removeSourceEntityOverrideCmd",new RemoveSourceEntityOverrideCommand);Rt(this,"addComponentOverrideCmd",new AddComponentOverrideCommand);Rt(this,"updateAddedComponentOverrideCmd",new UpdateAddedComponentOverrideCommand);Rt(this,"removeSourceComponentOverrideCmd",new RemoveSourceComponentOverrideCommand);Rt(this,"revertOverrideCmd",new RevertOverrideCommand);Rt(this,"acceptOverrideCmd",new AcceptOverrideCommand);Rt(this,"rebaseInstancesCmd",new RebaseInstancesCommand);Rt(this,"_logger");this.root=_e,this._logger=_e.createLogger("PrefabFacade")}persistScene(){var _e,tt;(_e=this.root.domainStore)!=null&&_e.isHistoryPaused||(tt=this.root.projectStore)==null||tt.persistSceneDebounced("PrefabFacade")}get state(){return this.root.domainStore.state}getPrefabStateForSerialization(){var nt,it,at;const _e=this.root.domainStore.state.prefab;if(!_e||Object.keys(_e.bindings).length===0)return null;const tt=this.root.domainStore.state.entities,et={bindings:{},byAssetId:{}};for(const[ot,st]of Object.entries(_e.bindings)){const ct=tt[st.instanceRootEntityId];((nt=ct==null?void 0:ct.instance)==null?void 0:nt.bindingId)===ot&&(et.bindings[ot]=structuredClone(st))}for(const ot of Object.values(et.bindings))for(const st of Object.keys(ot.overrides.addedEntities??{}))tt[st]||delete ot.overrides.addedEntities[st];for(const[ot,st]of Object.entries(et.bindings)){const ct=(it=et.byAssetId)[at=st.assetId]??(it[at]=[]);ct.includes(ot)||ct.push(ot)}return Object.keys(et.bindings).length===0?null:et}instantiate(_e){var st;const tt=_e.bindingId??`binding-${v4().slice(0,8)}`,et=_e.assetId,nt=_e.parentId??null,it=this.buildInstantiateEntities(_e.sourceEntities,tt,et),at=((st=it[0])==null?void 0:st.id)??"",ot={assetId:et,bindingId:tt,parentId:nt,rootTransform:_e.rootTransform,entities:it};return this.root.commandBus.execute(this.instantiateCmd,ot,"prefab.instantiate"),this.persistScene(),{bindingId:tt,rootEntityId:at}}instantiateFromSchema(_e){const tt=_e.schemas.map(et=>({sourceEntityId:et.sourceEntityId,name:et.name,parentSourceId:et.parentSourceId??null,transform:et.transform,components:et.components}));return this.instantiate({assetId:_e.assetId,parentId:_e.parentId??null,bindingId:_e.bindingId,rootTransform:_e.rootTransform,sourceEntities:tt})}bindExistingInstance(_e){const tt=_e.bindingId??`binding-${v4().slice(0,8)}`,et={assetId:_e.assetId,assetKind:_e.assetKind,bindingId:tt,instanceRootEntityId:_e.instanceRootEntityId,sourceRevision:_e.sourceRevision,entityMappings:_e.entityMappings,componentMappings:_e.componentMappings,sourceEntitySnapshots:_e.sourceEntitySnapshots};if(_e.undoable)this.root.commandBus.execute(this.bindExistingInstanceCmd,et,"prefab.bindExistingInstance");else{const nt=this.bindExistingInstanceCmd.execute(this.root.domainStore.state,et);this.root.domainStore.applySystem(nt.operations)}return this.persistScene(),tt}updateBindingSourceBaseline(_e){const tt=this.updateBindingSourceBaselineCmd.execute(this.root.domainStore.state,_e);this.root.domainStore.applySystem(tt.operations)}unpack(_e,tt){this.root.commandBus.execute(this.unpackCmd,{bindingId:_e,replacementRootInstance:tt==null?void 0:tt.replacementRootInstance},"prefab.unpack"),this.persistScene()}unpackByAsset(_e){this.root.commandBus.execute(this.unpackByAssetCmd,{assetId:_e},"prefab.unpackByAsset"),this.persistScene()}setEntityOverride(_e,tt){this.root.commandBus.execute(this.setEntityOverrideCmd,{entityId:_e,overrides:tt},"prefab.setEntityOverride"),this.persistScene()}setComponentOverride(_e,tt,et){this.root.commandBus.execute(this.setComponentOverrideCmd,{entityId:_e,componentId:tt,overrides:et},"prefab.setComponentOverride"),this.persistScene()}addEntityOverride(_e,tt){const et=tt.entityId??`entity-${v4().slice(0,8)}`;return this.root.commandBus.execute(this.addEntityOverrideCmd,{bindingId:_e,entityId:et,name:tt.name,parentSourceEntityId:tt.parentSourceEntityId,parentSceneEntityId:tt.parentSceneEntityId,index:tt.index??0,transform:tt.transform,components:tt.components},"prefab.addEntityOverride"),this.persistScene(),et}addExistingEntityOverride(_e,tt,et){this.root.commandBus.execute(this.addExistingEntityOverrideCmd,{bindingId:_e,entityId:tt.entityId,parentSourceEntityId:tt.parentSourceEntityId,parentSceneEntityId:tt.parentSceneEntityId,index:tt.index??0},"prefab.addExistingEntityOverride"),(et==null?void 0:et.persist)!==!1&&this.persistScene()}removeSourceEntityForSceneEntity(_e){this.root.commandBus.execute(this.removeSourceEntityOverrideCmd,{entityId:_e},"prefab.removeSourceEntityOverride"),this.persistScene()}addComponentOverride(_e,tt){const et=tt.componentId??`comp-${v4().slice(0,8)}`;return this.root.commandBus.execute(this.addComponentOverrideCmd,{entityId:_e,componentId:et,type:tt.type,refId:tt.refId,scriptKey:tt.scriptKey,props:tt.props??{},calls:tt.calls},"prefab.addComponentOverride"),this.persistScene(),et}updateAddedComponentOverride(_e,tt,et){this.root.commandBus.execute(this.updateAddedComponentOverrideCmd,{entityId:_e,componentId:tt,overrides:et},"prefab.updateAddedComponentOverride"),this.persistScene()}removeSourceComponent(_e,tt){this.root.commandBus.execute(this.removeSourceComponentOverrideCmd,{entityId:_e,componentId:tt},"prefab.removeSourceComponentOverride"),this.persistScene()}revertOverride(_e,tt,et){this.root.commandBus.execute(this.revertOverrideCmd,{bindingId:_e,type:tt,...et},"prefab.revertOverride"),this.persistScene()}acceptOverride(_e,tt,et){this.root.commandBus.execute(this.acceptOverrideCmd,{bindingId:_e,type:tt,...et},"prefab.acceptOverride"),this.persistScene()}updatePrefabContent(_e,tt){const et=this.rebaseInstancesCmd.execute(this.root.domainStore.state,{assetId:_e,newRevision:tt});this.root.domainStore.applySystem(et.operations),this.persistScene()}buildInstantiateEntities(_e,tt,et){const nt=new Map;for(const it of _e)nt.set(it.sourceEntityId,`entity-${v4().slice(0,8)}`);return _e.map(it=>{var ct;const at=nt.get(it.sourceEntityId),ot=it.parentSourceId!==null?nt.get(it.parentSourceId)??null:null,st=(ct=it.components)==null?void 0:ct.map(dt=>({id:`comp-${v4().slice(0,8)}`,type:dt.type,props:dt.props??{},sourceComponentKey:dt.sourceComponentKey}));return{id:at,name:it.name,parentId:ot,sourceEntityId:it.sourceEntityId,transform:it.transform,components:st}})}}function collectCreateByAddResumeCandidates(rt){if(rt.commandName!=="redo:asset.create")return[];const _e=[],tt=new Set;for(const et of rt.operations){if(et.op!=="add")continue;const nt=et.path.match(/^\/assets\/([^/]+)$/);if(!nt)continue;const it=nt[1];if(tt.has(it))continue;const at=rt.assets[it];at&&at.status==="uploading"&&(typeof at.stagingRef!="string"||!at.stagingRef.startsWith("local/")||at.serverId||at.url||(tt.add(it),_e.push(it)))}return _e}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/**
|
|
711
711
|
* @license React
|
|
712
712
|
* react-jsx-runtime.production.min.js
|
|
713
713
|
*
|
|
@@ -29225,7 +29225,7 @@ gl_FragColor = baseColor ; }`]]}]}]};Shader.find("plain-color")||Shader._createF
|
|
|
29225
29225
|
componentClass: ${it}
|
|
29226
29226
|
domainComponentId: ${vt}
|
|
29227
29227
|
engineProjection: ${this.root.engineProjection?"exists":"null"}
|
|
29228
|
-
Possible causes: ComponentFactory not injected, component type not registered, or projection apply failed.`)}else mt=this.engineObject.addComponent(EditorComponent.getEngineComponent(it));if(St){vt&&(St.id=vt),et!==void 0?this._components.splice(et,0,St):this._components.push(St),(ht=St.onAddToEntity)==null||ht.call(St,this),await St.bindEngineObject(mt),this.root.viewportStore.onComponentAdd(St);const{EditorScene:At}=await __vitePreload(()=>Promise.resolve().then(()=>EditorScene$1),void 0);return this.entityManager instanceof At&&MessageCenter.dispatch("ComponentAddToScene",St),St}}return null}removeComponent(tt){let et;if(typeof tt!="number"?et=this.components.indexOf(tt):et=tt,et===-1)return;const nt=this.components[et];EditorComponent.removeCheck(this,nt)&&(nt.isPrefabComponent?this._removePrefabComponent(nt):this._removeSelfComponent(et),this.root.projectStore.debouncedUpdateSceneAsset())}setComponentIndex(tt,et){const nt=this._components,it=nt.indexOf(tt);it===-1||it===et||(nt.splice(it,1),nt.splice(et,0,tt),this.root.projectStore.debouncedUpdateSceneAsset())}_removeSelfComponent(tt){var it;const et=this.components[tt];et.destroy(!0),tt>=this._components.length?(it=this.strippedEntity)==null||it._components.splice(tt-this._components.length,1):this._components.splice(tt,1);const nt=EditorComponent.getRegisteredComponent(et.type);nt&&nt.external&&nt.refMap.delete(this.id)}addComponentFromDomain(tt,et){var ct,dt,ut,ht,ft,pt;if(this.components.find(mt=>mt.id===tt))return;const nt={type:et.type,...et.refId?{script:{$ref:et.refId,...et.scriptKey?{key:et.scriptKey}:{}}}:{},...et.props?{props:et.props}:{},...(ct=et.calls)!=null&&ct.length?{calls:et.calls}:{}},it=EditorComponent.createComponentModel(nt,this);if(!it)return;if(et.props){const mt=(dt=getComponentSemantics(et.type))==null?void 0:dt.methodKeys;if(mt)for(const vt of mt)vt in et.props&&(it[vt]=toJS(et.props[vt]))}traceLog("EntityModel",`[AddCompFromDomain] created ${et.type} for entity ${this.name}`),it.id=tt,this._components.push(it),(ut=it.onAddToEntity)==null||ut.call(it,this);const at=(ht=this.root.engineProjection)==null?void 0:ht.getComponent(tt),ot=!at&&et.type==="Transform"&&!!((ft=this.engineObject)!=null&&ft.transform),st=at??(ot?(pt=this.engineObject)==null?void 0:pt.transform:void 0);st&&(ot?it.bindEngineObject(st,{ownsEngineObject:!1}):it.bindEngineObject(st)).then(()=>{var vt,_t;traceLog("EntityModel",`[AddCompFromDomain] bound ${et.type} engineComp, material: ${(_t=(vt=st==null?void 0:st.getMaterial)==null?void 0:vt.call(st,0))==null?void 0:_t.name}`),it.ownsEngineObject!==!1&&this.root.viewportStore.onComponentAdd(it)})}removeComponentFromDomain(tt){removeComponentFromDomain({components:this.components,removeSelfComponent:et=>this._removeSelfComponent(et)},tt)}syncRemovedComponentPlaceholdersFromDomain(){var nt;const tt=this._collectRemovedComponentPlaceholdersFromDomain(),et=new Set(tt.map(it=>it.id));for(let it=this._components.length-1;it>=0;it--){const at=this._components[it];at.removedComponentMeta&&(et.has(at.id)||this._components.splice(it,1))}for(const it of tt){const at=this._components.find(st=>st.id===it.id);if(at){at.removedComponentMeta=it.meta,at.removedComponent=!0;continue}const ot=EditorComponent.createComponentModel(it.schema,this);if(!ot)throw new Error(`Cannot materialize removed prefab component placeholder "${it.meta.componentType}" on entity "${this.id}"`);ot.id=it.id,EditorComponent.convertToPrefabComponent(ot),ot.removeByPrefab(it.meta),(nt=ot.onAddToEntity)==null||nt.call(ot,this),this._components.splice(Math.min(it.meta.componentIndex,this._components.length),0,ot)}}_collectRemovedComponentPlaceholdersFromDomain(){var at,ot;const tt=this.root.domainStore.getNormalizedState();if(!tt.entities[this.id])return[];const nt=new Set(tt.relations.entityComponents[this.id]??[]),it=[];for(const st of Object.values(tt.prefab.bindings??{}))for(const[ct,dt]of Object.entries(st.overrides.removedComponents??{})){if((at=st.overrides.removedEntities)!=null&&at[ct]||getSceneEntityIdForPrefabSource(st,ct)!==this.id)continue;const ht=(ot=st.sourceEntitySnapshots)==null?void 0:ot[ct];if(!ht)throw new Error(`Cannot materialize removed prefab component placeholders: binding "${st.id}" is missing source snapshot "${ct}"`);const ft=Object.keys(ht.components??{});for(const[pt,mt]of Object.entries(dt??{})){if(!mt)continue;const vt=ht.components[pt];if(!vt)throw new Error(`Cannot materialize removed prefab component placeholder: source component "${pt}" not found in binding "${st.id}"`);if(nt.has(vt.sceneComponentId))continue;const _t=Math.max(ft.indexOf(pt),0);it.push({id:this._removedComponentPlaceholderId(st.id,ct,pt),schema:{type:vt.type,props:cloneDeep$1(vt.props)},meta:{bindingId:st.id,sourceEntityId:ct,sourceComponentKey:pt,sceneComponentId:vt.sceneComponentId,componentType:vt.type,componentIndex:_t}})}}return it.sort((st,ct)=>st.meta.componentIndex-ct.meta.componentIndex)}_removedComponentPlaceholderId(tt,et,nt){return`removed:${tt}:${et}:${nt}`}getComponent(tt){return this.components[tt]}getComponentById(tt){for(let et=0;et<this.components.length;et++)if(this.components[et].id===tt)return this.components[et];return null}getComponentByTypeName(tt){for(let et=0;et<this.components.length;et++){const nt=this.components[et];if(!nt.removedComponent&&nt.type===tt)return nt}return null}getComponentsByTypeName(tt,et=[]){for(let nt=0;nt<this.components.length;nt++){const it=this.components[nt];!it.removedComponent&&it.type===tt&&et.push(it)}return et}getComponentsIncludeChildren(tt,et=[]){this.getComponentsByTypeName(tt,et);for(let nt=0;nt<this.children.length;nt++)this.children[nt].getComponentsIncludeChildren(tt,et);return et}cloneVector3(tt,et){tt.x=et.x,tt.y=et.y,tt.z=et.z}checkIsAssetRef(tt){return hasEntitySchemaInstanceLink(tt)}addComponent(tt){return this.addEditorComponent({class:tt},!0)}getComponents(){return this._components}makeEntityCanPick(){EditorPicker.makeEntityCanPick(this)}get isRoot(){return this.parent===DEFAULT_SCENE||!this.parent}removeFromParent(){this.root.entityFacade.moveEntity(this.id,null)}addChild(tt,et){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.addChild(tt,et);this._addSelfChild(tt,et)}_addSelfChild(tt,et){const{id:nt}=tt;this._childrenId.includes(nt)||(et!==void 0?(this._childrenId.splice(et,0,nt),tt.onReady().then(()=>{var st;if(tt.status!=="ready")return;const it=this.root.domainStore.getNormalizedState(),at=!!it.entities[this.id],ot=!!it.entities[nt];at&&ot?(st=this.root.engineProjection)==null||st.addEntityChild(this.id,nt,et):this.engineObject.addChild(et,tt.engineObject)})):(this._childrenId.push(nt),tt.onReady().then(()=>{var st;if(tt.status!=="ready")return;const it=this.root.domainStore.getNormalizedState(),at=!!it.entities[this.id],ot=!!it.entities[nt];at&&ot?(st=this.root.engineProjection)==null||st.addEntityChild(this.id,nt):this.engineObject.addChild(tt.engineObject)})),tt.parent=this.id)}addChildren(tt,et){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.addChildren(tt,et);const nt=tt.map(it=>it.id);et!==void 0?(this._childrenId.splice(et,0,...nt),tt.forEach((it,at)=>it.onReady().then(()=>{var dt;if(it.status!=="ready")return;const ot=this.root.domainStore.getNormalizedState(),st=!!ot.entities[this.id],ct=!!ot.entities[it.id];st&&ct?(dt=this.root.engineProjection)==null||dt.addEntityChild(this.id,it.id,et+at):this.engineObject.addChild(et+at,it.engineObject)}))):(this._childrenId.push(...nt),tt.forEach(it=>{it.onReady().then(()=>{var ct;if(it.status!=="ready")return;const at=this.root.domainStore.getNormalizedState(),ot=!!at.entities[this.id],st=!!at.entities[it.id];ot&&st?(ct=this.root.engineProjection)==null||ct.addEntityChild(this.id,it.id):this.engineObject.addChild(it.engineObject)})})),tt.forEach(it=>it.parent=this.id)}resetParent(){if(this.root.domainStore.getNormalizedState().entities[this.id]){this.root.entityFacade.moveEntity(this.id,null);return}this.parent=null,this.engineObject.parent=null}setParent(tt){this.parent=tt}removeChildById(tt,et=!0){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.removeChildById(tt,et);this._removeSelfChild(tt,et)}_removeSelfChild(tt,et=!0){const nt=this.entityManager.entities.get(tt);this._childrenId=this._childrenId.filter(it=>it!==tt),et&&nt.destroy(!0)}toJSON(tt=!1){var it,at;const et={},nt=this.isGLTFRefEntity||!tt&&this.isPrefabRefEntity;if(this.isStrippedEntity){const{prefabInstanceId:ot,prefabSource:st}=this.originalEntity._getPrefabInfo();et.strippedId=this.id,et.prefabInstanceId=ot,et.prefabSource=st}else{const ot=this.parentEntity;if(et.id=this.id,et.name=this.name,et.isActive=this.isActive,et.layer=combineLayersByBitwise(this.layer),!this.isPrefabRefEntity||tt){const st=(it=this.transform)==null?void 0:it.toJSON();st&&(et.transform={class:st.type,props:st.props??{}})}et.parent=(ot==null?void 0:ot.id)??null,ot!=null&&ot.isPrefabRefEntity&&(ot.isGLTFRefEntity||!tt)&&(et.parent=ot._strippedEntityId)}if(nt){et.children=[],et.components=[];const ot=resolveEntityInstanceRef({instance:(at=this._domainEntity)==null?void 0:at.instance});ot&&(et.instance={...ot},et.isClone=!0,this.assetTemplateDiffs&&(et.assetTemplateDiffs=this.assetTemplateDiffs))}else{const st=this.childrenId.filter(ct=>this.entityManager.entities.get(ct)&&this.entityManager.entities.get(ct)._engineObject);Object.assign(et,{children:st,components:this.components.filter(ct=>!ct.ignoreToJSON).map(ct=>{const dt=ct.toJSON();return{id:ct.id,class:dt.type,props:dt.props}})})}return et}toV2(tt,et=!1){var ct;const nt={id:this.id},it=resolveEntityInstanceSemantics({instance:((ct=this._domainEntity)==null?void 0:ct.instance)??this.pendingInstance}),at=it.role==="added",st=it.assetKind==="glTF"&&it.role!=="linked"&&!at||!et&&this.isPrefabRefEntity&&!at;if(!st){this.name&&(nt.name=this.name),this.isActive||(nt.isActive=!1),this.isLocked&&(nt.isLocked=!0);const dt=combineLayersByBitwise(this.layer);dt!==0&&(nt.layer=dt)}if((!st||et)&&Ur._writeTransformTuples(nt,this._getSerializableTransform()),!st){const ut=this.childrenId.filter(ht=>tt.hasEntityId(ht));ut.length&&(nt.children=ut)}if(!st){const dt=this.components.filter(ut=>!ut.ignoreToJSON).map(ut=>tt.registerComponent(ut));dt.length&&(nt.components=dt)}if(st){const dt=this._serializeInstanceSchema(tt,{includeContainingBinding:et});dt&&(nt.instance=dt)}return nt}_serializeInstanceSchema(tt,et={}){var ht,ft;const nt=((ht=this._domainEntity)==null?void 0:ht.instance)??this.pendingInstance,it=resolveEntityInstanceRef({instance:nt});if(!it)return;let at=this._collectInstanceOverrides(tt);const ot=nt!=null&&nt.bindingId?this.root.domainStore.state.prefab.bindings[nt.bindingId]:void 0,st=et.containingBinding??(et.includeContainingBinding&&ot?(ft=this._findContainingPrefabBindingForInstance(ot))==null?void 0:ft.binding:void 0),ct=ot?this._collectContainingAddedEntitiesForInstance(st,ot,this.id,tt):[];ct.length>0&&(at={...at??{},addedEntities:[...(at==null?void 0:at.addedEntities)??[],...ct]});const dt=this._collectInstanceRootEntityProps();if(dt){const pt=(at==null?void 0:at.entityProps)??{},mt=this._requireSerializableInstanceRootOverrideTarget(nt,ot);at={...at??{},entityProps:{...pt,[mt]:{...dt,...pt[mt]??{}}}}}const ut={asset:{$ref:tt.resolveVirtualPath(it.assetId),...nt!=null&&nt.assetKey?{key:nt.assetKey}:{}}};return at&&(ut.overrides=bundleInstanceOverrides(at)),ut}_resolveSerializableInstanceRootOverrideTarget(tt,et){return(et==null?void 0:et.sourceRootEntityId)??(tt==null?void 0:tt.sourceEntityId)??((tt==null?void 0:tt.assetKind)==="glTF"?"root":void 0)}_requireSerializableInstanceRootOverrideTarget(tt,et){const nt=this._resolveSerializableInstanceRootOverrideTarget(tt,et);if(nt)return nt;throw new Error(`Cannot serialize instance root override for entity "${this.id}": missing source root entity id for asset "${(tt==null?void 0:tt.assetId)??"<unknown>"}"`)}_collectInstanceRootEntityProps(){const tt={};this.name&&(tt.name=this.name),this.isActive||(tt.isActive=!1);const et=combineLayersByBitwise(this.layer);return et!==0&&(tt.layer=et),Object.keys(tt).length>0?tt:void 0}_collectInstanceOverrides(tt){var at,ot,st;const et={};let nt=!1;if((at=this.assetTemplateDiffs)!=null&&at.entityProps){const ct={};for(const[dt,ut]of Object.entries(this.assetTemplateDiffs.entityProps)){const ht={};if(ut.name!==void 0&&(ht.name=ut.name),ut.isActive!==void 0&&(ht.isActive=ut.isActive),ut.layer!==void 0&&(ht.layer=ut.layer),ut.transform){const ft=ut.transform;ft.position&&(ht.position=[ft.position.x,ft.position.y,ft.position.z]),ft.rotation&&(ht.rotation=[ft.rotation.x,ft.rotation.y,ft.rotation.z]),ft.scale&&(ht.scale=[ft.scale.x,ft.scale.y,ft.scale.z])}ct[dt]=ht}Object.keys(ct).length&&(et.entityProps=ct,nt=!0)}const it=(st=(ot=this._domainEntity)==null?void 0:ot.instance)==null?void 0:st.bindingId;if(it){const ct=this.root.domainStore.state.prefab.bindings[it];if(ct){const dt=collectEntityPropsFromBinding(ct);Object.keys(dt).length>0&&(et.entityProps={...et.entityProps??{},...dt},nt=!0);const ut=collectComponentPropsFromBinding(ct,(vt,{sourceEntityId:_t,sourceComponentKey:yt})=>{var Et,St,At,xt,Ct,Pt,Tt,wt;const bt=this._findLiveComponentFromBinding(ct,_t,yt);if(!bt){const It=ct.sourceToSceneEntity[_t],Ot=(xt=(At=(St=(Et=ct.sourceEntitySnapshots)==null?void 0:Et[_t])==null?void 0:St.components)==null?void 0:At[yt])==null?void 0:xt.sceneComponentId;throw new Error(`Prefab binding "${ct.id}" componentProps override "${yt}" on source entity "${_t}" cannot be serialized without live component "${Ot??yt}" on scene entity "${It??"<missing>"}"`)}return this._serializeLiveComponentPropsOverride(bt,vt,tt,(wt=(Tt=(Pt=(Ct=ct.sourceEntitySnapshots)==null?void 0:Ct[_t])==null?void 0:Pt.components)==null?void 0:Tt[yt])==null?void 0:wt.props)});Object.keys(ut).length>0&&(et.componentProps=ut,nt=!0);const ht=this._collectAddedEntitiesFromBinding(ct,tt);ht.length>0&&(et.addedEntities=ht,nt=!0);const ft=this._collectAddedComponentsFromBinding(ct,tt);ft.length>0&&(et.addedComponents=ft,nt=!0);const pt=this._collectRemovedEntitiesFromBinding(ct);pt.length>0&&(et.removedEntities=pt,nt=!0);const mt=this._collectRemovedComponentsFromBinding(ct);Object.keys(mt).length>0&&(et.removedComponents=mt,nt=!0)}}return nt?et:void 0}_collectAddedEntitiesFromBinding(tt,et){const nt=Object.values(tt.overrides.addedEntities??{}).filter(at=>!sourceEntityIsCoveredByRemovedEntity(tt,at.parentSourceEntityId)).flatMap(at=>{var ot;if(!((ot=tt.sourceEntitySnapshots)!=null&&ot[at.parentSourceEntityId])){if(this._isAddedEntityNestedUnderInstanceSourceParent(tt,at.entityId,at.parentSourceEntityId))return[];throw new Error(`Prefab binding "${tt.id}" added entity "${at.entityId}" has an unresolved source parent "${at.parentSourceEntityId}"`)}return[{entry:at,parentSourceEntityId:at.parentSourceEntityId}]}).sort((at,ot)=>{const st=at.parentSourceEntityId.localeCompare(ot.parentSourceEntityId);return st!==0?st:at.entry.index!==ot.entry.index?at.entry.index-ot.entry.index:at.entry.entityId.localeCompare(ot.entry.entityId)}),it=[];for(const{entry:at,parentSourceEntityId:ot}of nt){const st=this.entityManager.entities.get(at.entityId),ct=this.root.domainStore.state.entities[at.entityId];!st&&!ct||it.push({id:at.entityId,parent:ot,entity:st?this._serializeEntityInline(st,et,tt):this._serializeDomainEntityInline(tt,at.entityId,et)})}return it}_isAddedEntityNestedUnderInstanceSourceParent(tt,et,nt){var ot,st,ct;const it=this.root.domainStore.state;let at=((ot=it.entities[et])==null?void 0:ot.parentId)??null;for(;at;){if(tt.overrides.addedEntities[at]){const dt=it.entities[at],ut=(st=dt==null?void 0:dt.instance)==null?void 0:st.bindingId,ht=ut?it.prefab.bindings[ut]:void 0;if(ht&&ht.id!==tt.id&&sourceEntityIdToPath(ht,nt)!==null)return!0}at=((ct=it.entities[at])==null?void 0:ct.parentId)??null}return!1}_collectContainingAddedEntitiesForInstance(tt,et,nt,it){if(!tt||tt.id===et.id)return[];const at=[],ot=Object.values(tt.overrides.addedEntities??{}).filter(st=>st.entityId!==nt).filter(st=>this._isNormalizedAncestorOrSelf(nt,st.entityId)).flatMap(st=>{var ct;return(ct=et.sourceEntitySnapshots)!=null&&ct[st.parentSourceEntityId]?[{entry:st,parentSourceEntityId:st.parentSourceEntityId}]:[]}).sort((st,ct)=>{const dt=st.parentSourceEntityId.localeCompare(ct.parentSourceEntityId);return dt!==0?dt:st.entry.index!==ct.entry.index?st.entry.index-ct.entry.index:st.entry.entityId.localeCompare(ct.entry.entityId)});for(const{entry:st,parentSourceEntityId:ct}of ot){const dt=this.entityManager.entities.get(st.entityId),ut=this.root.domainStore.state.entities[st.entityId];!dt&&!ut||at.push({id:st.entityId,parent:ct,entity:dt?this._serializeEntityInline(dt,it,tt):this._serializeDomainEntityInline(tt,st.entityId,it)})}return at}_collectDomainInstanceOverrides(tt,et){const nt={};let it=!1;const at=collectEntityPropsFromBinding(tt);Object.keys(at).length>0&&(nt.entityProps=at,it=!0);const ot=collectComponentPropsFromBinding(tt,ht=>et.convertRefs(ht));Object.keys(ot).length>0&&(nt.componentProps=ot,it=!0);const st=this._collectAddedEntitiesFromBinding(tt,et);st.length>0&&(nt.addedEntities=st,it=!0);const ct=this._collectDomainAddedComponentsFromBinding(tt,et);ct.length>0&&(nt.addedComponents=ct,it=!0);const dt=this._collectRemovedEntitiesFromBinding(tt);dt.length>0&&(nt.removedEntities=dt,it=!0);const ut=this._collectRemovedComponentsFromBinding(tt);return Object.keys(ut).length>0&&(nt.removedComponents=ut,it=!0),it?nt:void 0}_collectRemovedEntitiesFromBinding(tt){return Object.keys(tt.overrides.removedEntities??{}).filter(et=>!sourceEntityIsCoveredByAnotherRemovedEntity(tt,et))}_collectRemovedComponentsFromBinding(tt){const et={},nt=tt.sourceEntitySnapshots??{};for(const[it,at]of Object.entries(tt.overrides.removedComponents??{})){if(sourceEntityIsCoveredByRemovedEntity(tt,it))continue;const ot=nt[it];if(!ot)throw new Error(`Prefab binding "${tt.id}" removed component target "${it}" cannot be encoded without a source snapshot`);const st=Object.keys(at).filter(ct=>!!ot.components[ct]).sort();st.length>0&&(et[it]=st)}return et}_collectAddedComponentsFromBinding(tt,et){var at;const nt=Object.entries(tt.overrides.addedComponents??{}).flatMap(([ot,st])=>{var ct;if(sourceEntityIsCoveredByRemovedEntity(tt,ot))return[];if(!((ct=tt.sourceEntitySnapshots)!=null&&ct[ot]))throw new Error(`Prefab binding "${tt.id}" added component target "${ot}" cannot be encoded without a source snapshot`);return Object.keys(st).map(dt=>({sourceEntityId:ot,componentId:dt}))}).sort((ot,st)=>{const ct=ot.sourceEntityId.localeCompare(st.sourceEntityId);return ct!==0?ct:ot.componentId.localeCompare(st.componentId)}),it=[];for(const{sourceEntityId:ot,componentId:st}of nt){const ct=tt.sourceToSceneEntity[ot],dt=this._findLiveComponentBySceneComponentId(ct,st),ut=ct?(at=this.root.domainStore.state.entities[ct])==null?void 0:at.components[st]:void 0;if(!(!dt&&!ut)){if(!dt)throw new Error(`Prefab binding "${tt.id}" added component "${st}" on source entity "${ot}" cannot be serialized without live component`);it.push({id:st,owner:ot,component:et.serializeComponent(dt)})}}return it}_collectDomainAddedComponentsFromBinding(tt,et){var at;const nt=Object.entries(tt.overrides.addedComponents??{}).flatMap(([ot,st])=>{var ct;if(sourceEntityIsCoveredByRemovedEntity(tt,ot))return[];if(!((ct=tt.sourceEntitySnapshots)!=null&&ct[ot]))throw new Error(`Prefab binding "${tt.id}" added component target "${ot}" cannot be encoded without a source snapshot`);return Object.keys(st).map(dt=>({sourceEntityId:ot,componentId:dt}))}).sort((ot,st)=>{const ct=ot.sourceEntityId.localeCompare(st.sourceEntityId);return ct!==0?ct:ot.componentId.localeCompare(st.componentId)}),it=[];for(const{sourceEntityId:ot,componentId:st}of nt){const ct=tt.sourceToSceneEntity[ot],dt=ct?(at=this.root.domainStore.state.entities[ct])==null?void 0:at.components[st]:void 0;dt&&it.push({id:st,owner:ot,component:Ur._domainComponentToV2(dt,et)})}return it}_findLiveComponentFromBinding(tt,et,nt){var ot,st,ct,dt;const it=tt.sourceToSceneEntity[et],at=(dt=(ct=(st=(ot=tt.sourceEntitySnapshots)==null?void 0:ot[et])==null?void 0:st.components)==null?void 0:ct[nt])==null?void 0:dt.sceneComponentId;return this._findLiveComponentBySceneComponentId(it,at)}_findLiveComponentBySceneComponentId(tt,et){var it;if(!tt||!et)return;const nt=(it=this.entityManager.entities.get(tt))==null?void 0:it._components.find(at=>at.id===et);return nt&&typeof nt.toJSON=="function"?nt:void 0}_serializeLiveComponentPropsOverride(tt,et,nt,it){const at={};for(const ct of Object.keys(et))at[ct]=it==null?void 0:it[ct];const ot=readComponentSourcePropsWithEditorValues(tt,at,ct=>nt.serializeComponent(ct)),st=readComponentSourceProps(tt,ct=>nt.serializeComponent(ct));return diffSourceValueRecord(ot,st)}_getSerializableTransform(){var tt;return((tt=this._domainEntity)==null?void 0:tt.transform)??this.transform}static _writeTransformTuples(tt,et){if(!et)return;const nt=et.position;(nt.x!==0||nt.y!==0||nt.z!==0)&&(tt.position=[nt.x,nt.y,nt.z]);const it=et.rotation;(it.x!==0||it.y!==0||it.z!==0)&&(tt.rotation=[it.x,it.y,it.z]);const at=et.scale;(at.x!==1||at.y!==1||at.z!==1)&&(tt.scale=[at.x,at.y,at.z])}_serializeEntityInline(tt,et,nt){var dt;const it=resolveEntityInstanceSemantics({instance:((dt=tt._domainEntity)==null?void 0:dt.instance)??tt.pendingInstance});if(it.assetId&&it.role!=="added"){const ut=tt._serializeInstanceSchema(et,{containingBinding:nt});if(ut)return{instance:ut}}const at={};tt.name&&(at.name=tt.name),tt.isActive||(at.isActive=!1);const ot=combineLayersByBitwise(tt.layer);ot!==0&&(at.layer=ot),Ur._writeTransformTuples(at,tt._getSerializableTransform());const st=tt._components.filter(ut=>!ut.ignoreToJSON).map(ut=>et.serializeComponent(ut));st.length&&(at.components=st);const ct=tt.children.map(ut=>this._serializeEntityInline(ut,et,nt));return ct.length&&(at.children=ct),at}_serializeDomainEntityInline(tt,et,nt,it=new Set){if(it.has(et))throw new Error(`Prefab binding "${tt.id}" added entity "${et}" contains a cyclic child reference`);const at=this.root.domainStore.state.entities[et];if(!at)throw new Error(`Prefab binding "${tt.id}" added entity "${et}" is missing from DomainStore`);it.add(et);const ot=this._serializeDomainInstanceInline(tt,at,nt);if(ot)return ot;const st=Ur._domainEntityToInlineSchema(at,nt),ct=at.children.map(dt=>this._serializeDomainEntityInline(tt,dt,nt,new Set(it)));return ct.length&&(st.children=ct),st}_serializeDomainInstanceInline(tt,et,nt){var dt;if(!((dt=et.instance)!=null&&dt.assetId)||et.instance.role==="added")return;const it={instance:{asset:{$ref:nt.resolveVirtualPath(et.instance.assetId),...et.instance.assetKey?{key:et.instance.assetKey}:{}}}},at=et.instance.bindingId?this.root.domainStore.state.prefab.bindings[et.instance.bindingId]:void 0,ot=at?this._collectDomainInstanceOverrides(at,nt):void 0,st=at?this._collectContainingAddedEntitiesForInstance(tt,at,et.id,nt):[],ct=st.length>0?{...ot??{},addedEntities:[...(ot==null?void 0:ot.addedEntities)??[],...st]}:ot;return ct&&(it.instance.overrides=bundleInstanceOverrides(ct)),it}static _domainEntityToInlineSchema(tt,et){const nt={};tt.name&&(nt.name=tt.name),tt.isActive||(nt.isActive=!1),tt.layer!==void 0&&tt.layer!==0&&(nt.layer=tt.layer),Ur._writeTransformTuples(nt,tt.transform);const it=Object.values(tt.components).map(at=>Ur._domainComponentToV2(at,et));return it.length&&(nt.components=it),nt}static _domainComponentToV2(tt,et){var at;const nt={type:tt.type},it=et.convertRefs(tt.props??{});return it&&typeof it=="object"&&!Array.isArray(it)&&Object.keys(it).length>0&&(nt.props=it),tt.refId&&(nt.script={$ref:et.resolveVirtualPath(tt.refId),...tt.scriptKey?{key:tt.scriptKey}:{}}),(at=tt.calls)!=null&&at.length&&(nt.calls=et.convertRefs(tt.calls)),nt}getEditable(tt){return!0}findChildByName(tt){return this.entityManager.findChildByName(this,tt)}findByPath(tt){return this.entityManager.findByPath(this,tt)}findByIndexPath(tt){return this.entityManager.findByIndexPath(this,tt)}getAddedComponents(tt=!0){const et=[],nt=this.strippedEntity;return nt!=null&&nt.components.length&&et.push({target:{entityId:"",componentId:""},strippedId:this.strippedEntity.id}),tt&&this.children.filter(it=>!it.isAddedEntity&&!it.isGLTFRefEntity).forEach((it,at)=>{const ot=it.getAddedComponents().map(({target:st,strippedId:ct})=>{const{entityId:dt}=st;return{target:{entityId:`${at}${dt?"/"+dt:""}`,componentId:""},strippedId:ct}});et.push(...ot)}),et}getRemovedComponents(tt=!0){const et=[];return this._components.forEach(nt=>{if(nt.removedComponent){const it=this.getComponentsByTypeName(nt.type).indexOf(nt);et.push({entityId:"",componentId:`:${nt.type}/${it}`})}}),tt&&this.children.filter(nt=>!nt.isAddedEntity&&!nt.isGLTFRefEntity).forEach((nt,it)=>{const at=nt.getRemovedComponents().map(ot=>{const{entityId:st,componentId:ct}=ot,dt=`${it}${st?"/"+st:""}`,ut=ct.split(":"),ht=ut[ut.length-1],ft=`${ht?dt+":"+ht:""}`;return{entityId:dt,componentId:ft}});et.push(...at)}),et}getAddedEntities(tt=!0){const et=[],nt=this.strippedEntity;return nt!=null&&nt.children.length&&et.push({target:{entityId:"",componentId:""},strippedId:this.strippedEntity.id}),tt&&this.children.filter(it=>!it.isAddedEntity&&!it.isGLTFRefEntity).forEach((it,at)=>{const ot=it.getAddedEntities().map(({target:st,strippedId:ct})=>{const{entityId:dt}=st;return{target:{entityId:`${at}${dt?"/"+dt:""}`,componentId:""},strippedId:ct}});et.push(...ot)}),et}getRemovedEntities(tt=!0){const et=[];return this.prefabEntityRemoved&&et.push({entityId:"",componentId:""}),tt&&this.children.filter(nt=>!nt.isAddedEntity&&!nt.isGLTFRefEntity).forEach((nt,it)=>{const at=nt.getRemovedEntities().map(ot=>{const{entityId:st}=ot;return{entityId:`${it}${st?"/"+st:""}`,componentId:""}});et.push(...at)}),et}applyRemovedComponent(tt){const{entityId:et,componentId:nt}=tt,it=this.findByIndexPath(et);if(it&&nt){const at=nt.split(":")[1].split("/"),ot=at[0],st=at[1],ct=it.getComponentsByTypeName(ot)[st];ct&&it._removePrefabComponent(ct)}}applyRemovedEntity(tt){const{entityId:et}=tt,nt=this.findByIndexPath(et);nt&&this.entityManager.removePrefabSubEntity(nt)}applyAddedEntity(tt){const{target:et,strippedId:nt}=tt,it=this.findByIndexPath(et.entityId),at=this.entityManager.strippedEntities.get(nt);at.children.forEach(ot=>{it.addChild(ot)}),at._childrenId.length=0}applyAddedComponent(tt){const{target:et,strippedId:nt}=tt,it=this.findByIndexPath(et.entityId),at=this.entityManager.strippedEntities.get(nt);at.components.forEach(ot=>{it.addEditorComponent(ot.toJSON())}),at._components.length=0}async _getPrefabSourceApplyAsset(tt){if(tt.assetKind!=="Prefab")throw new Error(`Prefab binding "${tt.id}" targets ${tt.assetKind} asset "${tt.assetId}" and does not support applyToPrefab. glTF source assets are immutable; record editable overrides on a containing Prefab binding.`);const et=await this.root.assetStore.getAssetByRef({refId:tt.assetId}),it=["applyEntityPropsOverride","applyComponentPropsOverride","applyAddedEntityOverride","applyNestedInstanceAddedEntityOverride","applyRemovedEntityOverride","applyAddedComponentOverride","applyRemovedComponentOverride","refreshFromData"].filter(at=>typeof(et==null?void 0:et[at])!="function");if(it.length>0)throw new Error(`Prefab asset "${tt.assetId}" does not support applyToPrefab: missing ${it.join(", ")}`);return et}async _acceptPrefabOverrideAndRefresh(tt,et,nt,it,at){const ot=this.root.domainStore.getNormalizedState().prefab.bindings[et],st=nt===5&&it.sourceEntityId!==void 0&&it.sourceEntityId===(ot==null?void 0:ot.sourceRootEntityId);await this.root.domainStore.runAsRemote(()=>{this.root.prefabFacade.acceptOverride(et,OVERRIDE_TYPE_BY_APPLY_TYPE[nt],it)});const ct={};st&&(ct.resetRootTransformBindingIds=[et]),STRUCTURAL_PREFAB_APPLY_TYPES.has(nt)&&(ct.structuralDeltaMode="domain-source-replace"),Object.keys(ct).length>0?await tt.refreshFromData(ct):await tt.refreshFromData(),this._restoreSelectionAfterApplyToPrefab(et,at)}_restoreSelectionAfterApplyToPrefab(tt,et){var at;if(!et){this.entityManager.selectEntity(null);return}const nt=(at=this.root.domainStore.getNormalizedState().prefab.bindings)==null?void 0:at[tt],it=nt?getSceneEntityIdForPrefabSource(nt,et):null;this.entityManager.selectEntity(it)}_getPrefabBindingForApply(tt){var nt;const et=(nt=this.root.domainStore.getNormalizedState().prefab.bindings)==null?void 0:nt[tt];if(!et)throw new Error(`Prefab binding "${tt}" not found while applying override to source prefab`);return et}_findPrefabBindingOwningAddedEntity(tt){return Object.values(tt??{}).find(et=>et.assetKind==="Prefab"&&!!et.overrides.addedEntities[this.id])??null}_isNormalizedAncestorOrSelf(tt,et){var ot;const nt=this.root.domainStore.getNormalizedState().entities,it=new Set;let at=et;for(;at&&!it.has(at);){if(at===tt)return!0;it.add(at),at=((ot=nt[at])==null?void 0:ot.parentId)??null}return!1}_getNormalizedHierarchyDepth(tt){var ot;const et=this.root.domainStore.getNormalizedState().entities,nt=new Set;let it=0,at=tt;for(;at&&!nt.has(at);){nt.add(at);const st=((ot=et[at])==null?void 0:ot.parentId)??null;if(!st)break;it+=1,at=st}return it}_findContainingPrefabBindingForInstance(tt){const et=resolveContainingPrefabBindingForInstance(this.root.domainStore.getNormalizedState(),tt);return et!=null&&et.sourceEntityId?{binding:et.binding,sourceEntityId:et.sourceEntityId}:null}_sourceEntityPathSegments(tt,et){const nt=sourceEntityIdToPath(tt,et);if(nt===null)throw new Error(`Prefab binding "${tt.id}" cannot resolve source entity path "${et}"`);return nt===""?[]:nt.split("/").map(it=>{const at=Number(it);if(!Number.isInteger(at)||at<0)throw new Error(`Prefab binding "${tt.id}" resolved invalid source path "${nt}"`);return at})}_trySourceEntityPathSegments(tt,et){const nt=sourceEntityIdToPath(tt,et);if(nt===null)return null;if(nt==="")return[];const it=[];for(const at of nt.split("/")){const ot=Number(at);if(!Number.isInteger(ot)||ot<0)return null;it.push(ot)}return it}_resolveAddedEntityApplyTarget(){var ct;const tt=this.root.domainStore.getNormalizedState(),et=tt.prefab.bindings,nt=tt.entities[this.id],it=(ct=nt==null?void 0:nt.instance)==null?void 0:ct.bindingId;if(!it)throw new Error(`Entity "${this.id}" is not a prefab instance entity and cannot be applied to prefab`);const at=this._getPrefabBindingForApply(it),ot=at.overrides.addedEntities[this.id];if(ot){if(at.assetKind==="Prefab")return{kind:"sourceEntity",overrideBindingId:at.id,prefabBinding:at,addedEntity:ot};const dt=this._findContainingPrefabBindingForInstance(at);return dt?{kind:"nestedInstance",overrideBindingId:at.id,prefabBinding:dt.binding,addedEntity:ot,instanceSourceEntityId:dt.sourceEntityId,parentSourceEntityId:ot.parentSourceEntityId}:{kind:"sourceEntity",overrideBindingId:at.id,prefabBinding:at,addedEntity:ot}}const st=this._findPrefabBindingOwningAddedEntity(et);if(st)return{kind:"sourceEntity",overrideBindingId:st.id,prefabBinding:st,addedEntity:st.overrides.addedEntities[this.id]};throw new Error(`Prefab added entity override for "${this.id}" not found`)}_resolveNestedInstanceAddedEntityFromSceneParent(tt,et,nt){var ct,dt;const it=this.root.domainStore.getNormalizedState(),at=(ct=it.entities[this.id])==null?void 0:ct.parentId;if(!at)return null;const ot=tt.prefabFile;if(!Array.isArray(ot==null?void 0:ot.entities))return null;let st=null;for(const ut of Object.values(it.prefab.bindings??{})){if(ut.id===et.id||ut.assetKind!=="Prefab"&&ut.assetKind!=="glTF"||!this._isNormalizedAncestorOrSelf(ut.instanceRootEntityId,at)||!this._isNormalizedAncestorOrSelf(et.instanceRootEntityId,ut.instanceRootEntityId)||this._trySourceEntityPathSegments(ut,nt)===null)continue;const ft=getSceneEntityIdForPrefabSource(ut,nt);if(ft&&ft!==at)continue;const pt=getSourceEntityIdForPrefabScene(et,ut.instanceRootEntityId);if(!pt)continue;const mt=ot.entities.findIndex(_t=>_t.id===pt);if(mt<0||!((dt=ot.entities[mt])!=null&&dt.instance))continue;const vt=this._getNormalizedHierarchyDepth(ut.instanceRootEntityId);(!st||st.depth<vt)&&(st={depth:vt,target:{instanceSourceEntityId:pt,parentSourceEntityId:nt}})}return(st==null?void 0:st.target)??null}_resolveSourceRootInstanceAddedEntityTarget(tt,et,nt){var st,ct;const it=tt.prefabFile;if(!Array.isArray(it==null?void 0:it.entities)||typeof it.root!="string")return null;const at=it.root,ot=it.entities.findIndex(dt=>dt.id===at);return ot<0||!((st=it.entities[ot])!=null&&st.instance)||!((ct=et.sourceEntitySnapshots)!=null&&ct[nt])?null:{instanceSourceEntityId:at,parentSourceEntityId:nt}}_resolveNestedInstanceAddedEntitySourceTarget(tt,et,nt){const it=tt.prefabFile;if(!Array.isArray(it==null?void 0:it.entities)||this._prefabFileHasSourceEntity(tt,nt))return null;const at=et.sourceEntitySnapshots??{},ot=[],st=new Set;let ct=nt;const dt=()=>this._resolveNestedInstanceAddedEntityFromSceneParent(tt,et,nt)??this._resolveSourceRootInstanceAddedEntityTarget(tt,et,nt);for(;ct;){if(st.has(ct))return dt();st.add(ct);const ut=at[ct];if(!ut)return dt();if(!Number.isInteger(ut.childIndex)||ut.childIndex<0)throw new Error(`Prefab binding "${et.id}" has invalid childIndex for source entity "${ct}"`);ot.unshift(ut.childIndex);const ht=ut.parentSourceEntityId;if(!ht)return dt();const ft=it.entities.findIndex(pt=>pt.id===ht);if(ft>=0){const pt=it.entities[ft];return pt!=null&&pt.instance?{instanceSourceEntityId:ht,parentSourceEntityId:nt}:dt()}ct=ht}return dt()}_prefabFileHasSourceEntity(tt,et){var nt,it;return!!((it=(nt=tt.prefabFile)==null?void 0:nt.entities)!=null&&it.some(at=>at.id===et))}_resolveAddedAncestorApplyTarget(tt,et){var at,ot;const nt=this.root.domainStore.getNormalizedState();let it=((at=nt.entities[this.id])==null?void 0:at.parentId)??null;for(;it;){const st=et.overrides.addedEntities[it];if(st){const ct=this._resolveNestedInstanceAddedEntitySourceTarget(tt,et,st.parentSourceEntityId);if(ct||this._prefabFileHasSourceEntity(tt,st.parentSourceEntityId)){const dt=this.entityManager.entities.get(it);if(!dt)throw new Error(`Prefab added ancestor "${it}" is not materialized`);return{entityId:it,entity:dt,addedEntity:st,nestedSourceTarget:ct}}}it=((ot=nt.entities[it])==null?void 0:ot.parentId)??null}return null}_findPrefabBindingOwningSourceOverride(tt,et,nt){var it,at,ot;for(const st of Object.values(tt??{})){if(st.assetKind!=="Prefab")continue;const ct=getSourceEntityIdForPrefabScene(st,this.id);if(ct){if(et===5&&st.overrides.entityProps[ct])return{binding:st,sourceEntityId:ct};if(et===3&&st.overrides.removedEntities[ct])return{binding:st,sourceEntityId:ct};if(et===0){const{sourceComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((it=st.overrides.componentProps[ct])!=null&&it[dt]))return{binding:st,sourceEntityId:ct}}if(et===2){const{sceneComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((at=st.overrides.addedComponents[ct])!=null&&at[dt]))return{binding:st,sourceEntityId:ct}}if(et===1){const{sourceComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((ot=st.overrides.removedComponents[ct])!=null&&ot[dt]))return{binding:st,sourceEntityId:ct}}}}return null}_resolvePrefabApplyTarget(tt,et){var dt;const nt=this.root.domainStore.getNormalizedState(),it=nt.prefab.bindings,at=nt.entities[this.id],ot=(dt=at==null?void 0:at.instance)==null?void 0:dt.bindingId;if(!ot)throw new Error(`Entity "${this.id}" is not a prefab instance entity and cannot be applied to prefab`);const st=this._getPrefabBindingForApply(ot);if(st.assetKind==="Prefab")return{bindingId:ot,binding:st,sourceEntityId:getNormalizedSourceEntityId(nt,this.id)};const ct=this._findPrefabBindingOwningSourceOverride(it,tt,et);return ct?{bindingId:ct.binding.id,binding:ct.binding,sourceEntityId:ct.sourceEntityId}:{bindingId:ot,binding:st,sourceEntityId:getNormalizedSourceEntityId(nt,this.id)}}_getComponentTargetIndex(tt){return typeof tt=="number"?tt:tt==null?void 0:tt.componentIndex}_formatComponentTarget(tt){return typeof tt=="number"||tt===void 0?String(tt??0):JSON.stringify(tt)}_getSourceComponentKeyFromSnapshot(tt,et,nt){var at,ot,st;if(!tt||!et||!nt)return;const it=((ot=(at=tt.sourceEntitySnapshots)==null?void 0:at[et])==null?void 0:ot.components)??{};return(st=Object.entries(it).find(([,ct])=>ct.sceneComponentId===nt))==null?void 0:st[0]}_getSourceComponentKeyForApply(tt,et,nt){var ft;const it=this.root.domainStore.getNormalizedState(),at=this._getComponentTargetIndex(tt),ot=typeof tt=="object"?tt:void 0,st=at!==void 0?this.components[at]:void 0,ct=st==null?void 0:st.removedComponentMeta,dt=(ot==null?void 0:ot.sceneComponentId)??(ct==null?void 0:ct.sceneComponentId)??(st==null?void 0:st.id),ut=dt?getNormalizedComponent(it,this.id,dt):void 0,ht=(ot==null?void 0:ot.sourceComponentId)??(ot==null?void 0:ot.sourceComponentKey)??(ct==null?void 0:ct.sourceComponentKey)??((ft=ut==null?void 0:ut.instance)==null?void 0:ft.sourceComponentKey)??this._getSourceComponentKeyFromSnapshot(et,nt,dt);return{componentIndex:at,sceneComponentId:dt,sourceComponentId:ht}}async applyToPrefab(tt,et){var ct,dt,ut,ht;if(tt===4){const ft=this._resolveAddedEntityApplyTarget(),pt=await this._getPrefabSourceApplyAsset(ft.prefabBinding);let mt=this.id;if(ft.kind==="nestedInstance")await pt.applyNestedInstanceAddedEntityOverride(ft.instanceSourceEntityId,ft.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1});else{const vt=this._resolveNestedInstanceAddedEntitySourceTarget(pt,ft.prefabBinding,ft.addedEntity.parentSourceEntityId);if(vt)await pt.applyNestedInstanceAddedEntityOverride(vt.instanceSourceEntityId,vt.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1});else{const _t=this._prefabFileHasSourceEntity(pt,ft.addedEntity.parentSourceEntityId)?null:this._resolveAddedAncestorApplyTarget(pt,ft.prefabBinding);_t?(mt=_t.entityId,_t.nestedSourceTarget?await pt.applyNestedInstanceAddedEntityOverride(_t.nestedSourceTarget.instanceSourceEntityId,_t.nestedSourceTarget.parentSourceEntityId,_t.addedEntity.index,_t.entity,{refresh:!1}):await pt.applyAddedEntityOverride(_t.addedEntity.parentSourceEntityId,_t.addedEntity.index,_t.entity,{refresh:!1})):await pt.applyAddedEntityOverride(ft.addedEntity.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1})}}await this._acceptPrefabOverrideAndRefresh(pt,ft.overrideBindingId,tt,{entityId:mt},this.id);return}const{bindingId:nt,binding:it,sourceEntityId:at}=this._resolvePrefabApplyTarget(tt,et),ot=this.root.domainStore.getNormalizedState(),st=await this._getPrefabSourceApplyAsset(it);if(tt===5){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const ft=it.overrides.entityProps[at];await st.applyEntityPropsOverride(at,ft,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at},at);return}if(tt===3){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const ft=((ct=it.sourceEntitySnapshots[at])==null?void 0:ct.parentSourceEntityId)??null;await st.applyRemovedEntityOverride(at,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at},ft);return}if(tt===0){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sourceComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab component target "${this._formatComponentTarget(et)}" not found`);const pt=(dt=it.overrides.componentProps[at])==null?void 0:dt[ft];await st.applyComponentPropsOverride(ft,pt,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at);return}if(tt===2){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sceneComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab added component target "${this._formatComponentTarget(et)}" not found`);const pt=getNormalizedComponent(ot,this.id,ft),mt=(ut=it.overrides.addedComponents[at])==null?void 0:ut[ft],vt=this._components.find(yt=>yt.id===ft&&typeof yt.toJSON=="function"),_t=(vt==null?void 0:vt.toJSON())??{type:(mt==null?void 0:mt.type)??(pt==null?void 0:pt.type)??"",props:(mt==null?void 0:mt.props)??(pt==null?void 0:pt.props)??{}};if(!_t.type)throw new Error(`Prefab added component "${ft}" has no component type`);await st.applyAddedComponentOverride(at,ft,_t,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at);return}if(tt===1){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sourceComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" not found`);if(!((ht=it.overrides.removedComponents[at])!=null&&ht[ft]))throw new Error(`Prefab removed component override "${ft}" on source entity "${at}" not found`);await st.applyRemovedComponentOverride(ft,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at)}}unpackPrefab(){var et;const tt=this.root.domainStore.getNormalizedState().entities[this.id];if((et=tt==null?void 0:tt.instance)!=null&&et.bindingId){const nt=this.root.domainStore.state.prefab.bindings[tt.instance.bindingId];this.root.prefabFacade.unpack(tt.instance.bindingId,{replacementRootInstance:nt?this._resolveRootInstanceReplacementForUnpack(nt):void 0})}}_resolveRootInstanceReplacementForUnpack(tt){var dt,ut,ht,ft,pt,mt;if(tt.assetKind!=="Prefab")return;const et=(dt=this.root.assetStore.assets)==null?void 0:dt[tt.assetId],nt=et==null?void 0:et.prefabFile,it=typeof(nt==null?void 0:nt.root)=="string"?nt.entities.find(vt=>vt.id===nt.root):void 0,at=(ut=it==null?void 0:it.instance)==null?void 0:ut.asset,ot=at==null?void 0:at.$ref;if(!ot)return;const st=(ft=(ht=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ft.call(ht,ot),ct=(mt=(pt=st==null?void 0:st.getMetaConfig)==null?void 0:pt.call(st))==null?void 0:mt.type;if(ct==="glTF")return{assetId:st.id,assetKind:ct,assetKey:at.key,sourceRevision:1}}convertToPrefabRefEntity(){this.isPrefabRefEntity=!0,this.selfComponents.forEach(tt=>{EditorComponent.convertToPrefabComponent(tt)}),this.selfChildren.forEach(tt=>{!tt.isGLTFRefEntity&&tt.convertToPrefabRefEntity()})}convertToNormalEntity(){this.selfComponents.forEach(tt=>{EditorComponent.convertToNormalComponent(tt)}),this.selfChildren.forEach(tt=>{!tt.isGLTFRefEntity&&tt.convertToNormalEntity()})}_applyStrippedDataToSelf(){if(this.children.forEach(tt=>{!tt.isGLTFRefEntity&&tt._applyStrippedDataToSelf()}),this.strippedEntity){const tt=this.strippedEntity.components.map(nt=>nt.toJSON());this.strippedEntity._components.length=0,tt.forEach(nt=>{this.addEditorComponent(nt)});const et=this.strippedEntity.children.slice();this.strippedEntity._childrenId.length=0,et.forEach(nt=>{this.addChild(nt)})}}revertPrefab(tt,et){var ct,dt;const nt=this.root.domainStore.getNormalizedState(),it=(dt=(ct=nt.entities[this.id])==null?void 0:ct.instance)==null?void 0:dt.bindingId,at=getNormalizedSourceEntityId(nt,this.id),ot=it?this._getPrefabBindingForApply(it):void 0,st=this._getComponentTargetIndex(et);if(tt===5&&it&&at&&this.root.prefabFacade.revertOverride(it,"entityProps",{sourceEntityId:at}),tt===4&&this.entityManager.removeEntity(this.id),tt===3&&this.entityManager.revertPrefabSubEntity(this),tt===0&&it&&at){const{sourceComponentId:ut}=this._getSourceComponentKeyForApply(et,ot,at);if(!ut)throw new Error(`Prefab component target "${this._formatComponentTarget(et)}" has no source key`);this.root.prefabFacade.revertOverride(it,"componentProps",{sourceEntityId:at,componentId:ut})}if(tt===2&&this.removeComponent(st),tt===1){if(it&&at){const{sourceComponentId:pt}=this._getSourceComponentKeyForApply(et,ot,at);if(!pt)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" has no source key`);this.root.prefabFacade.revertOverride(it,"removedComponents",{sourceEntityId:at,componentId:pt}),this.root.projectStore.debouncedUpdateSceneAsset();return}const ut=st??0,ht=this._components[ut];if(!ht)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" not found`);ht.removedComponent=!1;const ft=ht.toJSON();this._removeSelfComponent(ut),this._addEditorComponent(ft,ut),EditorComponent.convertToPrefabComponent(this.components[ut])}this.root.projectStore.debouncedUpdateSceneAsset()}async getPrefabAsset(){const tt=this._getPrefabInfo().prefabSource;return this.root.assetStore.getAssetByRef({refId:tt.assetId})}_removePrefabComponent(tt){tt.removeByPrefab(),this.root.projectStore.debouncedUpdateSceneAsset()}_getPrefabInfo(){var nt;let tt="",et=this;for(;(nt=et.parentEntity)!=null&&nt.isPrefabRefEntity;){const it=et;et=et.parentEntity;const at=et.childrenId.indexOf(it.id);tt=tt?`${at}/${tt}`:`${at}`}return{prefabInstanceId:et.id,prefabSource:{assetId:et.instanceAssetId,entityId:tt}}}_getOrCreateTransformSchema(tt,et=!1){let nt=tt.transform;if(nt){if(et){nt=cloneDeep$1(nt);const it=nt.props;it.position&&(it.position=null),it.rotation&&(it.rotation=null),it.scale&&(it.scale=null)}}else{nt={class:"Transform",props:{}};const it=nt.props;if(!et){const{position:at,rotation:ot,scale:st}=tt;at&&(it.position=at),ot&&(it.rotation=ot),st&&(it.scale=st)}}return nt}updateLayer(tt,et){resolveLayerUpdateMode({entityId:this.id,domainEntities:this.root.domainStore.state.entities})==="domain"?this.root.entityFacade.setLayer(this.id,et):this.engineObject&&(this.engineObject.layer=et)}};__decorateClass$6([observable.ref],_EntityModel.prototype,"_domainEntityVersion",2);__decorateClass$6([action],_EntityModel.prototype,"invalidateFromDomain",1);__decorateClass$6([propertyField({label:"entity.layer.title",type:ComponentType.Select,info:"entity.layer.info",...getMultipleLayerOptions([...Object.values(LayerSetting),Layer.Nothing,Layer.Everything]),triggerAfterInit:!1})],_EntityModel.prototype,"layer",1);__decorateClass$6([observable],_EntityModel.prototype,"_localLayer",2);__decorateClass$6([propertyField({label:"entity.is-active"}),virtualProperty()],_EntityModel.prototype,"isActive",1);__decorateClass$6([observable],_EntityModel.prototype,"_localIsActive",2);__decorateClass$6([propertyField({label:"entity.name",triggerAfterInit:!1}),virtualProperty()],_EntityModel.prototype,"name",1);__decorateClass$6([observable],_EntityModel.prototype,"_localName",2);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"id",2);__decorateClass$6([computed],_EntityModel.prototype,"level",1);__decorateClass$6([virtualProperty(),computed],_EntityModel.prototype,"components",1);__decorateClass$6([virtualProperty(),observable],_EntityModel.prototype,"_parent",2);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceAssetId",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceSourceEntityId",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceAssetKind",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"isPrefabRefEntity",1);__decorateClass$6([observable],_EntityModel.prototype,"_localIsPrefabRefEntity",2);__decorateClass$6([observable],_EntityModel.prototype,"prefabEntityRemoved",2);__decorateClass$6([computed],_EntityModel.prototype,"isGLTFSubEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"isPrefabInstanceRoot",1);__decorateClass$6([computed],_EntityModel.prototype,"isPrefabSubEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"strippedEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"isAddedEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"showAdditiveModified",1);__decorateClass$6([observable],_EntityModel.prototype,"_childrenId",2);__decorateClass$6([observable],_EntityModel.prototype,"_components",2);__decorateClass$6([observable],_EntityModel.prototype,"_strippedEntityId",2);__decorateClass$6([observable],_EntityModel.prototype,"_isLocked",2);__decorateClass$6([computed],_EntityModel.prototype,"canCopy",1);__decorateClass$6([computed],_EntityModel.prototype,"canPasted",1);__decorateClass$6([computed],_EntityModel.prototype,"canDuplicated",1);__decorateClass$6([computed],_EntityModel.prototype,"nextSibling",1);__decorateClass$6([computed],_EntityModel.prototype,"hasCameraComponent",1);__decorateClass$6([action],_EntityModel.prototype,"applyLockedFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyParentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyChildrenFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyRemoveChildFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"initByFile",1);__decorateClass$6([action],_EntityModel.prototype,"initByEngineObject",1);__decorateClass$6([action],_EntityModel.prototype,"initBySchema",1);__decorateClass$6([action],_EntityModel.prototype,"destroy",1);__decorateClass$6([action],_EntityModel.prototype,"clear",1);__decorateClass$6([action],_EntityModel.prototype,"_addEditorComponent",1);__decorateClass$6([action],_EntityModel.prototype,"_removeSelfComponent",1);__decorateClass$6([action],_EntityModel.prototype,"addComponentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"removeComponentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"syncRemovedComponentPlaceholdersFromDomain",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponent",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponentById",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponentByTypeName",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"addComponent",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponents",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"makeEntityCanPick",1);__decorateClass$6([action],_EntityModel.prototype,"_addSelfChild",1);__decorateClass$6([action],_EntityModel.prototype,"addChildren",1);__decorateClass$6([action],_EntityModel.prototype,"resetParent",1);__decorateClass$6([action],_EntityModel.prototype,"setParent",1);__decorateClass$6([action],_EntityModel.prototype,"_removeSelfChild",1);__decorateClass$6([action],_EntityModel.prototype,"unpackPrefab",1);__decorateClass$6([action],_EntityModel.prototype,"convertToPrefabRefEntity",1);__decorateClass$6([action],_EntityModel.prototype,"convertToNormalEntity",1);__decorateClass$6([action],_EntityModel.prototype,"_applyStrippedDataToSelf",1);__decorateClass$6([action],_EntityModel.prototype,"revertPrefab",1);let EntityModel=_EntityModel;var __defProp$6=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$5(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$6(_e,tt,nt),nt};class RootEntityModel{constructor(_e){Rt(this,"id",DEFAULT_SCENE);Rt(this,"name","Scene");Rt(this,"parent",null);Rt(this,"entityManager");Rt(this,"isExpanded",!0);Object.defineProperty(this,"entityManager",{enumerable:!1,writable:!0,configurable:!0,value:_e}),makeObservable(this)}get childrenId(){return this.entityManager.displayedEntitiesIds}get level(){return 0}get children(){return this.entityManager.displayedEntities}get nextSibling(){return this.entityManager.rootEntitiesId[0]}}__decorateClass$5([computed],RootEntityModel.prototype,"childrenId",1);__decorateClass$5([observable],RootEntityModel.prototype,"isExpanded",2);__decorateClass$5([computed],RootEntityModel.prototype,"children",1);__decorateClass$5([computed],RootEntityModel.prototype,"nextSibling",1);class SerializeContext{constructor(_e,tt,et){Rt(this,"entityIndex");Rt(this,"entityIds");Rt(this,"components",[]);Rt(this,"componentIds",[]);Rt(this,"_resolveVirtualPath");Rt(this,"_sourceRefCodec");Rt(this,"_lookupComponentState");this.entityIds=_e,this._resolveVirtualPath=tt,this._sourceRefCodec=createSourceRefCodec({resolveAssetRef:tt}),this._lookupComponentState=et,this.entityIndex=new Map;for(let nt=0;nt<_e.length;nt++)this.entityIndex.set(_e[nt],nt)}resolveVirtualPath(_e){return this._sourceRefCodec.domainToSource(_e)}serializeComponent(_e){var nt,it,at,ot,st;const tt=_e.toJSON();tt.id=_e.id,tt.props&&(tt.props=this.convertRefs(tt.props));const et=(nt=this._lookupComponentState)==null?void 0:nt.call(this,_e.id);return et!=null&&et.refId&&!((it=tt.script)!=null&&it.$ref)?tt.script={$ref:this.resolveVirtualPath(et.refId),...et.scriptKey?{key:et.scriptKey}:{}}:(at=tt.script)!=null&&at.$ref&&(tt.script=normalizeSourceAssetRefRecord(tt.script),et!=null&&et.scriptKey&&!tt.script.key&&(tt.script.key=et.scriptKey)),(ot=et==null?void 0:et.calls)!=null&&ot.length&&!((st=tt.calls)!=null&&st.length)&&(tt.calls=this.convertRefs(et.calls)),tt}registerComponent(_e){return this.components.push(this.serializeComponent(_e)),this.componentIds.push(_e.id),_e.id}resolveEntityIndex(_e){return this.entityIndex.get(_e)??-1}hasEntityId(_e){return this.entityIndex.has(_e)}convertRefs(_e){return convertInternalRefsToSourceValue(_e,tt=>this.resolveVirtualPath(tt))}}function clone(rt){return structuredClone(rt)}function appendUnique(rt,_e){const tt=new Set(rt),et=[...rt];for(const nt of _e)tt.has(nt)||(tt.add(nt),et.push(nt));return et}function createEmptyPrefabState(){return{bindings:{},byAssetId:{}}}function normalizeSourceIdPrefabFile(rt){return assertSourceV2PrefabFileStructure(rt),rt}function snapshotComponentToDomainComponent(rt,_e,tt,et){var nt;return{type:tt.type,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:mergeSourceValueRecords(tt.props??{},et??{}),...(nt=tt.calls)!=null&&nt.length?{calls:clone(tt.calls)}:{},instance:{bindingId:rt,role:"linked",sourceComponentKey:_e}}}function mergeTransform(rt,_e){return _e?{position:{...rt.position,..._e.position??{}},rotation:{...rt.rotation,..._e.rotation??{}},scale:{...rt.scale,..._e.scale??{}}}:clone(rt)}function isRemovedSourceEntity(rt,_e){var et,nt,it,at,ot,st;if((et=rt.overrides.removedEntities)!=null&&et[_e])return!0;let tt=(it=(nt=rt.sourceEntitySnapshots)==null?void 0:nt[_e])==null?void 0:it.parentSourceEntityId;for(;tt;){if((at=rt.overrides.removedEntities)!=null&&at[tt])return!0;tt=((st=(ot=rt.sourceEntitySnapshots)==null?void 0:ot[tt])==null?void 0:st.parentSourceEntityId)??null}return!1}function derivePrefabSourceSnapshotsFromFile(rt,_e,tt,et,nt,it){var ft,pt,mt,vt,_t,yt;_e=normalizeSourceIdPrefabFile(_e),assertSourceV2PrefabFileStructure(_e);const at=buildSourceIdIndex(_e),ot=collectReachableSourceEntityIds(_e.entities,[_e.root]),st=new Map;for(const bt of ot){const Et=at.entityById.get(bt);isSourceInstanceBoundary(Et)||(ft=Et==null?void 0:Et.children)==null||ft.forEach(St=>{st.set(St,bt)})}const ct=Object.keys(rt.sourceEntitySnapshots??{}).length>0,dt=(bt,Et)=>{var St;return bt===null?0:Math.max(0,(((St=at.entityById.get(bt))==null?void 0:St.children)??[]).findIndex(At=>At===Et))},ut=new Map;for(const bt of ot){if(!at.entityById.get(bt))throw new Error(`Prefab source entity "${bt}" is missing from the source index`);const St=st.get(bt)??null;dt(St,bt);const At=findExactPreviousSourceEntitySnapshot(rt,bt);At&&ut.set(bt,At),rt.sourceToSceneEntity[bt]=selectSceneEntityIdForSourceSnapshot({binding:rt,sourceEntityId:bt,existingSceneEntityId:rt.sourceToSceneEntity[bt],previousSceneEntityId:At==null?void 0:At.sceneEntityId,allowExistingSceneEntityId:!ct||!!At,usedSceneEntityIds:nt})}const ht={};for(const bt of ot){const Et=at.entityById.get(bt);if(!Et)throw new Error(`Prefab source entity "${bt}" is missing from the source index`);const St=rt.sourceToSceneEntity[bt],At=ut.get(bt),xt=st.get(bt)??null,Ct=dt(xt,bt),Pt=isSourceInstanceBoundary(Et),Tt=Pt?[]:Et.children??[],wt={};for(const $t of Pt?[]:Et.components??[]){const Dt=at.componentById.get($t);if(!Dt)throw new Error(`Prefab source component "${$t}" is missing from the source index`);const Bt=findExactPreviousSourceComponentSnapshot(At,$t,Dt),Gt=Bt==null?void 0:Bt.sceneComponentId,zt=selectSceneComponentIdForSourceSnapshot({bindingId:rt.id,sceneEntityId:St,sourceComponentType:Dt.type,sourceComponentKey:$t,previousSceneComponentId:Gt,componentRecords:et,usedSceneComponentIds:it});wt[$t]={sceneComponentId:zt,type:Dt.type,...(pt=Dt.script)!=null&&pt.$ref?{refId:resolveSourceAssetRef(Dt.script.$ref,tt,"script")}:{},...(mt=Dt.script)!=null&&mt.key?{scriptKey:Dt.script.key}:{},props:convertAssetRefsToDomainRefs(Dt.props??{},tt.resolveSourceRef),...(vt=Dt.calls)!=null&&vt.length?{calls:convertAssetRefsToDomainRefs(Dt.calls,tt.resolveSourceRef)}:{}}}const It=(yt=(_t=Et.instance)==null?void 0:_t.asset)==null?void 0:yt.$ref,Ot=It?resolveSourceAssetRef(It,tt,"nested instance"):void 0,Nt=It&&Ot?resolveSourceAssetKind(It,Ot,tt,"nested instance"):void 0,Mt=resolveSourceInstanceRootOverrideTarget({sourceEntity:Et,fallbackSourceEntityId:bt,assetId:Ot,instanceAssetKind:Nt,resolvePrefabSourceFile:tt.resolvePrefabSourceFile}),Lt=readSourceEntityResolvedState(Et,bt,{...typeof Mt=="string"?{rootOverrideTarget:Mt}:{}});ht[bt]={sceneEntityId:St,parentSourceEntityId:xt,childSourceEntityIds:Tt,childIndex:Ct,...Nt?{instanceAssetKind:Nt}:{},name:Lt.name,isActive:Lt.isActive,...Lt.layer!==void 0?{layer:Lt.layer}:{},...Lt.isLocked!==void 0?{isLocked:Lt.isLocked}:{},transform:Lt.transform,components:wt}}return ht}function findExactPreviousSourceEntitySnapshot(rt,_e){var tt;return(tt=rt.sourceEntitySnapshots)==null?void 0:tt[_e]}function collectReachablePrefabEntityIds(rt){return collectReachableSourceEntityIds(rt.entities,[rt.root])}function findExactPreviousSourceComponentSnapshot(rt,_e,tt){var nt;const et=(nt=rt==null?void 0:rt.components)==null?void 0:nt[_e];return(et==null?void 0:et.type)===tt.type?et:void 0}function resolveSourceAssetRef(rt,_e,tt){var nt;const et=(nt=_e.resolveSourceRef)==null?void 0:nt.call(_e,rt);if(typeof et!="string"||et.length===0)throw new Error(`Unable to resolve source asset ref "${rt}" to an editor asset id while refreshing ${tt}`);return et}function resolveSourceAssetKind(rt,_e,tt,et){var it;const nt=(it=tt.resolveAssetKind)==null?void 0:it.call(tt,rt,_e);if(nt!=="Prefab"&&nt!=="glTF")throw new Error(`Unable to resolve supported source asset kind for "${rt}" while refreshing ${et}; expected Prefab or glTF`);return nt}function selectSceneEntityIdForSourceSnapshot(rt){const{binding:_e,sourceEntityId:tt,existingSceneEntityId:et,previousSceneEntityId:nt,allowExistingSceneEntityId:it,usedSceneEntityIds:at}=rt;if(tt===_e.sourceRootEntityId){const ut=_e.sourceToSceneEntity[tt]??nt??_e.instanceRootEntityId;return at.add(ut),ut}const ot=nt??(it?et:void 0);if(ot&&!at.has(ot))return at.add(ot),ot;const st=`prefab:${_e.id}:${tt}`;let ct=st,dt=1;for(;at.has(ct);)ct=`${st}:${dt++}`;return at.add(ct),ct}function selectSceneComponentIdForSourceSnapshot(rt){const{bindingId:_e,sourceComponentKey:tt,sourceComponentType:et,previousSceneComponentId:nt,componentRecords:it,sceneEntityId:at,usedSceneComponentIds:ot}=rt;if(nt&&!ot.has(nt)&&canUseSceneComponentIdForSourceComponent(nt,it,_e,at,tt,et))return ot.add(nt),nt;const st=`prefab:${rt.bindingId}:${rt.sourceComponentKey}`;let ct=st,dt=1;for(;ot.has(ct)||!canUseSceneComponentIdForSourceComponent(ct,it,_e,at,tt,et);)ct=`${st}:${dt++}`;return ot.add(ct),ct}function canUseSceneComponentIdForSourceComponent(rt,_e,tt,et,nt,it){const at=_e.get(rt);return!at||isSameLinkedSourceComponent(at,tt,et,nt,it)}function isSameLinkedSourceComponent(rt,_e,tt,et,nt){const it=rt.component.instance;return rt.entityId===tt&&rt.component.type===nt&&(it==null?void 0:it.bindingId)===_e&&it.role!=="added"&&it.sourceComponentKey===et}function collectComponentRecords(rt){const _e=new Map;for(const tt of Object.values(rt))for(const[et,nt]of Object.entries(tt.components??{}))_e.set(et,{entityId:tt.id,component:nt});return _e}function createEmptyPrefabOverrides(){return{entityProps:{},componentProps:{},removedEntities:{},removedComponents:{},addedEntities:{},addedComponents:{}}}function requireInlineOverrideId(rt,_e,tt){const et=rt??_e;if(typeof et!="string"||et.length===0)throw new Error(`Invalid source v2 scene file: ${tt} requires an explicit id`);return et}function seedPrefabOverridesFromInlineSource(rt,_e,tt){var at,ot,st,ct,dt,ut;const et=createEmptyPrefabOverrides();if(!rt)return et;const nt=buildSourceIdIndex(_e);for(const ht of rt.entityProps??[]){if(typeof ht.target!="string")throw new Error("Invalid source v2 scene file: entityProps override target must be a source entity id");if(!nt.entityById.has(ht.target))throw new Error(`Invalid source v2 scene file: entityProps override target "${ht.target}" does not exist`);et.entityProps[ht.target]=inlineEntityOverrideToDomainProps(ht,tt)}for(const ht of rt.componentProps??[]){if(typeof ht.target!="string")throw new Error("Invalid source v2 scene file: componentProps override target must be a source component id");const ft=nt.componentOwnerEntityIdById.get(ht.target);if(!ft)throw new Error(`Invalid source v2 scene file: componentProps override target "${ht.target}" does not exist`);const pt=(at=et.componentProps)[ft]??(at[ft]={});pt[ht.target]=convertAssetRefsToDomainRefs(ht.props??{},tt)}for(const ht of rt.removedEntities??[]){if(!nt.entityById.has(ht))throw new Error(`Invalid source v2 scene file: removed entity target "${ht}" does not exist`);et.removedEntities[ht]=!0}for(const ht of rt.removedComponents??[]){const ft=nt.componentOwnerEntityIdById.get(ht);if(!ft)throw new Error(`Invalid source v2 scene file: removed component target "${ht}" does not exist`);const pt=(ot=et.removedComponents)[ft]??(ot[ft]={});pt[ht]=!0}const it=new Map;for(const ht of rt.addedEntities??[]){const ft=requireInlineOverrideId(ht.id,ht.entity.id,"added entity override");if(!nt.entityById.has(ht.parent))throw new Error(`Invalid source v2 scene file: added entity parent "${ht.parent}" does not exist`);const pt=it.get(ht.parent)??0;it.set(ht.parent,pt+1),et.addedEntities[ft]={entityId:ft,parentSourceEntityId:ht.parent,index:ht.index??pt}}for(const ht of rt.addedComponents??[]){if(typeof ht.owner!="string")throw new Error("Invalid source v2 scene file: added component override owner must be a source entity id");if(!nt.entityById.has(ht.owner))throw new Error(`Invalid source v2 scene file: added component owner "${ht.owner}" does not exist`);const ft=requireInlineOverrideId(ht.id,ht.component.id,"added component override"),pt=ht.component,mt=(st=et.addedComponents)[ct=ht.owner]??(st[ct]={});mt[ft]={componentId:ft,ownerSourceEntityId:ht.owner,type:pt.type,...(dt=pt.script)!=null&&dt.$ref?{refId:tt(pt.script.$ref),...pt.script.key?{scriptKey:pt.script.key}:{}}:{},props:convertAssetRefsToDomainRefs(pt.props??{},tt),...(ut=pt.calls)!=null&&ut.length?{calls:convertAssetRefsToDomainRefs(pt.calls,tt)}:{}}}return et}function requireRootOnlyGLTFOverrideTarget(rt,_e){if(rt!=="root")throw new Error(`Invalid source v2 scene file: glTF ${_e} target "${rt}" is not the synthetic root`)}function seedRootOnlyGLTFOverridesFromInlineSource(rt,_e){var nt,it,at,ot,st;const tt=createEmptyPrefabOverrides();if(!rt)return tt;for(const ct of rt.entityProps??[])requireRootOnlyGLTFOverrideTarget(ct.target,"entityProps"),tt.entityProps.root=inlineEntityOverrideToDomainProps(ct,_e);for(const ct of rt.removedEntities??[])requireRootOnlyGLTFOverrideTarget(ct,"removed entity"),tt.removedEntities.root=!0;if((nt=rt.componentProps)!=null&&nt.length)throw new Error("Invalid source v2 scene file: glTF componentProps require source component topology and cannot be hydrated from a root-only glTF source instance");if((it=rt.removedComponents)!=null&&it.length)throw new Error("Invalid source v2 scene file: glTF removedComponents require source component topology and cannot be hydrated from a root-only glTF source instance");let et=0;for(const ct of rt.addedEntities??[]){requireRootOnlyGLTFOverrideTarget(ct.parent,"added entity parent");const dt=requireInlineOverrideId(ct.id,ct.entity.id,"added entity override");tt.addedEntities[dt]={entityId:dt,parentSourceEntityId:"root",index:ct.index??et++}}for(const ct of rt.addedComponents??[]){requireRootOnlyGLTFOverrideTarget(ct.owner,"added component owner");const dt=requireInlineOverrideId(ct.id,ct.component.id,"added component override"),ut=ct.component,ht=(at=tt.addedComponents).root??(at.root={});ht[dt]={componentId:dt,ownerSourceEntityId:"root",type:ut.type,...(ot=ut.script)!=null&&ot.$ref?{refId:_e(ut.script.$ref),...ut.script.key?{scriptKey:ut.script.key}:{}}:{},props:convertAssetRefsToDomainRefs(ut.props??{},_e),...(st=ut.calls)!=null&&st.length?{calls:convertAssetRefsToDomainRefs(ut.calls,_e)}:{}}}return tt}function filterPrefabOverridesForRefreshedSnapshots(rt){const{binding:_e,previousSourceRootEntityId:tt,nextSnapshots:et}=rt,nt=createEmptyPrefabOverrides(),it=ct=>ct===tt?_e.sourceRootEntityId:ct,at=ct=>{const dt=it(ct),ut=et[dt];if(!(!ut||isSourceEntityRemovedOrCovered(nt.removedEntities,et,dt)))return{currentSourceEntityId:dt,snapshot:ut}},ot=(ct,dt)=>{for(const[ut,ht]of Object.entries(ct??{})){const ft=at(ut);ft&&dt(ut,ft.currentSourceEntityId,ht,ft.snapshot)}},st=(ct,dt)=>{ot(ct,(ut,ht,ft,pt)=>{for(const[mt,vt]of Object.entries(ft))pt.components[mt]&&dt(ut,ht,mt,vt,pt)})};for(const ct of Object.keys(_e.overrides.removedEntities??{})){const dt=it(ct);et[dt]&&(isSourceEntityCoveredByRemovedAncestor(_e.overrides.removedEntities,et,dt)||(nt.removedEntities[dt]=!0))}st(_e.overrides.removedComponents,(ct,dt,ut)=>{var ft;const ht=(ft=nt.removedComponents)[dt]??(ft[dt]={});ht[ut]=!0}),ot(_e.overrides.entityProps,(ct,dt,ut)=>{if(nt.entityProps[dt])throw new Error(`Prefab override entityProps collision: source entity "${ct}" maps to "${dt}", which already has overrides from an earlier source entity`);nt.entityProps[dt]=clone(ut)}),st(_e.overrides.componentProps,(ct,dt,ut,ht)=>{var pt,mt;if((pt=nt.removedComponents[dt])!=null&&pt[ut])return;const ft=(mt=nt.componentProps)[dt]??(mt[dt]={});if(ft[ut])throw new Error(`Prefab override componentProps collision: source component "${ut}" on source entity "${ct}" maps to "${dt}", which already has overrides from an earlier source component`);ft[ut]=mergeSourceValueRecords({},ht)});for(const[ct,dt]of Object.entries(_e.overrides.addedEntities??{})){const ut=at(dt.parentSourceEntityId);if(!ut)continue;const{currentSourceEntityId:ht}=ut;nt.addedEntities[ct]={...clone(dt),parentSourceEntityId:ht}}return ot(_e.overrides.addedComponents,(ct,dt,ut)=>{var ft;const ht=(ft=nt.addedComponents)[dt]??(ft[dt]={});for(const[pt,mt]of Object.entries(ut)){if(ht[pt])throw new Error(`Prefab override addedComponents collision: added component "${pt}" on source entity "${ct}" maps to "${dt}", which already has an added component with the same id`);ht[pt]={...clone(mt),ownerSourceEntityId:dt}}}),nt}function isSourceEntityCoveredByRemovedAncestor(rt,_e,tt){var nt,it;let et=(nt=_e[tt])==null?void 0:nt.parentSourceEntityId;for(;et;){if(rt[et])return!0;et=((it=_e[et])==null?void 0:it.parentSourceEntityId)??null}return!1}function isSourceEntityRemovedOrCovered(rt,_e,tt){return!!(rt[tt]||isSourceEntityCoveredByRemovedAncestor(rt,_e,tt))}function collectReservedAddedSceneEntityIds(rt){const _e=new Set;for(const tt of Object.values(rt.bindings))for(const et of Object.values(tt.overrides.addedEntities??{}))_e.add(et.entityId);return _e}function collectReservedAddedSceneComponentIds(rt){const _e=new Set;for(const tt of Object.values(rt.bindings))for(const et of Object.values(tt.overrides.addedComponents??{}))for(const nt of Object.values(et))_e.add(nt.componentId);return _e}function refreshPrefabBindingSnapshotsFromSource(rt,_e,tt,et=[],nt=[]){if(!_e.resolvePrefabSourceFile)return rt;const it=clone(rt),at=collectComponentRecords(tt),ot=new Set([...et,...Object.keys(tt),...collectReservedAddedSceneEntityIds(it)]),st=new Set([...nt,...collectReservedAddedSceneComponentIds(it)]);for(const ct of Object.values(it.bindings)){if(ct.assetKind!=="Prefab")continue;const dt=_e.resolvePrefabSourceFile(ct.assetId);if(!dt)throw new Error(`Cannot refresh Prefab binding "${ct.id}" for asset "${ct.assetId}": source file is unavailable`);const ut=normalizeSourceIdPrefabFile(dt);assertSourceV2PrefabFileStructure(ut);const ht=ct.sourceRootEntityId,ft=ut.root;ft&&(ct.sourceRootEntityId=ft,ct.sourceToSceneEntity[ft]=ct.instanceRootEntityId);const pt=derivePrefabSourceSnapshotsFromFile(ct,ut,_e,at,ot,st);ct.sourceToSceneEntity=Object.fromEntries(Object.entries(pt).map(([mt,vt])=>[mt,ct.sourceToSceneEntity[mt]??vt.sceneEntityId])),ct.sourceEntitySnapshots=pt,ct.overrides=filterPrefabOverridesForRefreshedSnapshots({binding:ct,previousSourceRootEntityId:ht,nextSnapshots:pt})}return it}function seedSourceSceneInstanceBindings(rt,_e,tt){var it,at,ot,st,ct,dt;const et=clone(rt);let nt=!1;for(const ut of _e.entities){const ht=(at=(it=ut.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!ht)continue;const ft=resolveSourceAssetRef(ht,tt,"scene instance"),pt=resolveSourceAssetKind(ht,ft,tt,"scene instance");if(pt!=="Prefab"&&pt!=="glTF")continue;if(findBindingForInstanceRoot(et,ut.id,{assetId:ft,assetKind:pt})){seedInlineAddedSourceInstanceBindings(et,(ot=ut.instance)==null?void 0:ot.overrides,tt)&&(nt=!0);continue}let mt;if(pt==="Prefab"){if(!tt.resolvePrefabSourceFile)continue;const vt=tt.resolvePrefabSourceFile(ft);if(!vt)throw new Error(`Cannot rebuild Prefab binding for scene instance "${ut.id}" and asset "${ft}": source file is unavailable`);const _t=normalizeSourceIdPrefabFile(vt);assertSourceV2PrefabFileStructure(_t);const yt=_t.root,bt=`binding-${ft}-${ut.id}`,Et=seedPrefabOverridesFromInlineSource((st=ut.instance)==null?void 0:st.overrides,_t,tt.resolveSourceRef);mt={id:bt,assetId:ft,assetKind:pt,instanceRootEntityId:ut.id,sourceRootEntityId:yt,sourceRevision:1,sourceToSceneEntity:{[yt]:ut.id},sourceEntitySnapshots:{},overrides:Et}}else mt={id:createUniquePrefabBindingId(et.bindings,ft,ut.id),assetId:ft,assetKind:pt,instanceRootEntityId:ut.id,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:ut.id},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:ut,sourceEntityId:ut.id,sceneEntityId:ut.id})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ct=ut.instance)==null?void 0:ct.overrides,tt.resolveSourceRef)};et.bindings[mt.id]=mt,seedInlineAddedSourceInstanceBindings(et,(dt=ut.instance)==null?void 0:dt.overrides,tt),nt=!0}return nt?{bindings:et.bindings,byAssetId:rebuildPrefabBindingAssetIndex(et.bindings)}:rt}function rebuildPrefabBindingAssetIndex(rt){var tt;const _e={};for(const et of Object.values(rt)){const nt=_e[tt=et.assetId]??(_e[tt]=[]);nt.includes(et.id)||nt.push(et.id)}return _e}function sourceVec3Override(rt){if(!Array.isArray(rt)||rt.length<3)return;const[_e,tt,et]=rt;return typeof _e=="number"&&typeof tt=="number"&&typeof et=="number"?{x:_e,y:tt,z:et}:void 0}function inlineEntityOverrideToDomainProps(rt,_e){const{target:tt,position:et,rotation:nt,scale:it,...at}=rt,ot=convertAssetRefsToDomainRefs(at,_e),st={},ct=sourceVec3Override(et),dt=sourceVec3Override(nt),ut=sourceVec3Override(it);return ct&&(st.position=ct),dt&&(st.rotation=dt),ut&&(st.scale=ut),Object.keys(st).length>0&&(ot.transform=st),ot}function findBindingForInstanceRoot(rt,_e,tt){return Object.values(rt.bindings).find(et=>et.instanceRootEntityId===_e&&et.assetId===tt.assetId&&et.assetKind===tt.assetKind)}function getSceneEntityIdForSourceEntity(rt,_e){var tt,et;return rt.sourceToSceneEntity[_e]??((et=(tt=rt.sourceEntitySnapshots)==null?void 0:tt[_e])==null?void 0:et.sceneEntityId)}function prunePrefabBindingsToReachableSourceInstances(rt,_e,tt){const et=new Set,nt=at=>{var dt,ut,ht;if(et.has(at.id))return;et.add(at.id);for(const ft of Object.values(at.overrides.addedEntities??{}))for(const pt of Object.values(_e.bindings))pt.instanceRootEntityId===ft.entityId&&nt(pt);if(at.assetKind!=="Prefab")return;const ot=(dt=tt.resolvePrefabSourceFile)==null?void 0:dt.call(tt,at.assetId);if(!ot)return;const st=normalizeSourceIdPrefabFile(ot),ct=buildSourceIdIndex(st);for(const ft of collectReachablePrefabEntityIds(st)){const pt=ct.entityById.get(ft),mt=(ht=(ut=pt==null?void 0:pt.instance)==null?void 0:ut.asset)==null?void 0:ht.$ref;if(!pt||!ft||!mt)continue;const vt=resolveSourceAssetRef(mt,tt,"nested instance"),_t=resolveSourceAssetKind(mt,vt,tt,"nested instance"),yt=getSceneEntityIdForSourceEntity(at,ft);if(!yt)continue;const bt=findBindingForInstanceRoot(_e,yt,{assetId:vt,assetKind:_t});bt&&nt(bt)}};if(rt.entities.forEach(at=>{var ht,ft;const ot=at.id,st=(ft=(ht=at.instance)==null?void 0:ht.asset)==null?void 0:ft.$ref;if(!ot||!st)return;const ct=resolveSourceAssetRef(st,tt,"scene instance"),dt=resolveSourceAssetKind(st,ct,tt,"scene instance"),ut=findBindingForInstanceRoot(_e,ot,{assetId:ct,assetKind:dt});ut&&nt(ut)}),et.size===Object.keys(_e.bindings).length)return _e;const it={};for(const[at,ot]of Object.entries(_e.bindings))et.has(at)&&(it[at]=ot);return{bindings:it,byAssetId:rebuildPrefabBindingAssetIndex(it)}}function collectMissingNestedSourceInstanceBindings(rt,_e){var et,nt;const tt=[];if(!_e.resolvePrefabSourceFile)return tt;for(const it of Object.values(rt.bindings)){if(it.assetKind!=="Prefab")continue;const at=_e.resolvePrefabSourceFile(it.assetId);if(!at)throw new Error(`Cannot validate nested source instances for Prefab binding "${it.id}" for asset "${it.assetId}": source file is unavailable`);const ot=normalizeSourceIdPrefabFile(at),st=buildSourceIdIndex(ot);for(const ct of collectReachablePrefabEntityIds(ot)){const dt=st.entityById.get(ct),ut=(nt=(et=dt==null?void 0:dt.instance)==null?void 0:et.asset)==null?void 0:nt.$ref;if(!ct||!ut||isRemovedSourceEntity(it,ct))continue;const ht=resolveSourceAssetRef(ut,_e,"nested instance"),ft=resolveSourceAssetKind(ut,ht,_e,"nested instance"),pt=getSceneEntityIdForSourceEntity(it,ct);if(!pt)throw new Error(`Prefab binding "${it.id}" nested source instance "${ct}" (${ut}) is missing a scene entity mapping`);findBindingForInstanceRoot(rt,pt,{assetId:ht,assetKind:ft})||tt.push({bindingId:it.id,sourceEntityId:ct,sourceEntity:dt,sourceRef:ut,assetId:ht,assetKind:ft,sceneEntityId:pt})}}return tt}function assertNestedSourceInstanceBindingsPresent(rt,_e){const tt=collectMissingNestedSourceInstanceBindings(rt,_e);if(tt.length===0)return;const et=tt[0];throw new Error(`Prefab binding "${et.bindingId}" nested source instance "${et.sourceEntityId}" (${et.sourceRef}) materializes scene entity "${et.sceneEntityId}", but its ${et.assetKind} binding for asset "${et.assetId}" is missing`)}function createUniquePrefabBindingId(rt,_e,tt){const et=`binding-${_e}-${tt}`;if(!rt[et])return et;let nt=1;for(;rt[`${et}-${nt}`];)nt+=1;return`${et}-${nt}`}function createSyntheticGlTFRootSnapshot(rt){const _e={...rt.sourceEntity,id:rt.sourceEntityId,children:void 0,components:void 0},tt=readSourceEntityResolvedState(_e,rt.sourceEntityId,{rootOverrideTarget:"root"});return{sceneEntityId:rt.sceneEntityId,parentSourceEntityId:null,childSourceEntityIds:[],childIndex:0,name:tt.name,isActive:tt.isActive,...tt.layer!==void 0?{layer:tt.layer}:{},...tt.isLocked!==void 0?{isLocked:tt.isLocked}:{},transform:tt.transform,components:{}}}function createSourceInstanceBindingFromInlineSource(rt){var ct,dt,ut;const{prefab:_e,sourceEntity:tt,sceneEntityId:et,sourceRef:nt,assetId:it,assetKind:at,options:ot}=rt,st=createUniquePrefabBindingId(_e.bindings,it,et);if(at==="Prefab"){const ht=(ct=ot.resolvePrefabSourceFile)==null?void 0:ct.call(ot,it);if(!ht)throw new Error(`Cannot rebuild Prefab binding for source instance "${et}" (${nt}) and asset "${it}": source file is unavailable`);const ft=normalizeSourceIdPrefabFile(ht),pt=ft.root;return{id:st,assetId:it,assetKind:at,instanceRootEntityId:et,sourceRootEntityId:pt,sourceRevision:1,sourceToSceneEntity:{[pt]:et},sourceEntitySnapshots:{},overrides:seedPrefabOverridesFromInlineSource((dt=tt.instance)==null?void 0:dt.overrides,ft,ot.resolveSourceRef)}}return{id:st,assetId:it,assetKind:at,instanceRootEntityId:et,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:et},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:tt,sourceEntityId:et,sceneEntityId:et})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ut=tt.instance)==null?void 0:ut.overrides,ot.resolveSourceRef)}}function seedInlineAddedSourceInstanceBindings(rt,_e,tt){var nt,it,at,ot;if(!((nt=_e==null?void 0:_e.addedEntities)!=null&&nt.length))return!1;let et=!1;for(const st of _e.addedEntities){const ct=st.entity,dt=(at=(it=ct.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!dt)continue;const ut=requireInlineOverrideId(st.id,ct.id,"added entity override"),ht=resolveSourceAssetRef(dt,tt,"inline added instance"),ft=resolveSourceAssetKind(dt,ht,tt,"inline added instance");if(findBindingForInstanceRoot(rt,ut,{assetId:ht,assetKind:ft}))continue;const pt=createSourceInstanceBindingFromInlineSource({prefab:rt,sourceEntity:ct,sceneEntityId:ut,sourceRef:dt,assetId:ht,assetKind:ft,options:tt});rt.bindings[pt.id]=pt,et=!0,seedInlineAddedSourceInstanceBindings(rt,(ot=ct.instance)==null?void 0:ot.overrides,tt)&&(et=!0)}return et}function hasMissingInlineAddedSourceInstanceBindings(rt,_e,tt){var et,nt,it;if(!((et=_e==null?void 0:_e.addedEntities)!=null&&et.length))return!1;for(const at of _e.addedEntities){const ot=at.entity,st=(it=(nt=ot.instance)==null?void 0:nt.asset)==null?void 0:it.$ref;if(!st)continue;const ct=requireInlineOverrideId(at.id,ot.id,"added entity override"),dt=resolveSourceAssetRef(st,tt,"inline added instance"),ut=resolveSourceAssetKind(st,dt,tt,"inline added instance");if(!findBindingForInstanceRoot(rt,ct,{assetId:dt,assetKind:ut}))return!0}return!1}function seedInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e){var et,nt;if(!_e.resolvePrefabSourceFile)return!1;let tt=!1;for(const it of Object.values(rt.bindings)){if(it.assetKind!=="Prefab")continue;const at=_e.resolvePrefabSourceFile(it.assetId);if(!at)continue;const ot=normalizeSourceIdPrefabFile(at),st=buildSourceIdIndex(ot);for(const ct of collectReachablePrefabEntityIds(ot)){const dt=st.entityById.get(ct);if(!((et=dt==null?void 0:dt.instance)!=null&&et.overrides)||isRemovedSourceEntity(it,ct))continue;const ut=(nt=dt.instance.asset)==null?void 0:nt.$ref;if(!ut)continue;const ht=getSceneEntityIdForSourceEntity(it,ct);if(!ht)continue;const ft=resolveSourceAssetRef(ut,_e,"nested instance"),pt=resolveSourceAssetKind(ut,ft,_e,"nested instance");findBindingForInstanceRoot(rt,ht,{assetId:ft,assetKind:pt})&&seedInlineAddedSourceInstanceBindings(rt,dt.instance.overrides,_e)&&(tt=!0)}}return tt}function hasMissingInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e){var tt,et;if(!_e.resolvePrefabSourceFile)return!1;for(const nt of Object.values(rt.bindings)){if(nt.assetKind!=="Prefab")continue;const it=_e.resolvePrefabSourceFile(nt.assetId);if(!it)continue;const at=normalizeSourceIdPrefabFile(it),ot=buildSourceIdIndex(at);for(const st of collectReachablePrefabEntityIds(at)){const ct=ot.entityById.get(st);if(!((tt=ct==null?void 0:ct.instance)!=null&&tt.overrides)||isRemovedSourceEntity(nt,st))continue;const dt=(et=ct.instance.asset)==null?void 0:et.$ref;if(!dt)continue;const ut=getSceneEntityIdForSourceEntity(nt,st);if(!ut)continue;const ht=resolveSourceAssetRef(dt,_e,"nested instance"),ft=resolveSourceAssetKind(dt,ht,_e,"nested instance");if(findBindingForInstanceRoot(rt,ut,{assetId:ht,assetKind:ft})&&hasMissingInlineAddedSourceInstanceBindings(rt,ct.instance.overrides,_e))return!0}}return!1}function seedNestedSourceInstanceBindings(rt,_e,tt){var ot,st,ct,dt;const et=collectMissingNestedSourceInstanceBindings(rt,_e),nt=hasMissingInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e);if(et.length===0&&!nt)return{prefab:rt,changed:!1};const it=clone(rt);let at=!1;for(const ut of et){if(findBindingForInstanceRoot(it,ut.sceneEntityId,{assetId:ut.assetId,assetKind:ut.assetKind}))continue;const ht=rt.bindings[ut.bindingId],ft=tt.get(ut.bindingId)??(ht?[ht.assetId]:[]);if(ft.includes(ut.assetId))throw new Error(`Prefab source instance asset cycle detected: ${[...ft,ut.assetId].join(" -> ")}`);const pt=createUniquePrefabBindingId(it.bindings,ut.assetId,ut.sceneEntityId);let mt;if(ut.assetKind==="Prefab"){const vt=(ot=_e.resolvePrefabSourceFile)==null?void 0:ot.call(_e,ut.assetId);if(!vt)throw new Error(`Cannot rebuild nested Prefab binding for source instance "${ut.sourceEntityId}" and asset "${ut.assetId}": source file is unavailable`);const _t=normalizeSourceIdPrefabFile(vt),yt=_t.root;mt={id:pt,assetId:ut.assetId,assetKind:ut.assetKind,instanceRootEntityId:ut.sceneEntityId,sourceRootEntityId:yt,sourceRevision:1,sourceToSceneEntity:{[yt]:ut.sceneEntityId},sourceEntitySnapshots:{},overrides:seedPrefabOverridesFromInlineSource((st=ut.sourceEntity.instance)==null?void 0:st.overrides,_t,_e.resolveSourceRef)}}else mt={id:pt,assetId:ut.assetId,assetKind:ut.assetKind,instanceRootEntityId:ut.sceneEntityId,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:ut.sceneEntityId},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:ut.sourceEntity,sourceEntityId:ut.sourceEntityId,sceneEntityId:ut.sceneEntityId})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ct=ut.sourceEntity.instance)==null?void 0:ct.overrides,_e.resolveSourceRef)};it.bindings[mt.id]=mt,tt.set(mt.id,[...ft,ut.assetId]),seedInlineAddedSourceInstanceBindings(it,(dt=ut.sourceEntity.instance)==null?void 0:dt.overrides,_e),at=!0}return seedInlineAddedSourceInstanceBindingsForNestedSourceInstances(it,_e)&&(at=!0),at?{prefab:{bindings:it.bindings,byAssetId:rebuildPrefabBindingAssetIndex(it.bindings)},changed:!0}:{prefab:rt,changed:!1}}function rememberPrefabBindingAssetPaths(rt,_e){for(const tt of Object.values(rt.bindings))_e.has(tt.id)||_e.set(tt.id,[tt.assetId])}function refreshAndSeedPrefabBindingsFromSource(rt,_e,tt,et,nt,it){let at=seedSourceSceneInstanceBindings(rt,_e,tt);const ot=new Map;for(rememberPrefabBindingAssetPaths(at,ot);;){const st=Object.keys(at.bindings).length;at=refreshPrefabBindingSnapshotsFromSource(at,tt,et,nt,it);const ct=seedNestedSourceInstanceBindings(at,tt,ot);if(at=ct.prefab,rememberPrefabBindingAssetPaths(at,ot),!ct.changed)return at;if(Object.keys(at.bindings).length<=st)throw new Error(`Prefab source instance binding refresh did not make progress (${st} bindings). Check nested prefab/glTF source instance data for a cycle or invalid materialization state.`)}}function snapshotEntityToDomainEntity(rt,_e,tt,et){var vt,_t,yt,bt,Et;const nt=tt.sceneEntityId??rt.sourceToSceneEntity[_e];if(!nt)throw new Error(`Prefab binding "${rt.id}" snapshot "${_e}" is missing sceneEntityId`);const it=tt.parentSourceEntityId?rt.sourceToSceneEntity[tt.parentSourceEntityId]??null:(et==null?void 0:et.parentId)??null,at=(vt=rt.overrides.entityProps)==null?void 0:vt[_e],ot=et==null?void 0:et.instance,st=(ot==null?void 0:ot.bindingId)===rt.id&&ot.role!=="added"&&(ot.sourceEntityId===_e||ot.role==="root"&&ot.sourceEntityId===void 0&&_e===rt.sourceRootEntityId),ct=[];for(const St of tt.childSourceEntityIds??[]){if(isRemovedSourceEntity(rt,St))continue;const At=rt.sourceToSceneEntity[St];if(!At)throw new Error(`Prefab binding "${rt.id}" snapshot child "${St}" is missing sourceToSceneEntity mapping`);ct.push(At)}const dt=new Map(Object.entries(rt.sourceToSceneEntity).map(([St,At])=>[At,St])),ut=((et==null?void 0:et.children)??[]).filter(St=>{const At=dt.get(St);return!At||!isRemovedSourceEntity(rt,At)}),ht={};for(const[St,At]of Object.entries(tt.components??{})){const xt=At.sceneComponentId;xt&&((yt=(_t=rt.overrides.removedComponents)==null?void 0:_t[_e])!=null&&yt[St]||(ht[xt]=snapshotComponentToDomainComponent(rt.id,St,At,(Et=(bt=rt.overrides.componentProps)==null?void 0:bt[_e])==null?void 0:Et[St])))}const ft=_e!==rt.sourceRootEntityId&&tt.instanceAssetKind&&(ot==null?void 0:ot.role)==="root"&&ot.assetKind===tt.instanceAssetKind,pt=Object.fromEntries(Object.entries((et==null?void 0:et.components)??{}).filter(([,St])=>{const At=St.instance;return!((At==null?void 0:At.bindingId)===rt.id&&At.role!=="added")})),mt=(at==null?void 0:at.layer)??tt.layer??((et==null?void 0:et.layer)!==void 0&&!st&&!ft?et.layer:void 0);return{id:nt,name:(at==null?void 0:at.name)??(et&&!st&&!ft?et.name:tt.name),isActive:(at==null?void 0:at.isActive)??(et&&!st&&!ft?et.isActive:tt.isActive),parentId:it,children:appendUnique(ct,ut),transform:mergeTransform(et&&!st&&!ft?et.transform:clone(tt.transform),at==null?void 0:at.transform),components:{...pt,...ht},...mt!==void 0&&mt!==0?{layer:mt}:{},...(at==null?void 0:at.isLocked)!==void 0?{isLocked:at.isLocked}:tt.isLocked!==void 0?{isLocked:tt.isLocked}:(et==null?void 0:et.isLocked)!==void 0&&!st&&!ft?{isLocked:et.isLocked}:{},instance:ft?ot:{bindingId:rt.id,assetId:rt.assetId,assetKind:rt.assetKind,role:_e===rt.sourceRootEntityId?"root":"linked",sourceEntityId:_e}}}function orderPrefabBindingsForSnapshotMaterialization(rt){const _e=Object.values(rt.bindings),tt=new Map(_e.map(st=>[st.id,st])),et=new Map;for(const st of _e){let ct=et.get(st.id);ct||(ct=new Set,et.set(st.id,ct));for(const dt of Object.values(st.sourceEntitySnapshots??{})){if(!dt.instanceAssetKind)continue;const ut=_e.find(ht=>ht.id!==st.id&&ht.instanceRootEntityId===dt.sceneEntityId&&ht.assetKind===dt.instanceAssetKind);ut&&ct.add(ut.id)}}const nt=[],it=new Set,at=new Set,ot=st=>{if(!at.has(st.id)){if(it.has(st.id))throw new Error(`Prefab binding materialization dependency cycle detected at "${st.id}"`);it.add(st.id);for(const ct of et.get(st.id)??[]){const dt=tt.get(ct);dt&&ot(dt)}it.delete(st.id),at.add(st.id),nt.push(st)}};for(const st of _e)ot(st);return nt}function materializePrefabBindingSnapshots(rt,_e){for(const tt of orderPrefabBindingsForSnapshotMaterialization(_e))for(const[et,nt]of Object.entries(tt.sourceEntitySnapshots??{})){if(isRemovedSourceEntity(tt,et)){const at=nt.sceneEntityId??tt.sourceToSceneEntity[et];at&&delete rt[at];continue}const it=nt.sceneEntityId??tt.sourceToSceneEntity[et];it&&(rt[it]=snapshotEntityToDomainEntity(tt,et,nt,rt[it]))}}function assertNoUnmaterializedSourceInstances(rt,_e,tt){var et,nt;for(const it of Object.values(rt)){const at=(et=it.instance)==null?void 0:et.bindingId;if(!(!at||_e.bindings[at])&&!(tt.allowUnmaterializedGlTFInstances&&((nt=it.instance)==null?void 0:nt.assetKind)==="glTF"))throw new Error(`Cannot direct-hydrate source v2 instance entity "${it.id}" without prefab binding snapshots. Asset-backed instance expansion must happen before scene hydration enters DomainState; check that instantiate() ran for all referenced prefab assets.`)}}function assertAddedOverridesMaterialized(rt,_e){for(const tt of Object.values(rt.bindings)){for(const et of Object.values(tt.overrides.addedEntities??{}))if(!hasMaterializedAddedEntity(_e,tt.id,et.entityId))throw new Error(`Prefab binding "${tt.id}" added entity "${et.entityId}" is missing inline payload during source-v2 hydration`);for(const[et,nt]of Object.entries(tt.overrides.addedComponents??{}))for(const it of Object.values(nt))if(!hasMaterializedAddedComponent(_e,tt.id,et,it.componentId))throw new Error(`Prefab binding "${tt.id}" added component "${it.componentId}" is missing inline payload during source-v2 hydration`)}}function assertGLTFBindingsHaveSourceSnapshots(rt){for(const _e of Object.values(rt.bindings)){if(_e.assetKind!=="glTF")continue;const tt=_e.sourceEntitySnapshots??{};if(!(Object.keys(tt).length>0&&tt[_e.sourceRootEntityId]))throw new Error(`Cannot direct-hydrate glTF binding "${_e.id}" without source snapshots. glTF source baselines are not refreshed from source v2 scene hydration, so persisted binding snapshots must include the instance root.`)}}function createRequiredHydrationSourceRefResolver(rt){const _e=createSourceRefCodec({resolveSourceRef:rt});return tt=>_e.sourceToDomain(tt)}function hydrateSourceV2SceneToDomain(rt,_e={}){const tt=rt,et={},nt=[],it=createRequiredHydrationSourceRefResolver(_e.resolveSourceRef),at={..._e,resolveSourceRef:it};parseSceneFileV2(tt,et,nt,{...at,deferPrefabInlineOverrideMaterialization:!0});const ot=tt.entities.map(pt=>pt.id),st=tt.components.map(pt=>pt.id),ct=at.initialPrefabState?clone(at.initialPrefabState):createEmptyPrefabState(),dt=refreshAndSeedPrefabBindingsFromSource(ct,tt,at,et,ot,st),ut=prunePrefabBindingsToReachableSourceInstances(tt,dt,at);at.allowMissingNestedInstanceBindings||assertNestedSourceInstanceBindingsPresent(ut,at),assertGLTFBindingsHaveSourceSnapshots(ut),materializePrefabBindingSnapshots(et,ut);const ht=createAddedOverrideMaterializationReport();materializeAddedOverridesFromSource(tt,et,it,at.resolveAssetKind,ut,ht),assertAddedOverridesMaterialized(ut,ht),assertNoUnmaterializedSourceInstances(et,ut,at);const ft=extractSceneSettings(rt.scene,at);return{scene:{rootEntityIds:nt,...ft?{settings:ft}:{}},entities:et,prefab:ut}}function isSceneFile(rt){return"scene"in rt}function createRequiredLocalSourceRefResolver(rt){return _e=>{const tt=rt==null?void 0:rt(_e);if(typeof tt!="string"||tt.length===0)throw new Error(`Unable to resolve source asset ref "${_e}" to an editor asset id during local v2 hydration`);return tt}}function buildParentById(rt){const _e=new Map;return rt.entities.forEach(tt=>{var et;isSourceInstanceBoundary(tt)||(et=tt.children)==null||et.forEach(nt=>{_e.set(nt,tt.id)})}),_e}function componentToLocalSchema(rt,_e,tt){var et,nt;return{id:_e,type:rt.type,props:convertAssetRefsToDomainRefs(rt.props??{},tt),...(et=rt.script)!=null&&et.$ref?{script:{$ref:tt(rt.script.$ref),...rt.script.key?{key:rt.script.key}:{}}}:{},...(nt=rt.calls)!=null&&nt.length?{calls:convertAssetRefsToDomainRefs(rt.calls,tt)}:{}}}function readTransform(rt,_e){return readSourceEntityResolvedState(rt,"",{...typeof _e=="string"?{rootOverrideTarget:_e}:{}}).transform}function hasSourceTransformComponent(rt,_e){return(rt.components??[]).some(tt=>{var nt;const et=(nt=_e.componentById.get(tt))==null?void 0:nt.type;return et==="Transform"||et==="UITransform"})}function applySourceEntityStateToEngine(rt,_e,tt,et){const nt=readSourceEntityResolvedState(_e,tt,{...typeof et=="string"?{rootOverrideTarget:et}:{}});rt.name=tt,rt.isActive=nt.isActive,nt.layer!==void 0&&(rt.layer=nt.layer);const it=nt.transform;rt.transform.position=new Vector3(it.position.x,it.position.y,it.position.z),rt.transform.rotation=new Vector3(it.rotation.x,it.rotation.y,it.rotation.z),rt.transform.scale=new Vector3(it.scale.x,it.scale.y,it.scale.z)}function applySourceEntityState(rt,_e,tt){const et=readSourceEntityResolvedState(_e,rt.id,{...typeof tt=="string"?{rootOverrideTarget:tt}:{}});rt.name=et.name,rt.isActive=et.isActive,et.layer!==void 0&&(rt.layer=decomposeLayersByBitwise(et.layer));const nt=rt.engineObject;nt&&applySourceEntityStateToEngine(nt,_e,et.name,tt)}function insertLocalChild(rt,_e,tt){const et=rt.selfChildrenId.filter(Boolean);et.includes(_e.id)||(et.splice(Math.min(tt,et.length),0,_e.id),rt.applyChildrenFromDomain(et)),_e.applyParentFromDomain(rt.id),!(!rt.engineObject||!_e.engineObject||_e.engineObject.parent===rt.engineObject)&&rt.engineObject.addChild(Math.min(tt,rt.engineObject.children.length),_e.engineObject)}async function addSourceComponents(rt,_e,tt,et){const nt=readTransform(_e);!rt.transform&&!hasSourceTransformComponent(_e,tt)&&EditorComponent.getRegisteredComponent("Transform")&&await rt.addEditorComponent({id:`${rt.id}:Transform`,type:"Transform",props:nt});for(const it of _e.components??[]){const at=tt.componentById.get(it);if(!at)throw new Error(`Invalid source v2 local hydration: component "${it}" is missing from source index`);await rt.addEditorComponent(componentToLocalSchema(at,it,et))}}async function createSourceEntityModel(rt,_e,tt,et){var ct;const nt=_e.entityById.get(tt);if(!nt)throw new Error(`Invalid source v2 file: entity id "${tt}" cannot be hydrated`);const it=(ct=nt.instance)==null?void 0:ct.asset;if(it!=null&&it.$ref){const dt=et.resolveSourceRef(it.$ref),ut=et.resolveAssetKind(it.$ref,dt),ht=resolveSourceInstanceRootOverrideTarget({sourceEntity:nt,fallbackSourceEntityId:tt,assetId:dt,instanceAssetKind:ut,resolvePrefabSourceFile:et.resolvePrefabSourceFile}),ft=await rt.root.assetStore.getAssetByRef({refId:dt});if(!(ft!=null&&ft.instantiate))throw new Error(`Cannot hydrate source v2 instance entity "${tt}": asset "${dt}" is not instantiable`);const pt=readSourceEntityResolvedState(nt,tt,{...typeof ht=="string"?{rootOverrideTarget:ht}:{}}),mt=await ft.instantiate(rt,pt.transform,{expectedRootId:tt,...rt.isDomainScoped?{deferDomainBinding:!0,deferredInstanceBindings:et.deferredInstanceBindings}:{}});return await mt.ensureReady(),applySourceEntityState(mt,nt,ht),mt}const at=readSourceEntityResolvedState(nt,tt),ot=rt.createEntity(at.name,tt),st=new Entity(rt.engine,at.name);return applySourceEntityStateToEngine(st,nt,at.name),await ot.bindEngineObject(st),await ot.initImmediate(),await ot.ensureReady(),applySourceEntityState(ot,nt),await addSourceComponents(ot,nt,_e,et.resolveSourceRef),applySourceEntityState(ot,nt),ot}async function hydrateSourceV2LocalEntities(rt,_e,tt={}){isSceneFile(_e)?assertSourceV2SceneFileStructure(_e):assertSourceV2PrefabFileStructure(_e);const et=tt.clearExisting??!0;et&&rt.clear();const it={resolveSourceRef:createRequiredLocalSourceRefResolver(tt.resolveSourceRef),resolveAssetKind:tt.resolveAssetKind??(()=>{}),resolvePrefabSourceFile:tt.resolvePrefabSourceFile,clearExisting:et,registerDomain:tt.registerDomain??!0,deferredInstanceBindings:tt.deferredInstanceBindings??[]},at=buildSourceIdIndex(_e),ot=buildParentById(_e),st=getSourceRootEntityIds(_e),ct=collectReachableSourceEntityIds(_e.entities,st),dt=new Set(ct),ut=new Map,ht=async pt=>{const mt=ut.get(pt);if(mt)return mt;const vt=await createSourceEntityModel(rt,at,pt,it);ut.set(pt,vt);const _t=at.entityById.get(pt),yt=isSourceInstanceBoundary(_t)?[]:(_t==null?void 0:_t.children)??[];for(let bt=0;bt<yt.length;bt++){const Et=yt[bt];if(!dt.has(Et))throw new Error(`Invalid source v2 local hydration: child entity "${Et}" is not reachable`);const St=await ht(Et);insertLocalChild(vt,St,vt.selfChildrenId.length+bt)}return vt},ft=[];for(const pt of st)ft.push(await ht(pt));for(const pt of ct)!ot.has(pt)&&!st.includes(pt)&&ft.push(await ht(pt));if(et&&rt.setLocalRootEntityIds(ft.map(pt=>pt.id)),rt.isDomainScoped&&it.registerDomain){for(const mt of ft)rt.root.domainStore.state.entities[mt.id]||rt.registerEntityTreeInDomain(mt,null,void 0,{deferInstanceBinding:!0});const pt=it.deferredInstanceBindings.splice(0);for(const mt of pt)mt()}return ft}var __defProp$5=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$4(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$5(_e,tt,nt),nt};class SceneUIStore extends RootStore{constructor(tt){super(tt);Rt(this,"selectedKeys",new Set);Rt(this,"expandedKeys",new Set([DEFAULT_SCENE]));Rt(this,"visibilityById",observable.map());Rt(this,"hoveredEntityId",null);Rt(this,"searchText","");Rt(this,"lastSelectedId",null);Rt(this,"_logger",new TraceLogger("SceneUIStore"));Rt(this,"_selectionListeners",new Set);makeObservable(this)}onSelectionChange(tt){return this._selectionListeners.add(tt),()=>this._selectionListeners.delete(tt)}_notifySelectionChange(){for(const tt of[...this._selectionListeners])tt()}isEntityVisible(tt){return this.visibilityById.get(tt)??!0}isEntityExpanded(tt){return this.expandedKeys.has(tt)}selectEntity(tt,et=!1){this._logger.info("selectEntity",{id:tt,multiple:et}),et||this.selectedKeys.clear(),this.selectedKeys.add(tt),this.lastSelectedId=tt,this._notifySelectionChange()}replaceSelectedKeys(tt){this.selectedKeys.clear();for(const et of tt)this.selectedKeys.add(et);this._notifySelectionChange()}clearSelection(){this._logger.info("clearSelection"),this.selectedKeys.clear(),this.lastSelectedId=null,this._notifySelectionChange()}deselectEntity(tt){this._logger.info("deselectEntity",{id:tt}),this.selectedKeys.delete(tt),this.lastSelectedId===tt&&(this.lastSelectedId=Array.from(this.selectedKeys).pop()??null),this._notifySelectionChange()}setLastSelectedId(tt){this.lastSelectedId=tt}expandEntity(tt){this.expandedKeys.add(tt)}collapseEntity(tt){this.expandedKeys.delete(tt)}setSearchText(tt){this.searchText=tt}setHoveredEntity(tt){this.hoveredEntityId=tt}setEntityVisible(tt,et){this.visibilityById.set(tt,et)}removeEntity(tt){this.selectedKeys.delete(tt),this.expandedKeys.delete(tt),this.visibilityById.delete(tt),this.hoveredEntityId===tt&&(this.hoveredEntityId=null),this.lastSelectedId===tt&&(this.lastSelectedId=Array.from(this.selectedKeys).pop()??null)}clear(){this.selectedKeys.clear(),this.expandedKeys.clear(),this.expandedKeys.add(DEFAULT_SCENE),this.visibilityById.clear(),this.hoveredEntityId=null,this.searchText="",this.lastSelectedId=null}}__decorateClass$4([observable],SceneUIStore.prototype,"selectedKeys",2);__decorateClass$4([observable],SceneUIStore.prototype,"expandedKeys",2);__decorateClass$4([observable],SceneUIStore.prototype,"visibilityById",2);__decorateClass$4([observable],SceneUIStore.prototype,"hoveredEntityId",2);__decorateClass$4([observable],SceneUIStore.prototype,"searchText",2);__decorateClass$4([observable],SceneUIStore.prototype,"lastSelectedId",2);__decorateClass$4([action],SceneUIStore.prototype,"selectEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"replaceSelectedKeys",1);__decorateClass$4([action],SceneUIStore.prototype,"clearSelection",1);__decorateClass$4([action],SceneUIStore.prototype,"deselectEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setLastSelectedId",1);__decorateClass$4([action],SceneUIStore.prototype,"expandEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"collapseEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setSearchText",1);__decorateClass$4([action],SceneUIStore.prototype,"setHoveredEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setEntityVisible",1);__decorateClass$4([action],SceneUIStore.prototype,"removeEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"clear",1);function groupAddedRootsByStrippedId(rt,_e,tt){const et=new Map;for(let nt=0,it=rt.length;nt<it;nt++){const at=rt[nt];if(at.strippedId)continue;const ot=at.parent;if(!ot||ot===tt||!_e.has(ot))continue;const st=et.get(ot)??[];st.push(at),et.set(ot,st)}return et}function indexSchemas(rt){const _e=new Map,tt=[],et=new Set;for(let nt=0,it=rt.length;nt<it;nt++){const at=rt[nt],ot=at.strippedId||at.id;ot&&(_e.set(ot,at),at.strippedId&&(tt.push(at),et.add(at.strippedId)))}return{schemaByKey:_e,strippedSchemas:tt,strippedIdSet:et}}function resolveStrippedOriginal(rt){const{strippedSchema:_e,schemaByKey:tt,entities:et,findByIndexPath:nt}=rt,it=resolveStrippedPrefabLink(_e),at=it.prefabInstanceId;if(!at)return null;const ot=tt.get(at);if(!(ot!=null&&ot.id))return null;const st=et.get(ot.id);if(!st)return null;const ct=it.sourceEntityId;return typeof ct!="string"?null:nt(st,ct)}function collectSidecarAddedEntityOverrides(rt){var tt;const _e=new Map;for(const[et,nt]of Object.entries((rt==null?void 0:rt.bindings)??{}))for(const it of Object.values(((tt=nt.overrides)==null?void 0:tt.addedEntities)??{}))_e.set(it.entityId,{...it,bindingId:et});return _e}function prepareSidecarAddedEntityRestore(rt){var et,nt;const _e=[],tt=[];for(const it of rt.entitiesSchema){const at=it.id;if(!at||rt.existingEntityIds.has(at))continue;const ot=rt.addedOverrides.get(at);if(!ot)continue;const st=(et=rt.prefabBindings)==null?void 0:et[ot.bindingId],ct=(nt=st==null?void 0:st.sourceToSceneEntity)==null?void 0:nt[ot.parentSourceEntityId];if(!st||!ct){tt.push({bindingId:ot.bindingId,entityId:at,parentSourceEntityId:ot.parentSourceEntityId});continue}_e.push({schema:it,bindingId:ot.bindingId,entityId:at,parentSourceEntityId:ot.parentSourceEntityId,parentSceneEntityId:ct,index:ot.index})}return{plans:_e,missingParents:tt}}function applySceneEntitySelection(rt,_e,tt=!1,et=!1){return rt.selectedKeys.has(_e)?et?(rt.deselectEntity(_e),{changed:!0,selected:rt.selectedKeys.size>0}):{changed:!1,selected:!0}:(rt.selectEntity(_e,tt),{changed:!0,selected:!0})}function collectSubtreeIds(rt,_e){const tt=[],et=nt=>{if(rt.entities[nt]){tt.push(nt);for(const at of rt.relations.entityChildren[nt]??[])et(at)}};return et(_e),tt}function getSiblingPath(rt){return rt?`/entities/${encodeJsonPointerSegment(rt)}/children`:"/scene/rootEntityIds"}function getSiblings(rt,_e){return _e?[...rt.relations.entityChildren[_e]??[]]:[...rt.scene.rootEntityIds]}function pushRemovedNestedBindingOps(rt,_e,tt,et){var it;const nt=new Set;for(const at of tt){const ot=(it=rt.entities[at])==null?void 0:it.instance;!(ot!=null&&ot.bindingId)||ot.role!=="root"||ot.bindingId!==et&&rt.prefab.bindings[ot.bindingId]&&nt.add(ot.bindingId)}if(nt.size!==0){for(const at of nt)_e.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(at)}`});for(const[at,ot]of Object.entries(rt.prefab.byAssetId)){const st=ot.filter(dt=>!nt.has(dt));if(st.length===ot.length)continue;const ct=`/prefab/byAssetId/${encodeJsonPointerSegment(at)}`;_e.push(st.length===0?{op:"remove",path:ct}:{op:"replace",path:ct,value:st})}}}function collectPreservedAddedEntityIds(rt,_e,tt){var it;if(!tt)return new Set;const et=rt.prefab.bindings[tt];if(!et)return new Set;const nt=new Set;for(const at of Object.keys(((it=et.overrides)==null?void 0:it.addedEntities)??{}))if(_e.has(at))for(const ot of collectSubtreeIds(rt,at))nt.add(ot);return nt}function pushPreservedAddedEntityReparentOps(rt,_e,tt,et){var at,ot;if(!et||tt.size===0)return;const nt=rt.prefab.bindings[et];if(!nt)return;const it=new Map;for(const st of Object.values(((at=nt.overrides)==null?void 0:at.addedEntities)??{})){if(!tt.has(st.entityId))continue;const ct=nt.sourceToSceneEntity[st.parentSourceEntityId];if(!ct||!rt.entities[ct])continue;const dt=it.get(ct)??[];dt.push({entityId:st.entityId,index:st.index}),it.set(ct,dt),((ot=rt.entities[st.entityId])==null?void 0:ot.parentId)!==ct&&_e.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(st.entityId)}/parentId`,value:ct})}for(const[st,ct]of it){const dt=getSiblings(rt,st).filter(ut=>!tt.has(ut));ct.sort((ut,ht)=>ut.index===ht.index?ut.entityId.localeCompare(ht.entityId):ut.index-ht.index).forEach(({entityId:ut,index:ht})=>{dt.splice(Math.min(Math.max(ht,0),dt.length),0,ut)}),_e.push({op:"replace",path:getSiblingPath(st),value:dt})}}function buildReplaceEntityTreeOps(rt,_e,tt){var _t,yt,bt;if(_e===tt)return[];const et=rt.entities[_e],nt=rt.entities[tt];if(!et||!nt)return[];const it=et.parentId??null,at=nt.parentId??null,ot=getSiblingPath(it),st=getSiblingPath(at),ct=getSiblings(rt,it),dt=getSiblings(rt,at),ut=Math.max(ct.indexOf(_e),0),ht=[];st!==ot&&ht.push({op:"replace",path:st,value:dt.filter(Et=>Et!==tt)});const ft=ct.filter(Et=>Et!==_e&&Et!==tt);ft.splice(Math.min(ut,ft.length),0,tt),ht.push({op:"replace",path:ot,value:ft}),at!==it&&ht.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(tt)}/parentId`,value:it});const pt=collectSubtreeIds(rt,_e),mt=collectPreservedAddedEntityIds(rt,new Set(pt),(_t=et.instance)==null?void 0:_t.bindingId);pushPreservedAddedEntityReparentOps(rt,ht,mt,(yt=et.instance)==null?void 0:yt.bindingId);const vt=pt.filter(Et=>!mt.has(Et));pushRemovedNestedBindingOps(rt,ht,vt,(bt=et.instance)==null?void 0:bt.bindingId);for(const Et of[...vt].reverse())ht.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(Et)}`});return ht}function resolveUniqueEntityId(rt){const{isStripped:_e,localEntityMap:tt,domainEntities:et,uuid:nt}=rt;let it=rt.id??nt();for(;tt.has(it)||!_e&&et[it];)it=nt();return it}function selectEntityRemovalStrategy(rt){return rt.isPrefabSubEntity?"prefab-sub-entity":rt.isRoot||rt.existsInDomainState?"facade-delete":"parent-remove"}const logger=new TraceLogger("applyAssetTemplateDiffs");function applyAssetTemplateDiffs(rt,_e){const tt=rt.engineObject;tt&&(logger.info("applying",{rootName:rt.name,paths:Object.keys(_e.entityProps??{}),diffs:_e.entityProps}),applyAssetTemplateDiffs$1(tt,_e),logger.info("done",{rootName:rt.name}))}function getEntityModelChildren(rt){return rt.selfChildren??rt.children??[]}function findEntityModelByIndexPath(rt,_e){if(!_e)return rt;let tt=rt;for(const et of _e.split("/")){const nt=Number(et);if(!Number.isInteger(nt)||(tt=getEntityModelChildren(tt)[nt]??null,!tt))return null}return tt}function collectEntitySubtreeIds(rt,_e){const tt=[],et=nt=>{const it=rt.entities[nt];if(it){tt.push(nt);for(const at of it.children)et(at)}};return et(_e),tt}function removeEntityFromParentOps(rt,_e){const tt=rt.entities[_e];if(!tt)return[];if(tt.parentId){const nt=rt.entities[tt.parentId],it=(nt==null?void 0:nt.children.indexOf(_e))??-1;return it>=0?[{op:"remove",path:`/entities/${encodeJsonPointerSegment(tt.parentId)}/children/${it}`}]:[]}const et=rt.scene.rootEntityIds.indexOf(_e);return et>=0?[{op:"remove",path:`/scene/rootEntityIds/${et}`}]:[]}function removeEntityTreeOps(rt,_e){const tt=removeEntityFromParentOps(rt,_e);for(const et of collectEntitySubtreeIds(rt,_e).reverse())tt.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(et)}`});return tt}function hasRemovedAncestor(rt,_e,tt){var nt,it;let et=(nt=rt.entities[_e])==null?void 0:nt.parentId;for(;et;){if(tt.has(et))return!0;et=(it=rt.entities[et])==null?void 0:it.parentId}return!1}function hasPersistedBinding(rt,_e){var et;if(!_e)return!1;const tt=((et=rt.state.prefab)==null?void 0:et.bindings)??{};return Object.values(tt).some(nt=>nt.instanceRootEntityId===_e)}function clearPersistedEntityForReload(rt,_e){rt.getNormalizedState().entities[_e]&&rt.applySystem([{op:"remove",path:`/entities/${encodeJsonPointerSegment(_e)}`}])}function applyBindingOverridesOnReload(rt,_e,tt){var ht,ft,pt,mt,vt,_t,yt,bt;const et=rt.getNormalizedState(),nt=[],it=((ht=tt.overrides)==null?void 0:ht.removedEntities)??{},at=Object.keys(it).map(Et=>getNormalizedSceneEntityIdForSource(et,tt.id,Et)).filter(Et=>!!(Et&&rt.state.entities[Et])),ot=new Set(at);for(const Et of at)hasRemovedAncestor(rt.state,Et,ot)||nt.push(...removeEntityTreeOps(rt.state,Et));const st=((ft=tt.overrides)==null?void 0:ft.removedComponents)??{};for(const[Et,St]of Object.entries(st)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!(!At||!rt.state.entities[At]))for(const xt of Object.keys(St)){const Ct=findNormalizedComponentIdBySourceKey(et,At,xt);!Ct||!((pt=rt.state.entities[At])!=null&&pt.components[Ct])||nt.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(Ct)}`})}}const ct=((mt=tt.overrides)==null?void 0:mt.addedComponents)??{};for(const[Et,St]of Object.entries(ct)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!(!At||!rt.state.entities[At]))for(const[xt,Ct]of Object.entries(St)){const Pt=`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(xt)}`;nt.push({op:rt.state.entities[At].components[xt]?"replace":"add",path:Pt,value:{type:Ct.type,props:structuredClone(Ct.props??{}),instance:{bindingId:tt.id,role:"added"}}})}}const dt=((vt=tt.overrides)==null?void 0:vt.entityProps)??{};for(const[Et,St]of Object.entries(dt)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!At||!et.entities[At])continue;const xt=encodeJsonPointerSegment(At);if(St.name!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/name`,value:St.name}),St.isActive!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/isActive`,value:St.isActive}),St.layer!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/layer`,value:St.layer}),St.transform){const Ct=(_t=rt.state.entities[At])==null?void 0:_t.transform;if(!Ct)continue;St.transform.position&&nt.push({op:"replace",path:`/entities/${xt}/transform/position`,value:{...Ct.position,...St.transform.position}}),St.transform.rotation&&nt.push({op:"replace",path:`/entities/${xt}/transform/rotation`,value:{...Ct.rotation,...St.transform.rotation}}),St.transform.scale&&nt.push({op:"replace",path:`/entities/${xt}/transform/scale`,value:{...Ct.scale,...St.transform.scale}})}}const ut=((yt=tt.overrides)==null?void 0:yt.componentProps)??{};for(const[Et,St]of Object.entries(ut)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(At&&et.entities[At])for(const[xt,Ct]of Object.entries(St)){if((bt=st[Et])!=null&&bt[xt])continue;const Pt=findNormalizedComponentIdBySourceKey(et,At,xt);if(Pt&&getNormalizedComponent(et,At,Pt)){const Tt=encodeJsonPointerSegment(At),wt=encodeJsonPointerSegment(Pt);for(const[It,Ot]of Object.entries(Ct))nt.push({op:"replace",path:`/entities/${Tt}/components/${wt}/props/${encodeJsonPointerSegment(It)}`,value:Ot})}}}nt.length>0&&rt.applySystem(nt)}function syncAssetTemplateDiffsToDomain(rt,_e,tt){const et=tt.entityProps;if(!et)return;const nt=[];if(!_e.engineObject)return;const at=rt.getNormalizedState();for(const[ot,st]of Object.entries(et)){const ct=findEntityModelByIndexPath(_e,ot);if(!ct)continue;const dt=ct.id;if(!dt||!at.entities[dt])continue;const ut=encodeJsonPointerSegment(dt);st.transform&&(st.transform.rotation&&nt.push({op:"replace",path:`/entities/${ut}/transform/rotation`,value:st.transform.rotation}),st.transform.position&&nt.push({op:"replace",path:`/entities/${ut}/transform/position`,value:st.transform.position}),st.transform.scale&&nt.push({op:"replace",path:`/entities/${ut}/transform/scale`,value:st.transform.scale})),st.name!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/name`,value:st.name}),st.isActive!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/isActive`,value:st.isActive}),st.layer!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/layer`,value:st.layer})}nt.length>0&&rt.apply(nt,"prefab.assetTemplateDiffs")}function assertSourceV2LocalHydrationFile(rt,_e="source file"){if(!isRecord(rt))throw new Error(`${_e} is not a source v2 scene/prefab file.`);if(!isRecord(rt.asset)||rt.asset.version!=="2.0")throw new Error(`${_e} expected source v2 scene/prefab file with asset.version "2.0".`);if("scene"in rt){assertSourceV2SceneFileStructure(rt);return}assertSourceV2PrefabFileStructure(rt)}var __defProp$4=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$3(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$4(_e,tt,nt),nt};class EntityManager extends EngineObjectProxy{constructor(tt){super(tt);Rt(this,"engine");Rt(this,"engineSceneObject");Rt(this,"_sourceV2LocalHydrationDepth",0);Rt(this,"_localRootEntityIds",[]);Rt(this,"rootEntity");Rt(this,"entities",new Map);Rt(this,"strippedEntities",new Map);Rt(this,"_prefabRemovedSidecarIndexCache",null);Rt(this,"selectEntity",(tt,et=!1,nt=!1)=>{if(tt===DEFAULT_SCENE){this.sceneUIStore.clearSelection(),this.sceneUIStore.selectEntity(DEFAULT_SCENE),this._triggerUnSelect();return}if(!tt){this.sceneUIStore.setLastSelectedId(null),this.sceneUIStore.clearSelection(),this._triggerUnSelect();return}this.sceneUIStore.selectedKeys.has(DEFAULT_SCENE)&&(et=!1);const it=applySceneEntitySelection(this.sceneUIStore,tt,et,nt);if(!it.changed)return;if(!it.selected){this._triggerUnSelect();return}this._triggerSelectedEntity();let at=this.entities.get(tt);for(;at!=null&&at.parentEntity;)this.expandEntity(at.parentEntity.id),at=at.parentEntity});Rt(this,"selectEntityByRange",(tt,et)=>{const nt=this.displayedEntitiesIds.indexOf(tt),it=this.displayedEntitiesIds.indexOf(et),[at,ot]=[Math.min(nt,it),Math.max(nt,it)],st=this.displayedEntitiesIds.slice(at,ot+1);this.sceneUIStore.replaceSelectedKeys(st)});Rt(this,"expandEntity",tt=>{this.sceneUIStore.expandEntity(tt)});Rt(this,"collapseEntity",tt=>{this.sceneUIStore.collapseEntity(tt)});Rt(this,"setSearchText",tt=>{this.sceneUIStore.setSearchText(tt)});Rt(this,"removeEntity",tt=>{tt||(tt=Array.from(this.sceneUIStore.selectedKeys)),Array.isArray(tt)?tt.forEach(et=>{this.removeSingleEntity(et)}):this.removeSingleEntity(tt)});Rt(this,"removeSingleEntity",tt=>{let et;if(typeof tt=="string"){if(tt===DEFAULT_SCENE)return;et=this.entities.get(tt)}else et=tt;if(!et||et.prefabEntityRemoved)return;const nt=et.id,it=this.sceneUIStore.lastSelectedId===nt;this.sceneUIStore.removeEntity(nt),it&&this._triggerUnSelect();const at=et.parentEntity,ot=this.root.domainStore.getNormalizedState();switch(selectEntityRemovalStrategy({isPrefabSubEntity:et.isPrefabSubEntity,isRoot:et.isRoot,existsInDomainState:!!ot.entities[nt]})){case"prefab-sub-entity":this.removePrefabSubEntity(et);break;case"facade-delete":this.root.entityFacade.deleteEntity(nt);break;case"parent-remove":at==null||at.removeChildById(nt);break}this.root.projectStore.debouncedUpdateSceneAsset()});Rt(this,"isChildNode",(tt,et)=>{for(let nt=0;nt<tt.length;nt++){const it=[tt[nt]];for(;it.length>0;){const at=it.pop();if(at===et)return!0;const ot=this.entities.get(at);ot.childrenId&&ot.childrenId.length>0&&it.push(...ot.childrenId)}}return!1});Rt(this,"getEntityPath",tt=>{let et=this.entities.get(tt);const nt=[];for(;et;)nt.unshift(et.name),et=et.parentEntity;return nt.join("/")});Rt(this,"setHoveredEntity",tt=>{this.sceneUIStore.setHoveredEntity(tt),this.root.viewportStore.hoverEntity(this.entities.get(tt))});this.root=tt,this.engine=tt.projectStore.engine,this.engineSceneObject=new Scene(this.engine),this.rootEntity=new RootEntityModel(this),makeObservable(this)}get isDomainScoped(){return!1}get isHydratingSourceV2LocalEntities(){return this._sourceV2LocalHydrationDepth>0}get rootEntitiesId(){return this._localRootEntityIds}setLocalRootEntityIds(tt){this._localRootEntityIds=[...tt]}get sceneUIStore(){const tt=this.root;return tt.sceneUIStore||(tt.sceneUIStore=new SceneUIStore(this.root)),tt.sceneUIStore}get rootEntities(){return this.rootEntitiesId.map(tt=>this.entities.get(tt)).filter(Boolean)}get selectedEntities(){return Array.from(this.sceneUIStore.selectedKeys).map(tt=>this.entities.get(tt)).filter(Boolean)}get displayedEntities(){if(this.sceneUIStore.searchText){const tt=this.sceneUIStore.searchText.toLowerCase();return Array.from(this.entities.values()).filter(et=>et.name.toLowerCase().indexOf(tt)>-1)}return this.rootEntities}get displayedEntitiesIds(){const tt=[],et=it=>this.sceneUIStore.isEntityExpanded(it);function nt(it){tt.push(it.id),et(it.id)&&it.children.forEach(at=>{nt(at)})}return this.rootEntities.forEach(it=>{nt(it)}),tt}get lastSelectedEntity(){return this.entities.get(this.sceneUIStore.lastSelectedId)}getChildrenIds(tt){return tt.selfChildrenId.filter(Boolean)}getParentId(tt){return tt.selfParent}createEntityInStore(tt,et,nt,it){var st;const at=new Entity(this.engine,et.name??"Entity");et.isActive===!1&&(at.isActive=!1);const ot=(st=et.transform)==null?void 0:st.props;if(ot){const{position:ct,rotation:dt,scale:ut}=ot;ct&&at.transform.position.set(ct.x,ct.y,ct.z),dt&&at.transform.rotation.set(dt.x,dt.y,dt.z),ut&&at.transform.scale.set(ut.x,ut.y,ut.z)}it.bindEngineObject(at)}connectChildEntities(tt,et){if(tt.engineObject)for(const nt of et)nt.engineObject&&tt.engineObject.addChild(nt.engineObject)}onTemplateEntityCreated(tt,et){}async init(tt,et){this.clear();const nt=et??JSON.parse(tt.getMainData());assertSourceV2LocalHydrationFile(nt,`Asset "${tt.name??tt.id}"`);const it=at=>{var ot,st,ct;return(ct=(st=(ot=this.root)==null?void 0:ot.assetStore)==null?void 0:st.getAssetByVirtualPath)==null?void 0:ct.call(st,at)};return await this.hydrateSourceV2LocalEntities(nt,{resolveSourceRef:at=>{var st;const ot=(st=it(at))==null?void 0:st.id;if(typeof ot!="string"||ot.length===0)throw new Error(`[SceneV2] Unable to resolve asset ref "${at}" while loading asset "${tt.id}". Source-v2 $ref must be a virtualPath, not an editor asset id.`);return ot},resolveAssetKind:at=>{var st,ct,dt;const ot=(dt=(ct=(st=it(at))==null?void 0:st.getMetaConfig)==null?void 0:ct.call(st))==null?void 0:dt.type;return ot==="Prefab"||ot==="glTF"?ot:void 0}}),nt}async hydrateSourceV2LocalEntities(tt,et={}){this._sourceV2LocalHydrationDepth++;try{return await hydrateSourceV2LocalEntities(this,tt,et)}finally{this._sourceV2LocalHydrationDepth--}}hydrateDomainEntityModelsFromState(){if(!this.isDomainScoped)throw new Error("hydrateDomainEntityModelsFromState can only run on a domain-scoped EntityManager");this.clear();const tt=this.root.domainStore.state,et=[],nt=new Set,it=at=>{var dt;if(nt.has(at))return this.entities.get(at);const ot=tt.entities[at];if(!ot)return;ot.parentId&&it(ot.parentId),nt.add(at);let st=this.entities.get(at);st||(st=this.createEntity(ot.name,at)),st.applyParentFromDomain(ot.parentId),st.applyChildrenFromDomain(ot.children);const ct=(dt=this.root.engineProjection)==null?void 0:dt.getEntity(at);ct&&st.initImmediate(ct),st.transform||st.addComponentFromDomain(`${at}:Transform`,{type:"Transform",props:ot.transform});for(const[ut,ht]of Object.entries(ot.components))st.addComponentFromDomain(ut,ht);return ot.isLocked!==void 0&&st.applyLockedFromDomain(ot.isLocked),st.syncRemovedComponentPlaceholdersFromDomain(),st};for(const at of tt.scene.rootEntityIds){const ot=it(at);ot&&et.push(ot)}for(const at of Object.keys(tt.entities))it(at);return et}createEntity(tt,et=v4()){const nt=new EntityModel(this,et);return tt&&(nt.name=tt),this.entities.set(nt.id,nt),this._registerEntityRuntimeBinder(nt),nt}getEntityModel(tt){return this.entities.get(tt)}hasEntityModel(tt){return this.entities.has(tt)}setEntityModel(tt,et){this.entities.set(tt,et)}deleteEntityModel(tt){return this.entities.delete(tt)}iterateEntityModels(){return this.entities.entries()}getEntityRuntimeFlags(tt){const et=this.entities.get(tt);return{prefabEntityRemoved:this._isPrefabEntityRemovedBySidecar(tt)||((et==null?void 0:et.prefabEntityRemoved)??!1)}}_isPrefabEntityRemovedBySidecar(tt){var ot,st,ct,dt,ut;const et=(st=(ot=this.root.domainStore)==null?void 0:ot.getNormalizedState)==null?void 0:st.call(ot);if(!et)return!1;const nt=this._getPrefabRemovedSidecarIndex(et);if(nt.directEntityIds.has(tt))return!0;const it=nt.mappedBindingIdsBySceneEntityId.get(tt);if(!(it!=null&&it.size))return!1;const at=(ut=(dt=(ct=et.entities)==null?void 0:ct[tt])==null?void 0:dt.instance)==null?void 0:ut.bindingId;return at?it.has(at):!0}_getPrefabRemovedSidecarIndex(tt){var ot,st,ct,dt,ut,ht,ft,pt,mt,vt,_t;if(((ot=this._prefabRemovedSidecarIndexCache)==null?void 0:ot.normalizedState)===tt)return this._prefabRemovedSidecarIndexCache;const et=new Set,nt=new Map,it=(yt,bt)=>{if(!yt)return;const Et=nt.get(yt)??new Set;Et.add(bt),nt.set(yt,Et)},at=((st=tt.prefab)==null?void 0:st.bindings)??{};for(const[yt,bt]of Object.entries(tt.entities??{})){const Et=(ct=bt.instance)==null?void 0:ct.bindingId,St=(dt=bt.instance)==null?void 0:dt.sourceEntityId;!Et||!St||(ft=(ht=(ut=at[Et])==null?void 0:ut.overrides)==null?void 0:ht.removedEntities)!=null&&ft[St]&&et.add(yt)}for(const yt of Object.values(at)){const bt=((pt=yt.overrides)==null?void 0:pt.removedEntities)??{};for(const Et of Object.keys(bt))it((mt=yt.sourceToSceneEntity)==null?void 0:mt[Et],yt.id),it((_t=(vt=yt.sourceEntitySnapshots)==null?void 0:vt[Et])==null?void 0:_t.sceneEntityId,yt.id)}return this._prefabRemovedSidecarIndexCache={normalizedState:tt,directEntityIds:et,mappedBindingIdsBySceneEntityId:nt},this._prefabRemovedSidecarIndexCache}addEntityToParent(tt,et=DEFAULT_SCENE,nt){et===DEFAULT_SCENE&&(et=null);const it=this.entities.get(et);it?it.addChild(tt,nt):tt.parent=null,this.root.projectStore.debouncedUpdateSceneAsset()}registerEntityTreeInDomain(tt,et,nt,it){var mt,vt,_t,yt;const at=et===DEFAULT_SCENE?null:et,{engineProjection:ot,entityFacade:st}=this.root;if(!ot)return;const ct=[];let dt=!0;const ut=(bt,Et)=>{const St=bt.engineObject;St&&ot.registerExternalEntity(bt.id,St);const At=dt&&(it==null?void 0:it.transform);dt=!1;const xt=bt._components.filter(wt=>wt.type&&wt.id).map(wt=>{const It=wt.toJSON(),Ot={...normalizeComponentSchemaToDomainProps(It),...buildInitialComponentProps(wt)};if(wt.type==="Transform"&&At&&(it!=null&&it.transform)){const Nt=it.transform;Ot.position||(Ot.position=Nt.position),Ot.rotation||(Ot.rotation=Nt.rotation),Ot.scale||(Ot.scale=Nt.scale)}return{id:wt.id,type:wt.type,props:Ot}}),Ct=St==null?void 0:St.transform,Pt=At?it.transform:Ct?{position:{x:Ct.position.x,y:Ct.position.y,z:Ct.position.z},rotation:{x:Ct.rotation.x,y:Ct.rotation.y,z:Ct.rotation.z},scale:{x:Ct.scale.x,y:Ct.scale.y,z:Ct.scale.z}}:void 0,Tt=bt.pendingInstance;Tt&&(bt.pendingInstance=null),ct.push({id:bt.id,name:bt.name,parentId:Et,isActive:bt.isActive,layer:St==null?void 0:St.layer,transform:Pt,components:xt.length>0?xt:void 0,...Tt?{instance:Tt}:{}}),bt.selfChildren.forEach(wt=>ut(wt,bt.id))};ut(tt,at);const ht=this.root.domainStore.state.entities,ft=ct.filter(bt=>!ht[bt.id]);if(it!=null&&it.transform)for(const bt of ct){if(!ht[bt.id]||!ht[bt.id])continue;const St=this.root.domainStore.getNormalizedState(),At=bt.id.replace(/~/g,"~0").replace(/\//g,"~1"),xt=[];if(bt.transform&&(xt.push({op:"replace",path:`/entities/${At}/transform/position`,value:bt.transform.position}),xt.push({op:"replace",path:`/entities/${At}/transform/rotation`,value:bt.transform.rotation}),xt.push({op:"replace",path:`/entities/${At}/transform/scale`,value:bt.transform.scale})),bt.components&&bt.components.find(Pt=>Pt.type==="Transform")){const Pt=findNormalizedComponentIdByType(St,bt.id,"Transform");if(Pt){const Tt=Pt.replace(/~/g,"~0").replace(/\//g,"~1");(mt=bt.transform)!=null&&mt.position&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/position`,value:bt.transform.position}),(vt=bt.transform)!=null&&vt.rotation&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/rotation`,value:bt.transform.rotation}),(_t=bt.transform)!=null&&_t.scale&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/scale`,value:bt.transform.scale})}}xt.length>0&&this.root.domainStore.apply(xt,"entity.updateTransform")}ft.length>0&&st.batchCreateEntities(ft);const pt=(yt=ct[0])==null?void 0:yt.instance;if((pt==null?void 0:pt.assetKind)==="glTF"&&pt.assetId&&!(it!=null&&it.deferInstanceBinding)){const bt=pt.bindingId||void 0,Et=buildGlTFDomainInstanceBindingSync({state:this.root.domainStore.state,assetId:pt.assetId,rootEntityId:tt.id,pendingBindingId:bt,createBindingId:()=>`binding-${v4().slice(0,8)}`});Et.kind==="bind"?this.root.prefabFacade.bindExistingInstance({assetId:Et.assetId,assetKind:Et.assetKind,bindingId:Et.bindingId,instanceRootEntityId:Et.instanceRootEntityId,entityMappings:Et.entityMappings,componentMappings:Et.componentMappings,sourceEntitySnapshots:Et.sourceEntitySnapshots,undoable:!1}):Et.kind==="update"&&this.root.prefabFacade.updateBindingSourceBaseline(Et)}nt!==void 0&&st.moveEntity(tt.id,at,nt)}addEntityByTemplate(tt=this.sceneUIStore.lastSelectedId,et){var ot;const nt=tt===DEFAULT_SCENE?null:tt,it=this.root.entityFacade.createEntity({id:v4(),name:(et==null?void 0:et.name)??"Entity",parentId:nt,isActive:(et==null?void 0:et.isActive)??!0,transform:(ot=et==null?void 0:et.transform)!=null&&ot.props?{position:et.transform.props.position,rotation:et.transform.props.rotation,scale:et.transform.props.scale}:void 0}),at=this.entities.get(it);return at&&et&&at.initByFile(et),this.selectEntity(it),this.root.projectStore.debouncedUpdateSceneAsset(),at}createStrippedEntity(tt){const et=v4(),nt=new EntityModel(this,et);return this.strippedEntities.set(et,nt),this._registerEntityRuntimeBinder(nt),nt.originalEntity=tt,this.addEntityToParent(nt,null),nt}rename(tt,et){const nt=this.entities.get(tt);nt&&(nt.name=et)}setEntityVisible(tt,et){var at;const nt=this.entities.get(tt);if(!nt)return;this.sceneUIStore.setEntityVisible(tt,et);const it=this.root.domainStore.getNormalizedState().entities[tt];it?(at=this.root.engineProjection)==null||at.setEntityRuntimeActive(tt,it.isActive&&et):nt.engineObject&&(nt.engineObject.isActive=nt.isActive&&et)}setEntityLocked(tt,et){if(this.root.domainStore.getNormalizedState().entities[tt]){this.root.entityFacade.setLocked(tt,et);return}const it=this.entities.get(tt);it&&(it.isLocked=et)}async deserializeEntities(tt){var dt,ut,ht,ft,pt,mt;const et=[];tt=JSON.parse(JSON.stringify(tt));const{schemaByKey:nt,strippedSchemas:it,strippedIdSet:at}=indexSchemas(tt),ot=collectSidecarAddedEntityOverrides((ht=(ut=(dt=this.root)==null?void 0:dt.domainStore)==null?void 0:ut.state)==null?void 0:ht.prefab),st=groupAddedRootsByStrippedId(tt,at,DEFAULT_SCENE),ct=[];for(let vt=0,_t=tt.length;vt<_t;vt++){const yt=tt[vt];if(yt.strippedId||yt.id&&ot.has(yt.id))continue;const bt=yt.parent;bt&&bt!==DEFAULT_SCENE&&at.has(bt)||!(!bt||bt===DEFAULT_SCENE||!nt.has(bt))||(bt&&bt!==DEFAULT_SCENE&&!nt.has(bt)&&(yt.parent=null),ct.push(yt))}for(const vt of ct)try{await this.createBySchema(vt,nt)}catch(_t){console.error(_t)}(ft=this.root.engineProjection)==null||ft.flushDeferredComponentProps();for(let vt=0,_t=ct.length;vt<_t;vt++){const yt=ct[vt],bt=yt.id?this.entities.get(yt.id):null;bt&&et.push(bt)}this._localRootEntityIds=et.map(vt=>vt.id);for(let vt=0,_t=it.length;vt<_t;vt++){const yt=it[vt],bt=yt.strippedId;if(!bt)continue;const Et=new EntityModel(this,bt);this.strippedEntities.set(bt,Et),this._registerEntityRuntimeBinder(Et);const St=resolveStrippedOriginal({strippedSchema:yt,schemaByKey:nt,entities:this.entities,findByIndexPath:this.findByIndexPath.bind(this)});if(!St){const xt=resolveStrippedPrefabLink(yt);console.warn("[EntityManager] Failed to resolve original entity for stripped entity",{strippedId:bt,prefabInstanceId:xt.prefabInstanceId,prefabEntityId:xt.sourceEntityId});continue}const At=(pt=St.strippedEntity)==null?void 0:pt.id;At&&At!==bt&&this.strippedEntities.delete(At),Et.originalEntity=St,Et.initImmediate()}for(let vt=0,_t=it.length;vt<_t;vt++){const yt=it[vt],bt=yt.strippedId;if(!bt)continue;const Et=this.strippedEntities.get(bt),St=Et==null?void 0:Et.originalEntity;if(!Et||!St)continue;const At=yt.components??[];for(let Ct=0;Ct<At.length;Ct++)try{await Et.addEditorComponent(At[Ct],!1)}catch(Pt){console.warn("[EntityManager] Failed to apply stripped added component",{strippedId:bt,error:Pt})}const xt=st.get(bt)??[];for(let Ct=0;Ct<xt.length;Ct++){const Pt=xt[Ct],Tt=Pt.parent;Pt.parent=St.id;try{const wt=await this.createBySchema(Pt,nt);wt&&!Et.selfChildrenId.includes(wt.id)&&Et.selfChildrenId.push(wt.id)}catch(wt){console.warn("[EntityManager] Failed to create additive entity under prefab original",{strippedId:bt,originalEntityId:St.id,error:wt})}finally{Pt.parent=Tt}}}await this._restoreSidecarAddedEntities(tt,nt,ot);for(const vt of this.entities.values()){const _t=vt.syncRemovedComponentPlaceholdersFromDomain;typeof _t=="function"&&_t.call(vt)}return(mt=this.root.engineProjection)==null||mt.flushDeferredComponentProps(),et}async _restoreSidecarAddedEntities(tt,et,nt){var at,ot,st,ct;if(nt.size===0)return;const it=prepareSidecarAddedEntityRestore({entitiesSchema:tt,addedOverrides:nt,prefabBindings:(ct=(st=(ot=(at=this.root)==null?void 0:at.domainStore)==null?void 0:ot.state)==null?void 0:st.prefab)==null?void 0:ct.bindings,existingEntityIds:new Set(this.entities.keys())});for(const dt of it.missingParents)console.warn("[EntityManager] Failed to restore sidecar added entity: missing prefab source parent",dt);for(const dt of it.plans){const ut=dt.schema.parent;dt.schema.parent=dt.parentSceneEntityId;try{const ht=await this.createBySchema(dt.schema,et);ht&&this.root.prefabFacade.addExistingEntityOverride(dt.bindingId,{entityId:ht.id,parentSourceEntityId:dt.parentSourceEntityId,parentSceneEntityId:dt.parentSceneEntityId,index:dt.index},{persist:!1})}catch(ht){console.warn("[EntityManager] Failed to restore sidecar added entity",{bindingId:dt.bindingId,entityId:dt.entityId,error:ht})}finally{dt.schema.parent=ut}}}revertPrefabSubEntity(tt){var it,at,ot;let et;typeof tt=="string"?et=this.entities.get(tt):et=tt,et.prefabEntityRemoved=!1;const nt=(it=et.parentEntity)==null?void 0:it.id;if(nt){const st=this.root.domainStore.getNormalizedState(),ct=!!st.entities[nt],dt=!!st.entities[et.id];if(ct&&dt)(at=this.root.engineProjection)==null||at.addEntityChild(nt,et.id);else{const ut=(ot=et.parentEntity)==null?void 0:ot.engineObject,ht=et.engineObject;ut&&ht&&ut.addChild(ht)}}this.root.projectStore.debouncedUpdateSceneAsset()}removePrefabSubEntity(tt){var it,at,ot;const et=this.root.domainStore.getNormalizedState();if(et.entities[tt.id]){this.root.prefabFacade.removeSourceEntityForSceneEntity(tt.id);return}tt.prefabEntityRemoved=!0;const nt=(it=tt.parentEntity)==null?void 0:it.id;if(nt){const st=!!et.entities[nt],ct=!!et.entities[tt.id];st&&ct?(at=this.root.engineProjection)==null||at.removeEntityChild(nt,tt.id):(ot=tt.engineObject)!=null&&ot.parent&&tt.engineObject.parent.removeChild(tt.engineObject)}this.root.projectStore.debouncedUpdateSceneAsset()}getUniqIdByEntitySchema(tt,et){const nt=!!tt.strippedId,it=nt?this.strippedEntities:this.entities;return resolveUniqueEntityId({id:et??(nt?tt.strippedId:tt.id),isStripped:nt,localEntityMap:it,domainEntities:{},uuid:v4})}replaceEntity(tt,et,nt){const it=this.entities.get(tt),at=et.transform,ot=it==null?void 0:it.transform;if(at&&ot){const{position:pt,rotation:mt,scale:vt}=at,{position:_t,rotation:yt,scale:bt}=ot;pt.x=_t.x,pt.y=_t.y,pt.z=_t.z,mt.x=yt.x,mt.y=yt.y,mt.z=yt.z,vt.x=bt.x,vt.y=bt.y,vt.z=bt.z}const st=this.root.domainStore.getNormalizedState(),ct=st.entities[tt];((nt==null?void 0:nt.structuralDeltaMode)??(ct!=null&&ct.instance?"domain-source-replace":"legacy-preserve"))==="legacy-preserve"&&(it.getRemovedComponents().forEach(pt=>{et.applyRemovedComponent(pt)}),it.getRemovedEntities().forEach(pt=>{et.applyRemovedEntity(pt)}),it.getAddedEntities().forEach(pt=>{et.applyAddedEntity(pt)}),it.getAddedComponents().forEach(pt=>{et.applyAddedComponent(pt)}));const ut=it.parentEntity;let ht;ut?ht=ut.children.indexOf(it):ht=this.rootEntitiesId.indexOf(it.id);const ft=buildReplaceEntityTreeOps(st,it.id,et.id);if(ft.length>0){this.root.domainStore.applySystem(ft);return}this.removeEntity(it.id),this.addEntityToParent(et,ut==null?void 0:ut.id,ht)}clear(){this.entities.clear(),this._localRootEntityIds=[],this.sceneUIStore.clear()}toJSON(tt=!1){var ut,ht;const et=this._collectOrderedEntities(tt),nt=et.map(ft=>ft.id),it=(ut=this.root)==null?void 0:ut.assetStore,at=ft=>{var pt;return(pt=it==null?void 0:it.getAssetVirtualPath)==null?void 0:pt.call(it,ft)},ot=(ht=this.root)==null?void 0:ht.domainStore,st=ot?ft=>{const pt=ot.getNormalizedState().components[ft];if(pt)return{...pt.refId?{refId:pt.refId}:{},...pt.scriptKey?{scriptKey:pt.scriptKey}:{},...pt.calls?{calls:pt.calls}:{}}}:void 0,ct=new SerializeContext(nt,at,st);return{entities:et.map(ft=>ft.toV2(ct,tt)),components:ct.components}}_collectOrderedEntities(tt){const et=at=>!at.isPrefabSubEntity&&!this._isPrefabAddedEntityTree(at),nt=this.rootEntitiesId.map(at=>this.entities.get(at)).filter(Boolean),it=new Set(nt.map(at=>at.id));return nt.concat(Array.from(this.entities.values()).filter(at=>!it.has(at.id))).filter(et)}_isPrefabAddedEntityTree(tt){const et=new Set;let nt=tt;for(;nt&&!et.has(nt.id);){if(nt.isAddedEntity)return!0;et.add(nt.id),nt=nt.parentEntity}return!1}_triggerSelectedEntity(){this.root.inspectorStore.switchInspector(InspectorType.Entity,this.sceneUIStore.lastSelectedId),this.root.viewportStore.selectEntity(this.selectedEntities)}_triggerUnSelect(){this.root.inspectorStore.switchInspector(InspectorType.Scene,null),this.root.viewportStore.selectEntity(null)}_checkCanCopy(tt){const et=this.entities.get(tt);return et.isPrefabSubEntity||et.isGLTFRefEntity?(showEditorUiToastError("Cannot copy prefab sub entity or glTF entity"),!1):!0}_registerEntityRuntimeBinder(tt){this.root.runtimeBinderRegistry.ensureEntityBinder(tt.id).attachRuntimeHost({getFocusTarget:()=>{const nt=tt.engineObject;return nt&&!nt.destroyed?nt:null},alignToCamera:({cameraTransform:nt,fieldOfView:it})=>{var ot,st;if(!tt.hasCameraComponent||!nt)return;(st=(ot=tt.transform)==null?void 0:ot.syncTransformToEditor)==null||st.call(ot,nt);const at=tt.getComponentByTypeName("Camera");!(at!=null&&at.id)||it==null||this.root.componentFacade.updateComponent(tt.id,at.id,{fieldOfView:it})},applyToPrefab:(nt,it)=>tt.applyToPrefab(nt,it),revertPrefab:(nt,it)=>tt.revertPrefab(nt,it),unpackPrefab:()=>tt.unpackPrefab()})}createByEngineObject(tt,et){var at;const nt=this.createEntity(tt.name,et);nt.initByEngineObject(tt);const it=tt._templateResource;return it&&it!==((at=tt==null?void 0:tt.parent)==null?void 0:at._templateResource)&&nt.root.assetStore.engineObjectToAssetMap.get(it).addInstance(nt),nt}async createBySchema(tt,et){return this._checkIsAssetRef(tt)?this._createEntityByTemplateAsset(tt,et):this._createNormalEntityBySchema(tt,et)}async _createNormalEntityBySchema(tt,et,nt){nt=this.getUniqIdByEntitySchema(tt,nt);const it=!!tt.strippedId,at=new EntityModel(this,nt);this._registerEntityRuntimeBinder(at),this.createEntityInStore(nt,tt,it,at);const ot=tt.children??[],st=[];for(let dt=0,ut=ot.length;dt<ut;dt++){const ht=et.get(ot[dt]);ht&&(ht.parent=nt,st.push(this.createBySchema(ht,et)))}const ct=await Promise.all(st);return this.connectChildEntities(at,ct),tt.children=ct.map(dt=>dt.id),at.initBySchema(tt),it?(tt.strippedId=at.id,this.strippedEntities.set(nt,at)):(tt.id=at.id,this.entities.set(nt,at)),at.initImmediate(),at}async _createEntityByTemplateAsset(tt,et){var ot;const nt=resolveEntitySchemaInstanceAssetId(tt),it=nt?await this.root.assetStore.getAssetByRef({refId:nt}):null;let at;if(it){const ct=this===this.root.sceneStore&&hasPersistedBinding(this.root.domainStore,tt.id)?tt.id:null;ct&&clearPersistedEntityForReload(this.root.domainStore,ct);let dt,ut;if(ct){const ft=this.root.domainStore.getNormalizedState(),pt={assetId:resolveEntitySchemaInstanceAssetId(tt),assetKind:(ot=tt.instance)==null?void 0:ot.assetKind};ut=findNormalizedPrefabBindingByInstanceRootEntityId(ft,ct,pt);const mt=getNormalizedRootEntityOverride(ft,ct,pt);dt=mt==null?void 0:mt.transform}at=ct?await it.instantiate(this,dt,{expectedRootId:ct,expectedBindingId:ut==null?void 0:ut.id}):await it.instantiate(this),it.getMetaConfig().type==="glTF"&&(at!=null&&at.isGLTFWrapEntity)&&console.warn("[EntityManager] unexpected glTF wrapper entity from asset instantiate",{instanceAssetId:nt,wrapEntityId:at.id}),this.onTemplateEntityCreated(at,tt),at.name=tt.name,at.applyStructuralDeltasBySchema(tt),tt.assetTemplateDiffs&&(applyAssetTemplateDiffs(at,tt.assetTemplateDiffs),at.assetTemplateDiffs=tt.assetTemplateDiffs,syncAssetTemplateDiffsToDomain(this.root.domainStore,at,tt.assetTemplateDiffs)),ut&&applyBindingOverridesOnReload(this.root.domainStore,at,ut)}else console.error(`can't find instance asset id ${nt}`),at=await this._createNormalEntityBySchema(tt,et);return tt.id=at.id,at.initImmediate(),at}_checkIsAssetRef(tt){return hasEntitySchemaInstanceLink(tt)}getNextSibling(tt){if(!tt)return null;const et=tt.id;if(this.sceneUIStore.isEntityExpanded(tt.id)&&tt.children.length>0)return tt.children[0].id;const nt=tt.parentEntity;if(!nt){const ot=this.rootEntitiesId.findIndex(st=>st===et);return ot<this.rootEntitiesId.length-1?this.rootEntitiesId[ot+1]:null}const it=nt.children,at=it.findIndex(ot=>ot.id===et);if(at<it.length-1)return it[at+1].id;{let ot=tt.parentEntity,st=tt;for(;ot;){const dt=ot.children.findIndex(ut=>ut.id===st.id);if(dt<ot.children.length-1)return ot.children[dt+1].id;st=ot,ot=ot.parentEntity}const ct=this.rootEntitiesId.findIndex(dt=>dt===st.id);return ct<this.rootEntitiesId.length-1?this.rootEntitiesId[ct+1]:null}}getPreviousSibling(tt){if(!tt)return null;const et=tt.id;if(et===DEFAULT_SCENE)return null;const nt=tt.parentEntity;if(!nt){const ot=this.rootEntities.findIndex(st=>st.id===et);if(ot>0){let st=this.rootEntities[ot-1];for(;st.children.length>0&&this.sceneUIStore.isEntityExpanded(st.id);)st=st.children[st.children.length-1];return st.id}return ot===0?DEFAULT_SCENE:null}const it=nt.children.findIndex(ot=>ot===tt);if(it===0)return nt.id;let at=nt.children[it-1];for(;this.sceneUIStore.isEntityExpanded(at.id)&&at.children.length>0;)at=at.children[at.children.length-1];return at.id}findChildByName(tt,et){const nt=tt.children;for(let it=0,at=nt.length;it<at;it++){const ot=nt[it];if(et===ot.name)return ot}return null}findByPath(tt,et){const nt=et.split("/");let it=tt;for(let at=0,ot=nt.length;at<ot;++at){const st=nt[at];if(st&&(it=this.findChildByName(it,st),!it))return null}return it}findByIndexPath(tt,et){const nt=et.split("/");let it=tt;for(let at=0,ot=nt.length;at<ot;++at){const st=nt[at];if(st&&(it=it.children[parseInt(st)]),!it)return null}return it}getNodePath(tt){let et=tt.parent,nt=tt.id;const it=[],at=this.entities;for(;et&&et!==DEFAULT_SCENE;){const ot=at.get(et);it.unshift(ot.childrenId.indexOf(nt)),et=ot.parent,nt=ot.id}return it.unshift(this.rootEntitiesId.indexOf(nt)),it}}__decorateClass$3([observable],EntityManager.prototype,"entities",2);__decorateClass$3([observable],EntityManager.prototype,"strippedEntities",2);__decorateClass$3([action],EntityManager.prototype,"setLocalRootEntityIds",1);__decorateClass$3([computed],EntityManager.prototype,"selectedEntities",1);__decorateClass$3([computed],EntityManager.prototype,"lastSelectedEntity",1);__decorateClass$3([action],EntityManager.prototype,"hydrateDomainEntityModelsFromState",1);__decorateClass$3([action],EntityManager.prototype,"createEntity",1);__decorateClass$3([action],EntityManager.prototype,"setEntityModel",1);__decorateClass$3([action],EntityManager.prototype,"deleteEntityModel",1);__decorateClass$3([action],EntityManager.prototype,"addEntityToParent",1);__decorateClass$3([action],EntityManager.prototype,"addEntityByTemplate",1);__decorateClass$3([action],EntityManager.prototype,"createStrippedEntity",1);__decorateClass$3([action],EntityManager.prototype,"selectEntity",2);__decorateClass$3([action],EntityManager.prototype,"selectEntityByRange",2);__decorateClass$3([action],EntityManager.prototype,"expandEntity",2);__decorateClass$3([action],EntityManager.prototype,"collapseEntity",2);__decorateClass$3([action],EntityManager.prototype,"rename",1);__decorateClass$3([action],EntityManager.prototype,"setSearchText",2);__decorateClass$3([action],EntityManager.prototype,"setEntityVisible",1);__decorateClass$3([action],EntityManager.prototype,"setEntityLocked",1);__decorateClass$3([action],EntityManager.prototype,"removeEntity",2);__decorateClass$3([action],EntityManager.prototype,"removeSingleEntity",2);__decorateClass$3([action],EntityManager.prototype,"isChildNode",2);__decorateClass$3([action],EntityManager.prototype,"deserializeEntities",1);__decorateClass$3([action],EntityManager.prototype,"revertPrefabSubEntity",1);__decorateClass$3([action],EntityManager.prototype,"removePrefabSubEntity",1);__decorateClass$3([action],EntityManager.prototype,"clear",1);__decorateClass$3([action],EntityManager.prototype,"setHoveredEntity",2);function maybeMoveInstantiatedAssetEntity(rt){const{entityId:_e,targetParentId:tt,defaultSceneId:et,domainEntities:nt,moveEntity:it}=rt;if(!tt||tt===et)return;const at=!!nt[_e],ot=!!nt[tt];!at||!ot||it(_e,tt)}var __defProp$3=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$2(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$3(_e,tt,nt),nt};const log$1=logger$2("Scene"),SOURCE_SPECULAR_MODE_SKY=0,SOURCE_SPECULAR_MODE_CUSTOM=1;function readLoadedPrefabSourceFile(rt){const _e=rt==null?void 0:rt.prefabFile;if(!(!_e||typeof _e!="object")&&Array.isArray(_e.entities)&&Array.isArray(_e.components))return _e}class EditorScene extends EntityManager{constructor(tt){super(tt);Rt(this,"refId");Rt(this,"isBaking",!1);Rt(this,"_bakePromise",null);Rt(this,"_gate",new LifecycleGate);Rt(this,"ambientLight",null);Rt(this,"customAmbientLight",null);Rt(this,"diffuseMode",DiffuseMode.SphericalHarmonics);Rt(this,"diffuseSolidColor",{r:.03696758874771872,g:.0421494543549785,b:.05455383078270364,a:1,intensity:1});Rt(this,"diffuseIntensity",1);Rt(this,"specularMode",SOURCE_SPECULAR_MODE_SKY);Rt(this,"customSpecularTexture",null);Rt(this,"specularIntensity",1);Rt(this,"backgroundMode",BackgroundMode.SolidColor);Rt(this,"backgroundColor",{r:.05087608817155679,g:.05087608817155679,b:.05087608817155679,a:1});Rt(this,"backgroundTexture",null);Rt(this,"textureFillMode",BackgroundTextureFillMode.AspectFitHeight);Rt(this,"skyMaterial",null);Rt(this,"skyMesh",null);Rt(this,"castShadows",!0);Rt(this,"enableTransparentShadow",!1);Rt(this,"shadowResolution",ShadowResolution.Medium);Rt(this,"shadowCascades",ShadowCascadesMode.NoCascades);Rt(this,"shadowTwoCascadeSplits",1/3);Rt(this,"shadowFourCascadeSplits",{x:1/15,y:3/15,z:7/15});Rt(this,"shadowDistance",50);Rt(this,"shadowFadeBorder",.1);Rt(this,"fogMode",FogMode.None);Rt(this,"fogColor",{r:.21404114048223255,g:.21404114048223255,b:.21404114048223255,a:1});Rt(this,"fogStart",0);Rt(this,"fogEnd",300);Rt(this,"fogDensity",.01);Rt(this,"autoBake",!0);Rt(this,"bakerResolution",BakerResolution.R128);Rt(this,"bakeButton",null);Rt(this,"enabledAmbientOcclusion",!1);Rt(this,"quality",AmbientOcclusionQuality.Low);Rt(this,"intensity",1);Rt(this,"power",1);Rt(this,"radius",.3);Rt(this,"bilateralThreshold",.05);Rt(this,"bias",5e-4);Rt(this,"minHorizonAngle",0);Rt(this,"_originalSpecularTexture");Rt(this,"_customSpecularTexture");Rt(this,"_customBakedSpecularTexture");Rt(this,"_lastSkyMaterialRefId");Rt(this,"_initComplete",!1);Rt(this,"_autoBake",async(tt,et)=>{this._initComplete&&this.autoBake&&(et!=null&&et.refId?(await this.root.assetStore.getAssetByRef(et),this.onBake()):this.onBake())});Rt(this,"onBake",debounce$2(()=>this.bake(),500,{edges:["trailing"]}));window.editorSceneObject=this.engineSceneObject,makeObservable(this)}get isDomainScoped(){return!0}get status(){return this._gate.status}get error(){return this._gate.error}onReady(){return this._gate.onReady()}ensureReady(){return this._gate.ensureReady()}get initComplete(){return this._initComplete}get removable(){const tt=this.sceneUIStore.selectedKeys;if(tt.has(DEFAULT_SCENE))return!1;for(const et of tt){const nt=this.entities.get(et);if(nt&&!nt.prefabEntityRemoved)return!0}return!1}get rootEntitiesId(){return this.root.readModelStore.scene.rootEntityIds}getChildrenIds(tt){if(tt.isStrippedEntity)return tt.selfChildrenId.filter(Boolean);const et=this.root.readModelStore.getEntityChildren(tt.id).filter(Boolean);if(!tt.strippedEntity)return et;const nt=tt.strippedEntity.selfChildrenId.filter(Boolean);if(!nt.length)return et;const it=new Set(nt),at=et.filter(ct=>!it.has(ct)),ot=new Set,st=nt.filter(ct=>ot.has(ct)?!1:(ot.add(ct),!0));return at.concat(st)}getParentId(tt){return this.root.readModelStore.getEntityParent(tt.id)}createEntityInStore(tt,et,nt,it){var ot;if(nt)return;this.root.domainStore.beginBatch();try{const st=et.parent,ct=(ot=et.transform)==null?void 0:ot.props;this.root.entityFacade.createEntity({id:tt,name:et.name??"Entity",parentId:st&&st!==DEFAULT_SCENE?st:null,isActive:et.isActive??!0,transform:ct?{position:ct.position,rotation:ct.rotation,scale:ct.scale}:void 0,layer:et.layer})}finally{this.root.domainStore.commitBatch("entity.create")}const at=this.root.engineProjection.getEntity(tt);if(!at)throw this.root.entityFacade.deleteEntity(tt),new Error(`EngineProjection failed to create engine entity for "${tt}" after commitBatch.`);it.bindEngineObject(at)}connectChildEntities(){}onTemplateEntityCreated(tt,et){this.registerEntityTreeInDomain(tt,et.parent),maybeMoveInstantiatedAssetEntity({entityId:tt.id,targetParentId:et.parent,defaultSceneId:DEFAULT_SCENE,domainEntities:this.root.domainStore.state.entities,moveEntity:(nt,it)=>this.root.entityFacade.moveEntity(nt,it)})}getUniqIdByEntitySchema(tt,et){const nt=!!tt.strippedId,it=nt?this.strippedEntities:this.entities;return resolveUniqueEntityId({id:et??(nt?tt.strippedId:tt.id),isStripped:nt,localEntityMap:it,domainEntities:this.root.domainStore.state.entities,uuid:v4})}async ensureSourceInstancePrefabFilesLoaded(tt){const et=new Set,nt=tt.entities.map(it=>{var at,ot;return(ot=(at=it.instance)==null?void 0:at.asset)==null?void 0:ot.$ref}).filter(it=>typeof it=="string");await Promise.all(nt.map(async it=>{var st,ct,dt,ut;const at=(ct=(st=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ct.call(st,it);if(((ut=(dt=at==null?void 0:at.getMetaConfig)==null?void 0:dt.call(at))==null?void 0:ut.type)==="Prefab"){if(!at)throw new Error(`Source instance "${it}" references a Prefab asset, but the asset is not available`);if(!at.prefabFile&&typeof at.loadMainFile!="function")throw new Error(`Source instance "${it}" references a Prefab asset, but its source file cannot be loaded`);if(at.prefabFile||await at.loadMainFile(),!at.prefabFile)throw new Error(`Source instance "${it}" Prefab source file is unavailable after load`);await this.ensurePrefabSourceInstanceAssetsLoaded(at.prefabFile,it,et)}}))}async ensurePrefabSourceInstanceAssetsLoaded(tt,et,nt){var it,at,ot,st,ct,dt;for(const ut of tt.entities??[]){const ht=(at=(it=ut.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!ht)continue;const ft=(st=(ot=this.root.assetStore).getAssetByVirtualPath)==null?void 0:st.call(ot,ht),pt=ft==null?void 0:ft.id;if(!ft||!pt)throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but the asset is not available`);const mt=(dt=(ct=ft.getMetaConfig)==null?void 0:ct.call(ft))==null?void 0:dt.type;if(mt!=="Prefab"&&mt!=="glTF")throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but asset "${pt}" is type "${mt}"`);if(!nt.has(pt)){if(nt.add(pt),!ft.prefabFile){if(typeof ft.loadMainFile!="function")throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but asset "${pt}" cannot be loaded`);await ft.loadMainFile()}if(mt==="Prefab"){if(!ft.prefabFile)throw new Error(`Prefab binding "${et}" source references nested Prefab "${ht}", but its source file is unavailable after load`);await this.ensurePrefabSourceInstanceAssetsLoaded(ft.prefabFile,et,nt)}}}}registerExternalEntityTree(tt){const et=this.root.engineProjection,nt=tt.engineObject;et&&nt&&et.registerExternalEntity(tt.id,nt);for(const it of tt.selfChildren)this.registerExternalEntityTree(it)}async instantiateGLTFBindingEngineObjects(tt){if(this.root.engineProjection)for(const nt of Object.values(tt.prefab.bindings)){if(nt.assetKind!=="glTF")continue;const it=tt.entities[nt.instanceRootEntityId];if(!it)throw new Error(`glTF binding "${nt.id}" references missing instance root "${nt.instanceRootEntityId}"`);const at=this.root.assetStore.assets[nt.assetId];if(!at)throw new Error(`glTF binding "${nt.id}" references unavailable asset "${nt.assetId}"`);if(typeof at.loadMainFile=="function"&&await at.loadMainFile(),typeof at.instantiate!="function")throw new Error(`glTF binding "${nt.id}" asset "${nt.assetId}" cannot be instantiated`);const ot=await at.instantiate(this,it.transform,{expectedRootId:nt.instanceRootEntityId,expectedBindingId:nt.id});await ot.ensureReady(),this.registerExternalEntityTree(ot);for(const st of Object.values(nt.sourceToSceneEntity))if(tt.entities[st]&&!this.entities.has(st))throw new Error(`glTF binding "${nt.id}" asset "${nt.assetId}" did not instantiate expected scene entity "${st}"`)}}async init(tt){const et=parseSourceV2SceneFileJson(tt.getMainData());await this.ensureSourceInstancePrefabFilesLoaded(et);const nt=ot=>{var st,ct;return(ct=(st=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ct.call(st,ot)},it=createSourceRefCodec({resolveSourceRef:ot=>{var st;return(st=nt(ot))==null?void 0:st.id},resolveAssetKind:ot=>{var ct,dt,ut;const st=(ut=(dt=(ct=nt(ot))==null?void 0:ct.getMetaConfig)==null?void 0:dt.call(ct))==null?void 0:ut.type;return st==="Prefab"||st==="glTF"?st:void 0}}),at=hydrateSourceV2SceneToDomain(et,{resolveSourceRef:ot=>it.sourceToDomain(ot,`loading scene "${tt.id}"`),resolveAssetKind:ot=>it.maybeResolveAssetKind(ot),resolvePrefabSourceFile:ot=>readLoadedPrefabSourceFile(this.root.assetStore.assets[ot])});return await this.instantiateGLTFBindingEngineObjects(at),this.root.domainStore.reset({...this.root.domainStore.state,scene:at.scene,entities:at.entities,prefab:at.prefab}),this.hydrateDomainEntityModelsFromState(),this.refId=tt.id,await this.setupInspector(et),et}async setupInspector(tt){const et=this.formSchema;et.addGroup("scene.ambient-light.diffuse.title",["diffuseMode","diffuseSolidColor","diffuseIntensity"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.specular.title",["specularMode","customSpecularTexture","specularIntensity"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.bake.title",["autoBake","bakerResolution","bakeButton"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.title",["scene.ambient-light.diffuse.title","scene.ambient-light.specular.title","scene.ambient-light.bake.title"]),et.addGroup("scene.ambientOcclusion.title",["enabledAmbientOcclusion","quality","intensity","power","radius","bias","bilateralThreshold","minHorizonAngle"]),et.addGroup("scene.background.title",["backgroundMode","backgroundColor","backgroundTexture","skyMaterial","skyMesh","textureFillMode"]),et.addGroup("scene.shadow.title",["castShadows","enableTransparentShadow","shadowResolution","shadowCascades","shadowTwoCascadeSplits","shadowFourCascadeSplits","shadowDistance","shadowFadeBorder"]),et.addGroup("scene.fog.title",["fogMode","fogColor","fogStart","fogEnd","fogDensity"]),this.deserialize(tt),await this._gate.hydrate(async()=>{if(this.engineObject===this.engineSceneObject){await this.replayAllPropertyChange(!1);return}await this.bindEngineObject(this.engineSceneObject)})}deserialize(tt){const et=getSerializeConfigs(this),nt=sourceSceneSettingsToEditorSettings(tt.scene??{},at=>{var ot,st,ct;return(ct=(st=(ot=this.root.assetStore).getAssetByVirtualPath)==null?void 0:st.call(ot,at))==null?void 0:ct.id}),it={...tt,scene:nt};Object.keys(et).forEach(at=>{const ot=et[at],st=ot.key??at,ct=get$3(it,st);if(ct!==void 0){const dt=ot.onDeserialize?ot.onDeserialize(ct):ct;this[at]=dt}})}getDomainSettingPath(tt){if(tt.includes("/"))return normalizeSceneSettingPath(tt);const et=buildSceneSettingBindings(getSerializeConfigs(this)),nt=getSceneSettingPathByProperty(et,tt);if(!nt)throw new Error(`EditorScene.getDomainSettingPath: unknown scene setting property: ${tt}`);return nt}commitSceneSettingToDomain(tt,et){const nt=this.root.sceneFacade;if(!(nt!=null&&nt.updateSetting))throw new Error("EditorScene.commitSceneSettingToDomain requires root.sceneFacade.updateSetting");const it=this.getDomainSettingPath(tt);nt.updateSetting(it,et)}onInitComplete(){this._initComplete=!0}sync(){}toJSON(tt=!1){var ht;const{entities:et,components:nt}=super.toJSON(tt),it=getSerializeConfigs(this),at={};Object.keys(it).forEach(ft=>{const pt=it[ft],mt=pt.key??ft;let vt=toJS(this[ft]);pt.onSerialize&&(vt=pt.onSerialize(vt)),set$1(at,mt,vt)});const ot=editorSceneSettingsToSourceSettings(at.scene??{},ft=>{var pt,mt;return(mt=(pt=this.root.assetStore).getAssetVirtualPath)==null?void 0:mt.call(pt,ft)}),st=(ht=this.root.assetStore.assets[this.refId])==null?void 0:ht.name,ct=this.rootEntities.map(ft=>ft.id),dt={...st?{name:st}:{},rootEntities:ct,...ot};return{asset:{version:"2.0",generator:"Galacean Editor"},scene:dt,entities:et,components:nt}}destroy(){var tt;if(!this._destroyed){this._gate.dispose(),super.destroy();for(const et of this.entities.values())et.destroy();(tt=this.engineObject)==null||tt.destroy(),this.sceneUIStore.setLastSelectedId(null),this.engine=null,this._lastSkyMaterialRefId&&this.root.assetStore.getAssetByRef({refId:this._lastSkyMaterialRefId}).then(et=>{et&&et.removeListener("propertychange",this._autoBake),this._lastSkyMaterialRefId=null})}}async bake(){if(this._bakePromise)return this._bakePromise;const tt=(async()=>{log$1.info("bake"),this.isBaking=!0;try{const et="ambient",nt="custom_ambient",it=this.root.assetStore,at=this.root.assetFacade,ot=await it.createFolder(["Bake"]),st=this.specularMode===SOURCE_SPECULAR_MODE_CUSTOM&&this._customSpecularTexture,ct=[await findReusableBakedAmbientAsset(this,ot,et)].concat(st?await findReusableBakedAmbientAsset(this,ot,nt):[]),[dt,ut]=await Promise.all(ct.map(async(ht,ft)=>(ht?(await ht.loadMainFile(),ft===0?await ht.bakeFromScene(this.engine):await ht.bakeFromTexture(this._customSpecularTexture),ht.updateThumbnail(),await at.persistAssetMainImmediate(ht.id)):ft===0?ht=await at.createAssetByAdd({assetType:"AmbientLight",name:et,parentFolderId:ot,params:{from:"Scene"}}):ht=await at.createAssetByAdd({assetType:"AmbientLight",name:nt,parentFolderId:ot,params:{from:"Texture",srcTexture:this._customSpecularTexture}}),ht)));this.commitSceneSettingToDomain("ambientLight",dt.getCurrentRef()),ut&&this.commitSceneSettingToDomain("customAmbientLight",ut.getCurrentRef())}finally{this.isBaking=!1}})();this._bakePromise=tt;try{await tt}finally{this._bakePromise===tt&&(this._bakePromise=null)}}applySettingFromDomain(tt,et){const nt=buildSceneSettingBindings(getSerializeConfigs(this)),it=getSceneSettingPropertyByPath(nt,tt);if(!it)throw new Error(`EditorScene.applySettingFromDomain: unknown scene setting path: ${tt}`);if(!(it in this))throw new Error(`EditorScene.applySettingFromDomain: missing scene setting property "${it}" for path: ${tt}`);this[it]=et,this.triggerPropertyChange(it,!1)}}__decorateClass$2([observable],EditorScene.prototype,"isBaking",2);__decorateClass$2([observable,serialize({key:"scene.ambient.ambientLight"}),propertyField({type:ComponentType.AssetPicker,assetType:"AmbientLight",when:rt=>!1,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et&&(rt._originalSpecularTexture=et.specularTexture,rt.engineObject.ambientLight.diffuseSphericalHarmonics=et.diffuseSphericalHarmonics),rt.triggerPropertyChange("specularMode",!1)}})],EditorScene.prototype,"ambientLight",2);__decorateClass$2([observable,serialize({key:"scene.ambient.customAmbientLight"}),propertyField({type:ComponentType.AssetPicker,assetType:"AmbientLight",when:rt=>!1,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et?rt._customBakedSpecularTexture=et.specularTexture:rt._customBakedSpecularTexture=null,rt.triggerPropertyChange("specularMode",!1)}})],EditorScene.prototype,"customAmbientLight",2);__decorateClass$2([observable,serialize({key:"scene.ambient.diffuseMode"}),propertyField({label:"scene.ambient-light.diffuse.source",info:"scene.ambient-light.diffuse.source-info",type:ComponentType.Select,bindPath:"ambientLight.diffuseMode",options:[{label:"scene.ambient-light.diffuse.source-background",value:DiffuseMode.SphericalHarmonics},{label:"scene.ambient-light.diffuse.source-solid-color",value:DiffuseMode.SolidColor}]})],EditorScene.prototype,"diffuseMode",2);__decorateClass$2([observable,serialize(hdrColorSerializer({key:"scene.ambient.diffuseSolidColor"})),propertyField({type:ComponentType.Color,mode:"hdr",label:"scene.ambient-light.diffuse.solid-color",info:"scene.ambient-light.diffuse.solid-color-info",when:rt=>rt.diffuseMode===DiffuseMode.SolidColor,onChange(rt,_e,tt){rt.engineObject.ambientLight.diffuseSolidColor.copyFrom(serializeHDRColor(tt))}})],EditorScene.prototype,"diffuseSolidColor",2);__decorateClass$2([observable,serialize({key:"scene.ambient.diffuseIntensity"}),propertyField({type:ComponentType.Slider,label:"scene.ambient-light.diffuse.intensity",info:"scene.ambient-light.diffuse.intensity-info",bindPath:"ambientLight.diffuseIntensity",min:0,max:5,dragStep:.1})],EditorScene.prototype,"diffuseIntensity",2);__decorateClass$2([observable,serialize({key:"scene.ambient.specularMode"}),propertyField({label:"scene.ambient-light.specular.source",info:"scene.ambient-light.specular.source-info",type:ComponentType.Select,options:[{label:"scene.ambient-light.specular.source-background",value:SOURCE_SPECULAR_MODE_SKY},{label:"scene.ambient-light.specular.source-custom",value:SOURCE_SPECULAR_MODE_CUSTOM}],onChange:(rt,_e,tt)=>{tt===SOURCE_SPECULAR_MODE_SKY?rt.engineObject.ambientLight.specularTexture=rt._originalSpecularTexture:rt.engineObject.ambientLight.specularTexture=rt._customBakedSpecularTexture}})],EditorScene.prototype,"specularMode",2);__decorateClass$2([observable,serialize({key:"scene.ambient.customSpecularTexture"}),propertyField({label:"scene.ambient-light.specular.custom-texture",info:"scene.ambient-light.specular.custom-texture-info",type:ComponentType.AssetPicker,assetType:"Texture",customFilter:rt=>rt.shape==="Cube",when:rt=>rt.specularMode===SOURCE_SPECULAR_MODE_CUSTOM,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et?(rt._customSpecularTexture=et,rt._autoBake()):rt._customSpecularTexture=null}})],EditorScene.prototype,"customSpecularTexture",2);__decorateClass$2([observable,serialize({key:"scene.ambient.specularIntensity"}),propertyField({type:ComponentType.Slider,label:"scene.ambient-light.specular.intensity",info:"scene.ambient-light.specular.intensity-info",bindPath:"ambientLight.specularIntensity",min:0,max:5,dragStep:.1})],EditorScene.prototype,"specularIntensity",2);__decorateClass$2([observable,serialize({key:"scene.background.mode"}),propertyField({label:"scene.background.mode.title",info:"Class:Background.mode",type:ComponentType.Select,options:transformEnumToOptions(BackgroundMode,void 0,rt=>t$7(`scene.background.mode.${rt.toLowerCase()}`)),onChange(rt,_e,tt){rt.engineObject.background.mode=tt,rt._autoBake()}})],EditorScene.prototype,"backgroundMode",2);__decorateClass$2([observable,serialize({key:"scene.background.color"}),propertyField({label:"scene.background.color.title",info:"scene.background.color.info",type:ComponentType.Color,bindPath:"background.solidColor",when:rt=>rt.backgroundMode===BackgroundMode.SolidColor,onChange(rt){rt._autoBake()}})],EditorScene.prototype,"backgroundColor",2);__decorateClass$2([observable,serialize({key:"scene.background.texture"}),propertyField({label:"scene.background.texture.title",info:"scene.background.texture.info",type:ComponentType.AssetPicker,assetType:"Texture",bindPath:"background.texture",when:rt=>rt.backgroundMode===BackgroundMode.Texture,onChange:async rt=>{rt._autoBake()}})],EditorScene.prototype,"backgroundTexture",2);__decorateClass$2([observable,serialize({key:"scene.background.textureFillMode"}),propertyField({label:"scene.background.texture-fill-mode.title",info:"scene.background.texture-fill-mode.info",type:ComponentType.Select,options:transformEnumToOptions(BackgroundTextureFillMode,void 0,rt=>t$7(`scene.background.texture-fill-mode.${rt.toLowerCase()}`)),when:rt=>rt.backgroundMode===BackgroundMode.Texture,onChange(rt,_e,tt){rt.engineObject.background.textureFillMode=tt,rt._autoBake()}})],EditorScene.prototype,"textureFillMode",2);__decorateClass$2([observable,serialize({key:"scene.background.skyMaterial"}),propertyField({label:"scene.sky.material.title",info:"scene.sky.material.info",type:ComponentType.AssetPicker,assetType:"Material",when:rt=>rt.backgroundMode===BackgroundMode.Sky,onChange:async(rt,_e,tt)=>{const et=rt.engineObject.background.sky;if(rt._lastSkyMaterialRefId){const nt=await rt.root.assetStore.getAssetByRef({refId:rt._lastSkyMaterialRefId});nt&&nt.removeListener("propertychange",rt._autoBake),rt._lastSkyMaterialRefId=null}tt?(rt._lastSkyMaterialRefId=tt.id,et.material=tt.engineObject,tt.on("propertychange",rt._autoBake)):et.material=null,rt._autoBake()}})],EditorScene.prototype,"skyMaterial",2);__decorateClass$2([observable,serialize({key:"scene.background.skyMesh"}),propertyField({label:"scene.sky.mesh.title",info:"scene.sky.mesh.info",type:ComponentType.AssetPicker,assetType:["Mesh","PrimitiveMesh"],when:rt=>rt.backgroundMode===BackgroundMode.Sky,onChange:async(rt,_e,tt)=>{const et=rt.engineObject.background.sky,nt=tt==null?void 0:tt.engineObject;nt?et.mesh=nt:et.mesh=null}})],EditorScene.prototype,"skyMesh",2);__decorateClass$2([observable,serialize({key:"scene.shadow.castShadows"}),propertyField({label:"scene.shadow.cast-shadows.title",info:"scene.shadow.cast-shadows.info",type:ComponentType.Toggle,bindPath:"castShadows"})],EditorScene.prototype,"castShadows",2);__decorateClass$2([observable,serialize({key:"scene.shadow.enableTransparentShadow"}),propertyField({label:"scene.shadow.enable-transparent.title",info:"scene.shadow.enable-transparent.info",type:ComponentType.Toggle,bindPath:"enableTransparentShadow",when:rt=>rt.castShadows})],EditorScene.prototype,"enableTransparentShadow",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowResolution"}),propertyField({label:"scene.shadow.resolution.title",info:"scene.shadow.resolution.info",type:ComponentType.Select,options:transformEnumToOptions(ShadowResolution,void 0,rt=>t$7(`scene.shadow.resolution.${rt.toLowerCase()}`)),bindPath:"shadowResolution",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowResolution",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowCascades"}),propertyField({label:"scene.shadow.cascades.title",info:"scene.shadow.cascades.info",type:ComponentType.Select,options:transformEnumToOptions(ShadowCascadesMode,void 0,rt=>t$7(`scene.shadow.cascades.${rt.toLowerCase()}`)),bindPath:"shadowCascades",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowCascades",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowTwoCascadeSplits"}),propertyField({label:"scene.shadow.two-cascade-splits.title",info:"scene.shadow.two-cascade-splits.info",when:rt=>rt.castShadows&&rt.shadowCascades===ShadowCascadesMode.TwoCascades,customComponent:CustomTwoCascadeSlider,onChange(rt,_e,tt){rt.engineObject.shadowTwoCascadeSplits=tt}})],EditorScene.prototype,"shadowTwoCascadeSplits",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowFourCascadeSplits"}),propertyField({label:"scene.shadow.four-cascade-splits.title",info:"scene.shadow.four-cascade-splits.info",when:rt=>rt.castShadows&&rt.shadowCascades===ShadowCascadesMode.FourCascades,customComponent:CustomFourCascadeSlider,onChange(rt,_e,tt){rt.engineObject.shadowFourCascadeSplits.copyFrom(tt)}})],EditorScene.prototype,"shadowFourCascadeSplits",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowDistance"}),propertyField({label:"scene.shadow.distance.title",info:"scene.shadow.distance.info",type:ComponentType.Number,bindPath:"shadowDistance",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowDistance",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowFadeBorder"}),propertyField({label:"scene.shadow.fade-border.title",info:"scene.shadow.fade-border.info",type:ComponentType.Slider,min:0,max:1,dragStep:.01,bindPath:"shadowFadeBorder",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowFadeBorder",2);__decorateClass$2([observable,serialize({key:"scene.fog.mode"}),propertyField({label:"scene.fog.mode.title",info:"scene.fog.mode.info",type:ComponentType.Select,options:transformEnumToOptions(FogMode,void 0,rt=>t$7(`scene.fog.mode.${rt.toLowerCase()}`)),bindPath:"fogMode"})],EditorScene.prototype,"fogMode",2);__decorateClass$2([observable,serialize({key:"scene.fog.color"}),propertyField({label:"scene.fog.color.title",info:"scene.fog.color.info",type:ComponentType.Color,bindPath:"fogColor",when:rt=>rt.fogMode!==FogMode.None})],EditorScene.prototype,"fogColor",2);__decorateClass$2([observable,serialize({key:"scene.fog.start"}),propertyField({label:"scene.fog.start.title",info:"scene.fog.start.info",type:ComponentType.Number,bindPath:"fogStart",when:rt=>rt.fogMode===FogMode.Linear})],EditorScene.prototype,"fogStart",2);__decorateClass$2([observable,serialize({key:"scene.fog.end"}),propertyField({label:"scene.fog.end.title",info:"scene.fog.end.info",type:ComponentType.Number,bindPath:"fogEnd",when:rt=>rt.fogMode===FogMode.Linear})],EditorScene.prototype,"fogEnd",2);__decorateClass$2([observable,serialize({key:"scene.fog.density"}),propertyField({label:"scene.fog.density.title",info:"scene.fog.density.info",type:ComponentType.Number,bindPath:"fogDensity",dragStep:.001,when:rt=>rt.fogMode===FogMode.Exponential||rt.fogMode===FogMode.ExponentialSquared})],EditorScene.prototype,"fogDensity",2);__decorateClass$2([observable,serialize({key:"scene.autoBake"}),propertyField({label:"scene.ambient-light.bake.auto.title",info:"scene.ambient-light.bake.auto.info",type:ComponentType.Toggle,onChange(rt,_e,tt){tt&&rt._initComplete&&rt.bake()}})],EditorScene.prototype,"autoBake",2);__decorateClass$2([observable,serialize({key:"scene.ambient.bakerResolution"}),propertyField({label:"scene.ambient-light.bake.resolution.title",info:"scene.ambient-light.bake.resolution.info",type:ComponentType.Select,options:transformEnumToOptions(BakerResolution,void 0,rt=>t$7(`scene.ambient-light.bake.resolution.${rt.toLowerCase()}`)),onChange(rt){rt._autoBake()}})],EditorScene.prototype,"bakerResolution",2);__decorateClass$2([observable,propertyField({info:"scene.ambient-light.bake.button.info",when:rt=>!rt.autoBake,customComponent:CustomBakeButton})],EditorScene.prototype,"bakeButton",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.enabled"}),propertyField({label:"scene.ambientOcclusion.enabled",info:"scene.ambientOcclusion.enabled-info",type:ComponentType.Toggle,bindPath:"ambientOcclusion.enabled"})],EditorScene.prototype,"enabledAmbientOcclusion",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.quality"}),propertyField({label:"scene.ambientOcclusion.quality.title",info:"scene.ambientOcclusion.quality.info",type:ComponentType.Select,options:transformEnumToOptions(AmbientOcclusionQuality,void 0,rt=>t$7(`scene.ambientOcclusion.quality.${rt.toLowerCase()}`)),bindPath:"ambientOcclusion.quality",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"quality",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.intensity"}),propertyField({type:ComponentType.Number,label:"scene.ambientOcclusion.intensity",info:"scene.ambientOcclusion.intensity-info",bindPath:"ambientOcclusion.intensity",min:0,when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"intensity",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.power"}),propertyField({label:"scene.ambientOcclusion.power",info:"scene.ambientOcclusion.power-info",type:ComponentType.Slider,min:0,max:8,dragStep:.01,bindPath:"ambientOcclusion.power",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"power",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.radius"}),propertyField({label:"scene.ambientOcclusion.radius",info:"scene.ambientOcclusion.radius-info",type:ComponentType.Slider,min:.1,max:10,dragStep:.01,bindPath:"ambientOcclusion.radius",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"radius",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.bilateralThreshold"}),propertyField({label:"scene.ambientOcclusion.bilateralThreshold",info:"scene.ambientOcclusion.bilateralThreshold-info",type:ComponentType.Slider,min:1e-6,max:.1,dragStep:1e-4,bindPath:"ambientOcclusion.bilateralThreshold",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"bilateralThreshold",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.bias"}),propertyField({label:"scene.ambientOcclusion.bias",info:"scene.ambientOcclusion.bias-info",type:ComponentType.Slider,min:0,max:.5,dragStep:1e-5,bindPath:"ambientOcclusion.bias",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"bias",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.minHorizonAngle",...angleSerializer()}),propertyField({label:"scene.ambientOcclusion.minHorizonAngle",info:"scene.ambientOcclusion.minHorizonAngle-info",type:ComponentType.Slider,min:0,max:45,bindPath:"ambientOcclusion.minHorizonAngle",when:rt=>rt.enabledAmbientOcclusion}),propertyProxy({getPath:"ambientOcclusion.minHorizonAngle",getEditorValue:rt=>rt*180/Math.PI})],EditorScene.prototype,"minHorizonAngle",2);__decorateClass$2([observable],EditorScene.prototype,"_initComplete",2);__decorateClass$2([computed],EditorScene.prototype,"initComplete",1);__decorateClass$2([computed],EditorScene.prototype,"removable",1);__decorateClass$2([action],EditorScene.prototype,"setupInspector",1);__decorateClass$2([action],EditorScene.prototype,"onInitComplete",1);__decorateClass$2([action],EditorScene.prototype,"sync",1);__decorateClass$2([action],EditorScene.prototype,"destroy",1);__decorateClass$2([action],EditorScene.prototype,"applySettingFromDomain",1);async function findReusableBakedAmbientAsset(rt,_e,tt){const et=Object.values(rt.root.assetStore.assets).filter(nt=>nt.parentFolderId===_e&&nt.name===tt);for(const nt of et){if(canReuseBakedAmbientAsset(rt,nt))return nt;isSystemBakedAmbientAsset(rt,nt)&&await deleteUnusableBakedAmbientAsset(rt,nt)}}function canReuseBakedAmbientAsset(rt,_e){var nt;const tt=(nt=rt.root.domainStore)==null?void 0:nt.state.assets[_e.id],et=tt==null?void 0:tt.status;return et&&et!=="ready"?!1:!!(_e.url||tt!=null&&tt.url)}function isSystemBakedAmbientAsset(rt,_e){var nt,it,at;const tt=(nt=rt.root.domainStore)==null?void 0:nt.state.assets[_e.id];return(tt==null?void 0:tt.status)==="uploading"?!1:((tt==null?void 0:tt.type)??((at=(it=_e.getMetaConfig)==null?void 0:it.call(_e))==null?void 0:at.type))==="AmbientLight"}async function deleteUnusableBakedAmbientAsset(rt,_e){var et;const tt=(et=rt.root.assetFacade)==null?void 0:et.deleteAsset;if(typeof tt!="function")throw new Error(`Cannot replace unusable baked ambient asset "${_e.name}" (${_e.id}): root.assetFacade.deleteAsset is unavailable`);await tt.call(rt.root.assetFacade,_e.id)}const EditorScene$1=Object.freeze(Object.defineProperty({__proto__:null,EditorScene},Symbol.toStringTag,{value:"Module"})),viewportConfig={"2d":{setting:{mode:"2D",is3dMode:!1,projection:"orthographic",nearClipPlane:.03,farClipPlane:1e4,fieldOfView:60,isOrthographic:!0,orthographicSize:10,flySpeed:8,isDynamicClipping:!0},location:{eye:{x:0,y:0,z:10},target:{x:0,y:0,z:0},up:{x:0,y:1,z:0}},toolsetting:{grid:!0,gizmo:{state:8,anchorType:0,coordType:0}}},"3d":{setting:{mode:"3D",is3dMode:!0,projection:"perspective",nearClipPlane:.03,farClipPlane:1e4,fieldOfView:60,isOrthographic:!1,flySpeed:8,isDynamicClipping:!0},location:{eye:{x:15,y:7,z:15},target:{x:0,y:3.5,z:0},up:{x:0,y:1,z:0}},toolsetting:{grid:!0,gizmo:{state:1,anchorType:0,coordType:0}}}},VIEWPORT_TOOL_KEY="__viewportToolSetting__",VIEWPORT_CAMERA_KEY={id:"0",get location(){return`__viewportCameraLocation-${this.id}__`},get setting(){return`__viewportCameraSetting-${this.id}__`},set projectId(rt){this.id=rt}};function getConfig(){const rt=localStorage.getItem(VIEWPORT_CAMERA_KEY.setting);let _e;if(rt)try{_e=JSON.parse(rt)}catch(at){console.error("parse localStorage cameraSetting failed: "+at)}const tt=localStorage.getItem(VIEWPORT_CAMERA_KEY.location);let et;if(tt)try{et=JSON.parse(tt)}catch(at){console.error("parse localStorage cameraLocation failed: "+at)}const nt=localStorage.getItem(VIEWPORT_TOOL_KEY);let it;if(nt)try{it=JSON.parse(nt)}catch(at){console.error("parse localStorage toolSetting failed: "+at)}return{cameraSetting:_e,cameraLocation:et,toolSetting:it}}function setConfig(rt,_e,tt={}){if(VIEWPORT_CAMERA_KEY.projectId=rt,!localStorage.getItem(VIEWPORT_CAMERA_KEY.setting)){const at=viewportConfig[_e].setting;saveCameraSetting(JSON.stringify(at))}if(!localStorage.getItem(VIEWPORT_CAMERA_KEY.location)){const at=tt.cameraLocation??viewportConfig[_e].location;saveCameraLocation(JSON.stringify(at))}if(!localStorage.getItem(VIEWPORT_TOOL_KEY)){const at=viewportConfig[_e].toolsetting;saveToolSetting(JSON.stringify(at))}}function saveCameraSetting(rt){localStorage.setItem(VIEWPORT_CAMERA_KEY.setting,rt)}function saveToolSetting(rt){localStorage.setItem(VIEWPORT_TOOL_KEY,rt)}function saveCameraLocation(rt){localStorage.setItem(VIEWPORT_CAMERA_KEY.location,rt)}var __defProp$2=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$1(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$2(_e,tt,nt),nt};class PreviewManager{constructor(_e){Rt(this,"viewer",null);Rt(this,"isInit",!1);Rt(this,"isPreviewOn",!1);Rt(this,"isPreviewLockOn",!1);Rt(this,"hasUserRT",!1);this.projectStore=_e,makeObservable(this)}init(_e){this.viewer=new ViewportPreviewer,this.isInit=!0,this.viewer.init(_e)}togglePreviewLock(){this.isPreviewLockOn=!this.isPreviewLockOn}startPreview(_e){this.isPreviewOn=!0,this.hasUserRT=!!_e.renderTarget,this.viewer.startPreview(_e)}endPreview(_e=!1){(_e||this.isPreviewOn&&!this.isPreviewLockOn)&&(this.isPreviewOn=!1,this.hasUserRT=!1,this.viewer.endPreview())}updatePreview(_e,tt){var nt;if(_e.type!=="Camera")return;const et=this.projectStore.currentScene.sceneUIStore.lastSelectedId;!et||!this.projectStore.currentScene.entities.get(et)||(tt?((nt=this.viewer.previewCamera)==null?void 0:nt.instanceId)===_e.engineObject.instanceId&&this.endPreview():(this.endPreview(),!this.isPreviewLockOn&&this.startPreview(_e.engineObject)))}onSelect(_e){if(!this.isPreviewLockOn){const tt=_e.getComponent(Camera);this.endPreview(),tt&&this.startPreview(tt)}}}__decorateClass$1([observable],PreviewManager.prototype,"isInit",2);__decorateClass$1([observable],PreviewManager.prototype,"isPreviewOn",2);__decorateClass$1([observable],PreviewManager.prototype,"isPreviewLockOn",2);__decorateClass$1([observable],PreviewManager.prototype,"hasUserRT",2);__decorateClass$1([action],PreviewManager.prototype,"togglePreviewLock",1);__decorateClass$1([action],PreviewManager.prototype,"startPreview",1);__decorateClass$1([action],PreviewManager.prototype,"endPreview",1);__decorateClass$1([action],PreviewManager.prototype,"updatePreview",1);function resolveSceneCameraDefaultFromCandidates(rt){const _e=selectCameraCandidate(rt);return _e?computeCameraLocationFromTransform(_e.position,_e.rotationQuaternion,_e.focusPoint):null}function computeSceneCameraReapply(rt){return!rt.useSceneCameraAsFallback||rt.userAdjustedCamera?null:resolveSceneCameraDefaultFromCandidates(rt.candidates)}function selectCameraCandidate(rt){if(rt.length===0)return null;let _e=rt[0];for(let tt=1;tt<rt.length;tt++)rt[tt].priority<_e.priority&&(_e=rt[tt]);return _e}function computeCameraLocationFromTransform(rt,_e,tt){const et=rotateVectorByQuaternion({x:0,y:0,z:-1},_e),nt=rotateVectorByQuaternion({x:0,y:1,z:0},_e),it=resolveTargetDistance(rt,et,tt);return{eye:{x:rt.x,y:rt.y,z:rt.z},target:{x:rt.x+et.x*it,y:rt.y+et.y*it,z:rt.z+et.z*it},up:{x:nt.x,y:nt.y,z:nt.z}}}function rotateVectorByQuaternion(rt,_e){const tt=2*(_e.y*rt.z-_e.z*rt.y),et=2*(_e.z*rt.x-_e.x*rt.z),nt=2*(_e.x*rt.y-_e.y*rt.x);return{x:rt.x+_e.w*tt+(_e.y*nt-_e.z*et),y:rt.y+_e.w*et+(_e.z*tt-_e.x*nt),z:rt.z+_e.w*nt+(_e.x*et-_e.y*tt)}}function resolveTargetDistance(rt,_e,tt){if(tt){const nt=(tt.x-rt.x)*_e.x+(tt.y-rt.y)*_e.y+(tt.z-rt.z)*_e.z;if(nt>.1&&nt<1e3)return nt}if(_e.y<-1e-4&&rt.y>1e-4){const nt=-rt.y/_e.y;if(nt>.1&&nt<1e3)return nt}const et=Math.sqrt(rt.x*rt.x+rt.y*rt.y+rt.z*rt.z);return et>.1?et:10}function isPlainObject(rt){return typeof rt=="object"&&rt!==null&&!Array.isArray(rt)}function mergeViewportDefaults(rt,_e){if(!isPlainObject(rt))return _e===void 0?rt:_e;isPlainObject(_e)||(_e={});const tt={};for(const et in rt)tt[et]=mergeViewportDefaults(rt[et],_e[et]);return tt}function resolveViewportStoredConfig({defaults:rt,stored:_e}){return{cameraSetting:mergeViewportDefaults(rt.cameraSetting,_e.cameraSetting),cameraLocation:mergeViewportDefaults(rt.cameraLocation,_e.cameraLocation),toolSetting:mergeViewportDefaults(rt.toolSetting,_e.toolSetting)}}function alignEntityCameraToViewport({entity:rt,cameraTransform:_e,fieldOfView:tt,updateComponent:et}){if(!rt||!rt.hasCameraComponent)return!1;syncTransformToEditor(rt.transform,_e);const nt=rt.getComponentByTypeName("Camera");return!(nt!=null&&nt.id)||!et?!1:(et(rt.id,nt.id,{fieldOfView:tt}),!0)}function syncTransformToEditor(rt,_e){if(!rt||typeof rt!="object")return;const tt=rt.syncTransformToEditor;typeof tt=="function"&&tt(_e)}function alignEntityBinderToViewport({entityBinder:rt,cameraTransform:_e,fieldOfView:tt}){rt==null||rt.alignToCamera({cameraTransform:_e,fieldOfView:tt})}var __defProp$1=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$1(_e,tt,nt),nt},Gr;const _ViewportStore=(Gr=class{constructor(_e){Rt(this,"engine");Rt(this,"viewport");Rt(this,"previewManager");Rt(this,"isIcon3dMode",!0);Rt(this,"viewToolState",ViewToolState.None);Rt(this,"_wireframeVisibility");Rt(this,"_cameraEntity");Rt(this,"_stores",[]);Rt(this,"_projectStore");Rt(this,"_gridScript");Rt(this,"_iconScript");Rt(this,"_navigationScript");Rt(this,"_outlineScript");Rt(this,"_wireframeScript");Rt(this,"_controlScript");Rt(this,"_gizmoScript");Rt(this,"_pickerScript");Rt(this,"_useSceneCameraAsFallback",!1);Rt(this,"_userAdjustedCamera",!1);Rt(this,"playMode",!1);Rt(this,"AIViewerMode",!1);Rt(this,"toolSetting",{grid:!0,icons:!0,navigation:!0,gizmo:{state:State.translate,anchorType:AnchorType.Pivot,coordType:CoordinateType.Local},outline:!0});Rt(this,"cameraSetting",{is3dMode:!0,nearClipPlane:.001,farClipPlane:1e4,fieldOfView:60,orthographicSize:10,flySpeed:8,isDynamicClipping:!0,projection:"perspective",enableEase:!0,enableAcceleration:!0,enableSmooth:!0});Rt(this,"cameraLocation",{eye:{x:10,y:10,z:10},target:{x:0,y:0,z:0},up:{x:0,y:1,z:0}});this.projectStore=_e,makeObservable(this),this.previewManager=new PreviewManager(_e),this._projectStore=_e,this.viewport=viewport}static registerPlugin(_e,tt){this.pluginStoreClasses.push({type:tt.type,storeClass:_e}),tt.Panel&&this.panels.push(tt.Panel)}addScripts(_e={}){const tt=_e.mode??"editor";this._addControlScript(),this._addGridScript(),this._addNavigationScript(),tt==="editor"&&(this._addGizmoScript(),this._addIconScript(),this._addOutlineScript(),this._addWireframeScript(),this._addPickerScript())}_addControlScript(){const _e=viewport.addScript(CameraControl),{cameraSetting:tt,cameraLocation:et}=this;return _e.init({projection:tt.projection,fieldOfView:tt.fieldOfView,nearClipPlane:tt.nearClipPlane,farClipPlane:tt.farClipPlane,isDynamicClipping:tt.isDynamicClipping,flySpeed:tt.flySpeed,enableSmooth:tt.enableSmooth,enableEase:tt.enableEase,enableAcceleration:tt.enableAcceleration,orthographicSize:tt.orthographicSize,cameraLocation:et,is3dMode:tt.is3dMode,onSaveOrthoSize:nt=>{tt.orthographicSize=nt},onSaveCameraPosition:nt=>{this._userAdjustedCamera=!0;const{eye:it,target:at,up:ot}=nt;saveCameraLocation(JSON.stringify({eye:{x:it.x,y:it.y,z:it.z},target:{x:at.x,y:at.y,z:at.z},up:{x:ot.x,y:ot.y,z:ot.z}}))},onSaveCursor:(nt,it)=>{this.viewport.setCursor(nt,it)},onViewToolStateChange:nt=>{this.viewToolState=nt}}),this._controlScript=_e,_e}_addGizmoScript(){const _e=this._projectStore,{toolSetting:tt}=this,et=tt.gizmo,nt=viewport.addScript(GizmoControl);return nt.init({anchorType:et.anchorType,coordType:et.coordType,state:et.state,onGizmoMoveStart:()=>{const it=_e.currentScene.selectedEntities;if(!(it!=null&&it.length))return;_e.root.domainStore.beginBatch()},onGizmoMoving:()=>{const it=_e.currentScene.selectedEntities;if(!(!it||(it==null?void 0:it.length)<=0))for(const at of it)at.transform.syncEngineToEditor(),_e.debouncedUpdateSceneAsset()},onGizmoMoveEnd:()=>{const it=_e.currentScene.selectedEntities;if(!(it!=null&&it.length))return;const at=_e.root.entityFacade;for(const ot of it){const st=ot.engineObject.transform;at.setTransform(ot.id,{position:{x:st.position.x,y:st.position.y,z:st.position.z},rotation:{x:st.rotation.x,y:st.rotation.y,z:st.rotation.z},scale:{x:st.scale.x,y:st.scale.y,z:st.scale.z}})}_e.root.domainStore.commitBatch("gizmo.transform"),_e.debouncedUpdateSceneAsset()},onGizmoCancel:()=>{_e.root.domainStore.abortBatch()}}),this._gizmoScript=nt,nt}_addGridScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Grid);return tt.init({grid:_e.grid,is3dMode:viewport.is3dMode}),this._gridScript=tt,tt}_addIconScript(){const _e=viewport.addScript(IconScript);return this._iconScript=_e,_e}_addNavigationScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Navigation);return tt.init(_e.navigation,viewport.is3dMode),this._navigationScript=tt,tt}_addOutlineScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Outline);return tt.init(_e.outline),tt.mode=this.cameraSetting.is3dMode?"3d":"2d",this._outlineScript=tt,tt}_addWireframeScript(){const _e=viewport.addScript(WireframeScript);return this._wireframeVisibility=_e.visibility,this._wireframeScript=_e,_e}_addPickerScript(){const _e=this._projectStore,tt=viewport.addScript(Picker);return tt.init({onSelectEntity:(et,nt,it)=>{var at,ot;if(et){const st=((at=EditorPicker.subEntityPickerMap.get(et))==null?void 0:at.id)||((ot=EditorPicker.entityPickerMap.get(et))==null?void 0:ot.id);st&&_e.currentScene.selectEntity(st,nt,it)}else _e.currentScene.selectEntity(null)},onRemoveEntity:()=>{_e.currentScene.removeEntity()},onHoverEntity:et=>{var nt,it;if(et){const at=((nt=EditorPicker.subEntityPickerMap.get(et))==null?void 0:nt.id)||((it=EditorPicker.entityPickerMap.get(et))==null?void 0:it.id);at&&_e.currentScene.setHoveredEntity(at)}else _e.currentScene.setHoveredEntity(null)}}),this._pickerScript=tt,tt}init(_e,tt,et={}){const{projectStore:nt}=this;this.engine=tt.engine,this._useSceneCameraAsFallback=et.useSceneCameraAsFallback===!0;const it=this._useSceneCameraAsFallback?resolveSceneCameraDefaultFromCandidates(collectSceneCameraCandidates(tt))??void 0:void 0;setConfig(nt.id,_e,{cameraLocation:it});const at=resolveViewportStoredConfig({defaults:{cameraSetting:this.cameraSetting,cameraLocation:this.cameraLocation,toolSetting:this.toolSetting},stored:getConfig()});this.cameraSetting=at.cameraSetting,this.cameraLocation=at.cameraLocation,this.toolSetting=at.toolSetting,this.viewport.scene=tt,this.viewport.is3dMode=at.cameraSetting.is3dMode;const{camera:ot}=this.viewport;this._cameraEntity=ot.entity,this.previewManager.init(this._cameraEntity),this.addScripts(et),et.mode!=="viewer"&&this.toggleIconMode(this.isIcon3dMode),Gr.pluginStoreClasses.forEach(({storeClass:st,type:ct})=>{const dt=new st(nt.root);this[ct]=dt,dt.init(),this._stores.push(dt)}),reaction(()=>JSON.stringify(this.cameraSetting),debounce$2(st=>{saveCameraSetting(st)},1e3)),reaction(()=>JSON.stringify(this.toolSetting),debounce$2(st=>{saveToolSetting(st)},1e3))}switch(_e){this.previewManager.isPreviewOn=!1,this.viewport.scene=_e}switchDisplayMode(_e){const{cameraSetting:tt}=this;tt.is3dMode!==_e&&(tt.is3dMode=_e,this.switchProjection(_e?"perspective":"orthographic"),this.viewport.switchDisplayMode(_e,500))}switchProjection(_e){const{cameraSetting:tt}=this;tt.projection!==_e&&(tt.projection=_e,this.viewport.switchProjection())}reapplySceneCameraIfUntouched(){const _e=this.viewport.scene;if(!_e||!this._controlScript)return;const tt=computeSceneCameraReapply({useSceneCameraAsFallback:this._useSceneCameraAsFallback,userAdjustedCamera:this._userAdjustedCamera,candidates:collectSceneCameraCandidates(_e)});tt&&(this.cameraLocation=tt,this._controlScript.applyCameraLocation(tt),saveCameraLocation(JSON.stringify(tt)))}togglePlayMode(_e){this.playMode=_e??!this.playMode}toggleAIViewerMode(_e){this.AIViewerMode=_e??!this.AIViewerMode}focus(_e){const et=(_e?[_e]:this.projectStore.currentScene.selectedEntities.map(nt=>nt.engineObject)).filter(nt=>!!(nt&&!nt.destroyed));et.length!==0&&this.viewport.focus(et)}alignView(_e){var tt,et,nt;alignEntityCameraToViewport({entity:_e,cameraTransform:this._cameraEntity.transform,fieldOfView:this.viewport.camera.fieldOfView,updateComponent:(nt=(et=(tt=this._projectStore.root)==null?void 0:tt.componentFacade)==null?void 0:et.updateComponent)==null?void 0:nt.bind(this._projectStore.root.componentFacade)})}alignBinder(_e){alignEntityBinderToViewport({entityBinder:_e,cameraTransform:this._cameraEntity.transform,fieldOfView:this.viewport.camera.fieldOfView})}handleContainerResize(){this.viewport.resize()}selectEntity(_e){const tt=!_e||(_e==null?void 0:_e.length)<=0?null:_e.map(et=>et.engineObject).filter(et=>!!(et&&!et.destroyed));this.previewManager.endPreview(),this.viewport.selectEntity(tt!=null&&tt.length?tt:null);for(let et=0;et<(tt==null?void 0:tt.length);et++)this.previewManager.onSelect(tt[et])}hoverEntity(_e){const tt=_e==null?void 0:_e.engineObject;this.viewport.hoverEntity(tt&&!tt.destroyed?tt:null)}onComponentDestroy(_e){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||(this.viewport.onComponentDestroy(_e.engineObject),this.previewManager.updatePreview(_e,!0))}onComponentAdd(_e){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||(this.viewport.onComponentAdd(_e.engineObject),this.previewManager.updatePreview(_e,!1))}activeEntity(_e,tt){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||this.viewport.activeEntity(_e.engineObject,tt)}lockEntity(_e,tt){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||this.viewport.lockEntity(_e.engineObject,tt)}play(_e){this.viewport.play(_e)}toggleVisible(_e){this.toggleGrid(_e),this.toggleIcons(_e),this.toggleNavigation(_e),this.toggleOutline(_e),this._stores.forEach(tt=>{tt.toggleVisible&&tt.toggleVisible(_e)})}toggleGrid(_e){this._gridScript&&(this._gridScript.onToggleVisible(_e),this.toolSetting.grid=_e)}toggleIcons(_e){this._iconScript&&(this._iconScript.onToggleVisible(_e),this.toolSetting.icons=_e)}toggleIconMode(_e){this._iconScript&&(this._iconScript.toggleMode(_e),this.isIcon3dMode=_e)}toggleNavigation(_e){this._navigationScript&&(this._navigationScript.onToggleVisible(_e),this.toolSetting.navigation=_e)}toggleOutline(_e){this._outlineScript&&(this._outlineScript.onToggleVisible(_e),this.toolSetting.outline=_e)}setFieldOfView(_e){this.viewport.camera.fieldOfView=_e,this.cameraSetting.fieldOfView=_e}setDynamicClipping(_e){this.cameraSetting.isDynamicClipping=_e}setNearClipPlane(_e){this.viewport.camera.nearClipPlane=_e,this.cameraSetting.nearClipPlane=_e}setFarClipPlane(_e){this.viewport.camera.farClipPlane=_e,this.cameraSetting.farClipPlane=_e}setFlySpeed(_e){this.cameraSetting.flySpeed=_e,this._controlScript&&this._controlScript.handleCameraFlySpeed(_e)}setEnableSmooth(_e){this.cameraSetting.enableSmooth=_e,this._controlScript&&this._controlScript.handleCameraSmooth(_e)}setEnableEase(_e){this.cameraSetting.enableEase=_e,this._controlScript&&this._controlScript.handleCameraEase(_e)}setEnableAcceleration(_e){this.cameraSetting.enableAcceleration=_e,this._controlScript&&this._controlScript.handleCameraAcceleration(_e)}toggleClipping(_e){this._controlScript&&this._controlScript.toggleClipping(_e)}setGizmoState(_e){this.toolSetting.gizmo.state=_e,this._gizmoScript&&(this._gizmoScript.gizmoState=_e,this._controlScript.toggleHandTool(!1))}setGizmoAnchorType(_e){this._gizmoScript&&(this._gizmoScript.anchorType=_e)}setGizmoCoordType(_e){this._gizmoScript&&(this._gizmoScript.coordType=_e)}handleNavigation(){this._controlScript&&this._gizmoScript&&(this._controlScript.toggleHandTool(!0),this._gizmoScript.gizmoState=0)}toggleWireframe(_e,tt){this._wireframeScript&&(this._wireframeScript.toggleVisible(_e,tt),this._wireframeVisibility=this._wireframeScript.visibility)}isWireframeVisible(_e){return(this._wireframeVisibility&_e)===_e}async createEngine(_e){return await this.viewport.createEngine(_e)}async capture(_e,tt){return await this.viewport.capture(_e,tt)}},Rt(Gr,"panels",[]),Rt(Gr,"pluginStoreClasses",[]),Gr);__decorateClass([observable],_ViewportStore.prototype,"viewToolState",2);__decorateClass([observable],_ViewportStore.prototype,"playMode",2);__decorateClass([observable],_ViewportStore.prototype,"AIViewerMode",2);__decorateClass([observable],_ViewportStore.prototype,"toolSetting",2);__decorateClass([observable],_ViewportStore.prototype,"cameraSetting",2);__decorateClass([action],_ViewportStore.prototype,"togglePlayMode",1);__decorateClass([action],_ViewportStore.prototype,"toggleAIViewerMode",1);let ViewportStore=_ViewportStore;const EDITOR_ROOT_ENTITY_NAME="editorRoot",sceneFocusBounds=new BoundingBox,sceneFocusCenter=new Vector3;function collectSceneCameraCandidates(rt){const _e=[],tt=collectAuthorRootEntities(rt),et=collectSceneFocusPoint(tt);for(let nt=0;nt<tt.length;nt++){const it=tt[nt];walkEntityForCamera(it,_e)}if(et)for(const nt of _e)nt.focusPoint=et;return _e}function collectAuthorRootEntities(rt){const _e=[],tt=rt.rootEntitiesCount;for(let et=0;et<tt;et++){const nt=rt.rootEntities[et];nt.name!==EDITOR_ROOT_ENTITY_NAME&&_e.push(nt)}return _e}function collectSceneFocusPoint(rt){const _e=getBoundingBox(rt,sceneFocusBounds,BoundingBoxType.RendererAndUICanvas);if(_e)return _e.getCenter(sceneFocusCenter),{x:sceneFocusCenter.x,y:sceneFocusCenter.y,z:sceneFocusCenter.z}}function walkEntityForCamera(rt,_e){const tt=rt.getComponent(Camera);if(tt){const nt=rt.transform.worldPosition,it=rt.transform.worldRotationQuaternion;_e.push({position:{x:nt.x,y:nt.y,z:nt.z},rotationQuaternion:{x:it.x,y:it.y,z:it.z,w:it.w},priority:tt.priority})}const et=rt.children.length;for(let nt=0;nt<et;nt++)walkEntityForCamera(rt.children[nt],_e)}function ViewportPlugin(rt){return _e=>{ViewportStore.registerPlugin(_e,{...rt})}}const logProject=logger$2("project");class ObservableLocalWorkspaceSync extends LocalWorkspaceSync{constructor(_e){super(_e),makeObservable(this,{directoryHandle:observable.ref,directoryName:observable,directoryPath:observable,permissionStatus:observable,status:observable,errorMessage:observable,isRestoring:observable,progress:observable.ref,lastSyncedAt:observable,hasBinding:computed,isActive:computed,needsPermission:computed,syncProgressPercent:computed,setStatus:action,reset:action})}}class Project extends ProjectInfo{constructor(tt){super();Rt(this,"root",null);Rt(this,"syncStatus","idle");Rt(this,"engine",null);Rt(this,"canvas",null);Rt(this,"packageName",DEFAULT_PACKAGE_NAME);Rt(this,"useCompressedTextures",!1);Rt(this,"currentScene",null);Rt(this,"currentViewport");Rt(this,"assets");Rt(this,"plugins",[]);Rt(this,"pageLocked",!1);Rt(this,"animationEditing",!1);Rt(this,"_publisher",EventBus.createPublisher());Rt(this,"localWorkspaceSync",null);Rt(this,"exportSettings",null);Rt(this,"entityClipboard",null);Rt(this,"savingPromise",null);Rt(this,"_localSceneId",null);Rt(this,"_localSceneKey","");Rt(this,"debouncedUpdateSchema",debounce$2(this.updateSchema.bind(this),1500,{}));Rt(this,"_logger",createLogger("Project"));Rt(this,"_pendingLogger",null);Rt(this,"debouncedUpdateSceneAsset",debouncePromise(()=>this._updateSceneAssetAndCapture(),100,{edges:["trailing"]}));Rt(this,"debounceUpdateThumbnail",debounce$2(this.updateThumbnail.bind(this),5e3,{edges:["trailing"]}));this.root=tt,makeObservable(this,{packageName:observable,syncStatus:observable,currentScene:observable,exportSettings:observable,pageLocked:observable,useCompressedTextures:observable,entityClipboard:observable.ref,setSyncStatus:action,addPlugin:action,updatePlugin:action,renamePackageName:action,lockClick:action,unlockClick:action,plugins:observable.shallow}),this.currentViewport=new ViewportStore(this),this.localWorkspaceSync=new ObservableLocalWorkspaceSync(this)}async initEngine(tt){const et=await this.currentViewport.createEngine(tt);this.engine=et,this.canvas=tt,tt.tabIndex=tt.tabIndex}setSyncStatus(tt){this.syncStatus=tt}async init(tt){const et=tt,{root:{assetStore:nt}}=this;return runInAction(()=>{var at;logProject.success("init project success.","verbose"),Object.keys(et).filter(ot=>ot!=="content").forEach(ot=>{if(ot==="setting"){const st=et[ot];if(st){if(typeof st=="string")try{et.setting=JSON.parse(st)}catch(ct){console.warn("[project] Failed to parse project setting JSON:",ct),et.setting={}}this.setting={...defaultSetting,...et[ot]}}}else this[ot]=et[ot]}),this._localSceneKey=`${this.id}-localSceneId`,this._localSceneId=localStorage.getItem(this._localSceneKey),this.dependencies=et.setting.dependencies||{},this.content={...et.content,platform:et.platform},this.plugins=et.content.plugins,this.engineVersion=et.engineVersion,(at=this.exportSettings)==null||at.destroy(),this.exportSettings=new ExportSettings(this,tt),nt.initRegisteredAssets()}),et}queryInfo(){return this._storage.project.query(this.id)}async reloadProject(){const tt=await this._storage.project.query(this.id);runInAction(()=>{this.content={...tt.content,platform:tt.platform}}),await this.initAssets(tt.assets)}async initAssets(tt){tt=ensureBuiltinFolderAssets(tt);for(const et of builtinShaderDirectories)tt.push(et);for(const et of builtinShaders)tt.push(et);await this.root.assetStore.init(tt,this.engine),this.syncAssetsToDomain(tt)}syncAssetsToDomain(tt){const et=[];for(const nt of tt){if(!this.root.assetStore.assets[nt.uuid]||this.root.domainStore.state.assets[nt.uuid])continue;const it=this.parseAssetMetaForDomainSync(nt.meta,nt.uuid);et.push({op:"add",path:`/assets/${nt.uuid}`,value:{id:nt.uuid,name:nt.name,type:it.type??"Unknown",serverId:nt.id??null,parentFolderId:nt.parentId||null,url:nt.url||void 0,meta:it,status:"ready"}})}et.length>0&&this.root.domainStore.apply(et,"asset.init")}parseAssetMetaForDomainSync(tt,et){if(!tt)return{};try{const nt=JSON.parse(tt);if(!nt||typeof nt!="object")throw new Error("asset meta is not an object");return nt}catch(nt){return logProject.warn(`[Project] Invalid asset meta JSON for asset ${et}, fallback to empty meta`,nt),{}}}async initScene(){this.currentScene=new EditorScene(this.root),this.root.engineProjection?this.root.engineProjection.scene!==this.currentScene.engineSceneObject&&this.root.engineProjection.setScene(this.currentScene.engineSceneObject):this.root.initEngineProjection(this.currentScene.engineSceneObject);const tt=this.assets,et=this._localSceneId||this.content.scene;let nt=tt.find(at=>at.uuid===et);nt||(nt=tt.find(at=>/Scene/.test(at.meta))),nt||(nt={uuid:(await this.root.assetFacade.createAssetByAdd({assetType:"Scene",name:"Scene"})).id}),this.content.scene=nt.uuid;const it=await this.root.assetStore.getAssetByRef({refId:nt.uuid});await this.currentScene.init(it),this.root.sceneFacade.initSettings(collectSceneSettings(this.currentScene)),this.exportSettings.defaultSceneId=nt.uuid,this.engine.sceneManager.activeScene=this.currentScene.engineSceneObject}runEngine(tt){const{currentScene:et,currentViewport:nt}=this;this.engine.on("onReady",()=>{this.engine.run()}),nt.init(this.platform,et.engineSceneObject,tt),et.entities.forEach(it=>{it.components.forEach(at=>{nt.onComponentAdd(at)})}),window.runtimeEngine=this.engine}async updateSchema(tt){const{root:et}=this;this.setSyncStatus("syncing"),!tt&&(tt=this.getSchema());try{await this._storage.schema.update(tt,et.projectStore.id),this.setSyncStatus("success")}catch(nt){console.error(nt),this.setSyncStatus("error")}}async updateSceneAsset(tt){const{root:et}=this,nt=await et.assetStore.getAssetByRef({refId:et.sceneStore.refId}),it=tt==null?void 0:tt.pinnedId;this.savingPromise=it!=null?withTraceId(it,()=>nt.saveMain()):nt.saveMain(),await this.savingPromise,this._publisher.publish("asset-change",{type:"modify",assetId:this.currentScene.refId,main:nt.getMainData()})}persistSceneDebounced(tt){this._logger.info(`persistSceneDebounced ← ${tt}`),this._pendingLogger=this._logger.capture(),this.debouncedUpdateSceneAsset()}async _updateSceneAssetAndCapture(){if(!this.root.sceneStore.refId)return;const tt=this._pendingLogger??this._logger;this._pendingLogger=null,tt.info("updateSceneAsset → saveMain + capture");try{this.setSyncStatus("syncing"),await this.updateSceneAsset(tt);const et=await this.currentViewport.capture(634,346);this.debounceUpdateThumbnail(et),this.setSyncStatus("success")}catch(et){console.error(et),this.setSyncStatus("error")}}getSchema(){const{projectStore:{engineVersion:tt},sceneStore:et}=this.root;return{scene:et.refId,plugins:this.plugins,engineVersion:tt}}renamePackageName(tt){this.packageName=tt}changeUseCompressedTextures(tt){this.useCompressedTextures=tt}lockClick(){this.pageLocked=!0}unlockClick(){this.pageLocked=!1}reset(){var nt,it,at,ot;this.localWorkspaceSync.reset(),(nt=this.exportSettings)==null||nt.destroy(),this.exportSettings=null,(it=this.currentScene)==null||it.destroy(),this.root.assetStore.reset(),(at=this.engine)==null||at.pause(),(ot=this.engine)==null||ot.destroy();const tt=new Set(["BlinnPhong","PBR","Unlit","Sky/Skybox","Sky/SkyProcedural","2D/SpriteMask","2D/Sprite","Sky/BackgroundTexture","Effect/Particle","2D/UIDefault","Effect/Trail","2D/Text"]),et=Shader._shaderMap;for(const st in et)tt.has(st)||delete et[st];this.engine=null,this.canvas=null,this.packageName=DEFAULT_PACKAGE_NAME,this.useCompressedTextures=!1}async switchScene(tt){var it;if(this.syncStatus==="syncing"){n.error("syncing, please wait");return}if(tt.scene===this.currentScene.refId)return;this.content.scene=tt.scene,this._localSceneId=tt.scene,this.exportSettings.defaultSceneId=tt.scene,localStorage.setItem(this._localSceneKey,tt.scene);const et=new EditorScene(this.root);(it=this.root.engineProjection)==null||it.setScene(et.engineSceneObject);const nt=await this.root.assetStore.getAssetByRef({refId:tt.scene});await et.init(nt),this.root.sceneFacade.initSettingsSystem(collectSceneSettings(et)),this.root.viewportStore.switch(et.engineSceneObject),et._autoBake(),this.currentScene.destroy(),this.currentScene=et,this.updateSchema(),n.success(`switch scene to ${this.currentScene.engineObject.name}`)}async setActiveEditorScene(tt){var ct,dt;if(this.syncStatus==="syncing")throw new Error("project is syncing, cannot switch active scene now");if(tt===this.currentScene.refId)return;await this.flushCurrentScenePersistenceOrThrow();const et=await this.root.assetStore.getAssetByRef({refId:tt}),nt=this.currentScene,it=nt.engineSceneObject,at=this.root.domainStore.state,ot=new EditorScene(this.root);let st=!1;try{this.currentScene=ot,(ct=this.root.engineProjection)==null||ct.setScene(ot.engineSceneObject),await ot.init(et),this.root.sceneFacade.initSettingsSystem(collectSceneSettings(ot)),this.root.viewportStore.switch(ot.engineSceneObject),ot._autoBake(),st=!0}catch(ut){if(this.currentScene=nt,(dt=this.root.engineProjection)==null||dt.setScene(it),this.root.domainStore.state!==at)try{this.root.domainStore.reset(at)}catch{}try{ot.destroy()}catch{}throw ut}st&&nt.destroy()}async flushCurrentScenePersistenceOrThrow(){if(await this.debouncedUpdateSceneAsset.flush(),this.syncStatus==="error")throw new Error("current scene failed to save, refusing to switch to avoid data loss");this.savingPromise&&await this.savingPromise}async saveCurrentSceneForPreview(){var nt;const tt=(nt=this.currentScene)==null?void 0:nt.refId;if(!tt)return;const et=await this.root.assetStore.getAssetByRef({refId:tt});this.savingPromise=et.saveMainImmediately({skipEvent:!0}),await this.savingPromise,this._publisher.publish("asset-change",{type:"modify",assetId:tt,main:et.getMainData()})}async getFreshPreviewUrl(tt,et){return await this.saveCurrentSceneForPreview(),getPreviewUrl(this.id,tt,et)}async launch(){var et,nt;const tt=window.open("","_blank");if(!tt){n.error("Preview window was blocked by browser");return}try{tt.location.href=await this.getFreshPreviewUrl((et=this.currentScene)==null?void 0:et.refId)}catch(it){throw console.error(it),(nt=tt.close)==null||nt.call(tt),n.error("Failed to prepare preview"),it}}async addPlugin(tt){this.plugins.find(et=>et.packageName===tt.packageName)||(this.plugins.push(tt),this.root.projectStore.debouncedUpdateSchema(),setTimeout(()=>{window.history.go(0)},3e3))}async updatePlugin(tt,et="add"){if(et==="delete")this.plugins=this.plugins.filter(nt=>nt.packageName!==tt.packageName);else{const nt=this.plugins.find(it=>it.packageName===tt.packageName);nt?nt.version=tt.version:this.plugins.push(tt)}this.root.projectStore.debouncedUpdateSchema(),setTimeout(()=>{window.history.go(0)},3e3)}toJSON(){const tt=this.root.assetStore.toJSON();return{id:this.id,name:this.name,platform:this.platform,setting:this.setting,content:this.content,engineVersion:this.engineVersion,assets:tt,dependencies:this.dependencies}}}var __defProp=Object.defineProperty,__defNormalProp=(rt,_e,tt)=>_e in rt?__defProp(rt,_e,{enumerable:!0,configurable:!0,writable:!0,value:tt}):rt[_e]=tt,__publicField=(rt,_e,tt)=>__defNormalProp(rt,typeof _e!="symbol"?_e+"":_e,tt);const _Orientation=class $a{constructor(_e){__publicField(this,"_name"),this._name=_e}static flip(_e){return _e===$a.HORZ?$a.VERT:$a.HORZ}getName(){return this._name}toString(){return this._name}};__publicField(_Orientation,"HORZ",new _Orientation("horz"));__publicField(_Orientation,"VERT",new _Orientation("vert"));let Orientation=_Orientation;class Rect{constructor(_e,tt,et,nt){__publicField(this,"x"),__publicField(this,"y"),__publicField(this,"width"),__publicField(this,"height"),this.x=_e,this.y=tt,this.width=et,this.height=nt}static empty(){return new Rect(0,0,0,0)}static fromJson(_e){return new Rect(_e.x,_e.y,_e.width,_e.height)}toJson(){return{x:this.x,y:this.y,width:this.width,height:this.height}}snap(_e){this.x=Math.round(this.x/_e)*_e,this.y=Math.round(this.y/_e)*_e,this.width=Math.round(this.width/_e)*_e,this.height=Math.round(this.height/_e)*_e}static getBoundingClientRect(_e){const{x:tt,y:et,width:nt,height:it}=_e.getBoundingClientRect();return new Rect(tt,et,nt,it)}static getContentRect(_e){const tt=_e.getBoundingClientRect(),et=window.getComputedStyle(_e),nt=parseFloat(et.paddingLeft),it=parseFloat(et.paddingRight),at=parseFloat(et.paddingTop),ot=parseFloat(et.paddingBottom),st=parseFloat(et.borderLeftWidth),ct=parseFloat(et.borderRightWidth),dt=parseFloat(et.borderTopWidth),ut=parseFloat(et.borderBottomWidth),ht=tt.width-st-nt-it-ct,ft=tt.height-dt-at-ot-ut;return new Rect(tt.left+st+nt,tt.top+dt+at,ht,ft)}static fromDomRect(_e){return new Rect(_e.x,_e.y,_e.width,_e.height)}relativeTo(_e){return new Rect(this.x-_e.x,this.y-_e.y,this.width,this.height)}clone(){return new Rect(this.x,this.y,this.width,this.height)}equals(_e){return this.x===(_e==null?void 0:_e.x)&&this.y===(_e==null?void 0:_e.y)&&this.width===(_e==null?void 0:_e.width)&&this.height===(_e==null?void 0:_e.height)}equalSize(_e){return this.width===(_e==null?void 0:_e.width)&&this.height===(_e==null?void 0:_e.height)}getBottom(){return this.y+this.height}getRight(){return this.x+this.width}get bottom(){return this.y+this.height}get right(){return this.x+this.width}getCenter(){return{x:this.x+this.width/2,y:this.y+this.height/2}}positionElement(_e,tt){this.styleWithPosition(_e.style,tt)}styleWithPosition(_e,tt="absolute"){return _e.left=this.x+"px",_e.top=this.y+"px",_e.width=Math.max(0,this.width)+"px",_e.height=Math.max(0,this.height)+"px",_e.position=tt,_e}contains(_e,tt){return this.x<=_e&&_e<=this.getRight()&&this.y<=tt&&tt<=this.getBottom()}removeInsets(_e){return new Rect(this.x+_e.left,this.y+_e.top,Math.max(0,this.width-_e.left-_e.right),Math.max(0,this.height-_e.top-_e.bottom))}centerInRect(_e){this.x=(_e.width-this.width)/2,this.y=(_e.height-this.height)/2}_getSize(_e){let tt=this.width;return _e===Orientation.VERT&&(tt=this.height),tt}toString(){return"(Rect: x="+this.x+", y="+this.y+", width="+this.width+", height="+this.height+")"}}const _DockLocation=class tr{constructor(_e,tt,et){__publicField(this,"name"),__publicField(this,"orientation"),__publicField(this,"indexPlus"),this.name=_e,this.orientation=tt,this.indexPlus=et,tr.values.set(this.name,this)}static getByName(_e){return tr.values.get(_e)}static getLocation(_e,tt,et){if(tt=(tt-_e.x)/_e.width,et=(et-_e.y)/_e.height,tt>=.25&&tt<.75&&et>=.25&&et<.75)return tr.CENTER;const nt=et>=tt,it=et>=1-tt;return nt?it?tr.BOTTOM:tr.LEFT:it?tr.RIGHT:tr.TOP}getName(){return this.name}getOrientation(){return this.orientation}getDockRect(_e){return this===tr.TOP?new Rect(_e.x,_e.y,_e.width,_e.height/2):this===tr.BOTTOM?new Rect(_e.x,_e.getBottom()-_e.height/2,_e.width,_e.height/2):this===tr.LEFT?new Rect(_e.x,_e.y,_e.width/2,_e.height):this===tr.RIGHT?new Rect(_e.getRight()-_e.width/2,_e.y,_e.width/2,_e.height):_e.clone()}split(_e,tt){if(this===tr.TOP){const et=new Rect(_e.x,_e.y,_e.width,tt),nt=new Rect(_e.x,_e.y+tt,_e.width,_e.height-tt);return{start:et,end:nt}}else if(this===tr.LEFT){const et=new Rect(_e.x,_e.y,tt,_e.height),nt=new Rect(_e.x+tt,_e.y,_e.width-tt,_e.height);return{start:et,end:nt}}if(this===tr.RIGHT){const et=new Rect(_e.getRight()-tt,_e.y,tt,_e.height),nt=new Rect(_e.x,_e.y,_e.width-tt,_e.height);return{start:et,end:nt}}else{const et=new Rect(_e.x,_e.getBottom()-tt,_e.width,tt),nt=new Rect(_e.x,_e.y,_e.width,_e.height-tt);return{start:et,end:nt}}}reflect(){return this===tr.TOP?tr.BOTTOM:this===tr.LEFT?tr.RIGHT:this===tr.RIGHT?tr.LEFT:tr.TOP}toString(){return"(DockLocation: name="+this.name+", orientation="+this.orientation+")"}};__publicField(_DockLocation,"values",new Map);__publicField(_DockLocation,"TOP",new _DockLocation("top",Orientation.VERT,0));__publicField(_DockLocation,"BOTTOM",new _DockLocation("bottom",Orientation.VERT,1));__publicField(_DockLocation,"LEFT",new _DockLocation("left",Orientation.HORZ,0));__publicField(_DockLocation,"RIGHT",new _DockLocation("right",Orientation.HORZ,1));__publicField(_DockLocation,"CENTER",new _DockLocation("center",Orientation.VERT,0));let DockLocation=_DockLocation;var I18nLabel=(rt=>(rt.Close_Tab="Close",rt.Close_Tabset="Close tab set",rt.Active_Tabset="Active tab set",rt.Move_Tabset="Move tab set",rt.Move_Tabs="Move tabs(?)",rt.Maximize="Maximize tab set",rt.Restore="Restore tab set",rt.Popout_Tab="Popout selected tab",rt.Overflow_Menu_Tooltip="Hidden tabs",rt.Error_rendering_component="Error rendering component",rt.Error_rendering_component_retry="Retry",rt))(I18nLabel||{}),CLASSES=(rt=>(rt.FLEXLAYOUT__BORDER="flexlayout__border",rt.FLEXLAYOUT__BORDER_="flexlayout__border_",rt.FLEXLAYOUT__BORDER_TAB_CONTENTS="flexlayout__border_tab_contents",rt.FLEXLAYOUT__BORDER_BUTTON="flexlayout__border_button",rt.FLEXLAYOUT__BORDER_BUTTON_="flexlayout__border_button_",rt.FLEXLAYOUT__BORDER_BUTTON_CONTENT="flexlayout__border_button_content",rt.FLEXLAYOUT__BORDER_BUTTON_LEADING="flexlayout__border_button_leading",rt.FLEXLAYOUT__BORDER_BUTTON_TRAILING="flexlayout__border_button_trailing",rt.FLEXLAYOUT__BORDER_BUTTON__SELECTED="flexlayout__border_button--selected",rt.FLEXLAYOUT__BORDER_BUTTON__UNSELECTED="flexlayout__border_button--unselected",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW="flexlayout__border_toolbar_button_overflow",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_="flexlayout__border_toolbar_button_overflow_",rt.FLEXLAYOUT__BORDER_INNER="flexlayout__border_inner",rt.FLEXLAYOUT__BORDER_INNER_="flexlayout__border_inner_",rt.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER="flexlayout__border_inner_tab_container",rt.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_="flexlayout__border_inner_tab_container_",rt.FLEXLAYOUT__BORDER_TAB_DIVIDER="flexlayout__border_tab_divider",rt.FLEXLAYOUT__BORDER_LEADING="flexlayout__border_leading",rt.FLEXLAYOUT__BORDER_SIZER="flexlayout__border_sizer",rt.FLEXLAYOUT__BORDER_TOOLBAR="flexlayout__border_toolbar",rt.FLEXLAYOUT__BORDER_TOOLBAR_="flexlayout__border_toolbar_",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON="flexlayout__border_toolbar_button",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT="flexlayout__border_toolbar_button-float",rt.FLEXLAYOUT__DRAG_RECT="flexlayout__drag_rect",rt.FLEXLAYOUT__EDGE_RECT="flexlayout__edge_rect",rt.FLEXLAYOUT__EDGE_RECT_TOP="flexlayout__edge_rect_top",rt.FLEXLAYOUT__EDGE_RECT_LEFT="flexlayout__edge_rect_left",rt.FLEXLAYOUT__EDGE_RECT_BOTTOM="flexlayout__edge_rect_bottom",rt.FLEXLAYOUT__EDGE_RECT_RIGHT="flexlayout__edge_rect_right",rt.FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER="flexlayout__error_boundary_container",rt.FLEXLAYOUT__ERROR_BOUNDARY_CONTENT="flexlayout__error_boundary_content",rt.FLEXLAYOUT__FLOATING_WINDOW_CONTENT="flexlayout__floating_window_content",rt.FLEXLAYOUT__LAYOUT="flexlayout__layout",rt.FLEXLAYOUT__LAYOUT_MOVEABLES="flexlayout__layout_moveables",rt.FLEXLAYOUT__LAYOUT_OVERLAY="flexlayout__layout_overlay",rt.FLEXLAYOUT__LAYOUT_TAB_STAMPS="flexlayout__layout_tab_stamps",rt.FLEXLAYOUT__LAYOUT_MAIN="flexlayout__layout_main",rt.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER="flexlayout__layout_border_container",rt.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER_INNER="flexlayout__layout_border_container_inner",rt.FLEXLAYOUT__OUTLINE_RECT="flexlayout__outline_rect",rt.FLEXLAYOUT__OUTLINE_RECT_EDGE="flexlayout__outline_rect_edge",rt.FLEXLAYOUT__SPLITTER="flexlayout__splitter",rt.FLEXLAYOUT__SPLITTER_EXTRA="flexlayout__splitter_extra",rt.FLEXLAYOUT__SPLITTER_="flexlayout__splitter_",rt.FLEXLAYOUT__SPLITTER_BORDER="flexlayout__splitter_border",rt.FLEXLAYOUT__SPLITTER_DRAG="flexlayout__splitter_drag",rt.FLEXLAYOUT__SPLITTER_HANDLE="flexlayout__splitter_handle",rt.FLEXLAYOUT__SPLITTER_HANDLE_HORZ="flexlayout__splitter_handle_horz",rt.FLEXLAYOUT__SPLITTER_HANDLE_VERT="flexlayout__splitter_handle_vert",rt.FLEXLAYOUT__ROW="flexlayout__row",rt.FLEXLAYOUT__TAB="flexlayout__tab",rt.FLEXLAYOUT__TAB_POSITION="flexlayout__tab_position",rt.FLEXLAYOUT__TAB_MOVEABLE="flexlayout__tab_moveable",rt.FLEXLAYOUT__TAB_OVERLAY="flexlayout__tab_overlay",rt.FLEXLAYOUT__TABSET="flexlayout__tabset",rt.FLEXLAYOUT__TABSET_CONTAINER="flexlayout__tabset_container",rt.FLEXLAYOUT__TABSET_HEADER="flexlayout__tabset_header",rt.FLEXLAYOUT__TABSET_HEADER_CONTENT="flexlayout__tabset_header_content",rt.FLEXLAYOUT__TABSET_MAXIMIZED="flexlayout__tabset-maximized",rt.FLEXLAYOUT__TABSET_SELECTED="flexlayout__tabset-selected",rt.FLEXLAYOUT__TABSET_TAB_DIVIDER="flexlayout__tabset_tab_divider",rt.FLEXLAYOUT__TABSET_CONTENT="flexlayout__tabset_content",rt.FLEXLAYOUT__TABSET_TABBAR_INNER="flexlayout__tabset_tabbar_inner",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_="flexlayout__tabset_tabbar_inner_",rt.FLEXLAYOUT__TABSET_LEADING="flexlayout__tabset_leading",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER="flexlayout__tabset_tabbar_inner_tab_container",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_="flexlayout__tabset_tabbar_inner_tab_container_",rt.FLEXLAYOUT__TABSET_TABBAR_OUTER="flexlayout__tabset_tabbar_outer",rt.FLEXLAYOUT__TABSET_TABBAR_OUTER_="flexlayout__tabset_tabbar_outer_",rt.FLEXLAYOUT__TAB_BORDER="flexlayout__tab_border",rt.FLEXLAYOUT__TAB_BORDER_="flexlayout__tab_border_",rt.FLEXLAYOUT__TAB_BUTTON="flexlayout__tab_button",rt.FLEXLAYOUT__TAB_BUTTON_STRETCH="flexlayout__tab_button_stretch",rt.FLEXLAYOUT__TAB_BUTTON_CONTENT="flexlayout__tab_button_content",rt.FLEXLAYOUT__TAB_BUTTON_LEADING="flexlayout__tab_button_leading",rt.FLEXLAYOUT__TAB_BUTTON_OVERFLOW="flexlayout__tab_button_overflow",rt.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT="flexlayout__tab_button_overflow_count",rt.FLEXLAYOUT__TAB_BUTTON_TEXTBOX="flexlayout__tab_button_textbox",rt.FLEXLAYOUT__TAB_BUTTON_TRAILING="flexlayout__tab_button_trailing",rt.FLEXLAYOUT__TAB_BUTTON_STAMP="flexlayout__tab_button_stamp",rt.FLEXLAYOUT__TAB_TOOLBAR="flexlayout__tab_toolbar",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON="flexlayout__tab_toolbar_button",rt.FLEXLAYOUT__TAB_TOOLBAR_ICON="flexlayout__tab_toolbar_icon",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_="flexlayout__tab_toolbar_button-",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT="flexlayout__tab_toolbar_button-float",rt.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER="flexlayout__tab_toolbar_sticky_buttons_container",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE="flexlayout__tab_toolbar_button-close",rt.FLEXLAYOUT__POPUP_MENU_CONTAINER="flexlayout__popup_menu_container",rt.FLEXLAYOUT__POPUP_MENU_ITEM="flexlayout__popup_menu_item",rt.FLEXLAYOUT__POPUP_MENU_ITEM__SELECTED="flexlayout__popup_menu_item--selected",rt.FLEXLAYOUT__POPUP_MENU="flexlayout__popup_menu",rt.FLEXLAYOUT__MINI_SCROLLBAR="flexlayout__mini_scrollbar",rt.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER="flexlayout__mini_scrollbar_container",rt))(CLASSES||{});class Action{constructor(_e,tt){__publicField(this,"type"),__publicField(this,"data"),this.type=_e,this.data=tt}}const _Actions=class sr{static addNode(_e,tt,et,nt,it){return new Action(sr.ADD_NODE,{json:_e,toNode:tt,location:et.getName(),index:nt,select:it})}static moveNode(_e,tt,et,nt,it){return new Action(sr.MOVE_NODE,{fromNode:_e,toNode:tt,location:et.getName(),index:nt,select:it})}static deleteTab(_e){return new Action(sr.DELETE_TAB,{node:_e})}static deleteTabset(_e){return new Action(sr.DELETE_TABSET,{node:_e})}static renameTab(_e,tt){return new Action(sr.RENAME_TAB,{node:_e,text:tt})}static selectTab(_e){return new Action(sr.SELECT_TAB,{tabNode:_e})}static setActiveTabset(_e,tt){return new Action(sr.SET_ACTIVE_TABSET,{tabsetNode:_e,windowId:tt})}static adjustWeights(_e,tt){return new Action(sr.ADJUST_WEIGHTS,{nodeId:_e,weights:tt})}static adjustBorderSplit(_e,tt){return new Action(sr.ADJUST_BORDER_SPLIT,{node:_e,pos:tt})}static maximizeToggle(_e,tt){return new Action(sr.MAXIMIZE_TOGGLE,{node:_e,windowId:tt})}static updateModelAttributes(_e){return new Action(sr.UPDATE_MODEL_ATTRIBUTES,{json:_e})}static updateNodeAttributes(_e,tt){return new Action(sr.UPDATE_NODE_ATTRIBUTES,{node:_e,json:tt})}static popoutTab(_e){return new Action(sr.POPOUT_TAB,{node:_e})}static popoutTabset(_e){return new Action(sr.POPOUT_TABSET,{node:_e})}static closeWindow(_e){return new Action(sr.CLOSE_WINDOW,{windowId:_e})}static createWindow(_e,tt){return new Action(sr.CREATE_WINDOW,{layout:_e,rect:tt})}};__publicField(_Actions,"ADD_NODE","FlexLayout_AddNode");__publicField(_Actions,"MOVE_NODE","FlexLayout_MoveNode");__publicField(_Actions,"DELETE_TAB","FlexLayout_DeleteTab");__publicField(_Actions,"DELETE_TABSET","FlexLayout_DeleteTabset");__publicField(_Actions,"RENAME_TAB","FlexLayout_RenameTab");__publicField(_Actions,"SELECT_TAB","FlexLayout_SelectTab");__publicField(_Actions,"SET_ACTIVE_TABSET","FlexLayout_SetActiveTabset");__publicField(_Actions,"ADJUST_WEIGHTS","FlexLayout_AdjustWeights");__publicField(_Actions,"ADJUST_BORDER_SPLIT","FlexLayout_AdjustBorderSplit");__publicField(_Actions,"MAXIMIZE_TOGGLE","FlexLayout_MaximizeToggle");__publicField(_Actions,"UPDATE_MODEL_ATTRIBUTES","FlexLayout_UpdateModelAttributes");__publicField(_Actions,"UPDATE_NODE_ATTRIBUTES","FlexLayout_UpdateNodeAttributes");__publicField(_Actions,"POPOUT_TAB","FlexLayout_PopoutTab");__publicField(_Actions,"POPOUT_TABSET","FlexLayout_PopoutTabset");__publicField(_Actions,"CLOSE_WINDOW","FlexLayout_CloseWindow");__publicField(_Actions,"CREATE_WINDOW","FlexLayout_CreateWindow");let Actions=_Actions;class Attribute{constructor(_e,tt,et,nt){__publicField(this,"name"),__publicField(this,"alias"),__publicField(this,"modelName"),__publicField(this,"pairedAttr"),__publicField(this,"pairedType"),__publicField(this,"defaultValue"),__publicField(this,"alwaysWriteJson"),__publicField(this,"type"),__publicField(this,"required"),__publicField(this,"fixed"),__publicField(this,"description"),this.name=_e,this.alias=void 0,this.modelName=tt,this.defaultValue=et,this.alwaysWriteJson=nt,this.required=!1,this.fixed=!1,this.type="any"}setType(_e){return this.type=_e,this}setAlias(_e){return this.alias=_e,this}setDescription(_e){this.description=_e}setRequired(){return this.required=!0,this}setFixed(){return this.fixed=!0,this}setpairedAttr(_e){this.pairedAttr=_e}setPairedType(_e){this.pairedType=_e}}__publicField(Attribute,"NUMBER","number");__publicField(Attribute,"STRING","string");__publicField(Attribute,"BOOLEAN","boolean");class AttributeDefinitions{constructor(){__publicField(this,"attributes"),__publicField(this,"nameToAttribute"),this.attributes=[],this.nameToAttribute=new Map}addWithAll(_e,tt,et,nt){const it=new Attribute(_e,tt,et,nt);return this.attributes.push(it),this.nameToAttribute.set(_e,it),it}addInherited(_e,tt){return this.addWithAll(_e,tt,void 0,!1)}add(_e,tt,et){return this.addWithAll(_e,void 0,tt,et)}getAttributes(){return this.attributes}getModelName(_e){const tt=this.nameToAttribute.get(_e);if(tt!==void 0)return tt.modelName}toJson(_e,tt){for(const et of this.attributes){const nt=tt[et.name];(et.alwaysWriteJson||nt!==et.defaultValue)&&(_e[et.name]=nt)}}fromJson(_e,tt){for(const et of this.attributes){let nt=_e[et.name];nt===void 0&&et.alias&&(nt=_e[et.alias]),nt===void 0?tt[et.name]=et.defaultValue:tt[et.name]=nt}}update(_e,tt){for(const et of this.attributes)if(Object.prototype.hasOwnProperty.call(_e,et.name)){const nt=_e[et.name];nt===void 0?delete tt[et.name]:tt[et.name]=nt}}setDefaults(_e){for(const tt of this.attributes)_e[tt.name]=tt.defaultValue}pairAttributes(_e,tt){for(const et of tt.attributes)if(et.modelName&&this.nameToAttribute.has(et.modelName)){const nt=this.nameToAttribute.get(et.modelName);nt.setpairedAttr(et),et.setpairedAttr(nt),nt.setPairedType(_e)}}toTypescriptInterface(_e,tt){var et,nt;const it=[],at=this.attributes.sort((ot,st)=>ot.name.localeCompare(st.name));it.push("export interface I"+_e+"Attributes {");for(let ot=0;ot<at.length;ot++){const st=at[ot];let ct=st.type,dt,ut=st,ht;ut.defaultValue!==void 0?dt=ut.defaultValue:ut.modelName!==void 0&&tt!==void 0&&tt.nameToAttribute.get(ut.modelName)!==void 0&&(ht=ut.modelName,ut=tt.nameToAttribute.get(ht),dt=ut.defaultValue,ct=ut.type);const ft=JSON.stringify(dt),pt=ut.required?"":"?";let mt=` /**
|
|
29228
|
+
Possible causes: ComponentFactory not injected, component type not registered, or projection apply failed.`)}else mt=this.engineObject.addComponent(EditorComponent.getEngineComponent(it));if(St){vt&&(St.id=vt),et!==void 0?this._components.splice(et,0,St):this._components.push(St),(ht=St.onAddToEntity)==null||ht.call(St,this),await St.bindEngineObject(mt),this.root.viewportStore.onComponentAdd(St);const{EditorScene:At}=await __vitePreload(()=>Promise.resolve().then(()=>EditorScene$1),void 0);return this.entityManager instanceof At&&MessageCenter.dispatch("ComponentAddToScene",St),St}}return null}removeComponent(tt){let et;if(typeof tt!="number"?et=this.components.indexOf(tt):et=tt,et===-1)return;const nt=this.components[et];EditorComponent.removeCheck(this,nt)&&(nt.isPrefabComponent?this._removePrefabComponent(nt):this._removeSelfComponent(et),this.root.projectStore.debouncedUpdateSceneAsset())}setComponentIndex(tt,et){const nt=this._components,it=nt.indexOf(tt);it===-1||it===et||(nt.splice(it,1),nt.splice(et,0,tt),this.root.projectStore.debouncedUpdateSceneAsset())}_removeSelfComponent(tt){var it;const et=this.components[tt];et.destroy(!0),tt>=this._components.length?(it=this.strippedEntity)==null||it._components.splice(tt-this._components.length,1):this._components.splice(tt,1);const nt=EditorComponent.getRegisteredComponent(et.type);nt&&nt.external&&nt.refMap.delete(this.id)}addComponentFromDomain(tt,et){var ct,dt,ut,ht,ft,pt;if(this.components.find(mt=>mt.id===tt))return;const nt={type:et.type,...et.refId?{script:{$ref:et.refId,...et.scriptKey?{key:et.scriptKey}:{}}}:{},...et.props?{props:et.props}:{},...(ct=et.calls)!=null&&ct.length?{calls:et.calls}:{}},it=EditorComponent.createComponentModel(nt,this);if(!it)return;if(et.props){const mt=(dt=getComponentSemantics(et.type))==null?void 0:dt.methodKeys;if(mt)for(const vt of mt)vt in et.props&&(it[vt]=toJS(et.props[vt]))}traceLog("EntityModel",`[AddCompFromDomain] created ${et.type} for entity ${this.name}`),it.id=tt,this._components.push(it),(ut=it.onAddToEntity)==null||ut.call(it,this);const at=(ht=this.root.engineProjection)==null?void 0:ht.getComponent(tt),ot=!at&&et.type==="Transform"&&!!((ft=this.engineObject)!=null&&ft.transform),st=at??(ot?(pt=this.engineObject)==null?void 0:pt.transform:void 0);st&&(ot?it.bindEngineObject(st,{ownsEngineObject:!1}):it.bindEngineObject(st)).then(()=>{var vt,_t;traceLog("EntityModel",`[AddCompFromDomain] bound ${et.type} engineComp, material: ${(_t=(vt=st==null?void 0:st.getMaterial)==null?void 0:vt.call(st,0))==null?void 0:_t.name}`),it.ownsEngineObject!==!1&&this.root.viewportStore.onComponentAdd(it)})}removeComponentFromDomain(tt){removeComponentFromDomain({components:this.components,removeSelfComponent:et=>this._removeSelfComponent(et)},tt)}syncRemovedComponentPlaceholdersFromDomain(){var nt;const tt=this._collectRemovedComponentPlaceholdersFromDomain(),et=new Set(tt.map(it=>it.id));for(let it=this._components.length-1;it>=0;it--){const at=this._components[it];at.removedComponentMeta&&(et.has(at.id)||this._components.splice(it,1))}for(const it of tt){const at=this._components.find(st=>st.id===it.id);if(at){at.removedComponentMeta=it.meta,at.removedComponent=!0;continue}const ot=EditorComponent.createComponentModel(it.schema,this);if(!ot)throw new Error(`Cannot materialize removed prefab component placeholder "${it.meta.componentType}" on entity "${this.id}"`);ot.id=it.id,EditorComponent.convertToPrefabComponent(ot),ot.removeByPrefab(it.meta),(nt=ot.onAddToEntity)==null||nt.call(ot,this),this._components.splice(Math.min(it.meta.componentIndex,this._components.length),0,ot)}}_collectRemovedComponentPlaceholdersFromDomain(){var at,ot;const tt=this.root.domainStore.getNormalizedState();if(!tt.entities[this.id])return[];const nt=new Set(tt.relations.entityComponents[this.id]??[]),it=[];for(const st of Object.values(tt.prefab.bindings??{}))for(const[ct,dt]of Object.entries(st.overrides.removedComponents??{})){if((at=st.overrides.removedEntities)!=null&&at[ct]||getSceneEntityIdForPrefabSource(st,ct)!==this.id)continue;const ht=(ot=st.sourceEntitySnapshots)==null?void 0:ot[ct];if(!ht)throw new Error(`Cannot materialize removed prefab component placeholders: binding "${st.id}" is missing source snapshot "${ct}"`);const ft=Object.keys(ht.components??{});for(const[pt,mt]of Object.entries(dt??{})){if(!mt)continue;const vt=ht.components[pt];if(!vt)throw new Error(`Cannot materialize removed prefab component placeholder: source component "${pt}" not found in binding "${st.id}"`);if(nt.has(vt.sceneComponentId))continue;const _t=Math.max(ft.indexOf(pt),0);it.push({id:this._removedComponentPlaceholderId(st.id,ct,pt),schema:{type:vt.type,props:cloneDeep$1(vt.props)},meta:{bindingId:st.id,sourceEntityId:ct,sourceComponentKey:pt,sceneComponentId:vt.sceneComponentId,componentType:vt.type,componentIndex:_t}})}}return it.sort((st,ct)=>st.meta.componentIndex-ct.meta.componentIndex)}_removedComponentPlaceholderId(tt,et,nt){return`removed:${tt}:${et}:${nt}`}getComponent(tt){return this.components[tt]}getComponentById(tt){for(let et=0;et<this.components.length;et++)if(this.components[et].id===tt)return this.components[et];return null}getComponentByTypeName(tt){for(let et=0;et<this.components.length;et++){const nt=this.components[et];if(!nt.removedComponent&&nt.type===tt)return nt}return null}getComponentsByTypeName(tt,et=[]){for(let nt=0;nt<this.components.length;nt++){const it=this.components[nt];!it.removedComponent&&it.type===tt&&et.push(it)}return et}getComponentsIncludeChildren(tt,et=[]){this.getComponentsByTypeName(tt,et);for(let nt=0;nt<this.children.length;nt++)this.children[nt].getComponentsIncludeChildren(tt,et);return et}cloneVector3(tt,et){tt.x=et.x,tt.y=et.y,tt.z=et.z}checkIsAssetRef(tt){return hasEntitySchemaInstanceLink(tt)}addComponent(tt){return this.addEditorComponent({class:tt},!0)}getComponents(){return this._components}makeEntityCanPick(){EditorPicker.makeEntityCanPick(this)}get isRoot(){return this.parent===DEFAULT_SCENE||!this.parent}removeFromParent(){this.root.entityFacade.moveEntity(this.id,null)}addChild(tt,et){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.addChild(tt,et);this._addSelfChild(tt,et)}_addSelfChild(tt,et){const{id:nt}=tt;this._childrenId.includes(nt)||(et!==void 0?(this._childrenId.splice(et,0,nt),tt.onReady().then(()=>{var st;if(tt.status!=="ready")return;const it=this.root.domainStore.getNormalizedState(),at=!!it.entities[this.id],ot=!!it.entities[nt];at&&ot?(st=this.root.engineProjection)==null||st.addEntityChild(this.id,nt,et):this.engineObject.addChild(et,tt.engineObject)})):(this._childrenId.push(nt),tt.onReady().then(()=>{var st;if(tt.status!=="ready")return;const it=this.root.domainStore.getNormalizedState(),at=!!it.entities[this.id],ot=!!it.entities[nt];at&&ot?(st=this.root.engineProjection)==null||st.addEntityChild(this.id,nt):this.engineObject.addChild(tt.engineObject)})),tt.parent=this.id)}addChildren(tt,et){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.addChildren(tt,et);const nt=tt.map(it=>it.id);et!==void 0?(this._childrenId.splice(et,0,...nt),tt.forEach((it,at)=>it.onReady().then(()=>{var dt;if(it.status!=="ready")return;const ot=this.root.domainStore.getNormalizedState(),st=!!ot.entities[this.id],ct=!!ot.entities[it.id];st&&ct?(dt=this.root.engineProjection)==null||dt.addEntityChild(this.id,it.id,et+at):this.engineObject.addChild(et+at,it.engineObject)}))):(this._childrenId.push(...nt),tt.forEach(it=>{it.onReady().then(()=>{var ct;if(it.status!=="ready")return;const at=this.root.domainStore.getNormalizedState(),ot=!!at.entities[this.id],st=!!at.entities[it.id];ot&&st?(ct=this.root.engineProjection)==null||ct.addEntityChild(this.id,it.id):this.engineObject.addChild(it.engineObject)})})),tt.forEach(it=>it.parent=this.id)}resetParent(){if(this.root.domainStore.getNormalizedState().entities[this.id]){this.root.entityFacade.moveEntity(this.id,null);return}this.parent=null,this.engineObject.parent=null}setParent(tt){this.parent=tt}removeChildById(tt,et=!0){if(this.isPrefabRefEntity&&this.strippedEntity)return this.strippedEntity.removeChildById(tt,et);this._removeSelfChild(tt,et)}_removeSelfChild(tt,et=!0){const nt=this.entityManager.entities.get(tt);this._childrenId=this._childrenId.filter(it=>it!==tt),et&&nt.destroy(!0)}toJSON(tt=!1){var it,at;const et={},nt=this.isGLTFRefEntity||!tt&&this.isPrefabRefEntity;if(this.isStrippedEntity){const{prefabInstanceId:ot,prefabSource:st}=this.originalEntity._getPrefabInfo();et.strippedId=this.id,et.prefabInstanceId=ot,et.prefabSource=st}else{const ot=this.parentEntity;if(et.id=this.id,et.name=this.name,et.isActive=this.isActive,et.layer=combineLayersByBitwise(this.layer),!this.isPrefabRefEntity||tt){const st=(it=this.transform)==null?void 0:it.toJSON();st&&(et.transform={class:st.type,props:st.props??{}})}et.parent=(ot==null?void 0:ot.id)??null,ot!=null&&ot.isPrefabRefEntity&&(ot.isGLTFRefEntity||!tt)&&(et.parent=ot._strippedEntityId)}if(nt){et.children=[],et.components=[];const ot=resolveEntityInstanceRef({instance:(at=this._domainEntity)==null?void 0:at.instance});ot&&(et.instance={...ot},et.isClone=!0,this.assetTemplateDiffs&&(et.assetTemplateDiffs=this.assetTemplateDiffs))}else{const st=this.childrenId.filter(ct=>this.entityManager.entities.get(ct)&&this.entityManager.entities.get(ct)._engineObject);Object.assign(et,{children:st,components:this.components.filter(ct=>!ct.ignoreToJSON).map(ct=>{const dt=ct.toJSON();return{id:ct.id,class:dt.type,props:dt.props}})})}return et}toV2(tt,et=!1){var ct;const nt={id:this.id},it=resolveEntityInstanceSemantics({instance:((ct=this._domainEntity)==null?void 0:ct.instance)??this.pendingInstance}),at=it.role==="added",st=it.assetKind==="glTF"&&it.role!=="linked"&&!at||!et&&this.isPrefabRefEntity&&!at;if(!st){this.name&&(nt.name=this.name),this.isActive||(nt.isActive=!1),this.isLocked&&(nt.isLocked=!0);const dt=combineLayersByBitwise(this.layer);dt!==0&&(nt.layer=dt)}if((!st||et)&&Ur._writeTransformTuples(nt,this._getSerializableTransform()),!st){const ut=this.childrenId.filter(ht=>tt.hasEntityId(ht));ut.length&&(nt.children=ut)}if(!st){const dt=this.components.filter(ut=>!ut.ignoreToJSON).map(ut=>tt.registerComponent(ut));dt.length&&(nt.components=dt)}if(st){const dt=this._serializeInstanceSchema(tt,{includeContainingBinding:et});dt&&(nt.instance=dt)}return nt}_serializeInstanceSchema(tt,et={}){var ht,ft;const nt=((ht=this._domainEntity)==null?void 0:ht.instance)??this.pendingInstance,it=resolveEntityInstanceRef({instance:nt});if(!it)return;let at=this._collectInstanceOverrides(tt);const ot=nt!=null&&nt.bindingId?this.root.domainStore.state.prefab.bindings[nt.bindingId]:void 0,st=et.containingBinding??(et.includeContainingBinding&&ot?(ft=this._findContainingPrefabBindingForInstance(ot))==null?void 0:ft.binding:void 0),ct=ot?this._collectContainingAddedEntitiesForInstance(st,ot,this.id,tt):[];ct.length>0&&(at={...at??{},addedEntities:[...(at==null?void 0:at.addedEntities)??[],...ct]});const dt=this._collectInstanceRootEntityProps();if(dt){const pt=(at==null?void 0:at.entityProps)??{},mt=this._requireSerializableInstanceRootOverrideTarget(nt,ot);at={...at??{},entityProps:{...pt,[mt]:{...dt,...pt[mt]??{}}}}}const ut={asset:{$ref:tt.resolveVirtualPath(it.assetId),...nt!=null&&nt.assetKey?{key:nt.assetKey}:{}}};return at&&(ut.overrides=bundleInstanceOverrides(at)),ut}_resolveSerializableInstanceRootOverrideTarget(tt,et){return(et==null?void 0:et.sourceRootEntityId)??(tt==null?void 0:tt.sourceEntityId)??((tt==null?void 0:tt.assetKind)==="glTF"?"root":void 0)}_requireSerializableInstanceRootOverrideTarget(tt,et){const nt=this._resolveSerializableInstanceRootOverrideTarget(tt,et);if(nt)return nt;throw new Error(`Cannot serialize instance root override for entity "${this.id}": missing source root entity id for asset "${(tt==null?void 0:tt.assetId)??"<unknown>"}"`)}_collectInstanceRootEntityProps(){const tt={};this.name&&(tt.name=this.name),this.isActive||(tt.isActive=!1);const et=combineLayersByBitwise(this.layer);return et!==0&&(tt.layer=et),Object.keys(tt).length>0?tt:void 0}_collectInstanceOverrides(tt){var at,ot,st;const et={};let nt=!1;if((at=this.assetTemplateDiffs)!=null&&at.entityProps){const ct={};for(const[dt,ut]of Object.entries(this.assetTemplateDiffs.entityProps)){const ht={};if(ut.name!==void 0&&(ht.name=ut.name),ut.isActive!==void 0&&(ht.isActive=ut.isActive),ut.layer!==void 0&&(ht.layer=ut.layer),ut.transform){const ft=ut.transform;ft.position&&(ht.position=[ft.position.x,ft.position.y,ft.position.z]),ft.rotation&&(ht.rotation=[ft.rotation.x,ft.rotation.y,ft.rotation.z]),ft.scale&&(ht.scale=[ft.scale.x,ft.scale.y,ft.scale.z])}ct[dt]=ht}Object.keys(ct).length&&(et.entityProps=ct,nt=!0)}const it=(st=(ot=this._domainEntity)==null?void 0:ot.instance)==null?void 0:st.bindingId;if(it){const ct=this.root.domainStore.state.prefab.bindings[it];if(ct){const dt=collectEntityPropsFromBinding(ct);Object.keys(dt).length>0&&(et.entityProps={...et.entityProps??{},...dt},nt=!0);const ut=collectComponentPropsFromBinding(ct,(vt,{sourceEntityId:_t,sourceComponentKey:yt})=>{var Et,St,At,xt,Ct,Pt,Tt,wt;const bt=this._findLiveComponentFromBinding(ct,_t,yt);if(!bt){const It=ct.sourceToSceneEntity[_t],Ot=(xt=(At=(St=(Et=ct.sourceEntitySnapshots)==null?void 0:Et[_t])==null?void 0:St.components)==null?void 0:At[yt])==null?void 0:xt.sceneComponentId;throw new Error(`Prefab binding "${ct.id}" componentProps override "${yt}" on source entity "${_t}" cannot be serialized without live component "${Ot??yt}" on scene entity "${It??"<missing>"}"`)}return this._serializeLiveComponentPropsOverride(bt,vt,tt,(wt=(Tt=(Pt=(Ct=ct.sourceEntitySnapshots)==null?void 0:Ct[_t])==null?void 0:Pt.components)==null?void 0:Tt[yt])==null?void 0:wt.props)});Object.keys(ut).length>0&&(et.componentProps=ut,nt=!0);const ht=this._collectAddedEntitiesFromBinding(ct,tt);ht.length>0&&(et.addedEntities=ht,nt=!0);const ft=this._collectAddedComponentsFromBinding(ct,tt);ft.length>0&&(et.addedComponents=ft,nt=!0);const pt=this._collectRemovedEntitiesFromBinding(ct);pt.length>0&&(et.removedEntities=pt,nt=!0);const mt=this._collectRemovedComponentsFromBinding(ct);Object.keys(mt).length>0&&(et.removedComponents=mt,nt=!0)}}return nt?et:void 0}_collectAddedEntitiesFromBinding(tt,et){const nt=Object.values(tt.overrides.addedEntities??{}).filter(at=>!sourceEntityIsCoveredByRemovedEntity(tt,at.parentSourceEntityId)).flatMap(at=>{var ot;if(!((ot=tt.sourceEntitySnapshots)!=null&&ot[at.parentSourceEntityId])){if(this._isAddedEntityNestedUnderInstanceSourceParent(tt,at.entityId,at.parentSourceEntityId))return[];throw new Error(`Prefab binding "${tt.id}" added entity "${at.entityId}" has an unresolved source parent "${at.parentSourceEntityId}"`)}return[{entry:at,parentSourceEntityId:at.parentSourceEntityId}]}).sort((at,ot)=>{const st=at.parentSourceEntityId.localeCompare(ot.parentSourceEntityId);return st!==0?st:at.entry.index!==ot.entry.index?at.entry.index-ot.entry.index:at.entry.entityId.localeCompare(ot.entry.entityId)}),it=[];for(const{entry:at,parentSourceEntityId:ot}of nt){const st=this.entityManager.entities.get(at.entityId),ct=this.root.domainStore.state.entities[at.entityId];!st&&!ct||it.push({id:at.entityId,parent:ot,entity:st?this._serializeEntityInline(st,et,tt):this._serializeDomainEntityInline(tt,at.entityId,et)})}return it}_isAddedEntityNestedUnderInstanceSourceParent(tt,et,nt){var ot,st,ct;const it=this.root.domainStore.state;let at=((ot=it.entities[et])==null?void 0:ot.parentId)??null;for(;at;){if(tt.overrides.addedEntities[at]){const dt=it.entities[at],ut=(st=dt==null?void 0:dt.instance)==null?void 0:st.bindingId,ht=ut?it.prefab.bindings[ut]:void 0;if(ht&&ht.id!==tt.id&&sourceEntityIdToPath(ht,nt)!==null)return!0}at=((ct=it.entities[at])==null?void 0:ct.parentId)??null}return!1}_collectContainingAddedEntitiesForInstance(tt,et,nt,it){if(!tt||tt.id===et.id)return[];const at=[],ot=Object.values(tt.overrides.addedEntities??{}).filter(st=>st.entityId!==nt).filter(st=>this._isNormalizedAncestorOrSelf(nt,st.entityId)).flatMap(st=>{var ct;return(ct=et.sourceEntitySnapshots)!=null&&ct[st.parentSourceEntityId]?[{entry:st,parentSourceEntityId:st.parentSourceEntityId}]:[]}).sort((st,ct)=>{const dt=st.parentSourceEntityId.localeCompare(ct.parentSourceEntityId);return dt!==0?dt:st.entry.index!==ct.entry.index?st.entry.index-ct.entry.index:st.entry.entityId.localeCompare(ct.entry.entityId)});for(const{entry:st,parentSourceEntityId:ct}of ot){const dt=this.entityManager.entities.get(st.entityId),ut=this.root.domainStore.state.entities[st.entityId];!dt&&!ut||at.push({id:st.entityId,parent:ct,entity:dt?this._serializeEntityInline(dt,it,tt):this._serializeDomainEntityInline(tt,st.entityId,it)})}return at}_collectDomainInstanceOverrides(tt,et){const nt={};let it=!1;const at=collectEntityPropsFromBinding(tt);Object.keys(at).length>0&&(nt.entityProps=at,it=!0);const ot=collectComponentPropsFromBinding(tt,ht=>et.convertRefs(ht));Object.keys(ot).length>0&&(nt.componentProps=ot,it=!0);const st=this._collectAddedEntitiesFromBinding(tt,et);st.length>0&&(nt.addedEntities=st,it=!0);const ct=this._collectDomainAddedComponentsFromBinding(tt,et);ct.length>0&&(nt.addedComponents=ct,it=!0);const dt=this._collectRemovedEntitiesFromBinding(tt);dt.length>0&&(nt.removedEntities=dt,it=!0);const ut=this._collectRemovedComponentsFromBinding(tt);return Object.keys(ut).length>0&&(nt.removedComponents=ut,it=!0),it?nt:void 0}_collectRemovedEntitiesFromBinding(tt){return Object.keys(tt.overrides.removedEntities??{}).filter(et=>!sourceEntityIsCoveredByAnotherRemovedEntity(tt,et))}_collectRemovedComponentsFromBinding(tt){const et={},nt=tt.sourceEntitySnapshots??{};for(const[it,at]of Object.entries(tt.overrides.removedComponents??{})){if(sourceEntityIsCoveredByRemovedEntity(tt,it))continue;const ot=nt[it];if(!ot)throw new Error(`Prefab binding "${tt.id}" removed component target "${it}" cannot be encoded without a source snapshot`);const st=Object.keys(at).filter(ct=>!!ot.components[ct]).sort();st.length>0&&(et[it]=st)}return et}_collectAddedComponentsFromBinding(tt,et){var at;const nt=Object.entries(tt.overrides.addedComponents??{}).flatMap(([ot,st])=>{var ct;if(sourceEntityIsCoveredByRemovedEntity(tt,ot))return[];if(!((ct=tt.sourceEntitySnapshots)!=null&&ct[ot]))throw new Error(`Prefab binding "${tt.id}" added component target "${ot}" cannot be encoded without a source snapshot`);return Object.keys(st).map(dt=>({sourceEntityId:ot,componentId:dt}))}).sort((ot,st)=>{const ct=ot.sourceEntityId.localeCompare(st.sourceEntityId);return ct!==0?ct:ot.componentId.localeCompare(st.componentId)}),it=[];for(const{sourceEntityId:ot,componentId:st}of nt){const ct=tt.sourceToSceneEntity[ot],dt=this._findLiveComponentBySceneComponentId(ct,st),ut=ct?(at=this.root.domainStore.state.entities[ct])==null?void 0:at.components[st]:void 0;if(!(!dt&&!ut)){if(!dt)throw new Error(`Prefab binding "${tt.id}" added component "${st}" on source entity "${ot}" cannot be serialized without live component`);it.push({id:st,owner:ot,component:et.serializeComponent(dt)})}}return it}_collectDomainAddedComponentsFromBinding(tt,et){var at;const nt=Object.entries(tt.overrides.addedComponents??{}).flatMap(([ot,st])=>{var ct;if(sourceEntityIsCoveredByRemovedEntity(tt,ot))return[];if(!((ct=tt.sourceEntitySnapshots)!=null&&ct[ot]))throw new Error(`Prefab binding "${tt.id}" added component target "${ot}" cannot be encoded without a source snapshot`);return Object.keys(st).map(dt=>({sourceEntityId:ot,componentId:dt}))}).sort((ot,st)=>{const ct=ot.sourceEntityId.localeCompare(st.sourceEntityId);return ct!==0?ct:ot.componentId.localeCompare(st.componentId)}),it=[];for(const{sourceEntityId:ot,componentId:st}of nt){const ct=tt.sourceToSceneEntity[ot],dt=ct?(at=this.root.domainStore.state.entities[ct])==null?void 0:at.components[st]:void 0;dt&&it.push({id:st,owner:ot,component:Ur._domainComponentToV2(dt,et)})}return it}_findLiveComponentFromBinding(tt,et,nt){var ot,st,ct,dt;const it=tt.sourceToSceneEntity[et],at=(dt=(ct=(st=(ot=tt.sourceEntitySnapshots)==null?void 0:ot[et])==null?void 0:st.components)==null?void 0:ct[nt])==null?void 0:dt.sceneComponentId;return this._findLiveComponentBySceneComponentId(it,at)}_findLiveComponentBySceneComponentId(tt,et){var it;if(!tt||!et)return;const nt=(it=this.entityManager.entities.get(tt))==null?void 0:it._components.find(at=>at.id===et);return nt&&typeof nt.toJSON=="function"?nt:void 0}_serializeLiveComponentPropsOverride(tt,et,nt,it){const at={};for(const ct of Object.keys(et))at[ct]=it==null?void 0:it[ct];const ot=readComponentSourcePropsWithEditorValues(tt,at,ct=>nt.serializeComponent(ct)),st=readComponentSourceProps(tt,ct=>nt.serializeComponent(ct));return diffSourceValueRecord(ot,st)}_getSerializableTransform(){var tt;return((tt=this._domainEntity)==null?void 0:tt.transform)??this.transform}static _writeTransformTuples(tt,et){if(!et)return;const nt=et.position;(nt.x!==0||nt.y!==0||nt.z!==0)&&(tt.position=[nt.x,nt.y,nt.z]);const it=et.rotation;(it.x!==0||it.y!==0||it.z!==0)&&(tt.rotation=[it.x,it.y,it.z]);const at=et.scale;(at.x!==1||at.y!==1||at.z!==1)&&(tt.scale=[at.x,at.y,at.z])}_serializeEntityInline(tt,et,nt){var dt;const it=resolveEntityInstanceSemantics({instance:((dt=tt._domainEntity)==null?void 0:dt.instance)??tt.pendingInstance});if(it.assetId&&it.role!=="added"){const ut=tt._serializeInstanceSchema(et,{containingBinding:nt});if(ut)return{instance:ut}}const at={};tt.name&&(at.name=tt.name),tt.isActive||(at.isActive=!1);const ot=combineLayersByBitwise(tt.layer);ot!==0&&(at.layer=ot),Ur._writeTransformTuples(at,tt._getSerializableTransform());const st=tt._components.filter(ut=>!ut.ignoreToJSON).map(ut=>et.serializeComponent(ut));st.length&&(at.components=st);const ct=tt.children.map(ut=>this._serializeEntityInline(ut,et,nt));return ct.length&&(at.children=ct),at}_serializeDomainEntityInline(tt,et,nt,it=new Set){if(it.has(et))throw new Error(`Prefab binding "${tt.id}" added entity "${et}" contains a cyclic child reference`);const at=this.root.domainStore.state.entities[et];if(!at)throw new Error(`Prefab binding "${tt.id}" added entity "${et}" is missing from DomainStore`);it.add(et);const ot=this._serializeDomainInstanceInline(tt,at,nt);if(ot)return ot;const st=Ur._domainEntityToInlineSchema(at,nt),ct=at.children.map(dt=>this._serializeDomainEntityInline(tt,dt,nt,new Set(it)));return ct.length&&(st.children=ct),st}_serializeDomainInstanceInline(tt,et,nt){var dt;if(!((dt=et.instance)!=null&&dt.assetId)||et.instance.role==="added")return;const it={instance:{asset:{$ref:nt.resolveVirtualPath(et.instance.assetId),...et.instance.assetKey?{key:et.instance.assetKey}:{}}}},at=et.instance.bindingId?this.root.domainStore.state.prefab.bindings[et.instance.bindingId]:void 0,ot=at?this._collectDomainInstanceOverrides(at,nt):void 0,st=at?this._collectContainingAddedEntitiesForInstance(tt,at,et.id,nt):[],ct=st.length>0?{...ot??{},addedEntities:[...(ot==null?void 0:ot.addedEntities)??[],...st]}:ot;return ct&&(it.instance.overrides=bundleInstanceOverrides(ct)),it}static _domainEntityToInlineSchema(tt,et){const nt={};tt.name&&(nt.name=tt.name),tt.isActive||(nt.isActive=!1),tt.layer!==void 0&&tt.layer!==0&&(nt.layer=tt.layer),Ur._writeTransformTuples(nt,tt.transform);const it=Object.values(tt.components).map(at=>Ur._domainComponentToV2(at,et));return it.length&&(nt.components=it),nt}static _domainComponentToV2(tt,et){var at;const nt={type:tt.type},it=et.convertRefs(tt.props??{});return it&&typeof it=="object"&&!Array.isArray(it)&&Object.keys(it).length>0&&(nt.props=it),tt.refId&&(nt.script={$ref:et.resolveVirtualPath(tt.refId),...tt.scriptKey?{key:tt.scriptKey}:{}}),(at=tt.calls)!=null&&at.length&&(nt.calls=et.convertRefs(tt.calls)),nt}getEditable(tt){return!0}findChildByName(tt){return this.entityManager.findChildByName(this,tt)}findByPath(tt){return this.entityManager.findByPath(this,tt)}findByIndexPath(tt){return this.entityManager.findByIndexPath(this,tt)}getAddedComponents(tt=!0){const et=[],nt=this.strippedEntity;return nt!=null&&nt.components.length&&et.push({target:{entityId:"",componentId:""},strippedId:this.strippedEntity.id}),tt&&this.children.filter(it=>!it.isAddedEntity&&!it.isGLTFRefEntity).forEach((it,at)=>{const ot=it.getAddedComponents().map(({target:st,strippedId:ct})=>{const{entityId:dt}=st;return{target:{entityId:`${at}${dt?"/"+dt:""}`,componentId:""},strippedId:ct}});et.push(...ot)}),et}getRemovedComponents(tt=!0){const et=[];return this._components.forEach(nt=>{if(nt.removedComponent){const it=this.getComponentsByTypeName(nt.type).indexOf(nt);et.push({entityId:"",componentId:`:${nt.type}/${it}`})}}),tt&&this.children.filter(nt=>!nt.isAddedEntity&&!nt.isGLTFRefEntity).forEach((nt,it)=>{const at=nt.getRemovedComponents().map(ot=>{const{entityId:st,componentId:ct}=ot,dt=`${it}${st?"/"+st:""}`,ut=ct.split(":"),ht=ut[ut.length-1],ft=`${ht?dt+":"+ht:""}`;return{entityId:dt,componentId:ft}});et.push(...at)}),et}getAddedEntities(tt=!0){const et=[],nt=this.strippedEntity;return nt!=null&&nt.children.length&&et.push({target:{entityId:"",componentId:""},strippedId:this.strippedEntity.id}),tt&&this.children.filter(it=>!it.isAddedEntity&&!it.isGLTFRefEntity).forEach((it,at)=>{const ot=it.getAddedEntities().map(({target:st,strippedId:ct})=>{const{entityId:dt}=st;return{target:{entityId:`${at}${dt?"/"+dt:""}`,componentId:""},strippedId:ct}});et.push(...ot)}),et}getRemovedEntities(tt=!0){const et=[];return this.prefabEntityRemoved&&et.push({entityId:"",componentId:""}),tt&&this.children.filter(nt=>!nt.isAddedEntity&&!nt.isGLTFRefEntity).forEach((nt,it)=>{const at=nt.getRemovedEntities().map(ot=>{const{entityId:st}=ot;return{entityId:`${it}${st?"/"+st:""}`,componentId:""}});et.push(...at)}),et}applyRemovedComponent(tt){const{entityId:et,componentId:nt}=tt,it=this.findByIndexPath(et);if(it&&nt){const at=nt.split(":")[1].split("/"),ot=at[0],st=at[1],ct=it.getComponentsByTypeName(ot)[st];ct&&it._removePrefabComponent(ct)}}applyRemovedEntity(tt){const{entityId:et}=tt,nt=this.findByIndexPath(et);nt&&this.entityManager.removePrefabSubEntity(nt)}applyAddedEntity(tt){const{target:et,strippedId:nt}=tt,it=this.findByIndexPath(et.entityId),at=this.entityManager.strippedEntities.get(nt);at.children.forEach(ot=>{it.addChild(ot)}),at._childrenId.length=0}applyAddedComponent(tt){const{target:et,strippedId:nt}=tt,it=this.findByIndexPath(et.entityId),at=this.entityManager.strippedEntities.get(nt);at.components.forEach(ot=>{it.addEditorComponent(ot.toJSON())}),at._components.length=0}async _getPrefabSourceApplyAsset(tt){if(tt.assetKind!=="Prefab")throw new Error(`Prefab binding "${tt.id}" targets ${tt.assetKind} asset "${tt.assetId}" and does not support applyToPrefab. glTF source assets are immutable; record editable overrides on a containing Prefab binding.`);const et=await this.root.assetStore.getAssetByRef({refId:tt.assetId}),it=["applyEntityPropsOverride","applyComponentPropsOverride","applyAddedEntityOverride","applyNestedInstanceAddedEntityOverride","applyRemovedEntityOverride","applyAddedComponentOverride","applyRemovedComponentOverride","refreshFromData"].filter(at=>typeof(et==null?void 0:et[at])!="function");if(it.length>0)throw new Error(`Prefab asset "${tt.assetId}" does not support applyToPrefab: missing ${it.join(", ")}`);return et}async _acceptPrefabOverrideAndRefresh(tt,et,nt,it,at){const ot=this.root.domainStore.getNormalizedState().prefab.bindings[et],st=nt===5&&it.sourceEntityId!==void 0&&it.sourceEntityId===(ot==null?void 0:ot.sourceRootEntityId);await this.root.domainStore.runAsRemote(()=>{this.root.prefabFacade.acceptOverride(et,OVERRIDE_TYPE_BY_APPLY_TYPE[nt],it)});const ct={};st&&(ct.resetRootTransformBindingIds=[et]),STRUCTURAL_PREFAB_APPLY_TYPES.has(nt)&&(ct.structuralDeltaMode="domain-source-replace"),Object.keys(ct).length>0?await tt.refreshFromData(ct):await tt.refreshFromData(),this._restoreSelectionAfterApplyToPrefab(et,at)}_restoreSelectionAfterApplyToPrefab(tt,et){var at;if(!et){this.entityManager.selectEntity(null);return}const nt=(at=this.root.domainStore.getNormalizedState().prefab.bindings)==null?void 0:at[tt],it=nt?getSceneEntityIdForPrefabSource(nt,et):null;this.entityManager.selectEntity(it)}_getPrefabBindingForApply(tt){var nt;const et=(nt=this.root.domainStore.getNormalizedState().prefab.bindings)==null?void 0:nt[tt];if(!et)throw new Error(`Prefab binding "${tt}" not found while applying override to source prefab`);return et}_findPrefabBindingOwningAddedEntity(tt){return Object.values(tt??{}).find(et=>et.assetKind==="Prefab"&&!!et.overrides.addedEntities[this.id])??null}_isNormalizedAncestorOrSelf(tt,et){var ot;const nt=this.root.domainStore.getNormalizedState().entities,it=new Set;let at=et;for(;at&&!it.has(at);){if(at===tt)return!0;it.add(at),at=((ot=nt[at])==null?void 0:ot.parentId)??null}return!1}_getNormalizedHierarchyDepth(tt){var ot;const et=this.root.domainStore.getNormalizedState().entities,nt=new Set;let it=0,at=tt;for(;at&&!nt.has(at);){nt.add(at);const st=((ot=et[at])==null?void 0:ot.parentId)??null;if(!st)break;it+=1,at=st}return it}_findContainingPrefabBindingForInstance(tt){const et=resolveContainingPrefabBindingForInstance(this.root.domainStore.getNormalizedState(),tt);return et!=null&&et.sourceEntityId?{binding:et.binding,sourceEntityId:et.sourceEntityId}:null}_sourceEntityPathSegments(tt,et){const nt=sourceEntityIdToPath(tt,et);if(nt===null)throw new Error(`Prefab binding "${tt.id}" cannot resolve source entity path "${et}"`);return nt===""?[]:nt.split("/").map(it=>{const at=Number(it);if(!Number.isInteger(at)||at<0)throw new Error(`Prefab binding "${tt.id}" resolved invalid source path "${nt}"`);return at})}_trySourceEntityPathSegments(tt,et){const nt=sourceEntityIdToPath(tt,et);if(nt===null)return null;if(nt==="")return[];const it=[];for(const at of nt.split("/")){const ot=Number(at);if(!Number.isInteger(ot)||ot<0)return null;it.push(ot)}return it}_resolveAddedEntityApplyTarget(){var ct;const tt=this.root.domainStore.getNormalizedState(),et=tt.prefab.bindings,nt=tt.entities[this.id],it=(ct=nt==null?void 0:nt.instance)==null?void 0:ct.bindingId;if(!it)throw new Error(`Entity "${this.id}" is not a prefab instance entity and cannot be applied to prefab`);const at=this._getPrefabBindingForApply(it),ot=at.overrides.addedEntities[this.id];if(ot){if(at.assetKind==="Prefab")return{kind:"sourceEntity",overrideBindingId:at.id,prefabBinding:at,addedEntity:ot};const dt=this._findContainingPrefabBindingForInstance(at);return dt?{kind:"nestedInstance",overrideBindingId:at.id,prefabBinding:dt.binding,addedEntity:ot,instanceSourceEntityId:dt.sourceEntityId,parentSourceEntityId:ot.parentSourceEntityId}:{kind:"sourceEntity",overrideBindingId:at.id,prefabBinding:at,addedEntity:ot}}const st=this._findPrefabBindingOwningAddedEntity(et);if(st)return{kind:"sourceEntity",overrideBindingId:st.id,prefabBinding:st,addedEntity:st.overrides.addedEntities[this.id]};throw new Error(`Prefab added entity override for "${this.id}" not found`)}_resolveNestedInstanceAddedEntityFromSceneParent(tt,et,nt){var ct,dt;const it=this.root.domainStore.getNormalizedState(),at=(ct=it.entities[this.id])==null?void 0:ct.parentId;if(!at)return null;const ot=tt.prefabFile;if(!Array.isArray(ot==null?void 0:ot.entities))return null;let st=null;for(const ut of Object.values(it.prefab.bindings??{})){if(ut.id===et.id||ut.assetKind!=="Prefab"&&ut.assetKind!=="glTF"||!this._isNormalizedAncestorOrSelf(ut.instanceRootEntityId,at)||!this._isNormalizedAncestorOrSelf(et.instanceRootEntityId,ut.instanceRootEntityId)||this._trySourceEntityPathSegments(ut,nt)===null)continue;const ft=getSceneEntityIdForPrefabSource(ut,nt);if(ft&&ft!==at)continue;const pt=getSourceEntityIdForPrefabScene(et,ut.instanceRootEntityId);if(!pt)continue;const mt=ot.entities.findIndex(_t=>_t.id===pt);if(mt<0||!((dt=ot.entities[mt])!=null&&dt.instance))continue;const vt=this._getNormalizedHierarchyDepth(ut.instanceRootEntityId);(!st||st.depth<vt)&&(st={depth:vt,target:{instanceSourceEntityId:pt,parentSourceEntityId:nt}})}return(st==null?void 0:st.target)??null}_resolveSourceRootInstanceAddedEntityTarget(tt,et,nt){var st,ct;const it=tt.prefabFile;if(!Array.isArray(it==null?void 0:it.entities)||typeof it.root!="string")return null;const at=it.root,ot=it.entities.findIndex(dt=>dt.id===at);return ot<0||!((st=it.entities[ot])!=null&&st.instance)||!((ct=et.sourceEntitySnapshots)!=null&&ct[nt])?null:{instanceSourceEntityId:at,parentSourceEntityId:nt}}_resolveNestedInstanceAddedEntitySourceTarget(tt,et,nt){const it=tt.prefabFile;if(!Array.isArray(it==null?void 0:it.entities)||this._prefabFileHasSourceEntity(tt,nt))return null;const at=et.sourceEntitySnapshots??{},ot=[],st=new Set;let ct=nt;const dt=()=>this._resolveNestedInstanceAddedEntityFromSceneParent(tt,et,nt)??this._resolveSourceRootInstanceAddedEntityTarget(tt,et,nt);for(;ct;){if(st.has(ct))return dt();st.add(ct);const ut=at[ct];if(!ut)return dt();if(!Number.isInteger(ut.childIndex)||ut.childIndex<0)throw new Error(`Prefab binding "${et.id}" has invalid childIndex for source entity "${ct}"`);ot.unshift(ut.childIndex);const ht=ut.parentSourceEntityId;if(!ht)return dt();const ft=it.entities.findIndex(pt=>pt.id===ht);if(ft>=0){const pt=it.entities[ft];return pt!=null&&pt.instance?{instanceSourceEntityId:ht,parentSourceEntityId:nt}:dt()}ct=ht}return dt()}_prefabFileHasSourceEntity(tt,et){var nt,it;return!!((it=(nt=tt.prefabFile)==null?void 0:nt.entities)!=null&&it.some(at=>at.id===et))}_resolveAddedAncestorApplyTarget(tt,et){var at,ot;const nt=this.root.domainStore.getNormalizedState();let it=((at=nt.entities[this.id])==null?void 0:at.parentId)??null;for(;it;){const st=et.overrides.addedEntities[it];if(st){const ct=this._resolveNestedInstanceAddedEntitySourceTarget(tt,et,st.parentSourceEntityId);if(ct||this._prefabFileHasSourceEntity(tt,st.parentSourceEntityId)){const dt=this.entityManager.entities.get(it);if(!dt)throw new Error(`Prefab added ancestor "${it}" is not materialized`);return{entityId:it,entity:dt,addedEntity:st,nestedSourceTarget:ct}}}it=((ot=nt.entities[it])==null?void 0:ot.parentId)??null}return null}_findPrefabBindingOwningSourceOverride(tt,et,nt){var it,at,ot;for(const st of Object.values(tt??{})){if(st.assetKind!=="Prefab")continue;const ct=getSourceEntityIdForPrefabScene(st,this.id);if(ct){if(et===5&&st.overrides.entityProps[ct])return{binding:st,sourceEntityId:ct};if(et===3&&st.overrides.removedEntities[ct])return{binding:st,sourceEntityId:ct};if(et===0){const{sourceComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((it=st.overrides.componentProps[ct])!=null&&it[dt]))return{binding:st,sourceEntityId:ct}}if(et===2){const{sceneComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((at=st.overrides.addedComponents[ct])!=null&&at[dt]))return{binding:st,sourceEntityId:ct}}if(et===1){const{sourceComponentId:dt}=this._getSourceComponentKeyForApply(nt,st,ct);if(dt&&((ot=st.overrides.removedComponents[ct])!=null&&ot[dt]))return{binding:st,sourceEntityId:ct}}}}return null}_resolvePrefabApplyTarget(tt,et){var dt;const nt=this.root.domainStore.getNormalizedState(),it=nt.prefab.bindings,at=nt.entities[this.id],ot=(dt=at==null?void 0:at.instance)==null?void 0:dt.bindingId;if(!ot)throw new Error(`Entity "${this.id}" is not a prefab instance entity and cannot be applied to prefab`);const st=this._getPrefabBindingForApply(ot);if(st.assetKind==="Prefab")return{bindingId:ot,binding:st,sourceEntityId:getNormalizedSourceEntityId(nt,this.id)};const ct=this._findPrefabBindingOwningSourceOverride(it,tt,et);return ct?{bindingId:ct.binding.id,binding:ct.binding,sourceEntityId:ct.sourceEntityId}:{bindingId:ot,binding:st,sourceEntityId:getNormalizedSourceEntityId(nt,this.id)}}_getComponentTargetIndex(tt){return typeof tt=="number"?tt:tt==null?void 0:tt.componentIndex}_formatComponentTarget(tt){return typeof tt=="number"||tt===void 0?String(tt??0):JSON.stringify(tt)}_getSourceComponentKeyFromSnapshot(tt,et,nt){var at,ot,st;if(!tt||!et||!nt)return;const it=((ot=(at=tt.sourceEntitySnapshots)==null?void 0:at[et])==null?void 0:ot.components)??{};return(st=Object.entries(it).find(([,ct])=>ct.sceneComponentId===nt))==null?void 0:st[0]}_getSourceComponentKeyForApply(tt,et,nt){var ft;const it=this.root.domainStore.getNormalizedState(),at=this._getComponentTargetIndex(tt),ot=typeof tt=="object"?tt:void 0,st=at!==void 0?this.components[at]:void 0,ct=st==null?void 0:st.removedComponentMeta,dt=(ot==null?void 0:ot.sceneComponentId)??(ct==null?void 0:ct.sceneComponentId)??(st==null?void 0:st.id),ut=dt?getNormalizedComponent(it,this.id,dt):void 0,ht=(ot==null?void 0:ot.sourceComponentId)??(ot==null?void 0:ot.sourceComponentKey)??(ct==null?void 0:ct.sourceComponentKey)??((ft=ut==null?void 0:ut.instance)==null?void 0:ft.sourceComponentKey)??this._getSourceComponentKeyFromSnapshot(et,nt,dt);return{componentIndex:at,sceneComponentId:dt,sourceComponentId:ht}}async applyToPrefab(tt,et){var ct,dt,ut,ht;if(tt===4){const ft=this._resolveAddedEntityApplyTarget(),pt=await this._getPrefabSourceApplyAsset(ft.prefabBinding);let mt=this.id;if(ft.kind==="nestedInstance")await pt.applyNestedInstanceAddedEntityOverride(ft.instanceSourceEntityId,ft.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1});else{const vt=this._resolveNestedInstanceAddedEntitySourceTarget(pt,ft.prefabBinding,ft.addedEntity.parentSourceEntityId);if(vt)await pt.applyNestedInstanceAddedEntityOverride(vt.instanceSourceEntityId,vt.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1});else{const _t=this._prefabFileHasSourceEntity(pt,ft.addedEntity.parentSourceEntityId)?null:this._resolveAddedAncestorApplyTarget(pt,ft.prefabBinding);_t?(mt=_t.entityId,_t.nestedSourceTarget?await pt.applyNestedInstanceAddedEntityOverride(_t.nestedSourceTarget.instanceSourceEntityId,_t.nestedSourceTarget.parentSourceEntityId,_t.addedEntity.index,_t.entity,{refresh:!1}):await pt.applyAddedEntityOverride(_t.addedEntity.parentSourceEntityId,_t.addedEntity.index,_t.entity,{refresh:!1})):await pt.applyAddedEntityOverride(ft.addedEntity.parentSourceEntityId,ft.addedEntity.index,this,{refresh:!1})}}await this._acceptPrefabOverrideAndRefresh(pt,ft.overrideBindingId,tt,{entityId:mt},this.id);return}const{bindingId:nt,binding:it,sourceEntityId:at}=this._resolvePrefabApplyTarget(tt,et),ot=this.root.domainStore.getNormalizedState(),st=await this._getPrefabSourceApplyAsset(it);if(tt===5){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const ft=it.overrides.entityProps[at];await st.applyEntityPropsOverride(at,ft,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at},at);return}if(tt===3){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const ft=((ct=it.sourceEntitySnapshots[at])==null?void 0:ct.parentSourceEntityId)??null;await st.applyRemovedEntityOverride(at,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at},ft);return}if(tt===0){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sourceComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab component target "${this._formatComponentTarget(et)}" not found`);const pt=(dt=it.overrides.componentProps[at])==null?void 0:dt[ft];await st.applyComponentPropsOverride(ft,pt,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at);return}if(tt===2){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sceneComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab added component target "${this._formatComponentTarget(et)}" not found`);const pt=getNormalizedComponent(ot,this.id,ft),mt=(ut=it.overrides.addedComponents[at])==null?void 0:ut[ft],vt=this._components.find(yt=>yt.id===ft&&typeof yt.toJSON=="function"),_t=(vt==null?void 0:vt.toJSON())??{type:(mt==null?void 0:mt.type)??(pt==null?void 0:pt.type)??"",props:(mt==null?void 0:mt.props)??(pt==null?void 0:pt.props)??{}};if(!_t.type)throw new Error(`Prefab added component "${ft}" has no component type`);await st.applyAddedComponentOverride(at,ft,_t,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at);return}if(tt===1){if(!at)throw new Error(`Entity "${this.id}" has no prefab source entity id`);const{sourceComponentId:ft}=this._getSourceComponentKeyForApply(et,it,at);if(!ft)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" not found`);if(!((ht=it.overrides.removedComponents[at])!=null&&ht[ft]))throw new Error(`Prefab removed component override "${ft}" on source entity "${at}" not found`);await st.applyRemovedComponentOverride(ft,{refresh:!1}),await this._acceptPrefabOverrideAndRefresh(st,nt,tt,{sourceEntityId:at,componentId:ft},at)}}unpackPrefab(){var et;const tt=this.root.domainStore.getNormalizedState().entities[this.id];if((et=tt==null?void 0:tt.instance)!=null&&et.bindingId){const nt=this.root.domainStore.state.prefab.bindings[tt.instance.bindingId];this.root.prefabFacade.unpack(tt.instance.bindingId,{replacementRootInstance:nt?this._resolveRootInstanceReplacementForUnpack(nt):void 0})}}_resolveRootInstanceReplacementForUnpack(tt){var dt,ut,ht,ft,pt,mt;if(tt.assetKind!=="Prefab")return;const et=(dt=this.root.assetStore.assets)==null?void 0:dt[tt.assetId],nt=et==null?void 0:et.prefabFile,it=typeof(nt==null?void 0:nt.root)=="string"?nt.entities.find(vt=>vt.id===nt.root):void 0,at=(ut=it==null?void 0:it.instance)==null?void 0:ut.asset,ot=at==null?void 0:at.$ref;if(!ot)return;const st=(ft=(ht=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ft.call(ht,ot),ct=(mt=(pt=st==null?void 0:st.getMetaConfig)==null?void 0:pt.call(st))==null?void 0:mt.type;if(ct==="glTF")return{assetId:st.id,assetKind:ct,assetKey:at.key,sourceRevision:1}}convertToPrefabRefEntity(){this.isPrefabRefEntity=!0,this.selfComponents.forEach(tt=>{EditorComponent.convertToPrefabComponent(tt)}),this.selfChildren.forEach(tt=>{!tt.isGLTFRefEntity&&tt.convertToPrefabRefEntity()})}convertToNormalEntity(){this.selfComponents.forEach(tt=>{EditorComponent.convertToNormalComponent(tt)}),this.selfChildren.forEach(tt=>{!tt.isGLTFRefEntity&&tt.convertToNormalEntity()})}_applyStrippedDataToSelf(){if(this.children.forEach(tt=>{!tt.isGLTFRefEntity&&tt._applyStrippedDataToSelf()}),this.strippedEntity){const tt=this.strippedEntity.components.map(nt=>nt.toJSON());this.strippedEntity._components.length=0,tt.forEach(nt=>{this.addEditorComponent(nt)});const et=this.strippedEntity.children.slice();this.strippedEntity._childrenId.length=0,et.forEach(nt=>{this.addChild(nt)})}}revertPrefab(tt,et){var ct,dt;const nt=this.root.domainStore.getNormalizedState(),it=(dt=(ct=nt.entities[this.id])==null?void 0:ct.instance)==null?void 0:dt.bindingId,at=getNormalizedSourceEntityId(nt,this.id),ot=it?this._getPrefabBindingForApply(it):void 0,st=this._getComponentTargetIndex(et);if(tt===5&&it&&at&&this.root.prefabFacade.revertOverride(it,"entityProps",{sourceEntityId:at}),tt===4&&this.entityManager.removeEntity(this.id),tt===3&&this.entityManager.revertPrefabSubEntity(this),tt===0&&it&&at){const{sourceComponentId:ut}=this._getSourceComponentKeyForApply(et,ot,at);if(!ut)throw new Error(`Prefab component target "${this._formatComponentTarget(et)}" has no source key`);this.root.prefabFacade.revertOverride(it,"componentProps",{sourceEntityId:at,componentId:ut})}if(tt===2&&this.removeComponent(st),tt===1){if(it&&at){const{sourceComponentId:pt}=this._getSourceComponentKeyForApply(et,ot,at);if(!pt)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" has no source key`);this.root.prefabFacade.revertOverride(it,"removedComponents",{sourceEntityId:at,componentId:pt}),this.root.projectStore.debouncedUpdateSceneAsset();return}const ut=st??0,ht=this._components[ut];if(!ht)throw new Error(`Prefab removed component target "${this._formatComponentTarget(et)}" not found`);ht.removedComponent=!1;const ft=ht.toJSON();this._removeSelfComponent(ut),this._addEditorComponent(ft,ut),EditorComponent.convertToPrefabComponent(this.components[ut])}this.root.projectStore.debouncedUpdateSceneAsset()}async getPrefabAsset(){const tt=this._getPrefabInfo().prefabSource;return this.root.assetStore.getAssetByRef({refId:tt.assetId})}_removePrefabComponent(tt){tt.removeByPrefab(),this.root.projectStore.debouncedUpdateSceneAsset()}_getPrefabInfo(){var nt;let tt="",et=this;for(;(nt=et.parentEntity)!=null&&nt.isPrefabRefEntity;){const it=et;et=et.parentEntity;const at=et.childrenId.indexOf(it.id);tt=tt?`${at}/${tt}`:`${at}`}return{prefabInstanceId:et.id,prefabSource:{assetId:et.instanceAssetId,entityId:tt}}}_getOrCreateTransformSchema(tt,et=!1){let nt=tt.transform;if(nt){if(et){nt=cloneDeep$1(nt);const it=nt.props;it.position&&(it.position=null),it.rotation&&(it.rotation=null),it.scale&&(it.scale=null)}}else{nt={class:"Transform",props:{}};const it=nt.props;if(!et){const{position:at,rotation:ot,scale:st}=tt;at&&(it.position=at),ot&&(it.rotation=ot),st&&(it.scale=st)}}return nt}updateLayer(tt,et){resolveLayerUpdateMode({entityId:this.id,domainEntities:this.root.domainStore.state.entities})==="domain"?this.root.entityFacade.setLayer(this.id,et):this.engineObject&&(this.engineObject.layer=et)}};__decorateClass$6([observable.ref],_EntityModel.prototype,"_domainEntityVersion",2);__decorateClass$6([action],_EntityModel.prototype,"invalidateFromDomain",1);__decorateClass$6([propertyField({label:"entity.layer.title",type:ComponentType.Select,info:"entity.layer.info",...getMultipleLayerOptions([...Object.values(LayerSetting),Layer.Nothing,Layer.Everything]),triggerAfterInit:!1})],_EntityModel.prototype,"layer",1);__decorateClass$6([observable],_EntityModel.prototype,"_localLayer",2);__decorateClass$6([propertyField({label:"entity.is-active"}),virtualProperty()],_EntityModel.prototype,"isActive",1);__decorateClass$6([observable],_EntityModel.prototype,"_localIsActive",2);__decorateClass$6([propertyField({label:"entity.name",triggerAfterInit:!1}),virtualProperty()],_EntityModel.prototype,"name",1);__decorateClass$6([observable],_EntityModel.prototype,"_localName",2);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"id",2);__decorateClass$6([computed],_EntityModel.prototype,"level",1);__decorateClass$6([virtualProperty(),computed],_EntityModel.prototype,"components",1);__decorateClass$6([virtualProperty(),observable],_EntityModel.prototype,"_parent",2);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceAssetId",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceSourceEntityId",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"instanceAssetKind",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"isPrefabRefEntity",1);__decorateClass$6([observable],_EntityModel.prototype,"_localIsPrefabRefEntity",2);__decorateClass$6([observable],_EntityModel.prototype,"prefabEntityRemoved",2);__decorateClass$6([computed],_EntityModel.prototype,"isGLTFSubEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"isPrefabInstanceRoot",1);__decorateClass$6([computed],_EntityModel.prototype,"isPrefabSubEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"strippedEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"isAddedEntity",1);__decorateClass$6([computed],_EntityModel.prototype,"showAdditiveModified",1);__decorateClass$6([observable],_EntityModel.prototype,"_childrenId",2);__decorateClass$6([observable],_EntityModel.prototype,"_components",2);__decorateClass$6([observable],_EntityModel.prototype,"_strippedEntityId",2);__decorateClass$6([observable],_EntityModel.prototype,"_isLocked",2);__decorateClass$6([computed],_EntityModel.prototype,"canCopy",1);__decorateClass$6([computed],_EntityModel.prototype,"canPasted",1);__decorateClass$6([computed],_EntityModel.prototype,"canDuplicated",1);__decorateClass$6([computed],_EntityModel.prototype,"nextSibling",1);__decorateClass$6([computed],_EntityModel.prototype,"hasCameraComponent",1);__decorateClass$6([action],_EntityModel.prototype,"applyLockedFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyParentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyChildrenFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"applyRemoveChildFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"initByFile",1);__decorateClass$6([action],_EntityModel.prototype,"initByEngineObject",1);__decorateClass$6([action],_EntityModel.prototype,"initBySchema",1);__decorateClass$6([action],_EntityModel.prototype,"destroy",1);__decorateClass$6([action],_EntityModel.prototype,"clear",1);__decorateClass$6([action],_EntityModel.prototype,"_addEditorComponent",1);__decorateClass$6([action],_EntityModel.prototype,"_removeSelfComponent",1);__decorateClass$6([action],_EntityModel.prototype,"addComponentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"removeComponentFromDomain",1);__decorateClass$6([action],_EntityModel.prototype,"syncRemovedComponentPlaceholdersFromDomain",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponent",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponentById",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponentByTypeName",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"addComponent",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"getComponents",1);__decorateClass$6([virtualProperty()],_EntityModel.prototype,"makeEntityCanPick",1);__decorateClass$6([action],_EntityModel.prototype,"_addSelfChild",1);__decorateClass$6([action],_EntityModel.prototype,"addChildren",1);__decorateClass$6([action],_EntityModel.prototype,"resetParent",1);__decorateClass$6([action],_EntityModel.prototype,"setParent",1);__decorateClass$6([action],_EntityModel.prototype,"_removeSelfChild",1);__decorateClass$6([action],_EntityModel.prototype,"unpackPrefab",1);__decorateClass$6([action],_EntityModel.prototype,"convertToPrefabRefEntity",1);__decorateClass$6([action],_EntityModel.prototype,"convertToNormalEntity",1);__decorateClass$6([action],_EntityModel.prototype,"_applyStrippedDataToSelf",1);__decorateClass$6([action],_EntityModel.prototype,"revertPrefab",1);let EntityModel=_EntityModel;var __defProp$6=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$5(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$6(_e,tt,nt),nt};class RootEntityModel{constructor(_e){Rt(this,"id",DEFAULT_SCENE);Rt(this,"name","Scene");Rt(this,"parent",null);Rt(this,"entityManager");Rt(this,"isExpanded",!0);Object.defineProperty(this,"entityManager",{enumerable:!1,writable:!0,configurable:!0,value:_e}),makeObservable(this)}get childrenId(){return this.entityManager.displayedEntitiesIds}get level(){return 0}get children(){return this.entityManager.displayedEntities}get nextSibling(){return this.entityManager.rootEntitiesId[0]}}__decorateClass$5([computed],RootEntityModel.prototype,"childrenId",1);__decorateClass$5([observable],RootEntityModel.prototype,"isExpanded",2);__decorateClass$5([computed],RootEntityModel.prototype,"children",1);__decorateClass$5([computed],RootEntityModel.prototype,"nextSibling",1);class SerializeContext{constructor(_e,tt,et){Rt(this,"entityIndex");Rt(this,"entityIds");Rt(this,"components",[]);Rt(this,"componentIds",[]);Rt(this,"_resolveVirtualPath");Rt(this,"_sourceRefCodec");Rt(this,"_lookupComponentState");this.entityIds=_e,this._resolveVirtualPath=tt,this._sourceRefCodec=createSourceRefCodec({resolveAssetRef:tt}),this._lookupComponentState=et,this.entityIndex=new Map;for(let nt=0;nt<_e.length;nt++)this.entityIndex.set(_e[nt],nt)}resolveVirtualPath(_e){return this._sourceRefCodec.domainToSource(_e)}serializeComponent(_e){var nt,it,at,ot,st;const tt=_e.toJSON();tt.id=_e.id,tt.props&&(tt.props=this.convertRefs(tt.props));const et=(nt=this._lookupComponentState)==null?void 0:nt.call(this,_e.id);return et!=null&&et.refId&&!((it=tt.script)!=null&&it.$ref)?tt.script={$ref:this.resolveVirtualPath(et.refId),...et.scriptKey?{key:et.scriptKey}:{}}:(at=tt.script)!=null&&at.$ref&&(tt.script=normalizeSourceAssetRefRecord(tt.script),et!=null&&et.scriptKey&&!tt.script.key&&(tt.script.key=et.scriptKey)),(ot=et==null?void 0:et.calls)!=null&&ot.length&&!((st=tt.calls)!=null&&st.length)&&(tt.calls=this.convertRefs(et.calls)),tt}registerComponent(_e){return this.components.push(this.serializeComponent(_e)),this.componentIds.push(_e.id),_e.id}resolveEntityIndex(_e){return this.entityIndex.get(_e)??-1}hasEntityId(_e){return this.entityIndex.has(_e)}convertRefs(_e){return convertInternalRefsToSourceValue(_e,tt=>this.resolveVirtualPath(tt))}}function clone(rt){return structuredClone(rt)}function appendUnique(rt,_e){const tt=new Set(rt),et=[...rt];for(const nt of _e)tt.has(nt)||(tt.add(nt),et.push(nt));return et}function createEmptyPrefabState(){return{bindings:{},byAssetId:{}}}function normalizeSourceIdPrefabFile(rt){return assertSourceV2PrefabFileStructure(rt),rt}function snapshotComponentToDomainComponent(rt,_e,tt,et){var nt;return{type:tt.type,...tt.refId?{refId:tt.refId}:{},...tt.scriptKey?{scriptKey:tt.scriptKey}:{},props:mergeSourceValueRecords(tt.props??{},et??{}),...(nt=tt.calls)!=null&&nt.length?{calls:clone(tt.calls)}:{},instance:{bindingId:rt,role:"linked",sourceComponentKey:_e}}}function mergeTransform(rt,_e){return _e?{position:{...rt.position,..._e.position??{}},rotation:{...rt.rotation,..._e.rotation??{}},scale:{...rt.scale,..._e.scale??{}}}:clone(rt)}function isRemovedSourceEntity(rt,_e){var et,nt,it,at,ot,st;if((et=rt.overrides.removedEntities)!=null&&et[_e])return!0;let tt=(it=(nt=rt.sourceEntitySnapshots)==null?void 0:nt[_e])==null?void 0:it.parentSourceEntityId;for(;tt;){if((at=rt.overrides.removedEntities)!=null&&at[tt])return!0;tt=((st=(ot=rt.sourceEntitySnapshots)==null?void 0:ot[tt])==null?void 0:st.parentSourceEntityId)??null}return!1}function derivePrefabSourceSnapshotsFromFile(rt,_e,tt,et,nt,it){var ft,pt,mt,vt,_t,yt;_e=normalizeSourceIdPrefabFile(_e),assertSourceV2PrefabFileStructure(_e);const at=buildSourceIdIndex(_e),ot=collectReachableSourceEntityIds(_e.entities,[_e.root]),st=new Map;for(const bt of ot){const Et=at.entityById.get(bt);isSourceInstanceBoundary(Et)||(ft=Et==null?void 0:Et.children)==null||ft.forEach(St=>{st.set(St,bt)})}const ct=Object.keys(rt.sourceEntitySnapshots??{}).length>0,dt=(bt,Et)=>{var St;return bt===null?0:Math.max(0,(((St=at.entityById.get(bt))==null?void 0:St.children)??[]).findIndex(At=>At===Et))},ut=new Map;for(const bt of ot){if(!at.entityById.get(bt))throw new Error(`Prefab source entity "${bt}" is missing from the source index`);const St=st.get(bt)??null;dt(St,bt);const At=findExactPreviousSourceEntitySnapshot(rt,bt);At&&ut.set(bt,At),rt.sourceToSceneEntity[bt]=selectSceneEntityIdForSourceSnapshot({binding:rt,sourceEntityId:bt,existingSceneEntityId:rt.sourceToSceneEntity[bt],previousSceneEntityId:At==null?void 0:At.sceneEntityId,allowExistingSceneEntityId:!ct||!!At,usedSceneEntityIds:nt})}const ht={};for(const bt of ot){const Et=at.entityById.get(bt);if(!Et)throw new Error(`Prefab source entity "${bt}" is missing from the source index`);const St=rt.sourceToSceneEntity[bt],At=ut.get(bt),xt=st.get(bt)??null,Ct=dt(xt,bt),Pt=isSourceInstanceBoundary(Et),Tt=Pt?[]:Et.children??[],wt={};for(const $t of Pt?[]:Et.components??[]){const Dt=at.componentById.get($t);if(!Dt)throw new Error(`Prefab source component "${$t}" is missing from the source index`);const Bt=findExactPreviousSourceComponentSnapshot(At,$t,Dt),Gt=Bt==null?void 0:Bt.sceneComponentId,zt=selectSceneComponentIdForSourceSnapshot({bindingId:rt.id,sceneEntityId:St,sourceComponentType:Dt.type,sourceComponentKey:$t,previousSceneComponentId:Gt,componentRecords:et,usedSceneComponentIds:it});wt[$t]={sceneComponentId:zt,type:Dt.type,...(pt=Dt.script)!=null&&pt.$ref?{refId:resolveSourceAssetRef(Dt.script.$ref,tt,"script")}:{},...(mt=Dt.script)!=null&&mt.key?{scriptKey:Dt.script.key}:{},props:convertAssetRefsToDomainRefs(Dt.props??{},tt.resolveSourceRef),...(vt=Dt.calls)!=null&&vt.length?{calls:convertAssetRefsToDomainRefs(Dt.calls,tt.resolveSourceRef)}:{}}}const It=(yt=(_t=Et.instance)==null?void 0:_t.asset)==null?void 0:yt.$ref,Ot=It?resolveSourceAssetRef(It,tt,"nested instance"):void 0,Nt=It&&Ot?resolveSourceAssetKind(It,Ot,tt,"nested instance"):void 0,Mt=resolveSourceInstanceRootOverrideTarget({sourceEntity:Et,fallbackSourceEntityId:bt,assetId:Ot,instanceAssetKind:Nt,resolvePrefabSourceFile:tt.resolvePrefabSourceFile}),Lt=readSourceEntityResolvedState(Et,bt,{...typeof Mt=="string"?{rootOverrideTarget:Mt}:{}});ht[bt]={sceneEntityId:St,parentSourceEntityId:xt,childSourceEntityIds:Tt,childIndex:Ct,...Nt?{instanceAssetKind:Nt}:{},name:Lt.name,isActive:Lt.isActive,...Lt.layer!==void 0?{layer:Lt.layer}:{},...Lt.isLocked!==void 0?{isLocked:Lt.isLocked}:{},transform:Lt.transform,components:wt}}return ht}function findExactPreviousSourceEntitySnapshot(rt,_e){var tt;return(tt=rt.sourceEntitySnapshots)==null?void 0:tt[_e]}function collectReachablePrefabEntityIds(rt){return collectReachableSourceEntityIds(rt.entities,[rt.root])}function findExactPreviousSourceComponentSnapshot(rt,_e,tt){var nt;const et=(nt=rt==null?void 0:rt.components)==null?void 0:nt[_e];return(et==null?void 0:et.type)===tt.type?et:void 0}function resolveSourceAssetRef(rt,_e,tt){var nt;const et=(nt=_e.resolveSourceRef)==null?void 0:nt.call(_e,rt);if(typeof et!="string"||et.length===0)throw new Error(`Unable to resolve source asset ref "${rt}" to an editor asset id while refreshing ${tt}`);return et}function resolveSourceAssetKind(rt,_e,tt,et){var it;const nt=(it=tt.resolveAssetKind)==null?void 0:it.call(tt,rt,_e);if(nt!=="Prefab"&&nt!=="glTF")throw new Error(`Unable to resolve supported source asset kind for "${rt}" while refreshing ${et}; expected Prefab or glTF`);return nt}function selectSceneEntityIdForSourceSnapshot(rt){const{binding:_e,sourceEntityId:tt,existingSceneEntityId:et,previousSceneEntityId:nt,allowExistingSceneEntityId:it,usedSceneEntityIds:at}=rt;if(tt===_e.sourceRootEntityId){const ut=_e.sourceToSceneEntity[tt]??nt??_e.instanceRootEntityId;return at.add(ut),ut}const ot=nt??(it?et:void 0);if(ot&&!at.has(ot))return at.add(ot),ot;const st=`prefab:${_e.id}:${tt}`;let ct=st,dt=1;for(;at.has(ct);)ct=`${st}:${dt++}`;return at.add(ct),ct}function selectSceneComponentIdForSourceSnapshot(rt){const{bindingId:_e,sourceComponentKey:tt,sourceComponentType:et,previousSceneComponentId:nt,componentRecords:it,sceneEntityId:at,usedSceneComponentIds:ot}=rt;if(nt&&!ot.has(nt)&&canUseSceneComponentIdForSourceComponent(nt,it,_e,at,tt,et))return ot.add(nt),nt;const st=`prefab:${rt.bindingId}:${rt.sourceComponentKey}`;let ct=st,dt=1;for(;ot.has(ct)||!canUseSceneComponentIdForSourceComponent(ct,it,_e,at,tt,et);)ct=`${st}:${dt++}`;return ot.add(ct),ct}function canUseSceneComponentIdForSourceComponent(rt,_e,tt,et,nt,it){const at=_e.get(rt);return!at||isSameLinkedSourceComponent(at,tt,et,nt,it)}function isSameLinkedSourceComponent(rt,_e,tt,et,nt){const it=rt.component.instance;return rt.entityId===tt&&rt.component.type===nt&&(it==null?void 0:it.bindingId)===_e&&it.role!=="added"&&it.sourceComponentKey===et}function collectComponentRecords(rt){const _e=new Map;for(const tt of Object.values(rt))for(const[et,nt]of Object.entries(tt.components??{}))_e.set(et,{entityId:tt.id,component:nt});return _e}function createEmptyPrefabOverrides(){return{entityProps:{},componentProps:{},removedEntities:{},removedComponents:{},addedEntities:{},addedComponents:{}}}function requireInlineOverrideId(rt,_e,tt){const et=rt??_e;if(typeof et!="string"||et.length===0)throw new Error(`Invalid source v2 scene file: ${tt} requires an explicit id`);return et}function seedPrefabOverridesFromInlineSource(rt,_e,tt){var at,ot,st,ct,dt,ut;const et=createEmptyPrefabOverrides();if(!rt)return et;const nt=buildSourceIdIndex(_e);for(const ht of rt.entityProps??[]){if(typeof ht.target!="string")throw new Error("Invalid source v2 scene file: entityProps override target must be a source entity id");if(!nt.entityById.has(ht.target))throw new Error(`Invalid source v2 scene file: entityProps override target "${ht.target}" does not exist`);et.entityProps[ht.target]=inlineEntityOverrideToDomainProps(ht,tt)}for(const ht of rt.componentProps??[]){if(typeof ht.target!="string")throw new Error("Invalid source v2 scene file: componentProps override target must be a source component id");const ft=nt.componentOwnerEntityIdById.get(ht.target);if(!ft)throw new Error(`Invalid source v2 scene file: componentProps override target "${ht.target}" does not exist`);const pt=(at=et.componentProps)[ft]??(at[ft]={});pt[ht.target]=convertAssetRefsToDomainRefs(ht.props??{},tt)}for(const ht of rt.removedEntities??[]){if(!nt.entityById.has(ht))throw new Error(`Invalid source v2 scene file: removed entity target "${ht}" does not exist`);et.removedEntities[ht]=!0}for(const ht of rt.removedComponents??[]){const ft=nt.componentOwnerEntityIdById.get(ht);if(!ft)throw new Error(`Invalid source v2 scene file: removed component target "${ht}" does not exist`);const pt=(ot=et.removedComponents)[ft]??(ot[ft]={});pt[ht]=!0}const it=new Map;for(const ht of rt.addedEntities??[]){const ft=requireInlineOverrideId(ht.id,ht.entity.id,"added entity override");if(!nt.entityById.has(ht.parent))throw new Error(`Invalid source v2 scene file: added entity parent "${ht.parent}" does not exist`);const pt=it.get(ht.parent)??0;it.set(ht.parent,pt+1),et.addedEntities[ft]={entityId:ft,parentSourceEntityId:ht.parent,index:ht.index??pt}}for(const ht of rt.addedComponents??[]){if(typeof ht.owner!="string")throw new Error("Invalid source v2 scene file: added component override owner must be a source entity id");if(!nt.entityById.has(ht.owner))throw new Error(`Invalid source v2 scene file: added component owner "${ht.owner}" does not exist`);const ft=requireInlineOverrideId(ht.id,ht.component.id,"added component override"),pt=ht.component,mt=(st=et.addedComponents)[ct=ht.owner]??(st[ct]={});mt[ft]={componentId:ft,ownerSourceEntityId:ht.owner,type:pt.type,...(dt=pt.script)!=null&&dt.$ref?{refId:tt(pt.script.$ref),...pt.script.key?{scriptKey:pt.script.key}:{}}:{},props:convertAssetRefsToDomainRefs(pt.props??{},tt),...(ut=pt.calls)!=null&&ut.length?{calls:convertAssetRefsToDomainRefs(pt.calls,tt)}:{}}}return et}function requireRootOnlyGLTFOverrideTarget(rt,_e){if(rt!=="root")throw new Error(`Invalid source v2 scene file: glTF ${_e} target "${rt}" is not the synthetic root`)}function seedRootOnlyGLTFOverridesFromInlineSource(rt,_e){var nt,it,at,ot,st;const tt=createEmptyPrefabOverrides();if(!rt)return tt;for(const ct of rt.entityProps??[])requireRootOnlyGLTFOverrideTarget(ct.target,"entityProps"),tt.entityProps.root=inlineEntityOverrideToDomainProps(ct,_e);for(const ct of rt.removedEntities??[])requireRootOnlyGLTFOverrideTarget(ct,"removed entity"),tt.removedEntities.root=!0;if((nt=rt.componentProps)!=null&&nt.length)throw new Error("Invalid source v2 scene file: glTF componentProps require source component topology and cannot be hydrated from a root-only glTF source instance");if((it=rt.removedComponents)!=null&&it.length)throw new Error("Invalid source v2 scene file: glTF removedComponents require source component topology and cannot be hydrated from a root-only glTF source instance");let et=0;for(const ct of rt.addedEntities??[]){requireRootOnlyGLTFOverrideTarget(ct.parent,"added entity parent");const dt=requireInlineOverrideId(ct.id,ct.entity.id,"added entity override");tt.addedEntities[dt]={entityId:dt,parentSourceEntityId:"root",index:ct.index??et++}}for(const ct of rt.addedComponents??[]){requireRootOnlyGLTFOverrideTarget(ct.owner,"added component owner");const dt=requireInlineOverrideId(ct.id,ct.component.id,"added component override"),ut=ct.component,ht=(at=tt.addedComponents).root??(at.root={});ht[dt]={componentId:dt,ownerSourceEntityId:"root",type:ut.type,...(ot=ut.script)!=null&&ot.$ref?{refId:_e(ut.script.$ref),...ut.script.key?{scriptKey:ut.script.key}:{}}:{},props:convertAssetRefsToDomainRefs(ut.props??{},_e),...(st=ut.calls)!=null&&st.length?{calls:convertAssetRefsToDomainRefs(ut.calls,_e)}:{}}}return tt}function filterPrefabOverridesForRefreshedSnapshots(rt){const{binding:_e,previousSourceRootEntityId:tt,nextSnapshots:et}=rt,nt=createEmptyPrefabOverrides(),it=ct=>ct===tt?_e.sourceRootEntityId:ct,at=ct=>{const dt=it(ct),ut=et[dt];if(!(!ut||isSourceEntityRemovedOrCovered(nt.removedEntities,et,dt)))return{currentSourceEntityId:dt,snapshot:ut}},ot=(ct,dt)=>{for(const[ut,ht]of Object.entries(ct??{})){const ft=at(ut);ft&&dt(ut,ft.currentSourceEntityId,ht,ft.snapshot)}},st=(ct,dt)=>{ot(ct,(ut,ht,ft,pt)=>{for(const[mt,vt]of Object.entries(ft))pt.components[mt]&&dt(ut,ht,mt,vt,pt)})};for(const ct of Object.keys(_e.overrides.removedEntities??{})){const dt=it(ct);et[dt]&&(isSourceEntityCoveredByRemovedAncestor(_e.overrides.removedEntities,et,dt)||(nt.removedEntities[dt]=!0))}st(_e.overrides.removedComponents,(ct,dt,ut)=>{var ft;const ht=(ft=nt.removedComponents)[dt]??(ft[dt]={});ht[ut]=!0}),ot(_e.overrides.entityProps,(ct,dt,ut)=>{if(nt.entityProps[dt])throw new Error(`Prefab override entityProps collision: source entity "${ct}" maps to "${dt}", which already has overrides from an earlier source entity`);nt.entityProps[dt]=clone(ut)}),st(_e.overrides.componentProps,(ct,dt,ut,ht)=>{var pt,mt;if((pt=nt.removedComponents[dt])!=null&&pt[ut])return;const ft=(mt=nt.componentProps)[dt]??(mt[dt]={});if(ft[ut])throw new Error(`Prefab override componentProps collision: source component "${ut}" on source entity "${ct}" maps to "${dt}", which already has overrides from an earlier source component`);ft[ut]=mergeSourceValueRecords({},ht)});for(const[ct,dt]of Object.entries(_e.overrides.addedEntities??{})){const ut=at(dt.parentSourceEntityId);if(!ut)continue;const{currentSourceEntityId:ht}=ut;nt.addedEntities[ct]={...clone(dt),parentSourceEntityId:ht}}return ot(_e.overrides.addedComponents,(ct,dt,ut)=>{var ft;const ht=(ft=nt.addedComponents)[dt]??(ft[dt]={});for(const[pt,mt]of Object.entries(ut)){if(ht[pt])throw new Error(`Prefab override addedComponents collision: added component "${pt}" on source entity "${ct}" maps to "${dt}", which already has an added component with the same id`);ht[pt]={...clone(mt),ownerSourceEntityId:dt}}}),nt}function isSourceEntityCoveredByRemovedAncestor(rt,_e,tt){var nt,it;let et=(nt=_e[tt])==null?void 0:nt.parentSourceEntityId;for(;et;){if(rt[et])return!0;et=((it=_e[et])==null?void 0:it.parentSourceEntityId)??null}return!1}function isSourceEntityRemovedOrCovered(rt,_e,tt){return!!(rt[tt]||isSourceEntityCoveredByRemovedAncestor(rt,_e,tt))}function collectReservedAddedSceneEntityIds(rt){const _e=new Set;for(const tt of Object.values(rt.bindings))for(const et of Object.values(tt.overrides.addedEntities??{}))_e.add(et.entityId);return _e}function collectReservedAddedSceneComponentIds(rt){const _e=new Set;for(const tt of Object.values(rt.bindings))for(const et of Object.values(tt.overrides.addedComponents??{}))for(const nt of Object.values(et))_e.add(nt.componentId);return _e}function refreshPrefabBindingSnapshotsFromSource(rt,_e,tt,et=[],nt=[]){if(!_e.resolvePrefabSourceFile)return rt;const it=clone(rt),at=collectComponentRecords(tt),ot=new Set([...et,...Object.keys(tt),...collectReservedAddedSceneEntityIds(it)]),st=new Set([...nt,...collectReservedAddedSceneComponentIds(it)]);for(const ct of Object.values(it.bindings)){if(ct.assetKind!=="Prefab")continue;const dt=_e.resolvePrefabSourceFile(ct.assetId);if(!dt)throw new Error(`Cannot refresh Prefab binding "${ct.id}" for asset "${ct.assetId}": source file is unavailable`);const ut=normalizeSourceIdPrefabFile(dt);assertSourceV2PrefabFileStructure(ut);const ht=ct.sourceRootEntityId,ft=ut.root;ft&&(ct.sourceRootEntityId=ft,ct.sourceToSceneEntity[ft]=ct.instanceRootEntityId);const pt=derivePrefabSourceSnapshotsFromFile(ct,ut,_e,at,ot,st);ct.sourceToSceneEntity=Object.fromEntries(Object.entries(pt).map(([mt,vt])=>[mt,ct.sourceToSceneEntity[mt]??vt.sceneEntityId])),ct.sourceEntitySnapshots=pt,ct.overrides=filterPrefabOverridesForRefreshedSnapshots({binding:ct,previousSourceRootEntityId:ht,nextSnapshots:pt})}return it}function seedSourceSceneInstanceBindings(rt,_e,tt){var it,at,ot,st,ct,dt;const et=clone(rt);let nt=!1;for(const ut of _e.entities){const ht=(at=(it=ut.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!ht)continue;const ft=resolveSourceAssetRef(ht,tt,"scene instance"),pt=resolveSourceAssetKind(ht,ft,tt,"scene instance");if(pt!=="Prefab"&&pt!=="glTF")continue;if(findBindingForInstanceRoot(et,ut.id,{assetId:ft,assetKind:pt})){seedInlineAddedSourceInstanceBindings(et,(ot=ut.instance)==null?void 0:ot.overrides,tt)&&(nt=!0);continue}let mt;if(pt==="Prefab"){if(!tt.resolvePrefabSourceFile)continue;const vt=tt.resolvePrefabSourceFile(ft);if(!vt)throw new Error(`Cannot rebuild Prefab binding for scene instance "${ut.id}" and asset "${ft}": source file is unavailable`);const _t=normalizeSourceIdPrefabFile(vt);assertSourceV2PrefabFileStructure(_t);const yt=_t.root,bt=`binding-${ft}-${ut.id}`,Et=seedPrefabOverridesFromInlineSource((st=ut.instance)==null?void 0:st.overrides,_t,tt.resolveSourceRef);mt={id:bt,assetId:ft,assetKind:pt,instanceRootEntityId:ut.id,sourceRootEntityId:yt,sourceRevision:1,sourceToSceneEntity:{[yt]:ut.id},sourceEntitySnapshots:{},overrides:Et}}else mt={id:createUniquePrefabBindingId(et.bindings,ft,ut.id),assetId:ft,assetKind:pt,instanceRootEntityId:ut.id,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:ut.id},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:ut,sourceEntityId:ut.id,sceneEntityId:ut.id})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ct=ut.instance)==null?void 0:ct.overrides,tt.resolveSourceRef)};et.bindings[mt.id]=mt,seedInlineAddedSourceInstanceBindings(et,(dt=ut.instance)==null?void 0:dt.overrides,tt),nt=!0}return nt?{bindings:et.bindings,byAssetId:rebuildPrefabBindingAssetIndex(et.bindings)}:rt}function rebuildPrefabBindingAssetIndex(rt){var tt;const _e={};for(const et of Object.values(rt)){const nt=_e[tt=et.assetId]??(_e[tt]=[]);nt.includes(et.id)||nt.push(et.id)}return _e}function sourceVec3Override(rt){if(!Array.isArray(rt)||rt.length<3)return;const[_e,tt,et]=rt;return typeof _e=="number"&&typeof tt=="number"&&typeof et=="number"?{x:_e,y:tt,z:et}:void 0}function inlineEntityOverrideToDomainProps(rt,_e){const{target:tt,position:et,rotation:nt,scale:it,...at}=rt,ot=convertAssetRefsToDomainRefs(at,_e),st={},ct=sourceVec3Override(et),dt=sourceVec3Override(nt),ut=sourceVec3Override(it);return ct&&(st.position=ct),dt&&(st.rotation=dt),ut&&(st.scale=ut),Object.keys(st).length>0&&(ot.transform=st),ot}function findBindingForInstanceRoot(rt,_e,tt){return Object.values(rt.bindings).find(et=>et.instanceRootEntityId===_e&&et.assetId===tt.assetId&&et.assetKind===tt.assetKind)}function getSceneEntityIdForSourceEntity(rt,_e){var tt,et;return rt.sourceToSceneEntity[_e]??((et=(tt=rt.sourceEntitySnapshots)==null?void 0:tt[_e])==null?void 0:et.sceneEntityId)}function prunePrefabBindingsToReachableSourceInstances(rt,_e,tt){const et=new Set,nt=at=>{var dt,ut,ht;if(et.has(at.id))return;et.add(at.id);for(const ft of Object.values(at.overrides.addedEntities??{}))for(const pt of Object.values(_e.bindings))pt.instanceRootEntityId===ft.entityId&&nt(pt);if(at.assetKind!=="Prefab")return;const ot=(dt=tt.resolvePrefabSourceFile)==null?void 0:dt.call(tt,at.assetId);if(!ot)return;const st=normalizeSourceIdPrefabFile(ot),ct=buildSourceIdIndex(st);for(const ft of collectReachablePrefabEntityIds(st)){const pt=ct.entityById.get(ft),mt=(ht=(ut=pt==null?void 0:pt.instance)==null?void 0:ut.asset)==null?void 0:ht.$ref;if(!pt||!ft||!mt)continue;const vt=resolveSourceAssetRef(mt,tt,"nested instance"),_t=resolveSourceAssetKind(mt,vt,tt,"nested instance"),yt=getSceneEntityIdForSourceEntity(at,ft);if(!yt)continue;const bt=findBindingForInstanceRoot(_e,yt,{assetId:vt,assetKind:_t});bt&&nt(bt)}};if(rt.entities.forEach(at=>{var ht,ft;const ot=at.id,st=(ft=(ht=at.instance)==null?void 0:ht.asset)==null?void 0:ft.$ref;if(!ot||!st)return;const ct=resolveSourceAssetRef(st,tt,"scene instance"),dt=resolveSourceAssetKind(st,ct,tt,"scene instance"),ut=findBindingForInstanceRoot(_e,ot,{assetId:ct,assetKind:dt});ut&&nt(ut)}),et.size===Object.keys(_e.bindings).length)return _e;const it={};for(const[at,ot]of Object.entries(_e.bindings))et.has(at)&&(it[at]=ot);return{bindings:it,byAssetId:rebuildPrefabBindingAssetIndex(it)}}function collectMissingNestedSourceInstanceBindings(rt,_e){var et,nt;const tt=[];if(!_e.resolvePrefabSourceFile)return tt;for(const it of Object.values(rt.bindings)){if(it.assetKind!=="Prefab")continue;const at=_e.resolvePrefabSourceFile(it.assetId);if(!at)throw new Error(`Cannot validate nested source instances for Prefab binding "${it.id}" for asset "${it.assetId}": source file is unavailable`);const ot=normalizeSourceIdPrefabFile(at),st=buildSourceIdIndex(ot);for(const ct of collectReachablePrefabEntityIds(ot)){const dt=st.entityById.get(ct),ut=(nt=(et=dt==null?void 0:dt.instance)==null?void 0:et.asset)==null?void 0:nt.$ref;if(!ct||!ut||isRemovedSourceEntity(it,ct))continue;const ht=resolveSourceAssetRef(ut,_e,"nested instance"),ft=resolveSourceAssetKind(ut,ht,_e,"nested instance"),pt=getSceneEntityIdForSourceEntity(it,ct);if(!pt)throw new Error(`Prefab binding "${it.id}" nested source instance "${ct}" (${ut}) is missing a scene entity mapping`);findBindingForInstanceRoot(rt,pt,{assetId:ht,assetKind:ft})||tt.push({bindingId:it.id,sourceEntityId:ct,sourceEntity:dt,sourceRef:ut,assetId:ht,assetKind:ft,sceneEntityId:pt})}}return tt}function assertNestedSourceInstanceBindingsPresent(rt,_e){const tt=collectMissingNestedSourceInstanceBindings(rt,_e);if(tt.length===0)return;const et=tt[0];throw new Error(`Prefab binding "${et.bindingId}" nested source instance "${et.sourceEntityId}" (${et.sourceRef}) materializes scene entity "${et.sceneEntityId}", but its ${et.assetKind} binding for asset "${et.assetId}" is missing`)}function createUniquePrefabBindingId(rt,_e,tt){const et=`binding-${_e}-${tt}`;if(!rt[et])return et;let nt=1;for(;rt[`${et}-${nt}`];)nt+=1;return`${et}-${nt}`}function createSyntheticGlTFRootSnapshot(rt){const _e={...rt.sourceEntity,id:rt.sourceEntityId,children:void 0,components:void 0},tt=readSourceEntityResolvedState(_e,rt.sourceEntityId,{rootOverrideTarget:"root"});return{sceneEntityId:rt.sceneEntityId,parentSourceEntityId:null,childSourceEntityIds:[],childIndex:0,name:tt.name,isActive:tt.isActive,...tt.layer!==void 0?{layer:tt.layer}:{},...tt.isLocked!==void 0?{isLocked:tt.isLocked}:{},transform:tt.transform,components:{}}}function createSourceInstanceBindingFromInlineSource(rt){var ct,dt,ut;const{prefab:_e,sourceEntity:tt,sceneEntityId:et,sourceRef:nt,assetId:it,assetKind:at,options:ot}=rt,st=createUniquePrefabBindingId(_e.bindings,it,et);if(at==="Prefab"){const ht=(ct=ot.resolvePrefabSourceFile)==null?void 0:ct.call(ot,it);if(!ht)throw new Error(`Cannot rebuild Prefab binding for source instance "${et}" (${nt}) and asset "${it}": source file is unavailable`);const ft=normalizeSourceIdPrefabFile(ht),pt=ft.root;return{id:st,assetId:it,assetKind:at,instanceRootEntityId:et,sourceRootEntityId:pt,sourceRevision:1,sourceToSceneEntity:{[pt]:et},sourceEntitySnapshots:{},overrides:seedPrefabOverridesFromInlineSource((dt=tt.instance)==null?void 0:dt.overrides,ft,ot.resolveSourceRef)}}return{id:st,assetId:it,assetKind:at,instanceRootEntityId:et,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:et},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:tt,sourceEntityId:et,sceneEntityId:et})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ut=tt.instance)==null?void 0:ut.overrides,ot.resolveSourceRef)}}function seedInlineAddedSourceInstanceBindings(rt,_e,tt){var nt,it,at,ot;if(!((nt=_e==null?void 0:_e.addedEntities)!=null&&nt.length))return!1;let et=!1;for(const st of _e.addedEntities){const ct=st.entity,dt=(at=(it=ct.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!dt)continue;const ut=requireInlineOverrideId(st.id,ct.id,"added entity override"),ht=resolveSourceAssetRef(dt,tt,"inline added instance"),ft=resolveSourceAssetKind(dt,ht,tt,"inline added instance");if(findBindingForInstanceRoot(rt,ut,{assetId:ht,assetKind:ft}))continue;const pt=createSourceInstanceBindingFromInlineSource({prefab:rt,sourceEntity:ct,sceneEntityId:ut,sourceRef:dt,assetId:ht,assetKind:ft,options:tt});rt.bindings[pt.id]=pt,et=!0,seedInlineAddedSourceInstanceBindings(rt,(ot=ct.instance)==null?void 0:ot.overrides,tt)&&(et=!0)}return et}function hasMissingInlineAddedSourceInstanceBindings(rt,_e,tt){var et,nt,it;if(!((et=_e==null?void 0:_e.addedEntities)!=null&&et.length))return!1;for(const at of _e.addedEntities){const ot=at.entity,st=(it=(nt=ot.instance)==null?void 0:nt.asset)==null?void 0:it.$ref;if(!st)continue;const ct=requireInlineOverrideId(at.id,ot.id,"added entity override"),dt=resolveSourceAssetRef(st,tt,"inline added instance"),ut=resolveSourceAssetKind(st,dt,tt,"inline added instance");if(!findBindingForInstanceRoot(rt,ct,{assetId:dt,assetKind:ut}))return!0}return!1}function seedInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e){var et,nt;if(!_e.resolvePrefabSourceFile)return!1;let tt=!1;for(const it of Object.values(rt.bindings)){if(it.assetKind!=="Prefab")continue;const at=_e.resolvePrefabSourceFile(it.assetId);if(!at)continue;const ot=normalizeSourceIdPrefabFile(at),st=buildSourceIdIndex(ot);for(const ct of collectReachablePrefabEntityIds(ot)){const dt=st.entityById.get(ct);if(!((et=dt==null?void 0:dt.instance)!=null&&et.overrides)||isRemovedSourceEntity(it,ct))continue;const ut=(nt=dt.instance.asset)==null?void 0:nt.$ref;if(!ut)continue;const ht=getSceneEntityIdForSourceEntity(it,ct);if(!ht)continue;const ft=resolveSourceAssetRef(ut,_e,"nested instance"),pt=resolveSourceAssetKind(ut,ft,_e,"nested instance");findBindingForInstanceRoot(rt,ht,{assetId:ft,assetKind:pt})&&seedInlineAddedSourceInstanceBindings(rt,dt.instance.overrides,_e)&&(tt=!0)}}return tt}function hasMissingInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e){var tt,et;if(!_e.resolvePrefabSourceFile)return!1;for(const nt of Object.values(rt.bindings)){if(nt.assetKind!=="Prefab")continue;const it=_e.resolvePrefabSourceFile(nt.assetId);if(!it)continue;const at=normalizeSourceIdPrefabFile(it),ot=buildSourceIdIndex(at);for(const st of collectReachablePrefabEntityIds(at)){const ct=ot.entityById.get(st);if(!((tt=ct==null?void 0:ct.instance)!=null&&tt.overrides)||isRemovedSourceEntity(nt,st))continue;const dt=(et=ct.instance.asset)==null?void 0:et.$ref;if(!dt)continue;const ut=getSceneEntityIdForSourceEntity(nt,st);if(!ut)continue;const ht=resolveSourceAssetRef(dt,_e,"nested instance"),ft=resolveSourceAssetKind(dt,ht,_e,"nested instance");if(findBindingForInstanceRoot(rt,ut,{assetId:ht,assetKind:ft})&&hasMissingInlineAddedSourceInstanceBindings(rt,ct.instance.overrides,_e))return!0}}return!1}function seedNestedSourceInstanceBindings(rt,_e,tt){var ot,st,ct,dt;const et=collectMissingNestedSourceInstanceBindings(rt,_e),nt=hasMissingInlineAddedSourceInstanceBindingsForNestedSourceInstances(rt,_e);if(et.length===0&&!nt)return{prefab:rt,changed:!1};const it=clone(rt);let at=!1;for(const ut of et){if(findBindingForInstanceRoot(it,ut.sceneEntityId,{assetId:ut.assetId,assetKind:ut.assetKind}))continue;const ht=rt.bindings[ut.bindingId],ft=tt.get(ut.bindingId)??(ht?[ht.assetId]:[]);if(ft.includes(ut.assetId))throw new Error(`Prefab source instance asset cycle detected: ${[...ft,ut.assetId].join(" -> ")}`);const pt=createUniquePrefabBindingId(it.bindings,ut.assetId,ut.sceneEntityId);let mt;if(ut.assetKind==="Prefab"){const vt=(ot=_e.resolvePrefabSourceFile)==null?void 0:ot.call(_e,ut.assetId);if(!vt)throw new Error(`Cannot rebuild nested Prefab binding for source instance "${ut.sourceEntityId}" and asset "${ut.assetId}": source file is unavailable`);const _t=normalizeSourceIdPrefabFile(vt),yt=_t.root;mt={id:pt,assetId:ut.assetId,assetKind:ut.assetKind,instanceRootEntityId:ut.sceneEntityId,sourceRootEntityId:yt,sourceRevision:1,sourceToSceneEntity:{[yt]:ut.sceneEntityId},sourceEntitySnapshots:{},overrides:seedPrefabOverridesFromInlineSource((st=ut.sourceEntity.instance)==null?void 0:st.overrides,_t,_e.resolveSourceRef)}}else mt={id:pt,assetId:ut.assetId,assetKind:ut.assetKind,instanceRootEntityId:ut.sceneEntityId,sourceRootEntityId:"root",sourceRevision:1,sourceToSceneEntity:{root:ut.sceneEntityId},sourceEntitySnapshots:{root:createSyntheticGlTFRootSnapshot({sourceEntity:ut.sourceEntity,sourceEntityId:ut.sourceEntityId,sceneEntityId:ut.sceneEntityId})},overrides:seedRootOnlyGLTFOverridesFromInlineSource((ct=ut.sourceEntity.instance)==null?void 0:ct.overrides,_e.resolveSourceRef)};it.bindings[mt.id]=mt,tt.set(mt.id,[...ft,ut.assetId]),seedInlineAddedSourceInstanceBindings(it,(dt=ut.sourceEntity.instance)==null?void 0:dt.overrides,_e),at=!0}return seedInlineAddedSourceInstanceBindingsForNestedSourceInstances(it,_e)&&(at=!0),at?{prefab:{bindings:it.bindings,byAssetId:rebuildPrefabBindingAssetIndex(it.bindings)},changed:!0}:{prefab:rt,changed:!1}}function rememberPrefabBindingAssetPaths(rt,_e){for(const tt of Object.values(rt.bindings))_e.has(tt.id)||_e.set(tt.id,[tt.assetId])}function refreshAndSeedPrefabBindingsFromSource(rt,_e,tt,et,nt,it){let at=seedSourceSceneInstanceBindings(rt,_e,tt);const ot=new Map;for(rememberPrefabBindingAssetPaths(at,ot);;){const st=Object.keys(at.bindings).length;at=refreshPrefabBindingSnapshotsFromSource(at,tt,et,nt,it);const ct=seedNestedSourceInstanceBindings(at,tt,ot);if(at=ct.prefab,rememberPrefabBindingAssetPaths(at,ot),!ct.changed)return at;if(Object.keys(at.bindings).length<=st)throw new Error(`Prefab source instance binding refresh did not make progress (${st} bindings). Check nested prefab/glTF source instance data for a cycle or invalid materialization state.`)}}function snapshotEntityToDomainEntity(rt,_e,tt,et){var vt,_t,yt,bt,Et;const nt=tt.sceneEntityId??rt.sourceToSceneEntity[_e];if(!nt)throw new Error(`Prefab binding "${rt.id}" snapshot "${_e}" is missing sceneEntityId`);const it=tt.parentSourceEntityId?rt.sourceToSceneEntity[tt.parentSourceEntityId]??null:(et==null?void 0:et.parentId)??null,at=(vt=rt.overrides.entityProps)==null?void 0:vt[_e],ot=et==null?void 0:et.instance,st=(ot==null?void 0:ot.bindingId)===rt.id&&ot.role!=="added"&&(ot.sourceEntityId===_e||ot.role==="root"&&ot.sourceEntityId===void 0&&_e===rt.sourceRootEntityId),ct=[];for(const St of tt.childSourceEntityIds??[]){if(isRemovedSourceEntity(rt,St))continue;const At=rt.sourceToSceneEntity[St];if(!At)throw new Error(`Prefab binding "${rt.id}" snapshot child "${St}" is missing sourceToSceneEntity mapping`);ct.push(At)}const dt=new Map(Object.entries(rt.sourceToSceneEntity).map(([St,At])=>[At,St])),ut=((et==null?void 0:et.children)??[]).filter(St=>{const At=dt.get(St);return!At||!isRemovedSourceEntity(rt,At)}),ht={};for(const[St,At]of Object.entries(tt.components??{})){const xt=At.sceneComponentId;xt&&((yt=(_t=rt.overrides.removedComponents)==null?void 0:_t[_e])!=null&&yt[St]||(ht[xt]=snapshotComponentToDomainComponent(rt.id,St,At,(Et=(bt=rt.overrides.componentProps)==null?void 0:bt[_e])==null?void 0:Et[St])))}const ft=_e!==rt.sourceRootEntityId&&tt.instanceAssetKind&&(ot==null?void 0:ot.role)==="root"&&ot.assetKind===tt.instanceAssetKind,pt=Object.fromEntries(Object.entries((et==null?void 0:et.components)??{}).filter(([,St])=>{const At=St.instance;return!((At==null?void 0:At.bindingId)===rt.id&&At.role!=="added")})),mt=(at==null?void 0:at.layer)??tt.layer??((et==null?void 0:et.layer)!==void 0&&!st&&!ft?et.layer:void 0);return{id:nt,name:(at==null?void 0:at.name)??(et&&!st&&!ft?et.name:tt.name),isActive:(at==null?void 0:at.isActive)??(et&&!st&&!ft?et.isActive:tt.isActive),parentId:it,children:appendUnique(ct,ut),transform:mergeTransform(et&&!st&&!ft?et.transform:clone(tt.transform),at==null?void 0:at.transform),components:{...pt,...ht},...mt!==void 0&&mt!==0?{layer:mt}:{},...(at==null?void 0:at.isLocked)!==void 0?{isLocked:at.isLocked}:tt.isLocked!==void 0?{isLocked:tt.isLocked}:(et==null?void 0:et.isLocked)!==void 0&&!st&&!ft?{isLocked:et.isLocked}:{},instance:ft?ot:{bindingId:rt.id,assetId:rt.assetId,assetKind:rt.assetKind,role:_e===rt.sourceRootEntityId?"root":"linked",sourceEntityId:_e}}}function orderPrefabBindingsForSnapshotMaterialization(rt){const _e=Object.values(rt.bindings),tt=new Map(_e.map(st=>[st.id,st])),et=new Map;for(const st of _e){let ct=et.get(st.id);ct||(ct=new Set,et.set(st.id,ct));for(const dt of Object.values(st.sourceEntitySnapshots??{})){if(!dt.instanceAssetKind)continue;const ut=_e.find(ht=>ht.id!==st.id&&ht.instanceRootEntityId===dt.sceneEntityId&&ht.assetKind===dt.instanceAssetKind);ut&&ct.add(ut.id)}}const nt=[],it=new Set,at=new Set,ot=st=>{if(!at.has(st.id)){if(it.has(st.id))throw new Error(`Prefab binding materialization dependency cycle detected at "${st.id}"`);it.add(st.id);for(const ct of et.get(st.id)??[]){const dt=tt.get(ct);dt&&ot(dt)}it.delete(st.id),at.add(st.id),nt.push(st)}};for(const st of _e)ot(st);return nt}function materializePrefabBindingSnapshots(rt,_e){for(const tt of orderPrefabBindingsForSnapshotMaterialization(_e))for(const[et,nt]of Object.entries(tt.sourceEntitySnapshots??{})){if(isRemovedSourceEntity(tt,et)){const at=nt.sceneEntityId??tt.sourceToSceneEntity[et];at&&delete rt[at];continue}const it=nt.sceneEntityId??tt.sourceToSceneEntity[et];it&&(rt[it]=snapshotEntityToDomainEntity(tt,et,nt,rt[it]))}}function assertNoUnmaterializedSourceInstances(rt,_e,tt){var et,nt;for(const it of Object.values(rt)){const at=(et=it.instance)==null?void 0:et.bindingId;if(!(!at||_e.bindings[at])&&!(tt.allowUnmaterializedGlTFInstances&&((nt=it.instance)==null?void 0:nt.assetKind)==="glTF"))throw new Error(`Cannot direct-hydrate source v2 instance entity "${it.id}" without prefab binding snapshots. Asset-backed instance expansion must happen before scene hydration enters DomainState; check that instantiate() ran for all referenced prefab assets.`)}}function assertAddedOverridesMaterialized(rt,_e){for(const tt of Object.values(rt.bindings)){for(const et of Object.values(tt.overrides.addedEntities??{}))if(!hasMaterializedAddedEntity(_e,tt.id,et.entityId))throw new Error(`Prefab binding "${tt.id}" added entity "${et.entityId}" is missing inline payload during source-v2 hydration`);for(const[et,nt]of Object.entries(tt.overrides.addedComponents??{}))for(const it of Object.values(nt))if(!hasMaterializedAddedComponent(_e,tt.id,et,it.componentId))throw new Error(`Prefab binding "${tt.id}" added component "${it.componentId}" is missing inline payload during source-v2 hydration`)}}function assertGLTFBindingsHaveSourceSnapshots(rt){for(const _e of Object.values(rt.bindings)){if(_e.assetKind!=="glTF")continue;const tt=_e.sourceEntitySnapshots??{};if(!(Object.keys(tt).length>0&&tt[_e.sourceRootEntityId]))throw new Error(`Cannot direct-hydrate glTF binding "${_e.id}" without source snapshots. glTF source baselines are not refreshed from source v2 scene hydration, so persisted binding snapshots must include the instance root.`)}}function createRequiredHydrationSourceRefResolver(rt){const _e=createSourceRefCodec({resolveSourceRef:rt});return tt=>_e.sourceToDomain(tt)}function hydrateSourceV2SceneToDomain(rt,_e={}){const tt=rt,et={},nt=[],it=createRequiredHydrationSourceRefResolver(_e.resolveSourceRef),at={..._e,resolveSourceRef:it};parseSceneFileV2(tt,et,nt,{...at,deferPrefabInlineOverrideMaterialization:!0});const ot=tt.entities.map(pt=>pt.id),st=tt.components.map(pt=>pt.id),ct=at.initialPrefabState?clone(at.initialPrefabState):createEmptyPrefabState(),dt=refreshAndSeedPrefabBindingsFromSource(ct,tt,at,et,ot,st),ut=prunePrefabBindingsToReachableSourceInstances(tt,dt,at);at.allowMissingNestedInstanceBindings||assertNestedSourceInstanceBindingsPresent(ut,at),assertGLTFBindingsHaveSourceSnapshots(ut),materializePrefabBindingSnapshots(et,ut);const ht=createAddedOverrideMaterializationReport();materializeAddedOverridesFromSource(tt,et,it,at.resolveAssetKind,ut,ht),assertAddedOverridesMaterialized(ut,ht),assertNoUnmaterializedSourceInstances(et,ut,at);const ft=extractSceneSettings(rt.scene,at);return{scene:{rootEntityIds:nt,...ft?{settings:ft}:{}},entities:et,prefab:ut}}function isSceneFile(rt){return"scene"in rt}function createRequiredLocalSourceRefResolver(rt){return _e=>{const tt=rt==null?void 0:rt(_e);if(typeof tt!="string"||tt.length===0)throw new Error(`Unable to resolve source asset ref "${_e}" to an editor asset id during local v2 hydration`);return tt}}function buildParentById(rt){const _e=new Map;return rt.entities.forEach(tt=>{var et;isSourceInstanceBoundary(tt)||(et=tt.children)==null||et.forEach(nt=>{_e.set(nt,tt.id)})}),_e}function componentToLocalSchema(rt,_e,tt){var et,nt;return{id:_e,type:rt.type,props:convertAssetRefsToDomainRefs(rt.props??{},tt),...(et=rt.script)!=null&&et.$ref?{script:{$ref:tt(rt.script.$ref),...rt.script.key?{key:rt.script.key}:{}}}:{},...(nt=rt.calls)!=null&&nt.length?{calls:convertAssetRefsToDomainRefs(rt.calls,tt)}:{}}}function readTransform(rt,_e){return readSourceEntityResolvedState(rt,"",{...typeof _e=="string"?{rootOverrideTarget:_e}:{}}).transform}function hasSourceTransformComponent(rt,_e){return(rt.components??[]).some(tt=>{var nt;const et=(nt=_e.componentById.get(tt))==null?void 0:nt.type;return et==="Transform"||et==="UITransform"})}function applySourceEntityStateToEngine(rt,_e,tt,et){const nt=readSourceEntityResolvedState(_e,tt,{...typeof et=="string"?{rootOverrideTarget:et}:{}});rt.name=tt,rt.isActive=nt.isActive,nt.layer!==void 0&&(rt.layer=nt.layer);const it=nt.transform;rt.transform.position=new Vector3(it.position.x,it.position.y,it.position.z),rt.transform.rotation=new Vector3(it.rotation.x,it.rotation.y,it.rotation.z),rt.transform.scale=new Vector3(it.scale.x,it.scale.y,it.scale.z)}function applySourceEntityState(rt,_e,tt){const et=readSourceEntityResolvedState(_e,rt.id,{...typeof tt=="string"?{rootOverrideTarget:tt}:{}});rt.name=et.name,rt.isActive=et.isActive,et.layer!==void 0&&(rt.layer=decomposeLayersByBitwise(et.layer));const nt=rt.engineObject;nt&&applySourceEntityStateToEngine(nt,_e,et.name,tt)}function insertLocalChild(rt,_e,tt){const et=rt.selfChildrenId.filter(Boolean);et.includes(_e.id)||(et.splice(Math.min(tt,et.length),0,_e.id),rt.applyChildrenFromDomain(et)),_e.applyParentFromDomain(rt.id),!(!rt.engineObject||!_e.engineObject||_e.engineObject.parent===rt.engineObject)&&rt.engineObject.addChild(Math.min(tt,rt.engineObject.children.length),_e.engineObject)}async function addSourceComponents(rt,_e,tt,et){const nt=readTransform(_e);!rt.transform&&!hasSourceTransformComponent(_e,tt)&&EditorComponent.getRegisteredComponent("Transform")&&await rt.addEditorComponent({id:`${rt.id}:Transform`,type:"Transform",props:nt});for(const it of _e.components??[]){const at=tt.componentById.get(it);if(!at)throw new Error(`Invalid source v2 local hydration: component "${it}" is missing from source index`);await rt.addEditorComponent(componentToLocalSchema(at,it,et))}}async function createSourceEntityModel(rt,_e,tt,et){var ct;const nt=_e.entityById.get(tt);if(!nt)throw new Error(`Invalid source v2 file: entity id "${tt}" cannot be hydrated`);const it=(ct=nt.instance)==null?void 0:ct.asset;if(it!=null&&it.$ref){const dt=et.resolveSourceRef(it.$ref),ut=et.resolveAssetKind(it.$ref,dt),ht=resolveSourceInstanceRootOverrideTarget({sourceEntity:nt,fallbackSourceEntityId:tt,assetId:dt,instanceAssetKind:ut,resolvePrefabSourceFile:et.resolvePrefabSourceFile}),ft=await rt.root.assetStore.getAssetByRef({refId:dt});if(!(ft!=null&&ft.instantiate))throw new Error(`Cannot hydrate source v2 instance entity "${tt}": asset "${dt}" is not instantiable`);const pt=readSourceEntityResolvedState(nt,tt,{...typeof ht=="string"?{rootOverrideTarget:ht}:{}}),mt=await ft.instantiate(rt,pt.transform,{expectedRootId:tt,...rt.isDomainScoped?{deferDomainBinding:!0,deferredInstanceBindings:et.deferredInstanceBindings}:{}});return await mt.ensureReady(),applySourceEntityState(mt,nt,ht),mt}const at=readSourceEntityResolvedState(nt,tt),ot=rt.createEntity(at.name,tt),st=new Entity(rt.engine,at.name);return applySourceEntityStateToEngine(st,nt,at.name),await ot.bindEngineObject(st),await ot.initImmediate(),await ot.ensureReady(),applySourceEntityState(ot,nt),await addSourceComponents(ot,nt,_e,et.resolveSourceRef),applySourceEntityState(ot,nt),ot}async function hydrateSourceV2LocalEntities(rt,_e,tt={}){isSceneFile(_e)?assertSourceV2SceneFileStructure(_e):assertSourceV2PrefabFileStructure(_e);const et=tt.clearExisting??!0;et&&rt.clear();const it={resolveSourceRef:createRequiredLocalSourceRefResolver(tt.resolveSourceRef),resolveAssetKind:tt.resolveAssetKind??(()=>{}),resolvePrefabSourceFile:tt.resolvePrefabSourceFile,clearExisting:et,registerDomain:tt.registerDomain??!0,deferredInstanceBindings:tt.deferredInstanceBindings??[]},at=buildSourceIdIndex(_e),ot=buildParentById(_e),st=getSourceRootEntityIds(_e),ct=collectReachableSourceEntityIds(_e.entities,st),dt=new Set(ct),ut=new Map,ht=async pt=>{const mt=ut.get(pt);if(mt)return mt;const vt=await createSourceEntityModel(rt,at,pt,it);ut.set(pt,vt);const _t=at.entityById.get(pt),yt=isSourceInstanceBoundary(_t)?[]:(_t==null?void 0:_t.children)??[];for(let bt=0;bt<yt.length;bt++){const Et=yt[bt];if(!dt.has(Et))throw new Error(`Invalid source v2 local hydration: child entity "${Et}" is not reachable`);const St=await ht(Et);insertLocalChild(vt,St,vt.selfChildrenId.length+bt)}return vt},ft=[];for(const pt of st)ft.push(await ht(pt));for(const pt of ct)!ot.has(pt)&&!st.includes(pt)&&ft.push(await ht(pt));if(et&&rt.setLocalRootEntityIds(ft.map(pt=>pt.id)),rt.isDomainScoped&&it.registerDomain){for(const mt of ft)rt.root.domainStore.state.entities[mt.id]||rt.registerEntityTreeInDomain(mt,null,void 0,{deferInstanceBinding:!0});const pt=it.deferredInstanceBindings.splice(0);for(const mt of pt)mt()}return ft}var __defProp$5=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$4(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$5(_e,tt,nt),nt};class SceneUIStore extends RootStore{constructor(tt){super(tt);Rt(this,"selectedKeys",new Set);Rt(this,"expandedKeys",new Set([DEFAULT_SCENE]));Rt(this,"visibilityById",observable.map());Rt(this,"hoveredEntityId",null);Rt(this,"searchText","");Rt(this,"lastSelectedId",null);Rt(this,"_logger",new TraceLogger("SceneUIStore"));Rt(this,"_selectionListeners",new Set);makeObservable(this)}onSelectionChange(tt){return this._selectionListeners.add(tt),()=>this._selectionListeners.delete(tt)}_notifySelectionChange(){for(const tt of[...this._selectionListeners])tt()}isEntityVisible(tt){return this.visibilityById.get(tt)??!0}isEntityExpanded(tt){return this.expandedKeys.has(tt)}selectEntity(tt,et=!1){this._logger.info("selectEntity",{id:tt,multiple:et}),et||this.selectedKeys.clear(),this.selectedKeys.add(tt),this.lastSelectedId=tt,this._notifySelectionChange()}replaceSelectedKeys(tt){this.selectedKeys.clear();for(const et of tt)this.selectedKeys.add(et);this._notifySelectionChange()}clearSelection(){this._logger.info("clearSelection"),this.selectedKeys.clear(),this.lastSelectedId=null,this._notifySelectionChange()}deselectEntity(tt){this._logger.info("deselectEntity",{id:tt}),this.selectedKeys.delete(tt),this.lastSelectedId===tt&&(this.lastSelectedId=Array.from(this.selectedKeys).pop()??null),this._notifySelectionChange()}setLastSelectedId(tt){this.lastSelectedId=tt}expandEntity(tt){this.expandedKeys.add(tt)}collapseEntity(tt){this.expandedKeys.delete(tt)}setSearchText(tt){this.searchText=tt}setHoveredEntity(tt){this.hoveredEntityId=tt}setEntityVisible(tt,et){this.visibilityById.set(tt,et)}removeEntity(tt){this.selectedKeys.delete(tt),this.expandedKeys.delete(tt),this.visibilityById.delete(tt),this.hoveredEntityId===tt&&(this.hoveredEntityId=null),this.lastSelectedId===tt&&(this.lastSelectedId=Array.from(this.selectedKeys).pop()??null)}clear(){this.selectedKeys.clear(),this.expandedKeys.clear(),this.expandedKeys.add(DEFAULT_SCENE),this.visibilityById.clear(),this.hoveredEntityId=null,this.searchText="",this.lastSelectedId=null}}__decorateClass$4([observable],SceneUIStore.prototype,"selectedKeys",2);__decorateClass$4([observable],SceneUIStore.prototype,"expandedKeys",2);__decorateClass$4([observable],SceneUIStore.prototype,"visibilityById",2);__decorateClass$4([observable],SceneUIStore.prototype,"hoveredEntityId",2);__decorateClass$4([observable],SceneUIStore.prototype,"searchText",2);__decorateClass$4([observable],SceneUIStore.prototype,"lastSelectedId",2);__decorateClass$4([action],SceneUIStore.prototype,"selectEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"replaceSelectedKeys",1);__decorateClass$4([action],SceneUIStore.prototype,"clearSelection",1);__decorateClass$4([action],SceneUIStore.prototype,"deselectEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setLastSelectedId",1);__decorateClass$4([action],SceneUIStore.prototype,"expandEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"collapseEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setSearchText",1);__decorateClass$4([action],SceneUIStore.prototype,"setHoveredEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"setEntityVisible",1);__decorateClass$4([action],SceneUIStore.prototype,"removeEntity",1);__decorateClass$4([action],SceneUIStore.prototype,"clear",1);function groupAddedRootsByStrippedId(rt,_e,tt){const et=new Map;for(let nt=0,it=rt.length;nt<it;nt++){const at=rt[nt];if(at.strippedId)continue;const ot=at.parent;if(!ot||ot===tt||!_e.has(ot))continue;const st=et.get(ot)??[];st.push(at),et.set(ot,st)}return et}function indexSchemas(rt){const _e=new Map,tt=[],et=new Set;for(let nt=0,it=rt.length;nt<it;nt++){const at=rt[nt],ot=at.strippedId||at.id;ot&&(_e.set(ot,at),at.strippedId&&(tt.push(at),et.add(at.strippedId)))}return{schemaByKey:_e,strippedSchemas:tt,strippedIdSet:et}}function resolveStrippedOriginal(rt){const{strippedSchema:_e,schemaByKey:tt,entities:et,findByIndexPath:nt}=rt,it=resolveStrippedPrefabLink(_e),at=it.prefabInstanceId;if(!at)return null;const ot=tt.get(at);if(!(ot!=null&&ot.id))return null;const st=et.get(ot.id);if(!st)return null;const ct=it.sourceEntityId;return typeof ct!="string"?null:nt(st,ct)}function collectSidecarAddedEntityOverrides(rt){var tt;const _e=new Map;for(const[et,nt]of Object.entries((rt==null?void 0:rt.bindings)??{}))for(const it of Object.values(((tt=nt.overrides)==null?void 0:tt.addedEntities)??{}))_e.set(it.entityId,{...it,bindingId:et});return _e}function prepareSidecarAddedEntityRestore(rt){var et,nt;const _e=[],tt=[];for(const it of rt.entitiesSchema){const at=it.id;if(!at||rt.existingEntityIds.has(at))continue;const ot=rt.addedOverrides.get(at);if(!ot)continue;const st=(et=rt.prefabBindings)==null?void 0:et[ot.bindingId],ct=(nt=st==null?void 0:st.sourceToSceneEntity)==null?void 0:nt[ot.parentSourceEntityId];if(!st||!ct){tt.push({bindingId:ot.bindingId,entityId:at,parentSourceEntityId:ot.parentSourceEntityId});continue}_e.push({schema:it,bindingId:ot.bindingId,entityId:at,parentSourceEntityId:ot.parentSourceEntityId,parentSceneEntityId:ct,index:ot.index})}return{plans:_e,missingParents:tt}}function applySceneEntitySelection(rt,_e,tt=!1,et=!1){return rt.selectedKeys.has(_e)?et?(rt.deselectEntity(_e),{changed:!0,selected:rt.selectedKeys.size>0}):{changed:!1,selected:!0}:(rt.selectEntity(_e,tt),{changed:!0,selected:!0})}function collectSubtreeIds(rt,_e){const tt=[],et=nt=>{if(rt.entities[nt]){tt.push(nt);for(const at of rt.relations.entityChildren[nt]??[])et(at)}};return et(_e),tt}function getSiblingPath(rt){return rt?`/entities/${encodeJsonPointerSegment(rt)}/children`:"/scene/rootEntityIds"}function getSiblings(rt,_e){return _e?[...rt.relations.entityChildren[_e]??[]]:[...rt.scene.rootEntityIds]}function pushRemovedNestedBindingOps(rt,_e,tt,et){var it;const nt=new Set;for(const at of tt){const ot=(it=rt.entities[at])==null?void 0:it.instance;!(ot!=null&&ot.bindingId)||ot.role!=="root"||ot.bindingId!==et&&rt.prefab.bindings[ot.bindingId]&&nt.add(ot.bindingId)}if(nt.size!==0){for(const at of nt)_e.push({op:"remove",path:`/prefab/bindings/${encodeJsonPointerSegment(at)}`});for(const[at,ot]of Object.entries(rt.prefab.byAssetId)){const st=ot.filter(dt=>!nt.has(dt));if(st.length===ot.length)continue;const ct=`/prefab/byAssetId/${encodeJsonPointerSegment(at)}`;_e.push(st.length===0?{op:"remove",path:ct}:{op:"replace",path:ct,value:st})}}}function collectPreservedAddedEntityIds(rt,_e,tt){var it;if(!tt)return new Set;const et=rt.prefab.bindings[tt];if(!et)return new Set;const nt=new Set;for(const at of Object.keys(((it=et.overrides)==null?void 0:it.addedEntities)??{}))if(_e.has(at))for(const ot of collectSubtreeIds(rt,at))nt.add(ot);return nt}function pushPreservedAddedEntityReparentOps(rt,_e,tt,et){var at,ot;if(!et||tt.size===0)return;const nt=rt.prefab.bindings[et];if(!nt)return;const it=new Map;for(const st of Object.values(((at=nt.overrides)==null?void 0:at.addedEntities)??{})){if(!tt.has(st.entityId))continue;const ct=nt.sourceToSceneEntity[st.parentSourceEntityId];if(!ct||!rt.entities[ct])continue;const dt=it.get(ct)??[];dt.push({entityId:st.entityId,index:st.index}),it.set(ct,dt),((ot=rt.entities[st.entityId])==null?void 0:ot.parentId)!==ct&&_e.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(st.entityId)}/parentId`,value:ct})}for(const[st,ct]of it){const dt=getSiblings(rt,st).filter(ut=>!tt.has(ut));ct.sort((ut,ht)=>ut.index===ht.index?ut.entityId.localeCompare(ht.entityId):ut.index-ht.index).forEach(({entityId:ut,index:ht})=>{dt.splice(Math.min(Math.max(ht,0),dt.length),0,ut)}),_e.push({op:"replace",path:getSiblingPath(st),value:dt})}}function buildReplaceEntityTreeOps(rt,_e,tt){var _t,yt,bt;if(_e===tt)return[];const et=rt.entities[_e],nt=rt.entities[tt];if(!et||!nt)return[];const it=et.parentId??null,at=nt.parentId??null,ot=getSiblingPath(it),st=getSiblingPath(at),ct=getSiblings(rt,it),dt=getSiblings(rt,at),ut=Math.max(ct.indexOf(_e),0),ht=[];st!==ot&&ht.push({op:"replace",path:st,value:dt.filter(Et=>Et!==tt)});const ft=ct.filter(Et=>Et!==_e&&Et!==tt);ft.splice(Math.min(ut,ft.length),0,tt),ht.push({op:"replace",path:ot,value:ft}),at!==it&&ht.push({op:"replace",path:`/entities/${encodeJsonPointerSegment(tt)}/parentId`,value:it});const pt=collectSubtreeIds(rt,_e),mt=collectPreservedAddedEntityIds(rt,new Set(pt),(_t=et.instance)==null?void 0:_t.bindingId);pushPreservedAddedEntityReparentOps(rt,ht,mt,(yt=et.instance)==null?void 0:yt.bindingId);const vt=pt.filter(Et=>!mt.has(Et));pushRemovedNestedBindingOps(rt,ht,vt,(bt=et.instance)==null?void 0:bt.bindingId);for(const Et of[...vt].reverse())ht.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(Et)}`});return ht}function resolveUniqueEntityId(rt){const{isStripped:_e,localEntityMap:tt,domainEntities:et,uuid:nt}=rt;let it=rt.id??nt();for(;tt.has(it)||!_e&&et[it];)it=nt();return it}function selectEntityRemovalStrategy(rt){return rt.isPrefabSubEntity?"prefab-sub-entity":rt.isRoot||rt.existsInDomainState?"facade-delete":"parent-remove"}const logger=new TraceLogger("applyAssetTemplateDiffs");function applyAssetTemplateDiffs(rt,_e){const tt=rt.engineObject;tt&&(logger.info("applying",{rootName:rt.name,paths:Object.keys(_e.entityProps??{}),diffs:_e.entityProps}),applyAssetTemplateDiffs$1(tt,_e),logger.info("done",{rootName:rt.name}))}function getEntityModelChildren(rt){return rt.selfChildren??rt.children??[]}function findEntityModelByIndexPath(rt,_e){if(!_e)return rt;let tt=rt;for(const et of _e.split("/")){const nt=Number(et);if(!Number.isInteger(nt)||(tt=getEntityModelChildren(tt)[nt]??null,!tt))return null}return tt}function collectEntitySubtreeIds(rt,_e){const tt=[],et=nt=>{const it=rt.entities[nt];if(it){tt.push(nt);for(const at of it.children)et(at)}};return et(_e),tt}function removeEntityFromParentOps(rt,_e){const tt=rt.entities[_e];if(!tt)return[];if(tt.parentId){const nt=rt.entities[tt.parentId],it=(nt==null?void 0:nt.children.indexOf(_e))??-1;return it>=0?[{op:"remove",path:`/entities/${encodeJsonPointerSegment(tt.parentId)}/children/${it}`}]:[]}const et=rt.scene.rootEntityIds.indexOf(_e);return et>=0?[{op:"remove",path:`/scene/rootEntityIds/${et}`}]:[]}function removeEntityTreeOps(rt,_e){const tt=removeEntityFromParentOps(rt,_e);for(const et of collectEntitySubtreeIds(rt,_e).reverse())tt.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(et)}`});return tt}function hasRemovedAncestor(rt,_e,tt){var nt,it;let et=(nt=rt.entities[_e])==null?void 0:nt.parentId;for(;et;){if(tt.has(et))return!0;et=(it=rt.entities[et])==null?void 0:it.parentId}return!1}function hasPersistedBinding(rt,_e){var et;if(!_e)return!1;const tt=((et=rt.state.prefab)==null?void 0:et.bindings)??{};return Object.values(tt).some(nt=>nt.instanceRootEntityId===_e)}function clearPersistedEntityForReload(rt,_e){rt.getNormalizedState().entities[_e]&&rt.applySystem([{op:"remove",path:`/entities/${encodeJsonPointerSegment(_e)}`}])}function applyBindingOverridesOnReload(rt,_e,tt){var ht,ft,pt,mt,vt,_t,yt,bt;const et=rt.getNormalizedState(),nt=[],it=((ht=tt.overrides)==null?void 0:ht.removedEntities)??{},at=Object.keys(it).map(Et=>getNormalizedSceneEntityIdForSource(et,tt.id,Et)).filter(Et=>!!(Et&&rt.state.entities[Et])),ot=new Set(at);for(const Et of at)hasRemovedAncestor(rt.state,Et,ot)||nt.push(...removeEntityTreeOps(rt.state,Et));const st=((ft=tt.overrides)==null?void 0:ft.removedComponents)??{};for(const[Et,St]of Object.entries(st)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!(!At||!rt.state.entities[At]))for(const xt of Object.keys(St)){const Ct=findNormalizedComponentIdBySourceKey(et,At,xt);!Ct||!((pt=rt.state.entities[At])!=null&&pt.components[Ct])||nt.push({op:"remove",path:`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(Ct)}`})}}const ct=((mt=tt.overrides)==null?void 0:mt.addedComponents)??{};for(const[Et,St]of Object.entries(ct)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!(!At||!rt.state.entities[At]))for(const[xt,Ct]of Object.entries(St)){const Pt=`/entities/${encodeJsonPointerSegment(At)}/components/${encodeJsonPointerSegment(xt)}`;nt.push({op:rt.state.entities[At].components[xt]?"replace":"add",path:Pt,value:{type:Ct.type,props:structuredClone(Ct.props??{}),instance:{bindingId:tt.id,role:"added"}}})}}const dt=((vt=tt.overrides)==null?void 0:vt.entityProps)??{};for(const[Et,St]of Object.entries(dt)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(!At||!et.entities[At])continue;const xt=encodeJsonPointerSegment(At);if(St.name!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/name`,value:St.name}),St.isActive!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/isActive`,value:St.isActive}),St.layer!==void 0&&nt.push({op:"replace",path:`/entities/${xt}/layer`,value:St.layer}),St.transform){const Ct=(_t=rt.state.entities[At])==null?void 0:_t.transform;if(!Ct)continue;St.transform.position&&nt.push({op:"replace",path:`/entities/${xt}/transform/position`,value:{...Ct.position,...St.transform.position}}),St.transform.rotation&&nt.push({op:"replace",path:`/entities/${xt}/transform/rotation`,value:{...Ct.rotation,...St.transform.rotation}}),St.transform.scale&&nt.push({op:"replace",path:`/entities/${xt}/transform/scale`,value:{...Ct.scale,...St.transform.scale}})}}const ut=((yt=tt.overrides)==null?void 0:yt.componentProps)??{};for(const[Et,St]of Object.entries(ut)){if(sourceEntityIsCoveredByRemovedEntity(tt,Et))continue;const At=getNormalizedSceneEntityIdForSource(et,tt.id,Et);if(At&&et.entities[At])for(const[xt,Ct]of Object.entries(St)){if((bt=st[Et])!=null&&bt[xt])continue;const Pt=findNormalizedComponentIdBySourceKey(et,At,xt);if(Pt&&getNormalizedComponent(et,At,Pt)){const Tt=encodeJsonPointerSegment(At),wt=encodeJsonPointerSegment(Pt);for(const[It,Ot]of Object.entries(Ct))nt.push({op:"replace",path:`/entities/${Tt}/components/${wt}/props/${encodeJsonPointerSegment(It)}`,value:Ot})}}}nt.length>0&&rt.applySystem(nt)}function syncAssetTemplateDiffsToDomain(rt,_e,tt){const et=tt.entityProps;if(!et)return;const nt=[];if(!_e.engineObject)return;const at=rt.getNormalizedState();for(const[ot,st]of Object.entries(et)){const ct=findEntityModelByIndexPath(_e,ot);if(!ct)continue;const dt=ct.id;if(!dt||!at.entities[dt])continue;const ut=encodeJsonPointerSegment(dt);st.transform&&(st.transform.rotation&&nt.push({op:"replace",path:`/entities/${ut}/transform/rotation`,value:st.transform.rotation}),st.transform.position&&nt.push({op:"replace",path:`/entities/${ut}/transform/position`,value:st.transform.position}),st.transform.scale&&nt.push({op:"replace",path:`/entities/${ut}/transform/scale`,value:st.transform.scale})),st.name!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/name`,value:st.name}),st.isActive!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/isActive`,value:st.isActive}),st.layer!==void 0&&nt.push({op:"replace",path:`/entities/${ut}/layer`,value:st.layer})}nt.length>0&&rt.apply(nt,"prefab.assetTemplateDiffs")}function assertSourceV2LocalHydrationFile(rt,_e="source file"){if(!isRecord(rt))throw new Error(`${_e} is not a source v2 scene/prefab file.`);if(!isRecord(rt.asset)||rt.asset.version!=="2.0")throw new Error(`${_e} expected source v2 scene/prefab file with asset.version "2.0".`);if("scene"in rt){assertSourceV2SceneFileStructure(rt);return}assertSourceV2PrefabFileStructure(rt)}var __defProp$4=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$3(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$4(_e,tt,nt),nt};class EntityManager extends EngineObjectProxy{constructor(tt){super(tt);Rt(this,"engine");Rt(this,"engineSceneObject");Rt(this,"_sourceV2LocalHydrationDepth",0);Rt(this,"_localRootEntityIds",[]);Rt(this,"rootEntity");Rt(this,"entities",new Map);Rt(this,"strippedEntities",new Map);Rt(this,"_prefabRemovedSidecarIndexCache",null);Rt(this,"selectEntity",(tt,et=!1,nt=!1)=>{if(tt===DEFAULT_SCENE){this.sceneUIStore.clearSelection(),this.sceneUIStore.selectEntity(DEFAULT_SCENE),this._triggerUnSelect();return}if(!tt){this.sceneUIStore.setLastSelectedId(null),this.sceneUIStore.clearSelection(),this._triggerUnSelect();return}this.sceneUIStore.selectedKeys.has(DEFAULT_SCENE)&&(et=!1);const it=applySceneEntitySelection(this.sceneUIStore,tt,et,nt);if(!it.changed)return;if(!it.selected){this._triggerUnSelect();return}this._triggerSelectedEntity();let at=this.entities.get(tt);for(;at!=null&&at.parentEntity;)this.expandEntity(at.parentEntity.id),at=at.parentEntity});Rt(this,"selectEntityByRange",(tt,et)=>{const nt=this.displayedEntitiesIds.indexOf(tt),it=this.displayedEntitiesIds.indexOf(et),[at,ot]=[Math.min(nt,it),Math.max(nt,it)],st=this.displayedEntitiesIds.slice(at,ot+1);this.sceneUIStore.replaceSelectedKeys(st)});Rt(this,"expandEntity",tt=>{this.sceneUIStore.expandEntity(tt)});Rt(this,"collapseEntity",tt=>{this.sceneUIStore.collapseEntity(tt)});Rt(this,"setSearchText",tt=>{this.sceneUIStore.setSearchText(tt)});Rt(this,"removeEntity",tt=>{tt||(tt=Array.from(this.sceneUIStore.selectedKeys)),Array.isArray(tt)?tt.forEach(et=>{this.removeSingleEntity(et)}):this.removeSingleEntity(tt)});Rt(this,"removeSingleEntity",tt=>{let et;if(typeof tt=="string"){if(tt===DEFAULT_SCENE)return;et=this.entities.get(tt)}else et=tt;if(!et||et.prefabEntityRemoved)return;const nt=et.id,it=this.sceneUIStore.lastSelectedId===nt;this.sceneUIStore.removeEntity(nt),it&&this._triggerUnSelect();const at=et.parentEntity,ot=this.root.domainStore.getNormalizedState();switch(selectEntityRemovalStrategy({isPrefabSubEntity:et.isPrefabSubEntity,isRoot:et.isRoot,existsInDomainState:!!ot.entities[nt]})){case"prefab-sub-entity":this.removePrefabSubEntity(et);break;case"facade-delete":this.root.entityFacade.deleteEntity(nt);break;case"parent-remove":at==null||at.removeChildById(nt);break}this.root.projectStore.debouncedUpdateSceneAsset()});Rt(this,"isChildNode",(tt,et)=>{for(let nt=0;nt<tt.length;nt++){const it=[tt[nt]];for(;it.length>0;){const at=it.pop();if(at===et)return!0;const ot=this.entities.get(at);ot.childrenId&&ot.childrenId.length>0&&it.push(...ot.childrenId)}}return!1});Rt(this,"getEntityPath",tt=>{let et=this.entities.get(tt);const nt=[];for(;et;)nt.unshift(et.name),et=et.parentEntity;return nt.join("/")});Rt(this,"setHoveredEntity",tt=>{this.sceneUIStore.setHoveredEntity(tt),this.root.viewportStore.hoverEntity(this.entities.get(tt))});this.root=tt,this.engine=tt.projectStore.engine,this.engineSceneObject=new Scene(this.engine),this.rootEntity=new RootEntityModel(this),makeObservable(this)}get isDomainScoped(){return!1}get isHydratingSourceV2LocalEntities(){return this._sourceV2LocalHydrationDepth>0}get rootEntitiesId(){return this._localRootEntityIds}setLocalRootEntityIds(tt){this._localRootEntityIds=[...tt]}get sceneUIStore(){const tt=this.root;return tt.sceneUIStore||(tt.sceneUIStore=new SceneUIStore(this.root)),tt.sceneUIStore}get rootEntities(){return this.rootEntitiesId.map(tt=>this.entities.get(tt)).filter(Boolean)}get selectedEntities(){return Array.from(this.sceneUIStore.selectedKeys).map(tt=>this.entities.get(tt)).filter(Boolean)}get displayedEntities(){if(this.sceneUIStore.searchText){const tt=this.sceneUIStore.searchText.toLowerCase();return Array.from(this.entities.values()).filter(et=>et.name.toLowerCase().indexOf(tt)>-1)}return this.rootEntities}get displayedEntitiesIds(){const tt=[],et=it=>this.sceneUIStore.isEntityExpanded(it);function nt(it){tt.push(it.id),et(it.id)&&it.children.forEach(at=>{nt(at)})}return this.rootEntities.forEach(it=>{nt(it)}),tt}get lastSelectedEntity(){return this.entities.get(this.sceneUIStore.lastSelectedId)}getChildrenIds(tt){return tt.selfChildrenId.filter(Boolean)}getParentId(tt){return tt.selfParent}createEntityInStore(tt,et,nt,it){var st;const at=new Entity(this.engine,et.name??"Entity");et.isActive===!1&&(at.isActive=!1);const ot=(st=et.transform)==null?void 0:st.props;if(ot){const{position:ct,rotation:dt,scale:ut}=ot;ct&&at.transform.position.set(ct.x,ct.y,ct.z),dt&&at.transform.rotation.set(dt.x,dt.y,dt.z),ut&&at.transform.scale.set(ut.x,ut.y,ut.z)}it.bindEngineObject(at)}connectChildEntities(tt,et){if(tt.engineObject)for(const nt of et)nt.engineObject&&tt.engineObject.addChild(nt.engineObject)}onTemplateEntityCreated(tt,et){}async init(tt,et){this.clear();const nt=et??JSON.parse(tt.getMainData());assertSourceV2LocalHydrationFile(nt,`Asset "${tt.name??tt.id}"`);const it=at=>{var ot,st,ct;return(ct=(st=(ot=this.root)==null?void 0:ot.assetStore)==null?void 0:st.getAssetByVirtualPath)==null?void 0:ct.call(st,at)};return await this.hydrateSourceV2LocalEntities(nt,{resolveSourceRef:at=>{var st;const ot=(st=it(at))==null?void 0:st.id;if(typeof ot!="string"||ot.length===0)throw new Error(`[SceneV2] Unable to resolve asset ref "${at}" while loading asset "${tt.id}". Source-v2 $ref must be a virtualPath, not an editor asset id.`);return ot},resolveAssetKind:at=>{var st,ct,dt;const ot=(dt=(ct=(st=it(at))==null?void 0:st.getMetaConfig)==null?void 0:ct.call(st))==null?void 0:dt.type;return ot==="Prefab"||ot==="glTF"?ot:void 0}}),nt}async hydrateSourceV2LocalEntities(tt,et={}){this._sourceV2LocalHydrationDepth++;try{return await hydrateSourceV2LocalEntities(this,tt,et)}finally{this._sourceV2LocalHydrationDepth--}}hydrateDomainEntityModelsFromState(){if(!this.isDomainScoped)throw new Error("hydrateDomainEntityModelsFromState can only run on a domain-scoped EntityManager");this.clear();const tt=this.root.domainStore.state,et=[],nt=new Set,it=at=>{var dt;if(nt.has(at))return this.entities.get(at);const ot=tt.entities[at];if(!ot)return;ot.parentId&&it(ot.parentId),nt.add(at);let st=this.entities.get(at);st||(st=this.createEntity(ot.name,at)),st.applyParentFromDomain(ot.parentId),st.applyChildrenFromDomain(ot.children);const ct=(dt=this.root.engineProjection)==null?void 0:dt.getEntity(at);ct&&st.initImmediate(ct),st.transform||st.addComponentFromDomain(`${at}:Transform`,{type:"Transform",props:ot.transform});for(const[ut,ht]of Object.entries(ot.components))st.addComponentFromDomain(ut,ht);return ot.isLocked!==void 0&&st.applyLockedFromDomain(ot.isLocked),st.syncRemovedComponentPlaceholdersFromDomain(),st};for(const at of tt.scene.rootEntityIds){const ot=it(at);ot&&et.push(ot)}for(const at of Object.keys(tt.entities))it(at);return et}createEntity(tt,et=v4()){const nt=new EntityModel(this,et);return tt&&(nt.name=tt),this.entities.set(nt.id,nt),this._registerEntityRuntimeBinder(nt),nt}getEntityModel(tt){return this.entities.get(tt)}hasEntityModel(tt){return this.entities.has(tt)}setEntityModel(tt,et){this.entities.set(tt,et)}deleteEntityModel(tt){return this.entities.delete(tt)}iterateEntityModels(){return this.entities.entries()}getEntityRuntimeFlags(tt){const et=this.entities.get(tt);return{prefabEntityRemoved:this._isPrefabEntityRemovedBySidecar(tt)||((et==null?void 0:et.prefabEntityRemoved)??!1)}}_isPrefabEntityRemovedBySidecar(tt){var ot,st,ct,dt,ut;const et=(st=(ot=this.root.domainStore)==null?void 0:ot.getNormalizedState)==null?void 0:st.call(ot);if(!et)return!1;const nt=this._getPrefabRemovedSidecarIndex(et);if(nt.directEntityIds.has(tt))return!0;const it=nt.mappedBindingIdsBySceneEntityId.get(tt);if(!(it!=null&&it.size))return!1;const at=(ut=(dt=(ct=et.entities)==null?void 0:ct[tt])==null?void 0:dt.instance)==null?void 0:ut.bindingId;return at?it.has(at):!0}_getPrefabRemovedSidecarIndex(tt){var ot,st,ct,dt,ut,ht,ft,pt,mt,vt,_t;if(((ot=this._prefabRemovedSidecarIndexCache)==null?void 0:ot.normalizedState)===tt)return this._prefabRemovedSidecarIndexCache;const et=new Set,nt=new Map,it=(yt,bt)=>{if(!yt)return;const Et=nt.get(yt)??new Set;Et.add(bt),nt.set(yt,Et)},at=((st=tt.prefab)==null?void 0:st.bindings)??{};for(const[yt,bt]of Object.entries(tt.entities??{})){const Et=(ct=bt.instance)==null?void 0:ct.bindingId,St=(dt=bt.instance)==null?void 0:dt.sourceEntityId;!Et||!St||(ft=(ht=(ut=at[Et])==null?void 0:ut.overrides)==null?void 0:ht.removedEntities)!=null&&ft[St]&&et.add(yt)}for(const yt of Object.values(at)){const bt=((pt=yt.overrides)==null?void 0:pt.removedEntities)??{};for(const Et of Object.keys(bt))it((mt=yt.sourceToSceneEntity)==null?void 0:mt[Et],yt.id),it((_t=(vt=yt.sourceEntitySnapshots)==null?void 0:vt[Et])==null?void 0:_t.sceneEntityId,yt.id)}return this._prefabRemovedSidecarIndexCache={normalizedState:tt,directEntityIds:et,mappedBindingIdsBySceneEntityId:nt},this._prefabRemovedSidecarIndexCache}addEntityToParent(tt,et=DEFAULT_SCENE,nt){et===DEFAULT_SCENE&&(et=null);const it=this.entities.get(et);it?it.addChild(tt,nt):tt.parent=null,this.root.projectStore.debouncedUpdateSceneAsset()}registerEntityTreeInDomain(tt,et,nt,it){var mt,vt,_t,yt;const at=et===DEFAULT_SCENE?null:et,{engineProjection:ot,entityFacade:st}=this.root;if(!ot)return;const ct=[];let dt=!0;const ut=(bt,Et)=>{const St=bt.engineObject;St&&ot.registerExternalEntity(bt.id,St);const At=dt&&(it==null?void 0:it.transform);dt=!1;const xt=bt._components.filter(wt=>wt.type&&wt.id).map(wt=>{const It=wt.toJSON(),Ot={...normalizeComponentSchemaToDomainProps(It),...buildInitialComponentProps(wt)};if(wt.type==="Transform"&&At&&(it!=null&&it.transform)){const Nt=it.transform;Ot.position||(Ot.position=Nt.position),Ot.rotation||(Ot.rotation=Nt.rotation),Ot.scale||(Ot.scale=Nt.scale)}return{id:wt.id,type:wt.type,props:Ot}}),Ct=St==null?void 0:St.transform,Pt=At?it.transform:Ct?{position:{x:Ct.position.x,y:Ct.position.y,z:Ct.position.z},rotation:{x:Ct.rotation.x,y:Ct.rotation.y,z:Ct.rotation.z},scale:{x:Ct.scale.x,y:Ct.scale.y,z:Ct.scale.z}}:void 0,Tt=bt.pendingInstance;Tt&&(bt.pendingInstance=null),ct.push({id:bt.id,name:bt.name,parentId:Et,isActive:bt.isActive,layer:St==null?void 0:St.layer,transform:Pt,components:xt.length>0?xt:void 0,...Tt?{instance:Tt}:{}}),bt.selfChildren.forEach(wt=>ut(wt,bt.id))};ut(tt,at);const ht=this.root.domainStore.state.entities,ft=ct.filter(bt=>!ht[bt.id]);if(it!=null&&it.transform)for(const bt of ct){if(!ht[bt.id]||!ht[bt.id])continue;const St=this.root.domainStore.getNormalizedState(),At=bt.id.replace(/~/g,"~0").replace(/\//g,"~1"),xt=[];if(bt.transform&&(xt.push({op:"replace",path:`/entities/${At}/transform/position`,value:bt.transform.position}),xt.push({op:"replace",path:`/entities/${At}/transform/rotation`,value:bt.transform.rotation}),xt.push({op:"replace",path:`/entities/${At}/transform/scale`,value:bt.transform.scale})),bt.components&&bt.components.find(Pt=>Pt.type==="Transform")){const Pt=findNormalizedComponentIdByType(St,bt.id,"Transform");if(Pt){const Tt=Pt.replace(/~/g,"~0").replace(/\//g,"~1");(mt=bt.transform)!=null&&mt.position&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/position`,value:bt.transform.position}),(vt=bt.transform)!=null&&vt.rotation&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/rotation`,value:bt.transform.rotation}),(_t=bt.transform)!=null&&_t.scale&&xt.push({op:"replace",path:`/entities/${At}/components/${Tt}/props/scale`,value:bt.transform.scale})}}xt.length>0&&this.root.domainStore.apply(xt,"entity.updateTransform")}ft.length>0&&st.batchCreateEntities(ft);const pt=(yt=ct[0])==null?void 0:yt.instance;if((pt==null?void 0:pt.assetKind)==="glTF"&&pt.assetId&&!(it!=null&&it.deferInstanceBinding)){const bt=pt.bindingId||void 0,Et=buildGlTFDomainInstanceBindingSync({state:this.root.domainStore.state,assetId:pt.assetId,rootEntityId:tt.id,pendingBindingId:bt,createBindingId:()=>`binding-${v4().slice(0,8)}`});Et.kind==="bind"?this.root.prefabFacade.bindExistingInstance({assetId:Et.assetId,assetKind:Et.assetKind,bindingId:Et.bindingId,instanceRootEntityId:Et.instanceRootEntityId,entityMappings:Et.entityMappings,componentMappings:Et.componentMappings,sourceEntitySnapshots:Et.sourceEntitySnapshots,undoable:!1}):Et.kind==="update"&&this.root.prefabFacade.updateBindingSourceBaseline(Et)}nt!==void 0&&st.moveEntity(tt.id,at,nt)}addEntityByTemplate(tt=this.sceneUIStore.lastSelectedId,et){var ot;const nt=tt===DEFAULT_SCENE?null:tt,it=this.root.entityFacade.createEntity({id:v4(),name:(et==null?void 0:et.name)??"Entity",parentId:nt,isActive:(et==null?void 0:et.isActive)??!0,transform:(ot=et==null?void 0:et.transform)!=null&&ot.props?{position:et.transform.props.position,rotation:et.transform.props.rotation,scale:et.transform.props.scale}:void 0}),at=this.entities.get(it);return at&&et&&at.initByFile(et),this.selectEntity(it),this.root.projectStore.debouncedUpdateSceneAsset(),at}createStrippedEntity(tt){const et=v4(),nt=new EntityModel(this,et);return this.strippedEntities.set(et,nt),this._registerEntityRuntimeBinder(nt),nt.originalEntity=tt,this.addEntityToParent(nt,null),nt}rename(tt,et){const nt=this.entities.get(tt);nt&&(nt.name=et)}setEntityVisible(tt,et){var at;const nt=this.entities.get(tt);if(!nt)return;this.sceneUIStore.setEntityVisible(tt,et);const it=this.root.domainStore.getNormalizedState().entities[tt];it?(at=this.root.engineProjection)==null||at.setEntityRuntimeActive(tt,it.isActive&&et):nt.engineObject&&(nt.engineObject.isActive=nt.isActive&&et)}setEntityLocked(tt,et){if(this.root.domainStore.getNormalizedState().entities[tt]){this.root.entityFacade.setLocked(tt,et);return}const it=this.entities.get(tt);it&&(it.isLocked=et)}async deserializeEntities(tt){var dt,ut,ht,ft,pt,mt;const et=[];tt=JSON.parse(JSON.stringify(tt));const{schemaByKey:nt,strippedSchemas:it,strippedIdSet:at}=indexSchemas(tt),ot=collectSidecarAddedEntityOverrides((ht=(ut=(dt=this.root)==null?void 0:dt.domainStore)==null?void 0:ut.state)==null?void 0:ht.prefab),st=groupAddedRootsByStrippedId(tt,at,DEFAULT_SCENE),ct=[];for(let vt=0,_t=tt.length;vt<_t;vt++){const yt=tt[vt];if(yt.strippedId||yt.id&&ot.has(yt.id))continue;const bt=yt.parent;bt&&bt!==DEFAULT_SCENE&&at.has(bt)||!(!bt||bt===DEFAULT_SCENE||!nt.has(bt))||(bt&&bt!==DEFAULT_SCENE&&!nt.has(bt)&&(yt.parent=null),ct.push(yt))}for(const vt of ct)try{await this.createBySchema(vt,nt)}catch(_t){console.error(_t)}(ft=this.root.engineProjection)==null||ft.flushDeferredComponentProps();for(let vt=0,_t=ct.length;vt<_t;vt++){const yt=ct[vt],bt=yt.id?this.entities.get(yt.id):null;bt&&et.push(bt)}this._localRootEntityIds=et.map(vt=>vt.id);for(let vt=0,_t=it.length;vt<_t;vt++){const yt=it[vt],bt=yt.strippedId;if(!bt)continue;const Et=new EntityModel(this,bt);this.strippedEntities.set(bt,Et),this._registerEntityRuntimeBinder(Et);const St=resolveStrippedOriginal({strippedSchema:yt,schemaByKey:nt,entities:this.entities,findByIndexPath:this.findByIndexPath.bind(this)});if(!St){const xt=resolveStrippedPrefabLink(yt);console.warn("[EntityManager] Failed to resolve original entity for stripped entity",{strippedId:bt,prefabInstanceId:xt.prefabInstanceId,prefabEntityId:xt.sourceEntityId});continue}const At=(pt=St.strippedEntity)==null?void 0:pt.id;At&&At!==bt&&this.strippedEntities.delete(At),Et.originalEntity=St,Et.initImmediate()}for(let vt=0,_t=it.length;vt<_t;vt++){const yt=it[vt],bt=yt.strippedId;if(!bt)continue;const Et=this.strippedEntities.get(bt),St=Et==null?void 0:Et.originalEntity;if(!Et||!St)continue;const At=yt.components??[];for(let Ct=0;Ct<At.length;Ct++)try{await Et.addEditorComponent(At[Ct],!1)}catch(Pt){console.warn("[EntityManager] Failed to apply stripped added component",{strippedId:bt,error:Pt})}const xt=st.get(bt)??[];for(let Ct=0;Ct<xt.length;Ct++){const Pt=xt[Ct],Tt=Pt.parent;Pt.parent=St.id;try{const wt=await this.createBySchema(Pt,nt);wt&&!Et.selfChildrenId.includes(wt.id)&&Et.selfChildrenId.push(wt.id)}catch(wt){console.warn("[EntityManager] Failed to create additive entity under prefab original",{strippedId:bt,originalEntityId:St.id,error:wt})}finally{Pt.parent=Tt}}}await this._restoreSidecarAddedEntities(tt,nt,ot);for(const vt of this.entities.values()){const _t=vt.syncRemovedComponentPlaceholdersFromDomain;typeof _t=="function"&&_t.call(vt)}return(mt=this.root.engineProjection)==null||mt.flushDeferredComponentProps(),et}async _restoreSidecarAddedEntities(tt,et,nt){var at,ot,st,ct;if(nt.size===0)return;const it=prepareSidecarAddedEntityRestore({entitiesSchema:tt,addedOverrides:nt,prefabBindings:(ct=(st=(ot=(at=this.root)==null?void 0:at.domainStore)==null?void 0:ot.state)==null?void 0:st.prefab)==null?void 0:ct.bindings,existingEntityIds:new Set(this.entities.keys())});for(const dt of it.missingParents)console.warn("[EntityManager] Failed to restore sidecar added entity: missing prefab source parent",dt);for(const dt of it.plans){const ut=dt.schema.parent;dt.schema.parent=dt.parentSceneEntityId;try{const ht=await this.createBySchema(dt.schema,et);ht&&this.root.prefabFacade.addExistingEntityOverride(dt.bindingId,{entityId:ht.id,parentSourceEntityId:dt.parentSourceEntityId,parentSceneEntityId:dt.parentSceneEntityId,index:dt.index},{persist:!1})}catch(ht){console.warn("[EntityManager] Failed to restore sidecar added entity",{bindingId:dt.bindingId,entityId:dt.entityId,error:ht})}finally{dt.schema.parent=ut}}}revertPrefabSubEntity(tt){var it,at,ot;let et;typeof tt=="string"?et=this.entities.get(tt):et=tt,et.prefabEntityRemoved=!1;const nt=(it=et.parentEntity)==null?void 0:it.id;if(nt){const st=this.root.domainStore.getNormalizedState(),ct=!!st.entities[nt],dt=!!st.entities[et.id];if(ct&&dt)(at=this.root.engineProjection)==null||at.addEntityChild(nt,et.id);else{const ut=(ot=et.parentEntity)==null?void 0:ot.engineObject,ht=et.engineObject;ut&&ht&&ut.addChild(ht)}}this.root.projectStore.debouncedUpdateSceneAsset()}removePrefabSubEntity(tt){var it,at,ot;const et=this.root.domainStore.getNormalizedState();if(et.entities[tt.id]){this.root.prefabFacade.removeSourceEntityForSceneEntity(tt.id);return}tt.prefabEntityRemoved=!0;const nt=(it=tt.parentEntity)==null?void 0:it.id;if(nt){const st=!!et.entities[nt],ct=!!et.entities[tt.id];st&&ct?(at=this.root.engineProjection)==null||at.removeEntityChild(nt,tt.id):(ot=tt.engineObject)!=null&&ot.parent&&tt.engineObject.parent.removeChild(tt.engineObject)}this.root.projectStore.debouncedUpdateSceneAsset()}getUniqIdByEntitySchema(tt,et){const nt=!!tt.strippedId,it=nt?this.strippedEntities:this.entities;return resolveUniqueEntityId({id:et??(nt?tt.strippedId:tt.id),isStripped:nt,localEntityMap:it,domainEntities:{},uuid:v4})}replaceEntity(tt,et,nt){const it=this.entities.get(tt),at=et.transform,ot=it==null?void 0:it.transform;if(at&&ot){const{position:pt,rotation:mt,scale:vt}=at,{position:_t,rotation:yt,scale:bt}=ot;pt.x=_t.x,pt.y=_t.y,pt.z=_t.z,mt.x=yt.x,mt.y=yt.y,mt.z=yt.z,vt.x=bt.x,vt.y=bt.y,vt.z=bt.z}const st=this.root.domainStore.getNormalizedState(),ct=st.entities[tt];((nt==null?void 0:nt.structuralDeltaMode)??(ct!=null&&ct.instance?"domain-source-replace":"legacy-preserve"))==="legacy-preserve"&&(it.getRemovedComponents().forEach(pt=>{et.applyRemovedComponent(pt)}),it.getRemovedEntities().forEach(pt=>{et.applyRemovedEntity(pt)}),it.getAddedEntities().forEach(pt=>{et.applyAddedEntity(pt)}),it.getAddedComponents().forEach(pt=>{et.applyAddedComponent(pt)}));const ut=it.parentEntity;let ht;ut?ht=ut.children.indexOf(it):ht=this.rootEntitiesId.indexOf(it.id);const ft=buildReplaceEntityTreeOps(st,it.id,et.id);if(ft.length>0){this.root.domainStore.applySystem(ft);return}this.removeEntity(it.id),this.addEntityToParent(et,ut==null?void 0:ut.id,ht)}clear(){this.entities.clear(),this._localRootEntityIds=[],this.sceneUIStore.clear()}toJSON(tt=!1){var ut,ht;const et=this._collectOrderedEntities(tt),nt=et.map(ft=>ft.id),it=(ut=this.root)==null?void 0:ut.assetStore,at=ft=>{var pt;return(pt=it==null?void 0:it.getAssetVirtualPath)==null?void 0:pt.call(it,ft)},ot=(ht=this.root)==null?void 0:ht.domainStore,st=ot?ft=>{const pt=ot.getNormalizedState().components[ft];if(pt)return{...pt.refId?{refId:pt.refId}:{},...pt.scriptKey?{scriptKey:pt.scriptKey}:{},...pt.calls?{calls:pt.calls}:{}}}:void 0,ct=new SerializeContext(nt,at,st);return{entities:et.map(ft=>ft.toV2(ct,tt)),components:ct.components}}_collectOrderedEntities(tt){const et=at=>!at.isPrefabSubEntity&&!this._isPrefabAddedEntityTree(at),nt=this.rootEntitiesId.map(at=>this.entities.get(at)).filter(Boolean),it=new Set(nt.map(at=>at.id));return nt.concat(Array.from(this.entities.values()).filter(at=>!it.has(at.id))).filter(et)}_isPrefabAddedEntityTree(tt){const et=new Set;let nt=tt;for(;nt&&!et.has(nt.id);){if(nt.isAddedEntity)return!0;et.add(nt.id),nt=nt.parentEntity}return!1}_triggerSelectedEntity(){this.root.inspectorStore.switchInspector(InspectorType.Entity,this.sceneUIStore.lastSelectedId),this.root.viewportStore.selectEntity(this.selectedEntities)}_triggerUnSelect(){this.root.inspectorStore.switchInspector(InspectorType.Scene,null),this.root.viewportStore.selectEntity(null)}_checkCanCopy(tt){const et=this.entities.get(tt);return et.isPrefabSubEntity||et.isGLTFRefEntity?(showEditorUiToastError("Cannot copy prefab sub entity or glTF entity"),!1):!0}_registerEntityRuntimeBinder(tt){this.root.runtimeBinderRegistry.ensureEntityBinder(tt.id).attachRuntimeHost({getFocusTarget:()=>{const nt=tt.engineObject;return nt&&!nt.destroyed?nt:null},alignToCamera:({cameraTransform:nt,fieldOfView:it})=>{var ot,st;if(!tt.hasCameraComponent||!nt)return;(st=(ot=tt.transform)==null?void 0:ot.syncTransformToEditor)==null||st.call(ot,nt);const at=tt.getComponentByTypeName("Camera");!(at!=null&&at.id)||it==null||this.root.componentFacade.updateComponent(tt.id,at.id,{fieldOfView:it})},applyToPrefab:(nt,it)=>tt.applyToPrefab(nt,it),revertPrefab:(nt,it)=>tt.revertPrefab(nt,it),unpackPrefab:()=>tt.unpackPrefab()})}createByEngineObject(tt,et){var at;const nt=this.createEntity(tt.name,et);nt.initByEngineObject(tt);const it=tt._templateResource;return it&&it!==((at=tt==null?void 0:tt.parent)==null?void 0:at._templateResource)&&nt.root.assetStore.engineObjectToAssetMap.get(it).addInstance(nt),nt}async createBySchema(tt,et){return this._checkIsAssetRef(tt)?this._createEntityByTemplateAsset(tt,et):this._createNormalEntityBySchema(tt,et)}async _createNormalEntityBySchema(tt,et,nt){nt=this.getUniqIdByEntitySchema(tt,nt);const it=!!tt.strippedId,at=new EntityModel(this,nt);this._registerEntityRuntimeBinder(at),this.createEntityInStore(nt,tt,it,at);const ot=tt.children??[],st=[];for(let dt=0,ut=ot.length;dt<ut;dt++){const ht=et.get(ot[dt]);ht&&(ht.parent=nt,st.push(this.createBySchema(ht,et)))}const ct=await Promise.all(st);return this.connectChildEntities(at,ct),tt.children=ct.map(dt=>dt.id),at.initBySchema(tt),it?(tt.strippedId=at.id,this.strippedEntities.set(nt,at)):(tt.id=at.id,this.entities.set(nt,at)),at.initImmediate(),at}async _createEntityByTemplateAsset(tt,et){var ot;const nt=resolveEntitySchemaInstanceAssetId(tt),it=nt?await this.root.assetStore.getAssetByRef({refId:nt}):null;let at;if(it){const ct=this===this.root.sceneStore&&hasPersistedBinding(this.root.domainStore,tt.id)?tt.id:null;ct&&clearPersistedEntityForReload(this.root.domainStore,ct);let dt,ut;if(ct){const ft=this.root.domainStore.getNormalizedState(),pt={assetId:resolveEntitySchemaInstanceAssetId(tt),assetKind:(ot=tt.instance)==null?void 0:ot.assetKind};ut=findNormalizedPrefabBindingByInstanceRootEntityId(ft,ct,pt);const mt=getNormalizedRootEntityOverride(ft,ct,pt);dt=mt==null?void 0:mt.transform}at=ct?await it.instantiate(this,dt,{expectedRootId:ct,expectedBindingId:ut==null?void 0:ut.id}):await it.instantiate(this),it.getMetaConfig().type==="glTF"&&(at!=null&&at.isGLTFWrapEntity)&&console.warn("[EntityManager] unexpected glTF wrapper entity from asset instantiate",{instanceAssetId:nt,wrapEntityId:at.id}),this.onTemplateEntityCreated(at,tt),at.name=tt.name,at.applyStructuralDeltasBySchema(tt),tt.assetTemplateDiffs&&(applyAssetTemplateDiffs(at,tt.assetTemplateDiffs),at.assetTemplateDiffs=tt.assetTemplateDiffs,syncAssetTemplateDiffsToDomain(this.root.domainStore,at,tt.assetTemplateDiffs)),ut&&applyBindingOverridesOnReload(this.root.domainStore,at,ut)}else console.error(`can't find instance asset id ${nt}`),at=await this._createNormalEntityBySchema(tt,et);return tt.id=at.id,at.initImmediate(),at}_checkIsAssetRef(tt){return hasEntitySchemaInstanceLink(tt)}getNextSibling(tt){if(!tt)return null;const et=tt.id;if(this.sceneUIStore.isEntityExpanded(tt.id)&&tt.children.length>0)return tt.children[0].id;const nt=tt.parentEntity;if(!nt){const ot=this.rootEntitiesId.findIndex(st=>st===et);return ot<this.rootEntitiesId.length-1?this.rootEntitiesId[ot+1]:null}const it=nt.children,at=it.findIndex(ot=>ot.id===et);if(at<it.length-1)return it[at+1].id;{let ot=tt.parentEntity,st=tt;for(;ot;){const dt=ot.children.findIndex(ut=>ut.id===st.id);if(dt<ot.children.length-1)return ot.children[dt+1].id;st=ot,ot=ot.parentEntity}const ct=this.rootEntitiesId.findIndex(dt=>dt===st.id);return ct<this.rootEntitiesId.length-1?this.rootEntitiesId[ct+1]:null}}getPreviousSibling(tt){if(!tt)return null;const et=tt.id;if(et===DEFAULT_SCENE)return null;const nt=tt.parentEntity;if(!nt){const ot=this.rootEntities.findIndex(st=>st.id===et);if(ot>0){let st=this.rootEntities[ot-1];for(;st.children.length>0&&this.sceneUIStore.isEntityExpanded(st.id);)st=st.children[st.children.length-1];return st.id}return ot===0?DEFAULT_SCENE:null}const it=nt.children.findIndex(ot=>ot===tt);if(it===0)return nt.id;let at=nt.children[it-1];for(;this.sceneUIStore.isEntityExpanded(at.id)&&at.children.length>0;)at=at.children[at.children.length-1];return at.id}findChildByName(tt,et){const nt=tt.children;for(let it=0,at=nt.length;it<at;it++){const ot=nt[it];if(et===ot.name)return ot}return null}findByPath(tt,et){const nt=et.split("/");let it=tt;for(let at=0,ot=nt.length;at<ot;++at){const st=nt[at];if(st&&(it=this.findChildByName(it,st),!it))return null}return it}findByIndexPath(tt,et){const nt=et.split("/");let it=tt;for(let at=0,ot=nt.length;at<ot;++at){const st=nt[at];if(st&&(it=it.children[parseInt(st)]),!it)return null}return it}getNodePath(tt){let et=tt.parent,nt=tt.id;const it=[],at=this.entities;for(;et&&et!==DEFAULT_SCENE;){const ot=at.get(et);it.unshift(ot.childrenId.indexOf(nt)),et=ot.parent,nt=ot.id}return it.unshift(this.rootEntitiesId.indexOf(nt)),it}}__decorateClass$3([observable],EntityManager.prototype,"entities",2);__decorateClass$3([observable],EntityManager.prototype,"strippedEntities",2);__decorateClass$3([action],EntityManager.prototype,"setLocalRootEntityIds",1);__decorateClass$3([computed],EntityManager.prototype,"selectedEntities",1);__decorateClass$3([computed],EntityManager.prototype,"lastSelectedEntity",1);__decorateClass$3([action],EntityManager.prototype,"hydrateDomainEntityModelsFromState",1);__decorateClass$3([action],EntityManager.prototype,"createEntity",1);__decorateClass$3([action],EntityManager.prototype,"setEntityModel",1);__decorateClass$3([action],EntityManager.prototype,"deleteEntityModel",1);__decorateClass$3([action],EntityManager.prototype,"addEntityToParent",1);__decorateClass$3([action],EntityManager.prototype,"addEntityByTemplate",1);__decorateClass$3([action],EntityManager.prototype,"createStrippedEntity",1);__decorateClass$3([action],EntityManager.prototype,"selectEntity",2);__decorateClass$3([action],EntityManager.prototype,"selectEntityByRange",2);__decorateClass$3([action],EntityManager.prototype,"expandEntity",2);__decorateClass$3([action],EntityManager.prototype,"collapseEntity",2);__decorateClass$3([action],EntityManager.prototype,"rename",1);__decorateClass$3([action],EntityManager.prototype,"setSearchText",2);__decorateClass$3([action],EntityManager.prototype,"setEntityVisible",1);__decorateClass$3([action],EntityManager.prototype,"setEntityLocked",1);__decorateClass$3([action],EntityManager.prototype,"removeEntity",2);__decorateClass$3([action],EntityManager.prototype,"removeSingleEntity",2);__decorateClass$3([action],EntityManager.prototype,"isChildNode",2);__decorateClass$3([action],EntityManager.prototype,"deserializeEntities",1);__decorateClass$3([action],EntityManager.prototype,"revertPrefabSubEntity",1);__decorateClass$3([action],EntityManager.prototype,"removePrefabSubEntity",1);__decorateClass$3([action],EntityManager.prototype,"clear",1);__decorateClass$3([action],EntityManager.prototype,"setHoveredEntity",2);function maybeMoveInstantiatedAssetEntity(rt){const{entityId:_e,targetParentId:tt,defaultSceneId:et,domainEntities:nt,moveEntity:it}=rt;if(!tt||tt===et)return;const at=!!nt[_e],ot=!!nt[tt];!at||!ot||it(_e,tt)}var __defProp$3=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$2(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$3(_e,tt,nt),nt};const log$1=logger$2("Scene"),SOURCE_SPECULAR_MODE_SKY=0,SOURCE_SPECULAR_MODE_CUSTOM=1;function readLoadedPrefabSourceFile(rt){const _e=rt==null?void 0:rt.prefabFile;if(!(!_e||typeof _e!="object")&&Array.isArray(_e.entities)&&Array.isArray(_e.components))return _e}class EditorScene extends EntityManager{constructor(tt){super(tt);Rt(this,"refId");Rt(this,"isBaking",!1);Rt(this,"_bakePromise",null);Rt(this,"_gate",new LifecycleGate);Rt(this,"ambientLight",null);Rt(this,"customAmbientLight",null);Rt(this,"diffuseMode",DiffuseMode.SphericalHarmonics);Rt(this,"diffuseSolidColor",{r:.03696758874771872,g:.0421494543549785,b:.05455383078270364,a:1,intensity:1});Rt(this,"diffuseIntensity",1);Rt(this,"specularMode",SOURCE_SPECULAR_MODE_SKY);Rt(this,"customSpecularTexture",null);Rt(this,"specularIntensity",1);Rt(this,"backgroundMode",BackgroundMode.SolidColor);Rt(this,"backgroundColor",{r:.05087608817155679,g:.05087608817155679,b:.05087608817155679,a:1});Rt(this,"backgroundTexture",null);Rt(this,"textureFillMode",BackgroundTextureFillMode.AspectFitHeight);Rt(this,"skyMaterial",null);Rt(this,"skyMesh",null);Rt(this,"castShadows",!0);Rt(this,"enableTransparentShadow",!1);Rt(this,"shadowResolution",ShadowResolution.Medium);Rt(this,"shadowCascades",ShadowCascadesMode.NoCascades);Rt(this,"shadowTwoCascadeSplits",1/3);Rt(this,"shadowFourCascadeSplits",{x:1/15,y:3/15,z:7/15});Rt(this,"shadowDistance",50);Rt(this,"shadowFadeBorder",.1);Rt(this,"fogMode",FogMode.None);Rt(this,"fogColor",{r:.21404114048223255,g:.21404114048223255,b:.21404114048223255,a:1});Rt(this,"fogStart",0);Rt(this,"fogEnd",300);Rt(this,"fogDensity",.01);Rt(this,"autoBake",!0);Rt(this,"bakerResolution",BakerResolution.R128);Rt(this,"bakeButton",null);Rt(this,"enabledAmbientOcclusion",!1);Rt(this,"quality",AmbientOcclusionQuality.Low);Rt(this,"intensity",1);Rt(this,"power",1);Rt(this,"radius",.3);Rt(this,"bilateralThreshold",.05);Rt(this,"bias",5e-4);Rt(this,"minHorizonAngle",0);Rt(this,"_originalSpecularTexture");Rt(this,"_customSpecularTexture");Rt(this,"_customBakedSpecularTexture");Rt(this,"_lastSkyMaterialRefId");Rt(this,"_initComplete",!1);Rt(this,"_autoBake",async(tt,et)=>{this._initComplete&&this.autoBake&&(et!=null&&et.refId?(await this.root.assetStore.getAssetByRef(et),this.onBake()):this.onBake())});Rt(this,"onBake",debounce$2(()=>this.bake(),500,{edges:["trailing"]}));window.editorSceneObject=this.engineSceneObject,makeObservable(this)}get isDomainScoped(){return!0}get status(){return this._gate.status}get error(){return this._gate.error}onReady(){return this._gate.onReady()}ensureReady(){return this._gate.ensureReady()}get initComplete(){return this._initComplete}get removable(){const tt=this.sceneUIStore.selectedKeys;if(tt.has(DEFAULT_SCENE))return!1;for(const et of tt){const nt=this.entities.get(et);if(nt&&!nt.prefabEntityRemoved)return!0}return!1}get rootEntitiesId(){return this.root.readModelStore.scene.rootEntityIds}getChildrenIds(tt){if(tt.isStrippedEntity)return tt.selfChildrenId.filter(Boolean);const et=this.root.readModelStore.getEntityChildren(tt.id).filter(Boolean);if(!tt.strippedEntity)return et;const nt=tt.strippedEntity.selfChildrenId.filter(Boolean);if(!nt.length)return et;const it=new Set(nt),at=et.filter(ct=>!it.has(ct)),ot=new Set,st=nt.filter(ct=>ot.has(ct)?!1:(ot.add(ct),!0));return at.concat(st)}getParentId(tt){return this.root.readModelStore.getEntityParent(tt.id)}createEntityInStore(tt,et,nt,it){var ot;if(nt)return;this.root.domainStore.beginBatch();try{const st=et.parent,ct=(ot=et.transform)==null?void 0:ot.props;this.root.entityFacade.createEntity({id:tt,name:et.name??"Entity",parentId:st&&st!==DEFAULT_SCENE?st:null,isActive:et.isActive??!0,transform:ct?{position:ct.position,rotation:ct.rotation,scale:ct.scale}:void 0,layer:et.layer})}finally{this.root.domainStore.commitBatch("entity.create")}const at=this.root.engineProjection.getEntity(tt);if(!at)throw this.root.entityFacade.deleteEntity(tt),new Error(`EngineProjection failed to create engine entity for "${tt}" after commitBatch.`);it.bindEngineObject(at)}connectChildEntities(){}onTemplateEntityCreated(tt,et){this.registerEntityTreeInDomain(tt,et.parent),maybeMoveInstantiatedAssetEntity({entityId:tt.id,targetParentId:et.parent,defaultSceneId:DEFAULT_SCENE,domainEntities:this.root.domainStore.state.entities,moveEntity:(nt,it)=>this.root.entityFacade.moveEntity(nt,it)})}getUniqIdByEntitySchema(tt,et){const nt=!!tt.strippedId,it=nt?this.strippedEntities:this.entities;return resolveUniqueEntityId({id:et??(nt?tt.strippedId:tt.id),isStripped:nt,localEntityMap:it,domainEntities:this.root.domainStore.state.entities,uuid:v4})}async ensureSourceInstancePrefabFilesLoaded(tt){const et=new Set,nt=tt.entities.map(it=>{var at,ot;return(ot=(at=it.instance)==null?void 0:at.asset)==null?void 0:ot.$ref}).filter(it=>typeof it=="string");await Promise.all(nt.map(async it=>{var st,ct,dt,ut;const at=(ct=(st=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ct.call(st,it);if(((ut=(dt=at==null?void 0:at.getMetaConfig)==null?void 0:dt.call(at))==null?void 0:ut.type)==="Prefab"){if(!at)throw new Error(`Source instance "${it}" references a Prefab asset, but the asset is not available`);if(!at.prefabFile&&typeof at.loadMainFile!="function")throw new Error(`Source instance "${it}" references a Prefab asset, but its source file cannot be loaded`);if(at.prefabFile||await at.loadMainFile(),!at.prefabFile)throw new Error(`Source instance "${it}" Prefab source file is unavailable after load`);await this.ensurePrefabSourceInstanceAssetsLoaded(at.prefabFile,it,et)}}))}async ensurePrefabSourceInstanceAssetsLoaded(tt,et,nt){var it,at,ot,st,ct,dt;for(const ut of tt.entities??[]){const ht=(at=(it=ut.instance)==null?void 0:it.asset)==null?void 0:at.$ref;if(!ht)continue;const ft=(st=(ot=this.root.assetStore).getAssetByVirtualPath)==null?void 0:st.call(ot,ht),pt=ft==null?void 0:ft.id;if(!ft||!pt)throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but the asset is not available`);const mt=(dt=(ct=ft.getMetaConfig)==null?void 0:ct.call(ft))==null?void 0:dt.type;if(mt!=="Prefab"&&mt!=="glTF")throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but asset "${pt}" is type "${mt}"`);if(!nt.has(pt)){if(nt.add(pt),!ft.prefabFile){if(typeof ft.loadMainFile!="function")throw new Error(`Prefab binding "${et}" source references instance asset "${ht}", but asset "${pt}" cannot be loaded`);await ft.loadMainFile()}if(mt==="Prefab"){if(!ft.prefabFile)throw new Error(`Prefab binding "${et}" source references nested Prefab "${ht}", but its source file is unavailable after load`);await this.ensurePrefabSourceInstanceAssetsLoaded(ft.prefabFile,et,nt)}}}}registerExternalEntityTree(tt){const et=this.root.engineProjection,nt=tt.engineObject;et&&nt&&et.registerExternalEntity(tt.id,nt);for(const it of tt.selfChildren)this.registerExternalEntityTree(it)}async instantiateGLTFBindingEngineObjects(tt){if(this.root.engineProjection)for(const nt of Object.values(tt.prefab.bindings)){if(nt.assetKind!=="glTF")continue;const it=tt.entities[nt.instanceRootEntityId];if(!it)throw new Error(`glTF binding "${nt.id}" references missing instance root "${nt.instanceRootEntityId}"`);const at=this.root.assetStore.assets[nt.assetId];if(!at)throw new Error(`glTF binding "${nt.id}" references unavailable asset "${nt.assetId}"`);if(typeof at.loadMainFile=="function"&&await at.loadMainFile(),typeof at.instantiate!="function")throw new Error(`glTF binding "${nt.id}" asset "${nt.assetId}" cannot be instantiated`);const ot=await at.instantiate(this,it.transform,{expectedRootId:nt.instanceRootEntityId,expectedBindingId:nt.id});await ot.ensureReady(),this.registerExternalEntityTree(ot);for(const st of Object.values(nt.sourceToSceneEntity))if(tt.entities[st]&&!this.entities.has(st))throw new Error(`glTF binding "${nt.id}" asset "${nt.assetId}" did not instantiate expected scene entity "${st}"`)}}async init(tt){const et=parseSourceV2SceneFileJson(tt.getMainData());await this.ensureSourceInstancePrefabFilesLoaded(et);const nt=ot=>{var st,ct;return(ct=(st=this.root.assetStore).getAssetByVirtualPath)==null?void 0:ct.call(st,ot)},it=createSourceRefCodec({resolveSourceRef:ot=>{var st;return(st=nt(ot))==null?void 0:st.id},resolveAssetKind:ot=>{var ct,dt,ut;const st=(ut=(dt=(ct=nt(ot))==null?void 0:ct.getMetaConfig)==null?void 0:dt.call(ct))==null?void 0:ut.type;return st==="Prefab"||st==="glTF"?st:void 0}}),at=hydrateSourceV2SceneToDomain(et,{resolveSourceRef:ot=>it.sourceToDomain(ot,`loading scene "${tt.id}"`),resolveAssetKind:ot=>it.maybeResolveAssetKind(ot),resolvePrefabSourceFile:ot=>readLoadedPrefabSourceFile(this.root.assetStore.assets[ot])});return await this.instantiateGLTFBindingEngineObjects(at),this.root.domainStore.reset({...this.root.domainStore.state,scene:at.scene,entities:at.entities,prefab:at.prefab}),this.hydrateDomainEntityModelsFromState(),this.refId=tt.id,await this.setupInspector(et),et}async setupInspector(tt){const et=this.formSchema;et.addGroup("scene.ambient-light.diffuse.title",["diffuseMode","diffuseSolidColor","diffuseIntensity"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.specular.title",["specularMode","customSpecularTexture","specularIntensity"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.bake.title",["autoBake","bakerResolution","bakeButton"],{collapsible:!1,nesting:!0}),et.addGroup("scene.ambient-light.title",["scene.ambient-light.diffuse.title","scene.ambient-light.specular.title","scene.ambient-light.bake.title"]),et.addGroup("scene.ambientOcclusion.title",["enabledAmbientOcclusion","quality","intensity","power","radius","bias","bilateralThreshold","minHorizonAngle"]),et.addGroup("scene.background.title",["backgroundMode","backgroundColor","backgroundTexture","skyMaterial","skyMesh","textureFillMode"]),et.addGroup("scene.shadow.title",["castShadows","enableTransparentShadow","shadowResolution","shadowCascades","shadowTwoCascadeSplits","shadowFourCascadeSplits","shadowDistance","shadowFadeBorder"]),et.addGroup("scene.fog.title",["fogMode","fogColor","fogStart","fogEnd","fogDensity"]),this.deserialize(tt),await this._gate.hydrate(async()=>{if(this.engineObject===this.engineSceneObject){await this.replayAllPropertyChange(!1);return}await this.bindEngineObject(this.engineSceneObject)})}deserialize(tt){const et=getSerializeConfigs(this),nt=sourceSceneSettingsToEditorSettings(tt.scene??{},at=>{var ot,st,ct;return(ct=(st=(ot=this.root.assetStore).getAssetByVirtualPath)==null?void 0:st.call(ot,at))==null?void 0:ct.id}),it={...tt,scene:nt};Object.keys(et).forEach(at=>{const ot=et[at],st=ot.key??at,ct=get$3(it,st);if(ct!==void 0){const dt=ot.onDeserialize?ot.onDeserialize(ct):ct;this[at]=dt}})}getDomainSettingPath(tt){if(tt.includes("/"))return normalizeSceneSettingPath(tt);const et=buildSceneSettingBindings(getSerializeConfigs(this)),nt=getSceneSettingPathByProperty(et,tt);if(!nt)throw new Error(`EditorScene.getDomainSettingPath: unknown scene setting property: ${tt}`);return nt}commitSceneSettingToDomain(tt,et){const nt=this.root.sceneFacade;if(!(nt!=null&&nt.updateSetting))throw new Error("EditorScene.commitSceneSettingToDomain requires root.sceneFacade.updateSetting");const it=this.getDomainSettingPath(tt);nt.updateSetting(it,et)}onInitComplete(){this._initComplete=!0}sync(){}toJSON(tt=!1){var ht;const{entities:et,components:nt}=super.toJSON(tt),it=getSerializeConfigs(this),at={};Object.keys(it).forEach(ft=>{const pt=it[ft],mt=pt.key??ft;let vt=toJS(this[ft]);pt.onSerialize&&(vt=pt.onSerialize(vt)),set$1(at,mt,vt)});const ot=editorSceneSettingsToSourceSettings(at.scene??{},ft=>{var pt,mt;return(mt=(pt=this.root.assetStore).getAssetVirtualPath)==null?void 0:mt.call(pt,ft)}),st=(ht=this.root.assetStore.assets[this.refId])==null?void 0:ht.name,ct=this.rootEntities.map(ft=>ft.id),dt={...st?{name:st}:{},rootEntities:ct,...ot};return{asset:{version:"2.0",generator:"Galacean Editor"},scene:dt,entities:et,components:nt}}destroy(){var tt;if(!this._destroyed){this._gate.dispose(),super.destroy();for(const et of this.entities.values())et.destroy();(tt=this.engineObject)==null||tt.destroy(),this.sceneUIStore.setLastSelectedId(null),this.engine=null,this._lastSkyMaterialRefId&&this.root.assetStore.getAssetByRef({refId:this._lastSkyMaterialRefId}).then(et=>{et&&et.removeListener("propertychange",this._autoBake),this._lastSkyMaterialRefId=null})}}async bake(){if(this._bakePromise)return this._bakePromise;const tt=(async()=>{log$1.info("bake"),this.isBaking=!0;try{const et="ambient",nt="custom_ambient",it=this.root.assetStore,at=this.root.assetFacade,ot=await it.createFolder(["Bake"]),st=this.specularMode===SOURCE_SPECULAR_MODE_CUSTOM&&this._customSpecularTexture,ct=[await findReusableBakedAmbientAsset(this,ot,et)].concat(st?await findReusableBakedAmbientAsset(this,ot,nt):[]),[dt,ut]=await Promise.all(ct.map(async(ht,ft)=>(ht?(await ht.loadMainFile(),ft===0?await ht.bakeFromScene(this.engine):await ht.bakeFromTexture(this._customSpecularTexture),ht.updateThumbnail(),await at.persistAssetMainImmediate(ht.id)):ft===0?ht=await at.createAssetByAdd({assetType:"AmbientLight",name:et,parentFolderId:ot,params:{from:"Scene"}}):ht=await at.createAssetByAdd({assetType:"AmbientLight",name:nt,parentFolderId:ot,params:{from:"Texture",srcTexture:this._customSpecularTexture}}),ht)));this.commitSceneSettingToDomain("ambientLight",dt.getCurrentRef()),ut&&this.commitSceneSettingToDomain("customAmbientLight",ut.getCurrentRef())}finally{this.isBaking=!1}})();this._bakePromise=tt;try{await tt}finally{this._bakePromise===tt&&(this._bakePromise=null)}}applySettingFromDomain(tt,et){const nt=buildSceneSettingBindings(getSerializeConfigs(this)),it=getSceneSettingPropertyByPath(nt,tt);if(!it)throw new Error(`EditorScene.applySettingFromDomain: unknown scene setting path: ${tt}`);if(!(it in this))throw new Error(`EditorScene.applySettingFromDomain: missing scene setting property "${it}" for path: ${tt}`);this[it]=et,this.triggerPropertyChange(it,!1)}}__decorateClass$2([observable],EditorScene.prototype,"isBaking",2);__decorateClass$2([observable,serialize({key:"scene.ambient.ambientLight"}),propertyField({type:ComponentType.AssetPicker,assetType:"AmbientLight",when:rt=>!1,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et&&(rt._originalSpecularTexture=et.specularTexture,rt.engineObject.ambientLight.diffuseSphericalHarmonics=et.diffuseSphericalHarmonics),rt.triggerPropertyChange("specularMode",!1)}})],EditorScene.prototype,"ambientLight",2);__decorateClass$2([observable,serialize({key:"scene.ambient.customAmbientLight"}),propertyField({type:ComponentType.AssetPicker,assetType:"AmbientLight",when:rt=>!1,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et?rt._customBakedSpecularTexture=et.specularTexture:rt._customBakedSpecularTexture=null,rt.triggerPropertyChange("specularMode",!1)}})],EditorScene.prototype,"customAmbientLight",2);__decorateClass$2([observable,serialize({key:"scene.ambient.diffuseMode"}),propertyField({label:"scene.ambient-light.diffuse.source",info:"scene.ambient-light.diffuse.source-info",type:ComponentType.Select,bindPath:"ambientLight.diffuseMode",options:[{label:"scene.ambient-light.diffuse.source-background",value:DiffuseMode.SphericalHarmonics},{label:"scene.ambient-light.diffuse.source-solid-color",value:DiffuseMode.SolidColor}]})],EditorScene.prototype,"diffuseMode",2);__decorateClass$2([observable,serialize(hdrColorSerializer({key:"scene.ambient.diffuseSolidColor"})),propertyField({type:ComponentType.Color,mode:"hdr",label:"scene.ambient-light.diffuse.solid-color",info:"scene.ambient-light.diffuse.solid-color-info",when:rt=>rt.diffuseMode===DiffuseMode.SolidColor,onChange(rt,_e,tt){rt.engineObject.ambientLight.diffuseSolidColor.copyFrom(serializeHDRColor(tt))}})],EditorScene.prototype,"diffuseSolidColor",2);__decorateClass$2([observable,serialize({key:"scene.ambient.diffuseIntensity"}),propertyField({type:ComponentType.Slider,label:"scene.ambient-light.diffuse.intensity",info:"scene.ambient-light.diffuse.intensity-info",bindPath:"ambientLight.diffuseIntensity",min:0,max:5,dragStep:.1})],EditorScene.prototype,"diffuseIntensity",2);__decorateClass$2([observable,serialize({key:"scene.ambient.specularMode"}),propertyField({label:"scene.ambient-light.specular.source",info:"scene.ambient-light.specular.source-info",type:ComponentType.Select,options:[{label:"scene.ambient-light.specular.source-background",value:SOURCE_SPECULAR_MODE_SKY},{label:"scene.ambient-light.specular.source-custom",value:SOURCE_SPECULAR_MODE_CUSTOM}],onChange:(rt,_e,tt)=>{tt===SOURCE_SPECULAR_MODE_SKY?rt.engineObject.ambientLight.specularTexture=rt._originalSpecularTexture:rt.engineObject.ambientLight.specularTexture=rt._customBakedSpecularTexture}})],EditorScene.prototype,"specularMode",2);__decorateClass$2([observable,serialize({key:"scene.ambient.customSpecularTexture"}),propertyField({label:"scene.ambient-light.specular.custom-texture",info:"scene.ambient-light.specular.custom-texture-info",type:ComponentType.AssetPicker,assetType:"Texture",customFilter:rt=>rt.shape==="Cube",when:rt=>rt.specularMode===SOURCE_SPECULAR_MODE_CUSTOM,onChange:async(rt,_e,tt)=>{const et=tt==null?void 0:tt.engineObject;et?(rt._customSpecularTexture=et,rt._autoBake()):rt._customSpecularTexture=null}})],EditorScene.prototype,"customSpecularTexture",2);__decorateClass$2([observable,serialize({key:"scene.ambient.specularIntensity"}),propertyField({type:ComponentType.Slider,label:"scene.ambient-light.specular.intensity",info:"scene.ambient-light.specular.intensity-info",bindPath:"ambientLight.specularIntensity",min:0,max:5,dragStep:.1})],EditorScene.prototype,"specularIntensity",2);__decorateClass$2([observable,serialize({key:"scene.background.mode"}),propertyField({label:"scene.background.mode.title",info:"Class:Background.mode",type:ComponentType.Select,options:transformEnumToOptions(BackgroundMode,void 0,rt=>t$7(`scene.background.mode.${rt.toLowerCase()}`)),onChange(rt,_e,tt){rt.engineObject.background.mode=tt,rt._autoBake()}})],EditorScene.prototype,"backgroundMode",2);__decorateClass$2([observable,serialize({key:"scene.background.color"}),propertyField({label:"scene.background.color.title",info:"scene.background.color.info",type:ComponentType.Color,bindPath:"background.solidColor",when:rt=>rt.backgroundMode===BackgroundMode.SolidColor,onChange(rt){rt._autoBake()}})],EditorScene.prototype,"backgroundColor",2);__decorateClass$2([observable,serialize({key:"scene.background.texture"}),propertyField({label:"scene.background.texture.title",info:"scene.background.texture.info",type:ComponentType.AssetPicker,assetType:"Texture",bindPath:"background.texture",when:rt=>rt.backgroundMode===BackgroundMode.Texture,onChange:async rt=>{rt._autoBake()}})],EditorScene.prototype,"backgroundTexture",2);__decorateClass$2([observable,serialize({key:"scene.background.textureFillMode"}),propertyField({label:"scene.background.texture-fill-mode.title",info:"scene.background.texture-fill-mode.info",type:ComponentType.Select,options:transformEnumToOptions(BackgroundTextureFillMode,void 0,rt=>t$7(`scene.background.texture-fill-mode.${rt.toLowerCase()}`)),when:rt=>rt.backgroundMode===BackgroundMode.Texture,onChange(rt,_e,tt){rt.engineObject.background.textureFillMode=tt,rt._autoBake()}})],EditorScene.prototype,"textureFillMode",2);__decorateClass$2([observable,serialize({key:"scene.background.skyMaterial"}),propertyField({label:"scene.sky.material.title",info:"scene.sky.material.info",type:ComponentType.AssetPicker,assetType:"Material",when:rt=>rt.backgroundMode===BackgroundMode.Sky,onChange:async(rt,_e,tt)=>{const et=rt.engineObject.background.sky;if(rt._lastSkyMaterialRefId){const nt=await rt.root.assetStore.getAssetByRef({refId:rt._lastSkyMaterialRefId});nt&&nt.removeListener("propertychange",rt._autoBake),rt._lastSkyMaterialRefId=null}tt?(rt._lastSkyMaterialRefId=tt.id,et.material=tt.engineObject,tt.on("propertychange",rt._autoBake)):et.material=null,rt._autoBake()}})],EditorScene.prototype,"skyMaterial",2);__decorateClass$2([observable,serialize({key:"scene.background.skyMesh"}),propertyField({label:"scene.sky.mesh.title",info:"scene.sky.mesh.info",type:ComponentType.AssetPicker,assetType:["Mesh","PrimitiveMesh"],when:rt=>rt.backgroundMode===BackgroundMode.Sky,onChange:async(rt,_e,tt)=>{const et=rt.engineObject.background.sky,nt=tt==null?void 0:tt.engineObject;nt?et.mesh=nt:et.mesh=null}})],EditorScene.prototype,"skyMesh",2);__decorateClass$2([observable,serialize({key:"scene.shadow.castShadows"}),propertyField({label:"scene.shadow.cast-shadows.title",info:"scene.shadow.cast-shadows.info",type:ComponentType.Toggle,bindPath:"castShadows"})],EditorScene.prototype,"castShadows",2);__decorateClass$2([observable,serialize({key:"scene.shadow.enableTransparentShadow"}),propertyField({label:"scene.shadow.enable-transparent.title",info:"scene.shadow.enable-transparent.info",type:ComponentType.Toggle,bindPath:"enableTransparentShadow",when:rt=>rt.castShadows})],EditorScene.prototype,"enableTransparentShadow",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowResolution"}),propertyField({label:"scene.shadow.resolution.title",info:"scene.shadow.resolution.info",type:ComponentType.Select,options:transformEnumToOptions(ShadowResolution,void 0,rt=>t$7(`scene.shadow.resolution.${rt.toLowerCase()}`)),bindPath:"shadowResolution",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowResolution",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowCascades"}),propertyField({label:"scene.shadow.cascades.title",info:"scene.shadow.cascades.info",type:ComponentType.Select,options:transformEnumToOptions(ShadowCascadesMode,void 0,rt=>t$7(`scene.shadow.cascades.${rt.toLowerCase()}`)),bindPath:"shadowCascades",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowCascades",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowTwoCascadeSplits"}),propertyField({label:"scene.shadow.two-cascade-splits.title",info:"scene.shadow.two-cascade-splits.info",when:rt=>rt.castShadows&&rt.shadowCascades===ShadowCascadesMode.TwoCascades,customComponent:CustomTwoCascadeSlider,onChange(rt,_e,tt){rt.engineObject.shadowTwoCascadeSplits=tt}})],EditorScene.prototype,"shadowTwoCascadeSplits",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowFourCascadeSplits"}),propertyField({label:"scene.shadow.four-cascade-splits.title",info:"scene.shadow.four-cascade-splits.info",when:rt=>rt.castShadows&&rt.shadowCascades===ShadowCascadesMode.FourCascades,customComponent:CustomFourCascadeSlider,onChange(rt,_e,tt){rt.engineObject.shadowFourCascadeSplits.copyFrom(tt)}})],EditorScene.prototype,"shadowFourCascadeSplits",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowDistance"}),propertyField({label:"scene.shadow.distance.title",info:"scene.shadow.distance.info",type:ComponentType.Number,bindPath:"shadowDistance",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowDistance",2);__decorateClass$2([observable,serialize({key:"scene.shadow.shadowFadeBorder"}),propertyField({label:"scene.shadow.fade-border.title",info:"scene.shadow.fade-border.info",type:ComponentType.Slider,min:0,max:1,dragStep:.01,bindPath:"shadowFadeBorder",when:rt=>rt.castShadows})],EditorScene.prototype,"shadowFadeBorder",2);__decorateClass$2([observable,serialize({key:"scene.fog.mode"}),propertyField({label:"scene.fog.mode.title",info:"scene.fog.mode.info",type:ComponentType.Select,options:transformEnumToOptions(FogMode,void 0,rt=>t$7(`scene.fog.mode.${rt.toLowerCase()}`)),bindPath:"fogMode"})],EditorScene.prototype,"fogMode",2);__decorateClass$2([observable,serialize({key:"scene.fog.color"}),propertyField({label:"scene.fog.color.title",info:"scene.fog.color.info",type:ComponentType.Color,bindPath:"fogColor",when:rt=>rt.fogMode!==FogMode.None})],EditorScene.prototype,"fogColor",2);__decorateClass$2([observable,serialize({key:"scene.fog.start"}),propertyField({label:"scene.fog.start.title",info:"scene.fog.start.info",type:ComponentType.Number,bindPath:"fogStart",when:rt=>rt.fogMode===FogMode.Linear})],EditorScene.prototype,"fogStart",2);__decorateClass$2([observable,serialize({key:"scene.fog.end"}),propertyField({label:"scene.fog.end.title",info:"scene.fog.end.info",type:ComponentType.Number,bindPath:"fogEnd",when:rt=>rt.fogMode===FogMode.Linear})],EditorScene.prototype,"fogEnd",2);__decorateClass$2([observable,serialize({key:"scene.fog.density"}),propertyField({label:"scene.fog.density.title",info:"scene.fog.density.info",type:ComponentType.Number,bindPath:"fogDensity",dragStep:.001,when:rt=>rt.fogMode===FogMode.Exponential||rt.fogMode===FogMode.ExponentialSquared})],EditorScene.prototype,"fogDensity",2);__decorateClass$2([observable,serialize({key:"scene.autoBake"}),propertyField({label:"scene.ambient-light.bake.auto.title",info:"scene.ambient-light.bake.auto.info",type:ComponentType.Toggle,onChange(rt,_e,tt){tt&&rt._initComplete&&rt.bake()}})],EditorScene.prototype,"autoBake",2);__decorateClass$2([observable,serialize({key:"scene.ambient.bakerResolution"}),propertyField({label:"scene.ambient-light.bake.resolution.title",info:"scene.ambient-light.bake.resolution.info",type:ComponentType.Select,options:transformEnumToOptions(BakerResolution,void 0,rt=>t$7(`scene.ambient-light.bake.resolution.${rt.toLowerCase()}`)),onChange(rt){rt._autoBake()}})],EditorScene.prototype,"bakerResolution",2);__decorateClass$2([observable,propertyField({info:"scene.ambient-light.bake.button.info",when:rt=>!rt.autoBake,customComponent:CustomBakeButton})],EditorScene.prototype,"bakeButton",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.enabled"}),propertyField({label:"scene.ambientOcclusion.enabled",info:"scene.ambientOcclusion.enabled-info",type:ComponentType.Toggle,bindPath:"ambientOcclusion.enabled"})],EditorScene.prototype,"enabledAmbientOcclusion",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.quality"}),propertyField({label:"scene.ambientOcclusion.quality.title",info:"scene.ambientOcclusion.quality.info",type:ComponentType.Select,options:transformEnumToOptions(AmbientOcclusionQuality,void 0,rt=>t$7(`scene.ambientOcclusion.quality.${rt.toLowerCase()}`)),bindPath:"ambientOcclusion.quality",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"quality",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.intensity"}),propertyField({type:ComponentType.Number,label:"scene.ambientOcclusion.intensity",info:"scene.ambientOcclusion.intensity-info",bindPath:"ambientOcclusion.intensity",min:0,when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"intensity",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.power"}),propertyField({label:"scene.ambientOcclusion.power",info:"scene.ambientOcclusion.power-info",type:ComponentType.Slider,min:0,max:8,dragStep:.01,bindPath:"ambientOcclusion.power",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"power",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.radius"}),propertyField({label:"scene.ambientOcclusion.radius",info:"scene.ambientOcclusion.radius-info",type:ComponentType.Slider,min:.1,max:10,dragStep:.01,bindPath:"ambientOcclusion.radius",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"radius",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.bilateralThreshold"}),propertyField({label:"scene.ambientOcclusion.bilateralThreshold",info:"scene.ambientOcclusion.bilateralThreshold-info",type:ComponentType.Slider,min:1e-6,max:.1,dragStep:1e-4,bindPath:"ambientOcclusion.bilateralThreshold",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"bilateralThreshold",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.bias"}),propertyField({label:"scene.ambientOcclusion.bias",info:"scene.ambientOcclusion.bias-info",type:ComponentType.Slider,min:0,max:.5,dragStep:1e-5,bindPath:"ambientOcclusion.bias",when:rt=>rt.enabledAmbientOcclusion})],EditorScene.prototype,"bias",2);__decorateClass$2([observable,serialize({key:"scene.ambientOcclusion.minHorizonAngle",...angleSerializer()}),propertyField({label:"scene.ambientOcclusion.minHorizonAngle",info:"scene.ambientOcclusion.minHorizonAngle-info",type:ComponentType.Slider,min:0,max:45,bindPath:"ambientOcclusion.minHorizonAngle",when:rt=>rt.enabledAmbientOcclusion}),propertyProxy({getPath:"ambientOcclusion.minHorizonAngle",getEditorValue:rt=>rt*180/Math.PI})],EditorScene.prototype,"minHorizonAngle",2);__decorateClass$2([observable],EditorScene.prototype,"_initComplete",2);__decorateClass$2([computed],EditorScene.prototype,"initComplete",1);__decorateClass$2([computed],EditorScene.prototype,"removable",1);__decorateClass$2([action],EditorScene.prototype,"setupInspector",1);__decorateClass$2([action],EditorScene.prototype,"onInitComplete",1);__decorateClass$2([action],EditorScene.prototype,"sync",1);__decorateClass$2([action],EditorScene.prototype,"destroy",1);__decorateClass$2([action],EditorScene.prototype,"applySettingFromDomain",1);async function findReusableBakedAmbientAsset(rt,_e,tt){const et=Object.values(rt.root.assetStore.assets).filter(nt=>nt.parentFolderId===_e&&nt.name===tt);for(const nt of et){if(canReuseBakedAmbientAsset(rt,nt))return nt;isSystemBakedAmbientAsset(rt,nt)&&await deleteUnusableBakedAmbientAsset(rt,nt)}}function canReuseBakedAmbientAsset(rt,_e){var nt;const tt=(nt=rt.root.domainStore)==null?void 0:nt.state.assets[_e.id],et=tt==null?void 0:tt.status;return et&&et!=="ready"?!1:!!(_e.url||tt!=null&&tt.url)}function isSystemBakedAmbientAsset(rt,_e){var nt,it,at;const tt=(nt=rt.root.domainStore)==null?void 0:nt.state.assets[_e.id];return(tt==null?void 0:tt.status)==="uploading"?!1:((tt==null?void 0:tt.type)??((at=(it=_e.getMetaConfig)==null?void 0:it.call(_e))==null?void 0:at.type))==="AmbientLight"}async function deleteUnusableBakedAmbientAsset(rt,_e){var et;const tt=(et=rt.root.assetFacade)==null?void 0:et.deleteAsset;if(typeof tt!="function")throw new Error(`Cannot replace unusable baked ambient asset "${_e.name}" (${_e.id}): root.assetFacade.deleteAsset is unavailable`);await tt.call(rt.root.assetFacade,_e.id)}const EditorScene$1=Object.freeze(Object.defineProperty({__proto__:null,EditorScene},Symbol.toStringTag,{value:"Module"})),viewportConfig={"2d":{setting:{mode:"2D",is3dMode:!1,projection:"orthographic",nearClipPlane:.03,farClipPlane:1e4,fieldOfView:60,isOrthographic:!0,orthographicSize:10,flySpeed:8,isDynamicClipping:!0},location:{eye:{x:0,y:0,z:10},target:{x:0,y:0,z:0},up:{x:0,y:1,z:0}},toolsetting:{grid:!0,gizmo:{state:8,anchorType:0,coordType:0}}},"3d":{setting:{mode:"3D",is3dMode:!0,projection:"perspective",nearClipPlane:.03,farClipPlane:1e4,fieldOfView:60,isOrthographic:!1,flySpeed:8,isDynamicClipping:!0},location:{eye:{x:15,y:7,z:15},target:{x:0,y:3.5,z:0},up:{x:0,y:1,z:0}},toolsetting:{grid:!0,gizmo:{state:1,anchorType:0,coordType:0}}}},VIEWPORT_TOOL_KEY="__viewportToolSetting__",VIEWPORT_CAMERA_KEY={id:"0",get location(){return`__viewportCameraLocation-${this.id}__`},get setting(){return`__viewportCameraSetting-${this.id}__`},set projectId(rt){this.id=rt}};function getConfig(){const rt=localStorage.getItem(VIEWPORT_CAMERA_KEY.setting);let _e;if(rt)try{_e=JSON.parse(rt)}catch(at){console.error("parse localStorage cameraSetting failed: "+at)}const tt=localStorage.getItem(VIEWPORT_CAMERA_KEY.location);let et;if(tt)try{et=JSON.parse(tt)}catch(at){console.error("parse localStorage cameraLocation failed: "+at)}const nt=localStorage.getItem(VIEWPORT_TOOL_KEY);let it;if(nt)try{it=JSON.parse(nt)}catch(at){console.error("parse localStorage toolSetting failed: "+at)}return{cameraSetting:_e,cameraLocation:et,toolSetting:it}}function setConfig(rt,_e,tt={}){if(VIEWPORT_CAMERA_KEY.projectId=rt,!localStorage.getItem(VIEWPORT_CAMERA_KEY.setting)){const at=viewportConfig[_e].setting;saveCameraSetting(JSON.stringify(at))}if(!localStorage.getItem(VIEWPORT_CAMERA_KEY.location)){const at=tt.cameraLocation??viewportConfig[_e].location;saveCameraLocation(JSON.stringify(at))}if(!localStorage.getItem(VIEWPORT_TOOL_KEY)){const at=viewportConfig[_e].toolsetting;saveToolSetting(JSON.stringify(at))}}function saveCameraSetting(rt){localStorage.setItem(VIEWPORT_CAMERA_KEY.setting,rt)}function saveToolSetting(rt){localStorage.setItem(VIEWPORT_TOOL_KEY,rt)}function saveCameraLocation(rt){localStorage.setItem(VIEWPORT_CAMERA_KEY.location,rt)}var __defProp$2=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc$1(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$2(_e,tt,nt),nt};class PreviewManager{constructor(_e){Rt(this,"viewer",null);Rt(this,"isInit",!1);Rt(this,"isPreviewOn",!1);Rt(this,"isPreviewLockOn",!1);Rt(this,"hasUserRT",!1);this.projectStore=_e,makeObservable(this)}init(_e){this.viewer=new ViewportPreviewer,this.isInit=!0,this.viewer.init(_e)}togglePreviewLock(){this.isPreviewLockOn=!this.isPreviewLockOn}startPreview(_e){this.isPreviewOn=!0,this.hasUserRT=!!_e.renderTarget,this.viewer.startPreview(_e)}endPreview(_e=!1){(_e||this.isPreviewOn&&!this.isPreviewLockOn)&&(this.isPreviewOn=!1,this.hasUserRT=!1,this.viewer.endPreview())}updatePreview(_e,tt){var nt;if(_e.type!=="Camera")return;const et=this.projectStore.currentScene.sceneUIStore.lastSelectedId;!et||!this.projectStore.currentScene.entities.get(et)||(tt?((nt=this.viewer.previewCamera)==null?void 0:nt.instanceId)===_e.engineObject.instanceId&&this.endPreview():(this.endPreview(),!this.isPreviewLockOn&&this.startPreview(_e.engineObject)))}onSelect(_e){if(!this.isPreviewLockOn){const tt=_e.getComponent(Camera);this.endPreview(),tt&&this.startPreview(tt)}}}__decorateClass$1([observable],PreviewManager.prototype,"isInit",2);__decorateClass$1([observable],PreviewManager.prototype,"isPreviewOn",2);__decorateClass$1([observable],PreviewManager.prototype,"isPreviewLockOn",2);__decorateClass$1([observable],PreviewManager.prototype,"hasUserRT",2);__decorateClass$1([action],PreviewManager.prototype,"togglePreviewLock",1);__decorateClass$1([action],PreviewManager.prototype,"startPreview",1);__decorateClass$1([action],PreviewManager.prototype,"endPreview",1);__decorateClass$1([action],PreviewManager.prototype,"updatePreview",1);function resolveSceneCameraDefaultFromCandidates(rt){const _e=selectCameraCandidate(rt);return _e?computeCameraLocationFromTransform(_e.position,_e.rotationQuaternion,_e.focusPoint):null}function computeSceneCameraReapply(rt){return!rt.useSceneCameraAsFallback||rt.userAdjustedCamera?null:resolveSceneCameraDefaultFromCandidates(rt.candidates)}function selectCameraCandidate(rt){if(rt.length===0)return null;let _e=rt[0];for(let tt=1;tt<rt.length;tt++)rt[tt].priority<_e.priority&&(_e=rt[tt]);return _e}function computeCameraLocationFromTransform(rt,_e,tt){const et=rotateVectorByQuaternion({x:0,y:0,z:-1},_e),nt=rotateVectorByQuaternion({x:0,y:1,z:0},_e),it=resolveTargetDistance(rt,et,tt);return{eye:{x:rt.x,y:rt.y,z:rt.z},target:{x:rt.x+et.x*it,y:rt.y+et.y*it,z:rt.z+et.z*it},up:{x:nt.x,y:nt.y,z:nt.z}}}function rotateVectorByQuaternion(rt,_e){const tt=2*(_e.y*rt.z-_e.z*rt.y),et=2*(_e.z*rt.x-_e.x*rt.z),nt=2*(_e.x*rt.y-_e.y*rt.x);return{x:rt.x+_e.w*tt+(_e.y*nt-_e.z*et),y:rt.y+_e.w*et+(_e.z*tt-_e.x*nt),z:rt.z+_e.w*nt+(_e.x*et-_e.y*tt)}}function resolveTargetDistance(rt,_e,tt){if(tt){const nt=(tt.x-rt.x)*_e.x+(tt.y-rt.y)*_e.y+(tt.z-rt.z)*_e.z;if(nt>.1&&nt<1e3)return nt}if(_e.y<-1e-4&&rt.y>1e-4){const nt=-rt.y/_e.y;if(nt>.1&&nt<1e3)return nt}const et=Math.sqrt(rt.x*rt.x+rt.y*rt.y+rt.z*rt.z);return et>.1?et:10}function isPlainObject(rt){return typeof rt=="object"&&rt!==null&&!Array.isArray(rt)}function mergeViewportDefaults(rt,_e){if(!isPlainObject(rt))return _e===void 0?rt:_e;isPlainObject(_e)||(_e={});const tt={};for(const et in rt)tt[et]=mergeViewportDefaults(rt[et],_e[et]);return tt}function resolveViewportStoredConfig({defaults:rt,stored:_e}){return{cameraSetting:mergeViewportDefaults(rt.cameraSetting,_e.cameraSetting),cameraLocation:mergeViewportDefaults(rt.cameraLocation,_e.cameraLocation),toolSetting:mergeViewportDefaults(rt.toolSetting,_e.toolSetting)}}function alignEntityCameraToViewport({entity:rt,cameraTransform:_e,fieldOfView:tt,updateComponent:et}){if(!rt||!rt.hasCameraComponent)return!1;syncTransformToEditor(rt.transform,_e);const nt=rt.getComponentByTypeName("Camera");return!(nt!=null&&nt.id)||!et?!1:(et(rt.id,nt.id,{fieldOfView:tt}),!0)}function syncTransformToEditor(rt,_e){if(!rt||typeof rt!="object")return;const tt=rt.syncTransformToEditor;typeof tt=="function"&&tt(_e)}function alignEntityBinderToViewport({entityBinder:rt,cameraTransform:_e,fieldOfView:tt}){rt==null||rt.alignToCamera({cameraTransform:_e,fieldOfView:tt})}var __defProp$1=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=(rt,_e,tt,et)=>{for(var nt=et>1?void 0:et?__getOwnPropDesc(_e,tt):_e,it=rt.length-1,at;it>=0;it--)(at=rt[it])&&(nt=(et?at(_e,tt,nt):at(nt))||nt);return et&&nt&&__defProp$1(_e,tt,nt),nt},Gr;const _ViewportStore=(Gr=class{constructor(_e){Rt(this,"engine");Rt(this,"viewport");Rt(this,"previewManager");Rt(this,"isIcon3dMode",!0);Rt(this,"viewToolState",ViewToolState.None);Rt(this,"_wireframeVisibility");Rt(this,"_cameraEntity");Rt(this,"_stores",[]);Rt(this,"_projectStore");Rt(this,"_gridScript");Rt(this,"_iconScript");Rt(this,"_navigationScript");Rt(this,"_outlineScript");Rt(this,"_wireframeScript");Rt(this,"_controlScript");Rt(this,"_gizmoScript");Rt(this,"_pickerScript");Rt(this,"_useSceneCameraAsFallback",!1);Rt(this,"_userAdjustedCamera",!1);Rt(this,"playMode",!1);Rt(this,"AIViewerMode",!1);Rt(this,"toolSetting",{grid:!0,icons:!0,navigation:!0,gizmo:{state:State.translate,anchorType:AnchorType.Pivot,coordType:CoordinateType.Local},outline:!0});Rt(this,"cameraSetting",{is3dMode:!0,nearClipPlane:.001,farClipPlane:1e4,fieldOfView:60,orthographicSize:10,flySpeed:8,isDynamicClipping:!0,projection:"perspective",enableEase:!0,enableAcceleration:!0,enableSmooth:!0});Rt(this,"cameraLocation",{eye:{x:10,y:10,z:10},target:{x:0,y:0,z:0},up:{x:0,y:1,z:0}});this.projectStore=_e,makeObservable(this),this.previewManager=new PreviewManager(_e),this._projectStore=_e,this.viewport=viewport}static registerPlugin(_e,tt){this.pluginStoreClasses.push({type:tt.type,storeClass:_e}),tt.Panel&&this.panels.push(tt.Panel)}addScripts(_e={}){const tt=_e.mode??"editor";this._addControlScript(),this._addGridScript(),this._addNavigationScript(),tt==="editor"&&(this._addGizmoScript(),this._addIconScript(),this._addOutlineScript(),this._addWireframeScript(),this._addPickerScript())}_addControlScript(){const _e=viewport.addScript(CameraControl),{cameraSetting:tt,cameraLocation:et}=this;return _e.init({projection:tt.projection,fieldOfView:tt.fieldOfView,nearClipPlane:tt.nearClipPlane,farClipPlane:tt.farClipPlane,isDynamicClipping:tt.isDynamicClipping,flySpeed:tt.flySpeed,enableSmooth:tt.enableSmooth,enableEase:tt.enableEase,enableAcceleration:tt.enableAcceleration,orthographicSize:tt.orthographicSize,cameraLocation:et,is3dMode:tt.is3dMode,onSaveOrthoSize:nt=>{tt.orthographicSize=nt},onSaveCameraPosition:nt=>{this._userAdjustedCamera=!0;const{eye:it,target:at,up:ot}=nt;saveCameraLocation(JSON.stringify({eye:{x:it.x,y:it.y,z:it.z},target:{x:at.x,y:at.y,z:at.z},up:{x:ot.x,y:ot.y,z:ot.z}}))},onSaveCursor:(nt,it)=>{this.viewport.setCursor(nt,it)},onViewToolStateChange:nt=>{this.viewToolState=nt}}),this._controlScript=_e,_e}_addGizmoScript(){const _e=this._projectStore,{toolSetting:tt}=this,et=tt.gizmo,nt=viewport.addScript(GizmoControl);return nt.init({anchorType:et.anchorType,coordType:et.coordType,state:et.state,onGizmoMoveStart:()=>{const it=_e.currentScene.selectedEntities;if(!(it!=null&&it.length))return;_e.root.domainStore.beginBatch()},onGizmoMoving:()=>{const it=_e.currentScene.selectedEntities;if(!(!it||(it==null?void 0:it.length)<=0))for(const at of it)at.transform.syncEngineToEditor(),_e.debouncedUpdateSceneAsset()},onGizmoMoveEnd:()=>{const it=_e.currentScene.selectedEntities;if(!(it!=null&&it.length))return;const at=_e.root.entityFacade;for(const ot of it){const st=ot.engineObject.transform;at.setTransform(ot.id,{position:{x:st.position.x,y:st.position.y,z:st.position.z},rotation:{x:st.rotation.x,y:st.rotation.y,z:st.rotation.z},scale:{x:st.scale.x,y:st.scale.y,z:st.scale.z}})}_e.root.domainStore.commitBatch("gizmo.transform"),_e.debouncedUpdateSceneAsset()},onGizmoCancel:()=>{_e.root.domainStore.abortBatch()}}),this._gizmoScript=nt,nt}_addGridScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Grid);return tt.init({grid:_e.grid,is3dMode:viewport.is3dMode}),this._gridScript=tt,tt}_addIconScript(){const _e=viewport.addScript(IconScript);return this._iconScript=_e,_e}_addNavigationScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Navigation);return tt.init(_e.navigation,viewport.is3dMode),this._navigationScript=tt,tt}_addOutlineScript(){const{toolSetting:_e}=this,tt=viewport.addScript(Outline);return tt.init(_e.outline),tt.mode=this.cameraSetting.is3dMode?"3d":"2d",this._outlineScript=tt,tt}_addWireframeScript(){const _e=viewport.addScript(WireframeScript);return this._wireframeVisibility=_e.visibility,this._wireframeScript=_e,_e}_addPickerScript(){const _e=this._projectStore,tt=viewport.addScript(Picker);return tt.init({onSelectEntity:(et,nt,it)=>{var at,ot;if(et){const st=((at=EditorPicker.subEntityPickerMap.get(et))==null?void 0:at.id)||((ot=EditorPicker.entityPickerMap.get(et))==null?void 0:ot.id);st&&_e.currentScene.selectEntity(st,nt,it)}else _e.currentScene.selectEntity(null)},onRemoveEntity:()=>{_e.currentScene.removeEntity()},onHoverEntity:et=>{var nt,it;if(et){const at=((nt=EditorPicker.subEntityPickerMap.get(et))==null?void 0:nt.id)||((it=EditorPicker.entityPickerMap.get(et))==null?void 0:it.id);at&&_e.currentScene.setHoveredEntity(at)}else _e.currentScene.setHoveredEntity(null)}}),this._pickerScript=tt,tt}init(_e,tt,et={}){const{projectStore:nt}=this;this.engine=tt.engine,this._useSceneCameraAsFallback=et.useSceneCameraAsFallback===!0;const it=this._useSceneCameraAsFallback?resolveSceneCameraDefaultFromCandidates(collectSceneCameraCandidates(tt))??void 0:void 0;setConfig(nt.id,_e,{cameraLocation:it});const at=resolveViewportStoredConfig({defaults:{cameraSetting:this.cameraSetting,cameraLocation:this.cameraLocation,toolSetting:this.toolSetting},stored:getConfig()});this.cameraSetting=at.cameraSetting,this.cameraLocation=at.cameraLocation,this.toolSetting=at.toolSetting,this.viewport.scene=tt,this.viewport.is3dMode=at.cameraSetting.is3dMode;const{camera:ot}=this.viewport;this._cameraEntity=ot.entity,this.previewManager.init(this._cameraEntity),this.addScripts(et),et.mode!=="viewer"&&this.toggleIconMode(this.isIcon3dMode),Gr.pluginStoreClasses.forEach(({storeClass:st,type:ct})=>{const dt=new st(nt.root);this[ct]=dt,dt.init(),this._stores.push(dt)}),reaction(()=>JSON.stringify(this.cameraSetting),debounce$2(st=>{saveCameraSetting(st)},1e3)),reaction(()=>JSON.stringify(this.toolSetting),debounce$2(st=>{saveToolSetting(st)},1e3))}switch(_e){this.previewManager.isPreviewOn=!1,this.viewport.scene=_e}switchDisplayMode(_e){const{cameraSetting:tt}=this;tt.is3dMode!==_e&&(tt.is3dMode=_e,this.switchProjection(_e?"perspective":"orthographic"),this.viewport.switchDisplayMode(_e,500))}switchProjection(_e){const{cameraSetting:tt}=this;tt.projection!==_e&&(tt.projection=_e,this.viewport.switchProjection())}reapplySceneCameraIfUntouched(){const _e=this.viewport.scene;if(!_e||!this._controlScript)return;const tt=computeSceneCameraReapply({useSceneCameraAsFallback:this._useSceneCameraAsFallback,userAdjustedCamera:this._userAdjustedCamera,candidates:collectSceneCameraCandidates(_e)});tt&&(this.cameraLocation=tt,this._controlScript.applyCameraLocation(tt),saveCameraLocation(JSON.stringify(tt)))}togglePlayMode(_e){this.playMode=_e??!this.playMode}toggleAIViewerMode(_e){this.AIViewerMode=_e??!this.AIViewerMode}focus(_e){const et=(_e?[_e]:this.projectStore.currentScene.selectedEntities.map(nt=>nt.engineObject)).filter(nt=>!!(nt&&!nt.destroyed));et.length!==0&&this.viewport.focus(et)}alignView(_e){var tt,et,nt;alignEntityCameraToViewport({entity:_e,cameraTransform:this._cameraEntity.transform,fieldOfView:this.viewport.camera.fieldOfView,updateComponent:(nt=(et=(tt=this._projectStore.root)==null?void 0:tt.componentFacade)==null?void 0:et.updateComponent)==null?void 0:nt.bind(this._projectStore.root.componentFacade)})}alignBinder(_e){alignEntityBinderToViewport({entityBinder:_e,cameraTransform:this._cameraEntity.transform,fieldOfView:this.viewport.camera.fieldOfView})}handleContainerResize(){this.viewport.resize()}selectEntity(_e){const tt=!_e||(_e==null?void 0:_e.length)<=0?null:_e.map(et=>et.engineObject).filter(et=>!!(et&&!et.destroyed));this.previewManager.endPreview(),this.viewport.selectEntity(tt!=null&&tt.length?tt:null);for(let et=0;et<(tt==null?void 0:tt.length);et++)this.previewManager.onSelect(tt[et])}hoverEntity(_e){const tt=_e==null?void 0:_e.engineObject;this.viewport.hoverEntity(tt&&!tt.destroyed?tt:null)}onComponentDestroy(_e){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||(this.viewport.onComponentDestroy(_e.engineObject),this.previewManager.updatePreview(_e,!0))}onComponentAdd(_e){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||(this.viewport.onComponentAdd(_e.engineObject),this.previewManager.updatePreview(_e,!1))}activeEntity(_e,tt){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||this.viewport.activeEntity(_e.engineObject,tt)}lockEntity(_e,tt){!(_e!=null&&_e.engineObject)||_e.engineObject.destroyed||this.viewport.lockEntity(_e.engineObject,tt)}play(_e){this.viewport.play(_e)}toggleVisible(_e){this.toggleGrid(_e),this.toggleIcons(_e),this.toggleNavigation(_e),this.toggleOutline(_e),this._stores.forEach(tt=>{tt.toggleVisible&&tt.toggleVisible(_e)})}toggleGrid(_e){this._gridScript&&(this._gridScript.onToggleVisible(_e),this.toolSetting.grid=_e)}toggleIcons(_e){this._iconScript&&(this._iconScript.onToggleVisible(_e),this.toolSetting.icons=_e)}toggleIconMode(_e){this._iconScript&&(this._iconScript.toggleMode(_e),this.isIcon3dMode=_e)}toggleNavigation(_e){this._navigationScript&&(this._navigationScript.onToggleVisible(_e),this.toolSetting.navigation=_e)}toggleOutline(_e){this._outlineScript&&(this._outlineScript.onToggleVisible(_e),this.toolSetting.outline=_e)}setFieldOfView(_e){this.viewport.camera.fieldOfView=_e,this.cameraSetting.fieldOfView=_e}setDynamicClipping(_e){this.cameraSetting.isDynamicClipping=_e}setNearClipPlane(_e){this.viewport.camera.nearClipPlane=_e,this.cameraSetting.nearClipPlane=_e}setFarClipPlane(_e){this.viewport.camera.farClipPlane=_e,this.cameraSetting.farClipPlane=_e}setFlySpeed(_e){this.cameraSetting.flySpeed=_e,this._controlScript&&this._controlScript.handleCameraFlySpeed(_e)}setEnableSmooth(_e){this.cameraSetting.enableSmooth=_e,this._controlScript&&this._controlScript.handleCameraSmooth(_e)}setEnableEase(_e){this.cameraSetting.enableEase=_e,this._controlScript&&this._controlScript.handleCameraEase(_e)}setEnableAcceleration(_e){this.cameraSetting.enableAcceleration=_e,this._controlScript&&this._controlScript.handleCameraAcceleration(_e)}toggleClipping(_e){this._controlScript&&this._controlScript.toggleClipping(_e)}setGizmoState(_e){this.toolSetting.gizmo.state=_e,this._gizmoScript&&(this._gizmoScript.gizmoState=_e,this._controlScript.toggleHandTool(!1))}setGizmoAnchorType(_e){this._gizmoScript&&(this._gizmoScript.anchorType=_e)}setGizmoCoordType(_e){this._gizmoScript&&(this._gizmoScript.coordType=_e)}handleNavigation(){this._controlScript&&this._gizmoScript&&(this._controlScript.toggleHandTool(!0),this._gizmoScript.gizmoState=0)}toggleWireframe(_e,tt){this._wireframeScript&&(this._wireframeScript.toggleVisible(_e,tt),this._wireframeVisibility=this._wireframeScript.visibility)}isWireframeVisible(_e){return(this._wireframeVisibility&_e)===_e}async createEngine(_e){return await this.viewport.createEngine(_e)}async capture(_e,tt){return await this.viewport.capture(_e,tt)}},Rt(Gr,"panels",[]),Rt(Gr,"pluginStoreClasses",[]),Gr);__decorateClass([observable],_ViewportStore.prototype,"viewToolState",2);__decorateClass([observable],_ViewportStore.prototype,"playMode",2);__decorateClass([observable],_ViewportStore.prototype,"AIViewerMode",2);__decorateClass([observable],_ViewportStore.prototype,"toolSetting",2);__decorateClass([observable],_ViewportStore.prototype,"cameraSetting",2);__decorateClass([action],_ViewportStore.prototype,"togglePlayMode",1);__decorateClass([action],_ViewportStore.prototype,"toggleAIViewerMode",1);let ViewportStore=_ViewportStore;const EDITOR_ROOT_ENTITY_NAME="editorRoot",sceneFocusBounds=new BoundingBox,sceneFocusCenter=new Vector3;function collectSceneCameraCandidates(rt){const _e=[],tt=collectAuthorRootEntities(rt),et=collectSceneFocusPoint(tt);for(let nt=0;nt<tt.length;nt++){const it=tt[nt];walkEntityForCamera(it,_e)}if(et)for(const nt of _e)nt.focusPoint=et;return _e}function collectAuthorRootEntities(rt){const _e=[],tt=rt.rootEntitiesCount;for(let et=0;et<tt;et++){const nt=rt.rootEntities[et];nt.name!==EDITOR_ROOT_ENTITY_NAME&&_e.push(nt)}return _e}function collectSceneFocusPoint(rt){const _e=getBoundingBox(rt,sceneFocusBounds,BoundingBoxType.RendererAndUICanvas);if(_e)return _e.getCenter(sceneFocusCenter),{x:sceneFocusCenter.x,y:sceneFocusCenter.y,z:sceneFocusCenter.z}}function walkEntityForCamera(rt,_e){const tt=rt.getComponent(Camera);if(tt){const nt=rt.transform.worldPosition,it=rt.transform.worldRotationQuaternion;_e.push({position:{x:nt.x,y:nt.y,z:nt.z},rotationQuaternion:{x:it.x,y:it.y,z:it.z,w:it.w},priority:tt.priority})}const et=rt.children.length;for(let nt=0;nt<et;nt++)walkEntityForCamera(rt.children[nt],_e)}function ViewportPlugin(rt){return _e=>{ViewportStore.registerPlugin(_e,{...rt})}}const logProject=logger$2("project");class ObservableLocalWorkspaceSync extends LocalWorkspaceSync{constructor(_e){super(_e),makeObservable(this,{directoryHandle:observable.ref,directoryName:observable,directoryPath:observable,permissionStatus:observable,status:observable,errorMessage:observable,isRestoring:observable,progress:observable.ref,lastSyncedAt:observable,hasBinding:computed,isActive:computed,needsPermission:computed,syncProgressPercent:computed,setStatus:action,reset:action})}}class Project extends ProjectInfo{constructor(tt){super();Rt(this,"root",null);Rt(this,"syncStatus","idle");Rt(this,"engine",null);Rt(this,"canvas",null);Rt(this,"packageName",DEFAULT_PACKAGE_NAME);Rt(this,"useCompressedTextures",!1);Rt(this,"currentScene",null);Rt(this,"currentViewport");Rt(this,"assets");Rt(this,"plugins",[]);Rt(this,"pageLocked",!1);Rt(this,"animationEditing",!1);Rt(this,"_publisher",EventBus.createPublisher());Rt(this,"localWorkspaceSync",null);Rt(this,"exportSettings",null);Rt(this,"entityClipboard",null);Rt(this,"savingPromise",null);Rt(this,"_localSceneId",null);Rt(this,"_localSceneKey","");Rt(this,"debouncedUpdateSchema",debounce$2(this.updateSchema.bind(this),1500,{}));Rt(this,"_logger",createLogger("Project"));Rt(this,"_pendingLogger",null);Rt(this,"debouncedUpdateSceneAsset",debouncePromise(()=>this._updateSceneAssetAndCapture(),100,{edges:["trailing"]}));Rt(this,"debounceUpdateThumbnail",debounce$2(this.updateThumbnail.bind(this),5e3,{edges:["trailing"]}));this.root=tt,makeObservable(this,{packageName:observable,syncStatus:observable,currentScene:observable,exportSettings:observable,pageLocked:observable,useCompressedTextures:observable,entityClipboard:observable.ref,setSyncStatus:action,addPlugin:action,updatePlugin:action,renamePackageName:action,lockClick:action,unlockClick:action,plugins:observable.shallow}),this.currentViewport=new ViewportStore(this),this.localWorkspaceSync=new ObservableLocalWorkspaceSync(this)}async initEngine(tt){const et=await this.currentViewport.createEngine(tt);this.engine=et,this.canvas=tt,tt.tabIndex=tt.tabIndex}setSyncStatus(tt){this.syncStatus=tt}async init(tt){const et=tt,{root:{assetStore:nt}}=this;return runInAction(()=>{var at;logProject.success("init project success.","verbose"),Object.keys(et).filter(ot=>ot!=="content").forEach(ot=>{if(ot==="setting"){const st=et[ot];if(st){if(typeof st=="string")try{et.setting=JSON.parse(st)}catch(ct){console.warn("[project] Failed to parse project setting JSON:",ct),et.setting={}}this.setting={...defaultSetting,...et[ot]}}}else this[ot]=et[ot]}),this._localSceneKey=`${this.id}-localSceneId`,this._localSceneId=localStorage.getItem(this._localSceneKey),this.dependencies=et.setting.dependencies||{},this.content={...et.content,platform:et.platform},this.plugins=et.content.plugins,this.engineVersion=et.engineVersion,(at=this.exportSettings)==null||at.destroy(),this.exportSettings=new ExportSettings(this,tt),nt.initRegisteredAssets()}),et}queryInfo(){return this._storage.project.query(this.id)}async reloadProject(){const tt=await this._storage.project.query(this.id);runInAction(()=>{this.content={...tt.content,platform:tt.platform}}),await this.initAssets(tt.assets)}async initAssets(tt){tt=ensureBuiltinFolderAssets(tt);for(const et of builtinShaderDirectories)tt.push(et);for(const et of builtinShaders)tt.push(et);await this.root.assetStore.init(tt,this.engine),this.syncAssetsToDomain(tt)}syncAssetsToDomain(tt){const et=[];for(const nt of tt){if(!this.root.assetStore.assets[nt.uuid]||this.root.domainStore.state.assets[nt.uuid])continue;const it=this.parseAssetMetaForDomainSync(nt.meta,nt.uuid);et.push({op:"add",path:`/assets/${nt.uuid}`,value:{id:nt.uuid,name:nt.name,type:it.type??"Unknown",serverId:nt.id??null,parentFolderId:nt.parentId||null,url:nt.url||void 0,meta:it,status:"ready"}})}et.length>0&&this.root.domainStore.apply(et,"asset.init")}parseAssetMetaForDomainSync(tt,et){if(!tt)return{};try{const nt=JSON.parse(tt);if(!nt||typeof nt!="object")throw new Error("asset meta is not an object");return nt}catch(nt){return logProject.warn(`[Project] Invalid asset meta JSON for asset ${et}, fallback to empty meta`,nt),{}}}async initScene(){this.currentScene=new EditorScene(this.root),this.root.engineProjection?this.root.engineProjection.scene!==this.currentScene.engineSceneObject&&this.root.engineProjection.setScene(this.currentScene.engineSceneObject):this.root.initEngineProjection(this.currentScene.engineSceneObject);const tt=this.assets,et=this._localSceneId||this.content.scene;let nt=tt.find(at=>at.uuid===et);nt||(nt=tt.find(at=>/Scene/.test(at.meta))),nt||(nt={uuid:(await this.root.assetFacade.createAssetByAdd({assetType:"Scene",name:"Scene"})).id}),this.content.scene=nt.uuid;const it=await this.root.assetStore.getAssetByRef({refId:nt.uuid});await this.currentScene.init(it),this.root.sceneFacade.initSettings(collectSceneSettings(this.currentScene)),this.exportSettings.defaultSceneId=nt.uuid,this.engine.sceneManager.activeScene=this.currentScene.engineSceneObject}runEngine(tt){const{currentScene:et,currentViewport:nt}=this;this.engine.on("onReady",()=>{this.engine.run()}),nt.init(this.platform,et.engineSceneObject,tt),et.entities.forEach(it=>{it.components.forEach(at=>{nt.onComponentAdd(at)})}),window.runtimeEngine=this.engine}async updateSchema(tt){const{root:et}=this;this.setSyncStatus("syncing"),!tt&&(tt=this.getSchema());try{await this._storage.schema.update(tt,et.projectStore.id),this.setSyncStatus("success")}catch(nt){console.error(nt),this.setSyncStatus("error")}}async updateSceneAsset(tt){const{root:et}=this,nt=await et.assetStore.getAssetByRef({refId:et.sceneStore.refId}),it=tt==null?void 0:tt.pinnedId;this.savingPromise=it!=null?withTraceId(it,()=>nt.saveMain()):nt.saveMain(),await this.savingPromise,this._publisher.publish("asset-change",{type:"modify",assetId:this.currentScene.refId,main:nt.getMainData()})}persistSceneDebounced(tt){this._logger.info(`persistSceneDebounced ← ${tt}`),this._pendingLogger=this._logger.capture(),this.debouncedUpdateSceneAsset()}async _updateSceneAssetAndCapture(){if(!this.root.sceneStore.refId)return;const tt=this._pendingLogger??this._logger;this._pendingLogger=null,tt.info("updateSceneAsset → saveMain + capture");try{this.setSyncStatus("syncing"),await this.updateSceneAsset(tt);const et=await this.currentViewport.capture(634,346);this.debounceUpdateThumbnail(et),this.setSyncStatus("success")}catch(et){console.error(et),this.setSyncStatus("error")}}getSchema(){const{projectStore:{engineVersion:tt},sceneStore:et}=this.root;return{scene:et.refId,plugins:this.plugins,engineVersion:tt}}renamePackageName(tt){this.packageName=tt}changeUseCompressedTextures(tt){this.useCompressedTextures=tt}lockClick(){this.pageLocked=!0}unlockClick(){this.pageLocked=!1}reset(){var nt,it,at,ot;this.localWorkspaceSync.reset(),(nt=this.exportSettings)==null||nt.destroy(),this.exportSettings=null,(it=this.currentScene)==null||it.destroy(),this.root.assetStore.reset(),(at=this.engine)==null||at.pause(),(ot=this.engine)==null||ot.destroy();const tt=new Set(["BlinnPhong","PBR","Unlit","Sky/Skybox","Sky/SkyProcedural","2D/SpriteMask","2D/Sprite","Sky/BackgroundTexture","Effect/Particle","2D/UIDefault","Effect/Trail","2D/Text"]),et=Shader._shaderMap;for(const st in et)tt.has(st)||delete et[st];this.engine=null,this.canvas=null,this.packageName=DEFAULT_PACKAGE_NAME,this.useCompressedTextures=!1}async switchScene(tt){var it;if(this.syncStatus==="syncing"){n.error("syncing, please wait");return}if(tt.scene===this.currentScene.refId)return;this.content.scene=tt.scene,this._localSceneId=tt.scene,this.exportSettings.defaultSceneId=tt.scene,localStorage.setItem(this._localSceneKey,tt.scene);const et=new EditorScene(this.root);(it=this.root.engineProjection)==null||it.setScene(et.engineSceneObject);const nt=await this.root.assetStore.getAssetByRef({refId:tt.scene});await et.init(nt),this.root.sceneFacade.initSettingsSystem(collectSceneSettings(et)),this.root.viewportStore.switch(et.engineSceneObject),et._autoBake(),this.currentScene.destroy(),this.currentScene=et,this.updateSchema(),n.success(`switch scene to ${this.currentScene.engineObject.name}`)}async setActiveEditorScene(tt){var ct,dt;if(this.syncStatus==="syncing")throw new Error("project is syncing, cannot switch active scene now");if(tt===this.currentScene.refId)return;await this.flushCurrentScenePersistenceOrThrow();const et=await this.root.assetStore.getAssetByRef({refId:tt}),nt=this.currentScene,it=nt.engineSceneObject,at=this.root.domainStore.state,ot=new EditorScene(this.root);let st=!1;try{this.currentScene=ot,(ct=this.root.engineProjection)==null||ct.setScene(ot.engineSceneObject),await ot.init(et),this.root.sceneFacade.initSettingsSystem(collectSceneSettings(ot)),this.root.viewportStore.switch(ot.engineSceneObject),ot._autoBake(),st=!0}catch(ut){if(this.currentScene=nt,(dt=this.root.engineProjection)==null||dt.setScene(it),this.root.domainStore.state!==at)try{this.root.domainStore.reset(at)}catch{}try{ot.destroy()}catch{}throw ut}st&&nt.destroy()}async flushCurrentScenePersistenceOrThrow(){if(await this.debouncedUpdateSceneAsset.flush(),this.syncStatus==="error")throw new Error("current scene failed to save, refusing to switch to avoid data loss");this.savingPromise&&await this.savingPromise}async flushCurrentScenePersistenceForAgent(){await this.flushCurrentScenePersistenceOrThrow()}async saveCurrentSceneForPreview(){var nt;const tt=(nt=this.currentScene)==null?void 0:nt.refId;if(!tt)return;const et=await this.root.assetStore.getAssetByRef({refId:tt});this.savingPromise=et.saveMainImmediately({skipEvent:!0}),await this.savingPromise,this._publisher.publish("asset-change",{type:"modify",assetId:tt,main:et.getMainData()})}async getFreshPreviewUrl(tt,et){return await this.saveCurrentSceneForPreview(),getPreviewUrl(this.id,tt,et)}async launch(){var et,nt;const tt=window.open("","_blank");if(!tt){n.error("Preview window was blocked by browser");return}try{tt.location.href=await this.getFreshPreviewUrl((et=this.currentScene)==null?void 0:et.refId)}catch(it){throw console.error(it),(nt=tt.close)==null||nt.call(tt),n.error("Failed to prepare preview"),it}}async addPlugin(tt){this.plugins.find(et=>et.packageName===tt.packageName)||(this.plugins.push(tt),this.root.projectStore.debouncedUpdateSchema(),setTimeout(()=>{window.history.go(0)},3e3))}async updatePlugin(tt,et="add"){if(et==="delete")this.plugins=this.plugins.filter(nt=>nt.packageName!==tt.packageName);else{const nt=this.plugins.find(it=>it.packageName===tt.packageName);nt?nt.version=tt.version:this.plugins.push(tt)}this.root.projectStore.debouncedUpdateSchema(),setTimeout(()=>{window.history.go(0)},3e3)}toJSON(){const tt=this.root.assetStore.toJSON();return{id:this.id,name:this.name,platform:this.platform,setting:this.setting,content:this.content,engineVersion:this.engineVersion,assets:tt,dependencies:this.dependencies}}}var __defProp=Object.defineProperty,__defNormalProp=(rt,_e,tt)=>_e in rt?__defProp(rt,_e,{enumerable:!0,configurable:!0,writable:!0,value:tt}):rt[_e]=tt,__publicField=(rt,_e,tt)=>__defNormalProp(rt,typeof _e!="symbol"?_e+"":_e,tt);const _Orientation=class $a{constructor(_e){__publicField(this,"_name"),this._name=_e}static flip(_e){return _e===$a.HORZ?$a.VERT:$a.HORZ}getName(){return this._name}toString(){return this._name}};__publicField(_Orientation,"HORZ",new _Orientation("horz"));__publicField(_Orientation,"VERT",new _Orientation("vert"));let Orientation=_Orientation;class Rect{constructor(_e,tt,et,nt){__publicField(this,"x"),__publicField(this,"y"),__publicField(this,"width"),__publicField(this,"height"),this.x=_e,this.y=tt,this.width=et,this.height=nt}static empty(){return new Rect(0,0,0,0)}static fromJson(_e){return new Rect(_e.x,_e.y,_e.width,_e.height)}toJson(){return{x:this.x,y:this.y,width:this.width,height:this.height}}snap(_e){this.x=Math.round(this.x/_e)*_e,this.y=Math.round(this.y/_e)*_e,this.width=Math.round(this.width/_e)*_e,this.height=Math.round(this.height/_e)*_e}static getBoundingClientRect(_e){const{x:tt,y:et,width:nt,height:it}=_e.getBoundingClientRect();return new Rect(tt,et,nt,it)}static getContentRect(_e){const tt=_e.getBoundingClientRect(),et=window.getComputedStyle(_e),nt=parseFloat(et.paddingLeft),it=parseFloat(et.paddingRight),at=parseFloat(et.paddingTop),ot=parseFloat(et.paddingBottom),st=parseFloat(et.borderLeftWidth),ct=parseFloat(et.borderRightWidth),dt=parseFloat(et.borderTopWidth),ut=parseFloat(et.borderBottomWidth),ht=tt.width-st-nt-it-ct,ft=tt.height-dt-at-ot-ut;return new Rect(tt.left+st+nt,tt.top+dt+at,ht,ft)}static fromDomRect(_e){return new Rect(_e.x,_e.y,_e.width,_e.height)}relativeTo(_e){return new Rect(this.x-_e.x,this.y-_e.y,this.width,this.height)}clone(){return new Rect(this.x,this.y,this.width,this.height)}equals(_e){return this.x===(_e==null?void 0:_e.x)&&this.y===(_e==null?void 0:_e.y)&&this.width===(_e==null?void 0:_e.width)&&this.height===(_e==null?void 0:_e.height)}equalSize(_e){return this.width===(_e==null?void 0:_e.width)&&this.height===(_e==null?void 0:_e.height)}getBottom(){return this.y+this.height}getRight(){return this.x+this.width}get bottom(){return this.y+this.height}get right(){return this.x+this.width}getCenter(){return{x:this.x+this.width/2,y:this.y+this.height/2}}positionElement(_e,tt){this.styleWithPosition(_e.style,tt)}styleWithPosition(_e,tt="absolute"){return _e.left=this.x+"px",_e.top=this.y+"px",_e.width=Math.max(0,this.width)+"px",_e.height=Math.max(0,this.height)+"px",_e.position=tt,_e}contains(_e,tt){return this.x<=_e&&_e<=this.getRight()&&this.y<=tt&&tt<=this.getBottom()}removeInsets(_e){return new Rect(this.x+_e.left,this.y+_e.top,Math.max(0,this.width-_e.left-_e.right),Math.max(0,this.height-_e.top-_e.bottom))}centerInRect(_e){this.x=(_e.width-this.width)/2,this.y=(_e.height-this.height)/2}_getSize(_e){let tt=this.width;return _e===Orientation.VERT&&(tt=this.height),tt}toString(){return"(Rect: x="+this.x+", y="+this.y+", width="+this.width+", height="+this.height+")"}}const _DockLocation=class tr{constructor(_e,tt,et){__publicField(this,"name"),__publicField(this,"orientation"),__publicField(this,"indexPlus"),this.name=_e,this.orientation=tt,this.indexPlus=et,tr.values.set(this.name,this)}static getByName(_e){return tr.values.get(_e)}static getLocation(_e,tt,et){if(tt=(tt-_e.x)/_e.width,et=(et-_e.y)/_e.height,tt>=.25&&tt<.75&&et>=.25&&et<.75)return tr.CENTER;const nt=et>=tt,it=et>=1-tt;return nt?it?tr.BOTTOM:tr.LEFT:it?tr.RIGHT:tr.TOP}getName(){return this.name}getOrientation(){return this.orientation}getDockRect(_e){return this===tr.TOP?new Rect(_e.x,_e.y,_e.width,_e.height/2):this===tr.BOTTOM?new Rect(_e.x,_e.getBottom()-_e.height/2,_e.width,_e.height/2):this===tr.LEFT?new Rect(_e.x,_e.y,_e.width/2,_e.height):this===tr.RIGHT?new Rect(_e.getRight()-_e.width/2,_e.y,_e.width/2,_e.height):_e.clone()}split(_e,tt){if(this===tr.TOP){const et=new Rect(_e.x,_e.y,_e.width,tt),nt=new Rect(_e.x,_e.y+tt,_e.width,_e.height-tt);return{start:et,end:nt}}else if(this===tr.LEFT){const et=new Rect(_e.x,_e.y,tt,_e.height),nt=new Rect(_e.x+tt,_e.y,_e.width-tt,_e.height);return{start:et,end:nt}}if(this===tr.RIGHT){const et=new Rect(_e.getRight()-tt,_e.y,tt,_e.height),nt=new Rect(_e.x,_e.y,_e.width-tt,_e.height);return{start:et,end:nt}}else{const et=new Rect(_e.x,_e.getBottom()-tt,_e.width,tt),nt=new Rect(_e.x,_e.y,_e.width,_e.height-tt);return{start:et,end:nt}}}reflect(){return this===tr.TOP?tr.BOTTOM:this===tr.LEFT?tr.RIGHT:this===tr.RIGHT?tr.LEFT:tr.TOP}toString(){return"(DockLocation: name="+this.name+", orientation="+this.orientation+")"}};__publicField(_DockLocation,"values",new Map);__publicField(_DockLocation,"TOP",new _DockLocation("top",Orientation.VERT,0));__publicField(_DockLocation,"BOTTOM",new _DockLocation("bottom",Orientation.VERT,1));__publicField(_DockLocation,"LEFT",new _DockLocation("left",Orientation.HORZ,0));__publicField(_DockLocation,"RIGHT",new _DockLocation("right",Orientation.HORZ,1));__publicField(_DockLocation,"CENTER",new _DockLocation("center",Orientation.VERT,0));let DockLocation=_DockLocation;var I18nLabel=(rt=>(rt.Close_Tab="Close",rt.Close_Tabset="Close tab set",rt.Active_Tabset="Active tab set",rt.Move_Tabset="Move tab set",rt.Move_Tabs="Move tabs(?)",rt.Maximize="Maximize tab set",rt.Restore="Restore tab set",rt.Popout_Tab="Popout selected tab",rt.Overflow_Menu_Tooltip="Hidden tabs",rt.Error_rendering_component="Error rendering component",rt.Error_rendering_component_retry="Retry",rt))(I18nLabel||{}),CLASSES=(rt=>(rt.FLEXLAYOUT__BORDER="flexlayout__border",rt.FLEXLAYOUT__BORDER_="flexlayout__border_",rt.FLEXLAYOUT__BORDER_TAB_CONTENTS="flexlayout__border_tab_contents",rt.FLEXLAYOUT__BORDER_BUTTON="flexlayout__border_button",rt.FLEXLAYOUT__BORDER_BUTTON_="flexlayout__border_button_",rt.FLEXLAYOUT__BORDER_BUTTON_CONTENT="flexlayout__border_button_content",rt.FLEXLAYOUT__BORDER_BUTTON_LEADING="flexlayout__border_button_leading",rt.FLEXLAYOUT__BORDER_BUTTON_TRAILING="flexlayout__border_button_trailing",rt.FLEXLAYOUT__BORDER_BUTTON__SELECTED="flexlayout__border_button--selected",rt.FLEXLAYOUT__BORDER_BUTTON__UNSELECTED="flexlayout__border_button--unselected",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW="flexlayout__border_toolbar_button_overflow",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_="flexlayout__border_toolbar_button_overflow_",rt.FLEXLAYOUT__BORDER_INNER="flexlayout__border_inner",rt.FLEXLAYOUT__BORDER_INNER_="flexlayout__border_inner_",rt.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER="flexlayout__border_inner_tab_container",rt.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_="flexlayout__border_inner_tab_container_",rt.FLEXLAYOUT__BORDER_TAB_DIVIDER="flexlayout__border_tab_divider",rt.FLEXLAYOUT__BORDER_LEADING="flexlayout__border_leading",rt.FLEXLAYOUT__BORDER_SIZER="flexlayout__border_sizer",rt.FLEXLAYOUT__BORDER_TOOLBAR="flexlayout__border_toolbar",rt.FLEXLAYOUT__BORDER_TOOLBAR_="flexlayout__border_toolbar_",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON="flexlayout__border_toolbar_button",rt.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT="flexlayout__border_toolbar_button-float",rt.FLEXLAYOUT__DRAG_RECT="flexlayout__drag_rect",rt.FLEXLAYOUT__EDGE_RECT="flexlayout__edge_rect",rt.FLEXLAYOUT__EDGE_RECT_TOP="flexlayout__edge_rect_top",rt.FLEXLAYOUT__EDGE_RECT_LEFT="flexlayout__edge_rect_left",rt.FLEXLAYOUT__EDGE_RECT_BOTTOM="flexlayout__edge_rect_bottom",rt.FLEXLAYOUT__EDGE_RECT_RIGHT="flexlayout__edge_rect_right",rt.FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER="flexlayout__error_boundary_container",rt.FLEXLAYOUT__ERROR_BOUNDARY_CONTENT="flexlayout__error_boundary_content",rt.FLEXLAYOUT__FLOATING_WINDOW_CONTENT="flexlayout__floating_window_content",rt.FLEXLAYOUT__LAYOUT="flexlayout__layout",rt.FLEXLAYOUT__LAYOUT_MOVEABLES="flexlayout__layout_moveables",rt.FLEXLAYOUT__LAYOUT_OVERLAY="flexlayout__layout_overlay",rt.FLEXLAYOUT__LAYOUT_TAB_STAMPS="flexlayout__layout_tab_stamps",rt.FLEXLAYOUT__LAYOUT_MAIN="flexlayout__layout_main",rt.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER="flexlayout__layout_border_container",rt.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER_INNER="flexlayout__layout_border_container_inner",rt.FLEXLAYOUT__OUTLINE_RECT="flexlayout__outline_rect",rt.FLEXLAYOUT__OUTLINE_RECT_EDGE="flexlayout__outline_rect_edge",rt.FLEXLAYOUT__SPLITTER="flexlayout__splitter",rt.FLEXLAYOUT__SPLITTER_EXTRA="flexlayout__splitter_extra",rt.FLEXLAYOUT__SPLITTER_="flexlayout__splitter_",rt.FLEXLAYOUT__SPLITTER_BORDER="flexlayout__splitter_border",rt.FLEXLAYOUT__SPLITTER_DRAG="flexlayout__splitter_drag",rt.FLEXLAYOUT__SPLITTER_HANDLE="flexlayout__splitter_handle",rt.FLEXLAYOUT__SPLITTER_HANDLE_HORZ="flexlayout__splitter_handle_horz",rt.FLEXLAYOUT__SPLITTER_HANDLE_VERT="flexlayout__splitter_handle_vert",rt.FLEXLAYOUT__ROW="flexlayout__row",rt.FLEXLAYOUT__TAB="flexlayout__tab",rt.FLEXLAYOUT__TAB_POSITION="flexlayout__tab_position",rt.FLEXLAYOUT__TAB_MOVEABLE="flexlayout__tab_moveable",rt.FLEXLAYOUT__TAB_OVERLAY="flexlayout__tab_overlay",rt.FLEXLAYOUT__TABSET="flexlayout__tabset",rt.FLEXLAYOUT__TABSET_CONTAINER="flexlayout__tabset_container",rt.FLEXLAYOUT__TABSET_HEADER="flexlayout__tabset_header",rt.FLEXLAYOUT__TABSET_HEADER_CONTENT="flexlayout__tabset_header_content",rt.FLEXLAYOUT__TABSET_MAXIMIZED="flexlayout__tabset-maximized",rt.FLEXLAYOUT__TABSET_SELECTED="flexlayout__tabset-selected",rt.FLEXLAYOUT__TABSET_TAB_DIVIDER="flexlayout__tabset_tab_divider",rt.FLEXLAYOUT__TABSET_CONTENT="flexlayout__tabset_content",rt.FLEXLAYOUT__TABSET_TABBAR_INNER="flexlayout__tabset_tabbar_inner",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_="flexlayout__tabset_tabbar_inner_",rt.FLEXLAYOUT__TABSET_LEADING="flexlayout__tabset_leading",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER="flexlayout__tabset_tabbar_inner_tab_container",rt.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_="flexlayout__tabset_tabbar_inner_tab_container_",rt.FLEXLAYOUT__TABSET_TABBAR_OUTER="flexlayout__tabset_tabbar_outer",rt.FLEXLAYOUT__TABSET_TABBAR_OUTER_="flexlayout__tabset_tabbar_outer_",rt.FLEXLAYOUT__TAB_BORDER="flexlayout__tab_border",rt.FLEXLAYOUT__TAB_BORDER_="flexlayout__tab_border_",rt.FLEXLAYOUT__TAB_BUTTON="flexlayout__tab_button",rt.FLEXLAYOUT__TAB_BUTTON_STRETCH="flexlayout__tab_button_stretch",rt.FLEXLAYOUT__TAB_BUTTON_CONTENT="flexlayout__tab_button_content",rt.FLEXLAYOUT__TAB_BUTTON_LEADING="flexlayout__tab_button_leading",rt.FLEXLAYOUT__TAB_BUTTON_OVERFLOW="flexlayout__tab_button_overflow",rt.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT="flexlayout__tab_button_overflow_count",rt.FLEXLAYOUT__TAB_BUTTON_TEXTBOX="flexlayout__tab_button_textbox",rt.FLEXLAYOUT__TAB_BUTTON_TRAILING="flexlayout__tab_button_trailing",rt.FLEXLAYOUT__TAB_BUTTON_STAMP="flexlayout__tab_button_stamp",rt.FLEXLAYOUT__TAB_TOOLBAR="flexlayout__tab_toolbar",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON="flexlayout__tab_toolbar_button",rt.FLEXLAYOUT__TAB_TOOLBAR_ICON="flexlayout__tab_toolbar_icon",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_="flexlayout__tab_toolbar_button-",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT="flexlayout__tab_toolbar_button-float",rt.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER="flexlayout__tab_toolbar_sticky_buttons_container",rt.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE="flexlayout__tab_toolbar_button-close",rt.FLEXLAYOUT__POPUP_MENU_CONTAINER="flexlayout__popup_menu_container",rt.FLEXLAYOUT__POPUP_MENU_ITEM="flexlayout__popup_menu_item",rt.FLEXLAYOUT__POPUP_MENU_ITEM__SELECTED="flexlayout__popup_menu_item--selected",rt.FLEXLAYOUT__POPUP_MENU="flexlayout__popup_menu",rt.FLEXLAYOUT__MINI_SCROLLBAR="flexlayout__mini_scrollbar",rt.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER="flexlayout__mini_scrollbar_container",rt))(CLASSES||{});class Action{constructor(_e,tt){__publicField(this,"type"),__publicField(this,"data"),this.type=_e,this.data=tt}}const _Actions=class sr{static addNode(_e,tt,et,nt,it){return new Action(sr.ADD_NODE,{json:_e,toNode:tt,location:et.getName(),index:nt,select:it})}static moveNode(_e,tt,et,nt,it){return new Action(sr.MOVE_NODE,{fromNode:_e,toNode:tt,location:et.getName(),index:nt,select:it})}static deleteTab(_e){return new Action(sr.DELETE_TAB,{node:_e})}static deleteTabset(_e){return new Action(sr.DELETE_TABSET,{node:_e})}static renameTab(_e,tt){return new Action(sr.RENAME_TAB,{node:_e,text:tt})}static selectTab(_e){return new Action(sr.SELECT_TAB,{tabNode:_e})}static setActiveTabset(_e,tt){return new Action(sr.SET_ACTIVE_TABSET,{tabsetNode:_e,windowId:tt})}static adjustWeights(_e,tt){return new Action(sr.ADJUST_WEIGHTS,{nodeId:_e,weights:tt})}static adjustBorderSplit(_e,tt){return new Action(sr.ADJUST_BORDER_SPLIT,{node:_e,pos:tt})}static maximizeToggle(_e,tt){return new Action(sr.MAXIMIZE_TOGGLE,{node:_e,windowId:tt})}static updateModelAttributes(_e){return new Action(sr.UPDATE_MODEL_ATTRIBUTES,{json:_e})}static updateNodeAttributes(_e,tt){return new Action(sr.UPDATE_NODE_ATTRIBUTES,{node:_e,json:tt})}static popoutTab(_e){return new Action(sr.POPOUT_TAB,{node:_e})}static popoutTabset(_e){return new Action(sr.POPOUT_TABSET,{node:_e})}static closeWindow(_e){return new Action(sr.CLOSE_WINDOW,{windowId:_e})}static createWindow(_e,tt){return new Action(sr.CREATE_WINDOW,{layout:_e,rect:tt})}};__publicField(_Actions,"ADD_NODE","FlexLayout_AddNode");__publicField(_Actions,"MOVE_NODE","FlexLayout_MoveNode");__publicField(_Actions,"DELETE_TAB","FlexLayout_DeleteTab");__publicField(_Actions,"DELETE_TABSET","FlexLayout_DeleteTabset");__publicField(_Actions,"RENAME_TAB","FlexLayout_RenameTab");__publicField(_Actions,"SELECT_TAB","FlexLayout_SelectTab");__publicField(_Actions,"SET_ACTIVE_TABSET","FlexLayout_SetActiveTabset");__publicField(_Actions,"ADJUST_WEIGHTS","FlexLayout_AdjustWeights");__publicField(_Actions,"ADJUST_BORDER_SPLIT","FlexLayout_AdjustBorderSplit");__publicField(_Actions,"MAXIMIZE_TOGGLE","FlexLayout_MaximizeToggle");__publicField(_Actions,"UPDATE_MODEL_ATTRIBUTES","FlexLayout_UpdateModelAttributes");__publicField(_Actions,"UPDATE_NODE_ATTRIBUTES","FlexLayout_UpdateNodeAttributes");__publicField(_Actions,"POPOUT_TAB","FlexLayout_PopoutTab");__publicField(_Actions,"POPOUT_TABSET","FlexLayout_PopoutTabset");__publicField(_Actions,"CLOSE_WINDOW","FlexLayout_CloseWindow");__publicField(_Actions,"CREATE_WINDOW","FlexLayout_CreateWindow");let Actions=_Actions;class Attribute{constructor(_e,tt,et,nt){__publicField(this,"name"),__publicField(this,"alias"),__publicField(this,"modelName"),__publicField(this,"pairedAttr"),__publicField(this,"pairedType"),__publicField(this,"defaultValue"),__publicField(this,"alwaysWriteJson"),__publicField(this,"type"),__publicField(this,"required"),__publicField(this,"fixed"),__publicField(this,"description"),this.name=_e,this.alias=void 0,this.modelName=tt,this.defaultValue=et,this.alwaysWriteJson=nt,this.required=!1,this.fixed=!1,this.type="any"}setType(_e){return this.type=_e,this}setAlias(_e){return this.alias=_e,this}setDescription(_e){this.description=_e}setRequired(){return this.required=!0,this}setFixed(){return this.fixed=!0,this}setpairedAttr(_e){this.pairedAttr=_e}setPairedType(_e){this.pairedType=_e}}__publicField(Attribute,"NUMBER","number");__publicField(Attribute,"STRING","string");__publicField(Attribute,"BOOLEAN","boolean");class AttributeDefinitions{constructor(){__publicField(this,"attributes"),__publicField(this,"nameToAttribute"),this.attributes=[],this.nameToAttribute=new Map}addWithAll(_e,tt,et,nt){const it=new Attribute(_e,tt,et,nt);return this.attributes.push(it),this.nameToAttribute.set(_e,it),it}addInherited(_e,tt){return this.addWithAll(_e,tt,void 0,!1)}add(_e,tt,et){return this.addWithAll(_e,void 0,tt,et)}getAttributes(){return this.attributes}getModelName(_e){const tt=this.nameToAttribute.get(_e);if(tt!==void 0)return tt.modelName}toJson(_e,tt){for(const et of this.attributes){const nt=tt[et.name];(et.alwaysWriteJson||nt!==et.defaultValue)&&(_e[et.name]=nt)}}fromJson(_e,tt){for(const et of this.attributes){let nt=_e[et.name];nt===void 0&&et.alias&&(nt=_e[et.alias]),nt===void 0?tt[et.name]=et.defaultValue:tt[et.name]=nt}}update(_e,tt){for(const et of this.attributes)if(Object.prototype.hasOwnProperty.call(_e,et.name)){const nt=_e[et.name];nt===void 0?delete tt[et.name]:tt[et.name]=nt}}setDefaults(_e){for(const tt of this.attributes)_e[tt.name]=tt.defaultValue}pairAttributes(_e,tt){for(const et of tt.attributes)if(et.modelName&&this.nameToAttribute.has(et.modelName)){const nt=this.nameToAttribute.get(et.modelName);nt.setpairedAttr(et),et.setpairedAttr(nt),nt.setPairedType(_e)}}toTypescriptInterface(_e,tt){var et,nt;const it=[],at=this.attributes.sort((ot,st)=>ot.name.localeCompare(st.name));it.push("export interface I"+_e+"Attributes {");for(let ot=0;ot<at.length;ot++){const st=at[ot];let ct=st.type,dt,ut=st,ht;ut.defaultValue!==void 0?dt=ut.defaultValue:ut.modelName!==void 0&&tt!==void 0&&tt.nameToAttribute.get(ut.modelName)!==void 0&&(ht=ut.modelName,ut=tt.nameToAttribute.get(ht),dt=ut.defaultValue,ct=ut.type);const ft=JSON.stringify(dt),pt=ut.required?"":"?";let mt=` /**
|
|
29229
29229
|
`;st.description?mt+=st.description:st.pairedType&&((et=st.pairedAttr)!=null&&et.description)&&(mt+=`Value for ${st.pairedType} attribute ${st.pairedAttr.name} if not overridden`,mt+=`
|
|
29230
29230
|
|
|
29231
29231
|
`,mt+=(nt=st.pairedAttr)==null?void 0:nt.description),mt+=`
|
|
@@ -29235,4 +29235,4 @@ gl_FragColor = baseColor ; }`]]}]}]};Shader.find("plain-color")||Shader._createF
|
|
|
29235
29235
|
`)}return it.push("}"),it.join(`
|
|
29236
29236
|
`)}}class DropInfo{constructor(_e,tt,et,nt,it){__publicField(this,"node"),__publicField(this,"rect"),__publicField(this,"location"),__publicField(this,"index"),__publicField(this,"className"),this.node=_e,this.rect=tt,this.location=et,this.index=nt,this.className=it}}class BorderSet{constructor(_e){__publicField(this,"borders"),__publicField(this,"borderMap"),__publicField(this,"layoutHorizontal"),this.borders=[],this.borderMap=new Map,this.layoutHorizontal=!0}static fromJson(_e,tt){const et=new BorderSet(tt);et.borders=_e.map(nt=>BorderNode.fromJson(nt,tt));for(const nt of et.borders)et.borderMap.set(nt.getLocation(),nt);return et}toJson(){return this.borders.map(_e=>_e.toJson())}getLayoutHorizontal(){return this.layoutHorizontal}getBorders(){return this.borders}getBorderMap(){return this.borderMap}forEachNode(_e){for(const tt of this.borders){_e(tt,0);for(const et of tt.getChildren())et.forEachNode(_e,1)}}setPaths(){for(const _e of this.borders){const tt="/border/"+_e.getLocation().getName();_e.setPath(tt);let et=0;for(const nt of _e.getChildren())nt.setPath(tt+"/t"+et),et++}}findDropTargetNode(_e,tt,et){for(const nt of this.borders)if(nt.isShowing()){const it=nt.canDrop(_e,tt,et);if(it!==void 0)return it}}}let Node$1=class{constructor(_e){__publicField(this,"model"),__publicField(this,"attributes"),__publicField(this,"parent"),__publicField(this,"children"),__publicField(this,"rect"),__publicField(this,"path"),__publicField(this,"listeners"),this.model=_e,this.attributes={},this.children=[],this.rect=Rect.empty(),this.listeners=new Map,this.path=""}getId(){let _e=this.attributes.id;return _e!==void 0||(_e=this.model.nextUniqueId(),this.setId(_e)),_e}getModel(){return this.model}getType(){return this.attributes.type}getParent(){return this.parent}getChildren(){return this.children}getRect(){return this.rect}getPath(){return this.path}getOrientation(){return this.parent===void 0?this.model.isRootOrientationVertical()?Orientation.VERT:Orientation.HORZ:Orientation.flip(this.parent.getOrientation())}setEventListener(_e,tt){this.listeners.set(_e,tt)}removeEventListener(_e){this.listeners.delete(_e)}setId(_e){this.attributes.id=_e}fireEvent(_e,tt){this.listeners.has(_e)&&this.listeners.get(_e)(tt)}getAttr(_e){let tt=this.attributes[_e];if(tt===void 0){const et=this.getAttributeDefinitions().getModelName(_e);et!==void 0&&(tt=this.model.getAttribute(et))}return tt}forEachNode(_e,tt){_e(this,tt),tt++;for(const et of this.children)et.forEachNode(_e,tt)}setPaths(_e){let tt=0;for(const et of this.children){let nt=_e;et.getType()==="row"?nt+="/r"+tt:et.getType()==="tabset"?nt+="/ts"+tt:et.getType()==="tab"&&(nt+="/t"+tt),et.path=nt,et.setPaths(nt),tt++}}setParent(_e){this.parent=_e}setRect(_e){this.rect=_e}setPath(_e){this.path=_e}setWeight(_e){this.attributes.weight=_e}setSelected(_e){this.attributes.selected=_e}findDropTargetNode(_e,tt,et,nt){let it;if(this.rect.contains(et,nt)){if(this.model.getMaximizedTabset(_e)!==void 0)it=this.model.getMaximizedTabset(_e).canDrop(tt,et,nt);else if(it=this.canDrop(tt,et,nt),it===void 0&&this.children.length!==0){for(const at of this.children)if(it=at.findDropTargetNode(_e,tt,et,nt),it!==void 0)break}}return it}canDrop(_e,tt,et){}canDockInto(_e,tt){if(tt!=null){if(tt.location===DockLocation.CENTER&&tt.node.isEnableDrop()===!1||tt.location===DockLocation.CENTER&&_e.getType()==="tabset"&&_e.getName()!==void 0||tt.location!==DockLocation.CENTER&&tt.node.isEnableDivide()===!1)return!1;if(this.model.getOnAllowDrop())return this.model.getOnAllowDrop()(_e,tt)}return!0}removeChild(_e){const tt=this.children.indexOf(_e);return tt!==-1&&this.children.splice(tt,1),tt}addChild(_e,tt){return tt!=null?this.children.splice(tt,0,_e):(this.children.push(_e),tt=this.children.length-1),_e.parent=this,tt}removeAll(){this.children=[]}styleWithPosition(_e){return _e==null&&(_e={}),this.rect.styleWithPosition(_e)}isEnableDivide(){return!0}toAttributeString(){return JSON.stringify(this.attributes,void 0," ")}};const _TabNode=class Vr extends Node$1{constructor(_e,tt,et=!0){super(_e),__publicField(this,"tabRect",Rect.empty()),__publicField(this,"moveableElement"),__publicField(this,"tabStamp"),__publicField(this,"renderedName"),__publicField(this,"extra"),__publicField(this,"visible"),__publicField(this,"rendered"),__publicField(this,"scrollTop"),__publicField(this,"scrollLeft"),this.extra={},this.moveableElement=null,this.tabStamp=null,this.rendered=!1,this.visible=!1,Vr.attributeDefinitions.fromJson(tt,this.attributes),et===!0&&_e.addNode(this)}static fromJson(_e,tt,et=!0){return new Vr(tt,_e,et)}getName(){return this.getAttr("name")}getHelpText(){return this.getAttr("helpText")}getComponent(){return this.getAttr("component")}getWindowId(){return this.parent instanceof TabSetNode?this.parent.getWindowId():Model.MAIN_WINDOW_ID}getWindow(){const _e=this.model.getwindowsMap().get(this.getWindowId());if(_e)return _e.window}getConfig(){return this.attributes.config}getExtraData(){return this.extra}isPoppedOut(){return this.getWindowId()!==Model.MAIN_WINDOW_ID}isSelected(){return this.getParent().getSelectedNode()===this}getIcon(){return this.getAttr("icon")}isEnableClose(){return this.getAttr("enableClose")}getCloseType(){return this.getAttr("closeType")}isEnablePopout(){return this.getAttr("enablePopout")}isEnablePopoutIcon(){return this.getAttr("enablePopoutIcon")}isEnablePopoutOverlay(){return this.getAttr("enablePopoutOverlay")}isEnableDrag(){return this.getAttr("enableDrag")}isEnableRename(){return this.getAttr("enableRename")}isEnableWindowReMount(){return this.getAttr("enableWindowReMount")}getClassName(){return this.getAttr("className")}getContentClassName(){return this.getAttr("contentClassName")}getTabSetClassName(){return this.getAttr("tabsetClassName")}isEnableRenderOnDemand(){return this.getAttr("enableRenderOnDemand")}getMinWidth(){return this.getAttr("minWidth")}getMinHeight(){return this.getAttr("minHeight")}getMaxWidth(){return this.getAttr("maxWidth")}getMaxHeight(){return this.getAttr("maxHeight")}isVisible(){return this.visible}toJson(){const _e={};return Vr.attributeDefinitions.toJson(_e,this.attributes),_e}saveScrollPosition(){this.moveableElement&&(this.scrollLeft=this.moveableElement.scrollLeft,this.scrollTop=this.moveableElement.scrollTop)}restoreScrollPosition(){this.scrollTop&&requestAnimationFrame(()=>{this.moveableElement&&this.scrollTop&&(this.moveableElement.scrollTop=this.scrollTop,this.moveableElement.scrollLeft=this.scrollLeft)})}setRect(_e){_e.equals(this.rect)||(this.fireEvent("resize",{rect:_e}),this.rect=_e)}setVisible(_e){_e!==this.visible&&(this.visible=_e,this.fireEvent("visibility",{visible:_e}))}getScrollTop(){return this.scrollTop}setScrollTop(_e){this.scrollTop=_e}getScrollLeft(){return this.scrollLeft}setScrollLeft(_e){this.scrollLeft=_e}isRendered(){return this.rendered}setRendered(_e){this.rendered=_e}getTabRect(){return this.tabRect}setTabRect(_e){this.tabRect=_e}getTabStamp(){return this.tabStamp}setTabStamp(_e){this.tabStamp=_e}getMoveableElement(){return this.moveableElement}setMoveableElement(_e){this.moveableElement=_e}setRenderedName(_e){this.renderedName=_e}getNameForOverflowMenu(){const _e=this.getAttr("altName");return _e!==void 0?_e:this.renderedName}setName(_e){this.attributes.name=_e}delete(){this.parent.remove(this),this.fireEvent("close",{})}updateAttrs(_e){Vr.attributeDefinitions.update(_e,this.attributes)}getAttributeDefinitions(){return Vr.attributeDefinitions}setBorderWidth(_e){this.attributes.borderWidth=_e}setBorderHeight(_e){this.attributes.borderHeight=_e}static getAttributeDefinitions(){return Vr.attributeDefinitions}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("type",Vr.TYPE,!0).setType(Attribute.STRING).setFixed(),_e.add("id",void 0).setType(Attribute.STRING).setDescription("the unique id of the tab, if left undefined a uuid will be assigned"),_e.add("name","[Unnamed Tab]").setType(Attribute.STRING).setDescription("name of tab to be displayed in the tab button"),_e.add("altName",void 0).setType(Attribute.STRING).setDescription("if there is no name specifed then this value will be used in the overflow menu"),_e.add("helpText",void 0).setType(Attribute.STRING).setDescription("An optional help text for the tab to be displayed upon tab hover."),_e.add("component",void 0).setType(Attribute.STRING).setDescription("string identifying which component to run (for factory)"),_e.add("config",void 0).setType("any").setDescription("a place to hold json config for the hosted component"),_e.add("tabsetClassName",void 0).setType(Attribute.STRING).setDescription("class applied to parent tabset when this is the only tab and it is stretched to fill the tabset"),_e.add("enableWindowReMount",!1).setType(Attribute.BOOLEAN).setDescription("if enabled the tab will re-mount when popped out/in"),_e.addInherited("enableClose","tabEnableClose").setType(Attribute.BOOLEAN).setDescription("allow user to close tab via close button"),_e.addInherited("closeType","tabCloseType").setType("ICloseType").setDescription("see values in ICloseType"),_e.addInherited("enableDrag","tabEnableDrag").setType(Attribute.BOOLEAN).setDescription("allow user to drag tab to new location"),_e.addInherited("enableRename","tabEnableRename").setType(Attribute.BOOLEAN).setDescription("allow user to rename tabs by double clicking"),_e.addInherited("className","tabClassName").setType(Attribute.STRING).setDescription("class applied to tab button"),_e.addInherited("contentClassName","tabContentClassName").setType(Attribute.STRING).setDescription("class applied to tab content"),_e.addInherited("icon","tabIcon").setType(Attribute.STRING).setDescription("the tab icon"),_e.addInherited("enableRenderOnDemand","tabEnableRenderOnDemand").setType(Attribute.BOOLEAN).setDescription("whether to avoid rendering component until tab is visible"),_e.addInherited("enablePopout","tabEnablePopout").setType(Attribute.BOOLEAN).setAlias("enableFloat").setDescription("enable popout (in popout capable browser)"),_e.addInherited("enablePopoutIcon","tabEnablePopoutIcon").setType(Attribute.BOOLEAN).setDescription("whether to show the popout icon in the tabset header if this tab enables popouts"),_e.addInherited("enablePopoutOverlay","tabEnablePopoutOverlay").setType(Attribute.BOOLEAN).setDescription(`if this tab will not work correctly in a popout window when the main window is backgrounded (inactive)
|
|
29237
29237
|
then enabling this option will gray out this tab`),_e.addInherited("borderWidth","tabBorderWidth").setType(Attribute.NUMBER).setDescription("width when added to border, -1 will use border size"),_e.addInherited("borderHeight","tabBorderHeight").setType(Attribute.NUMBER).setDescription("height when added to border, -1 will use border size"),_e.addInherited("minWidth","tabMinWidth").setType(Attribute.NUMBER).setDescription("the min width of this tab"),_e.addInherited("minHeight","tabMinHeight").setType(Attribute.NUMBER).setDescription("the min height of this tab"),_e.addInherited("maxWidth","tabMaxWidth").setType(Attribute.NUMBER).setDescription("the max width of this tab"),_e.addInherited("maxHeight","tabMaxHeight").setType(Attribute.NUMBER).setDescription("the max height of this tab"),_e}};__publicField(_TabNode,"TYPE","tab");__publicField(_TabNode,"attributeDefinitions",_TabNode.createAttributeDefinitions());let TabNode=_TabNode;function isDesktop(){return typeof window<"u"&&window.matchMedia&&window.matchMedia("(hover: hover) and (pointer: fine)").matches}function getRenderStateEx(rt,_e,tt){let et;const nt=_e.getName(),it=_e.getName();tt===void 0&&(tt=0),et===void 0&&_e.getIcon()!==void 0&&(tt!==0?et=jsxRuntimeExports.jsx("img",{style:{width:"1em",height:"1em",transform:"rotate("+tt+"deg)"},src:_e.getIcon(),alt:"leadingContent"}):et=jsxRuntimeExports.jsx("img",{style:{width:"1em",height:"1em"},src:_e.getIcon(),alt:"leadingContent"}));const ot={leading:et,content:nt,name:it,buttons:[]};return rt.customizeTab(_e,ot),_e.setRenderedName(ot.name),ot}function isAuxMouseEvent(rt){let _e=!1;return rt.nativeEvent instanceof MouseEvent&&(rt.nativeEvent.button!==0||rt.ctrlKey||rt.altKey||rt.metaKey||rt.shiftKey)&&(_e=!0),_e}function enablePointerOnIFrames(rt,_e){const tt=[...getElementsByTagName("iframe",_e),...getElementsByTagName("webview",_e)];for(const et of tt)et.style.pointerEvents=rt?"auto":"none"}function getElementsByTagName(rt,_e){return[..._e.getElementsByTagName(rt)]}function startDrag(rt,_e,tt,et,nt){_e.preventDefault();const it=st=>{st.preventDefault(),tt(st.clientX,st.clientY)},at=st=>{st.preventDefault(),nt()},ot=()=>{rt.removeEventListener("pointermove",it),rt.removeEventListener("pointerup",ot),rt.removeEventListener("pointercancel",at),et()};rt.addEventListener("pointermove",it),rt.addEventListener("pointerup",ot),rt.addEventListener("pointercancel",at)}function canDockToWindow(rt){if(rt instanceof TabNode)return rt.isEnablePopout();if(rt instanceof TabSetNode){for(const _e of rt.getChildren())if(_e.isEnablePopout()===!1)return!1;return!0}return!1}function copyInlineStyles(rt,_e){const tt=rt.getAttribute("style"),et=_e.getAttribute("style");return tt===et?!1:(tt?_e.setAttribute("style",tt):_e.removeAttribute("style"),!0)}function isSafari(){const rt=navigator.userAgent;return rt.includes("Safari")&&!rt.includes("Chrome")&&!rt.includes("Chromium")}function adjustSelectedIndex(rt,_e){if(rt!==void 0&&(rt instanceof TabSetNode||rt instanceof BorderNode)){const tt=rt.getSelected();tt!==-1&&(_e===tt&&rt.getChildren().length>0?_e>=rt.getChildren().length&&rt.setSelected(rt.getChildren().length-1):_e<tt?rt.setSelected(tt-1):_e>tt||rt.setSelected(-1))}}function randomUUID(){return("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,rt=>(rt^crypto.getRandomValues(new Uint8Array(1))[0]&15>>rt/4).toString(16))}const _TabSetNode=class Ir extends Node$1{constructor(_e,tt){super(_e),__publicField(this,"tabStripRect",Rect.empty()),__publicField(this,"contentRect",Rect.empty()),__publicField(this,"calculatedMinHeight"),__publicField(this,"calculatedMinWidth"),__publicField(this,"calculatedMaxHeight"),__publicField(this,"calculatedMaxWidth"),this.calculatedMinHeight=0,this.calculatedMinWidth=0,this.calculatedMaxHeight=0,this.calculatedMaxWidth=0,Ir.attributeDefinitions.fromJson(tt,this.attributes),_e.addNode(this)}static fromJson(_e,tt,et){const nt=new Ir(tt,_e);if(_e.children!=null)for(const it of _e.children){const at=TabNode.fromJson(it,tt);nt.addChild(at)}return nt.children.length===0&&nt.setSelected(-1),_e.maximized&&_e.maximized===!0&&(et.maximizedTabSet=nt),_e.active&&_e.active===!0&&(et.activeTabSet=nt),nt}getName(){return this.getAttr("name")}isEnableActiveIcon(){return this.getAttr("enableActiveIcon")}getSelected(){const _e=this.attributes.selected;return _e!==void 0?_e:-1}getSelectedNode(){const _e=this.getSelected();if(_e!==-1)return this.children[_e]}getWeight(){return this.getAttr("weight")}getAttrMinWidth(){return this.getAttr("minWidth")}getAttrMinHeight(){return this.getAttr("minHeight")}getMinWidth(){return this.calculatedMinWidth}getMinHeight(){return this.calculatedMinHeight}getMinSize(_e){return _e===Orientation.HORZ?this.getMinWidth():this.getMinHeight()}getAttrMaxWidth(){return this.getAttr("maxWidth")}getAttrMaxHeight(){return this.getAttr("maxHeight")}getMaxWidth(){return this.calculatedMaxWidth}getMaxHeight(){return this.calculatedMaxHeight}getMaxSize(_e){return _e===Orientation.HORZ?this.getMaxWidth():this.getMaxHeight()}getConfig(){return this.attributes.config}isMaximized(){return this.model.getMaximizedTabset(this.getWindowId())===this}isActive(){return this.model.getActiveTabset(this.getWindowId())===this}isEnableDeleteWhenEmpty(){return this.getAttr("enableDeleteWhenEmpty")}isEnableDrop(){return this.getAttr("enableDrop")}isEnableTabWrap(){return this.getAttr("enableTabWrap")}isEnableDrag(){return this.getAttr("enableDrag")}isEnableDivide(){return this.getAttr("enableDivide")}isEnableMaximize(){return this.getAttr("enableMaximize")}isEnableClose(){return this.getAttr("enableClose")}isEnableSingleTabStretch(){return this.getAttr("enableSingleTabStretch")}isEnableTabStrip(){return this.getAttr("enableTabStrip")}isAutoSelectTab(){return this.getAttr("autoSelectTab")}isEnableTabScrollbar(){return this.getAttr("enableTabScrollbar")}getClassNameTabStrip(){return this.getAttr("classNameTabStrip")}getTabLocation(){return this.getAttr("tabLocation")}toJson(){const _e={};return Ir.attributeDefinitions.toJson(_e,this.attributes),_e.children=this.children.map(tt=>tt.toJson()),this.isActive()&&(_e.active=!0),this.isMaximized()&&(_e.maximized=!0),_e}calcMinMaxSize(){this.calculatedMinHeight=this.getAttrMinHeight(),this.calculatedMinWidth=this.getAttrMinWidth(),this.calculatedMaxHeight=this.getAttrMaxHeight(),this.calculatedMaxWidth=this.getAttrMaxWidth();for(const _e of this.children){const tt=_e;this.calculatedMinWidth=Math.max(this.calculatedMinWidth,tt.getMinWidth()),this.calculatedMinHeight=Math.max(this.calculatedMinHeight,tt.getMinHeight()),this.calculatedMaxWidth=Math.min(this.calculatedMaxWidth,tt.getMaxWidth()),this.calculatedMaxHeight=Math.min(this.calculatedMaxHeight,tt.getMaxHeight())}this.calculatedMinHeight+=this.tabStripRect.height,this.calculatedMaxHeight+=this.tabStripRect.height}canMaximize(){return this.isEnableMaximize()?this.getModel().getMaximizedTabset(this.getWindowId())===this?!0:!(this.getParent()===this.getModel().getRoot(this.getWindowId())&&this.getModel().getRoot(this.getWindowId()).getChildren().length===1):!1}setContentRect(_e){this.contentRect=_e}getContentRect(){return this.contentRect}setTabStripRect(_e){this.tabStripRect=_e}setWeight(_e){this.attributes.weight=_e}setSelected(_e){this.attributes.selected=_e}getWindowId(){return this.parent.getWindowId()}canDrop(_e,tt,et){let nt;if(_e===this){const it=DockLocation.CENTER,at=this.tabStripRect;nt=new DropInfo(this,at,it,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}else{if(this.getWindowId()!==Model.MAIN_WINDOW_ID&&!canDockToWindow(_e))return;if(this.contentRect.contains(tt,et)){let it=DockLocation.CENTER;this.model.getMaximizedTabset(this.parent.getWindowId())===void 0&&(it=DockLocation.getLocation(this.contentRect,tt,et));const at=it.getDockRect(this.rect);nt=new DropInfo(this,at,it,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}else if(this.tabStripRect!=null&&this.tabStripRect.contains(tt,et)){let it,at,ot;if(this.children.length===0)it=this.tabStripRect.clone(),at=it.y+3,ot=it.height-4,it.width=2;else{let st=this.children[0];it=st.getTabRect(),at=it.y,ot=it.height;let ct=this.tabStripRect.x,dt=0;for(let ut=0;ut<this.children.length;ut++){if(st=this.children[ut],it=st.getTabRect(),it.y!==at&&(at=it.y,ct=this.tabStripRect.x),dt=it.x+it.width/2,ct<=tt&&tt<dt&&it.y<et&&et<it.getBottom()){const ht=DockLocation.CENTER,ft=new Rect(it.x-2,it.y,3,it.height);if(this.rect.x<it.x&&it.x<this.rect.getRight()){nt=new DropInfo(this,ft,ht,ut,CLASSES.FLEXLAYOUT__OUTLINE_RECT);break}else return}ct=dt}}if(nt==null&&it.getRight()<this.rect.getRight()){const st=DockLocation.CENTER,ct=new Rect(it.getRight()-2,at,3,ot);nt=new DropInfo(this,ct,st,this.children.length,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}}}if(_e.canDockInto(_e,nt))return nt}delete(){this.parent.removeChild(this)}remove(_e){const tt=this.removeChild(_e);this.model.tidy(),adjustSelectedIndex(this,tt)}drop(_e,tt,et,nt){const it=tt;if(this===_e)return;let at=_e.getParent(),ot=0;if(at!==void 0&&(ot=at.removeChild(_e),at instanceof BorderNode&&at.getSelected()===ot?at.setSelected(-1):adjustSelectedIndex(at,ot)),_e instanceof TabNode&&at===this&&ot<et&&et>0&&et--,it===DockLocation.CENTER){let st=et;if(st===-1&&(st=this.children.length),_e instanceof TabNode)this.addChild(_e,st),(nt||nt!==!1&&this.isAutoSelectTab())&&this.setSelected(st);else if(_e instanceof RowNode)_e.forEachNode((ct,dt)=>{ct instanceof TabNode&&(this.addChild(ct,st),st++)},0);else{for(let ct=0;ct<_e.getChildren().length;ct++){const dt=_e.getChildren()[ct];this.addChild(dt,st),st++}this.getSelected()===-1&&this.children.length>0&&this.setSelected(0)}this.model.setActiveTabset(this,this.parent.getWindowId())}else{let st=_e;if(_e instanceof TabNode){const ut=this.model.getOnCreateTabSet();st=new Ir(this.model,ut?ut(_e):{}),st.addChild(_e),at=st}else if(_e instanceof RowNode){const ut=this.getParent();if(_e.getOrientation()===ut.getOrientation()&&(tt.getOrientation()===ut.getOrientation()||tt===DockLocation.CENTER)){const ht=new RowNode(this.model,this.getWindowId(),{});ht.addChild(_e),st=ht}}else st=_e;const ct=this.parent,dt=ct.getChildren().indexOf(this);if(ct.getOrientation()===it.orientation)st.setWeight(this.getWeight()/2),this.setWeight(this.getWeight()/2),ct.addChild(st,dt+it.indexPlus);else{const ut=new RowNode(this.model,this.getWindowId(),{});ut.setWeight(this.getWeight()),ut.addChild(this),this.setWeight(50),st.setWeight(50),ut.addChild(st,it.indexPlus),ct.removeChild(this),ct.addChild(ut,dt)}st instanceof Ir&&this.model.setActiveTabset(st,this.getWindowId())}this.model.tidy()}updateAttrs(_e){Ir.attributeDefinitions.update(_e,this.attributes)}getAttributeDefinitions(){return Ir.attributeDefinitions}static getAttributeDefinitions(){return Ir.attributeDefinitions}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("type",Ir.TYPE,!0).setType(Attribute.STRING).setFixed(),_e.add("id",void 0).setType(Attribute.STRING).setDescription("the unique id of the tab set, if left undefined a uuid will be assigned"),_e.add("weight",100).setType(Attribute.NUMBER).setDescription("relative weight for sizing of this tabset in parent row"),_e.add("selected",0).setType(Attribute.NUMBER).setDescription("index of selected/visible tab in tabset"),_e.add("name",void 0).setType(Attribute.STRING),_e.add("config",void 0).setType("any").setDescription("a place to hold json config used in your own code"),_e.addInherited("enableDeleteWhenEmpty","tabSetEnableDeleteWhenEmpty").setDescription("whether to delete this tabset when is has no tabs"),_e.addInherited("enableDrop","tabSetEnableDrop").setDescription("allow user to drag tabs into this tabset"),_e.addInherited("enableDrag","tabSetEnableDrag").setDescription("allow user to drag tabs out this tabset"),_e.addInherited("enableDivide","tabSetEnableDivide").setDescription("allow user to drag tabs to region of this tabset, splitting into new tabset"),_e.addInherited("enableMaximize","tabSetEnableMaximize").setDescription("allow user to maximize tabset to fill view via maximize button"),_e.addInherited("enableClose","tabSetEnableClose").setDescription("allow user to close tabset via a close button"),_e.addInherited("enableSingleTabStretch","tabSetEnableSingleTabStretch").setDescription("if the tabset has only a single tab then stretch the single tab to fill area and display in a header style"),_e.addInherited("classNameTabStrip","tabSetClassNameTabStrip").setDescription("a class name to apply to the tab strip"),_e.addInherited("enableTabStrip","tabSetEnableTabStrip").setDescription("enable tab strip and allow multiple tabs in this tabset"),_e.addInherited("minWidth","tabSetMinWidth").setDescription("minimum width (in px) for this tabset"),_e.addInherited("minHeight","tabSetMinHeight").setDescription("minimum height (in px) for this tabset"),_e.addInherited("maxWidth","tabSetMaxWidth").setDescription("maximum width (in px) for this tabset"),_e.addInherited("maxHeight","tabSetMaxHeight").setDescription("maximum height (in px) for this tabset"),_e.addInherited("enableTabWrap","tabSetEnableTabWrap").setDescription("wrap tabs onto multiple lines"),_e.addInherited("tabLocation","tabSetTabLocation").setDescription("the location of the tabs either top or bottom"),_e.addInherited("autoSelectTab","tabSetAutoSelectTab").setType(Attribute.BOOLEAN).setDescription("whether to select new/moved tabs in tabset"),_e.addInherited("enableActiveIcon","tabSetEnableActiveIcon").setType(Attribute.BOOLEAN).setDescription("whether the active icon (*) should be displayed when the tabset is active"),_e.addInherited("enableTabScrollbar","tabSetEnableTabScrollbar").setType(Attribute.BOOLEAN).setDescription("whether to show a mini scrollbar for the tabs"),_e}};__publicField(_TabSetNode,"TYPE","tabset");__publicField(_TabSetNode,"attributeDefinitions",_TabSetNode.createAttributeDefinitions());let TabSetNode=_TabSetNode;const _RowNode=class ar extends Node$1{constructor(_e,tt,et){super(_e),__publicField(this,"windowId"),__publicField(this,"minHeight"),__publicField(this,"minWidth"),__publicField(this,"maxHeight"),__publicField(this,"maxWidth"),this.windowId=tt,this.minHeight=DefaultMin,this.minWidth=DefaultMin,this.maxHeight=DefaultMax,this.maxWidth=DefaultMax,ar.attributeDefinitions.fromJson(et,this.attributes),this.normalizeWeights(),_e.addNode(this)}static fromJson(_e,tt,et){const nt=new ar(tt,et.windowId,_e);if(_e.children!=null)for(const it of _e.children)if(it.type===TabSetNode.TYPE){const at=TabSetNode.fromJson(it,tt,et);nt.addChild(at)}else{const at=ar.fromJson(it,tt,et);nt.addChild(at)}return nt}getWeight(){return this.attributes.weight}toJson(){const _e={};ar.attributeDefinitions.toJson(_e,this.attributes),_e.children=[];for(const tt of this.children)_e.children.push(tt.toJson());return _e}getWindowId(){return this.windowId}setWindowId(_e){this.windowId=_e}setWeight(_e){this.attributes.weight=_e}getSplitterBounds(_e){const tt=this.getOrientation()===Orientation.HORZ,et=this.getChildren(),nt=this.model.getSplitterSize(),it=et[0].getRect(),at=et[et.length-1].getRect();let ot=tt?[it.x,at.getRight()]:[it.y,at.getBottom()];const st=tt?[it.x,at.getRight()]:[it.y,at.getBottom()];for(let ct=0;ct<_e;ct++){const dt=et[ct];ot[0]+=tt?dt.getMinWidth():dt.getMinHeight(),st[0]+=tt?dt.getMaxWidth():dt.getMaxHeight(),ct>0&&(ot[0]+=nt,st[0]+=nt)}for(let ct=et.length-1;ct>=_e;ct--){const dt=et[ct];ot[1]-=(tt?dt.getMinWidth():dt.getMinHeight())+nt,st[1]-=(tt?dt.getMaxWidth():dt.getMaxHeight())+nt}return ot=[Math.max(st[1],ot[0]),Math.min(st[0],ot[1])],ot}getSplitterInitials(_e){const tt=this.getOrientation()===Orientation.HORZ,et=this.getChildren(),nt=this.model.getSplitterSize(),it=[];let at=0;for(let ct=0;ct<et.length;ct++){const ut=et[ct].getRect(),ht=tt?ut.width:ut.height;it.push(ht),at+=ht}const ot=et[_e].getRect(),st=(tt?ot.x:ot.y)-nt;return{initialSizes:it,sum:at,startPosition:st}}calculateSplit(_e,tt,et,nt,it){const at=this.getOrientation()===Orientation.HORZ,ot=this.getChildren(),st=ot[_e],ct=at?st.getMaxWidth():st.getMaxHeight(),dt=[...et];if(tt<it){let ht=it-tt,ft=0;dt[_e]+ht>ct?(ft=dt[_e]+ht-ct,dt[_e]=ct):dt[_e]+=ht;for(let pt=_e-1;pt>=0;pt--){const mt=ot[pt],vt=at?mt.getMinWidth():mt.getMinHeight();if(dt[pt]-ht>vt){dt[pt]-=ht;break}else ht-=dt[pt]-vt,dt[pt]=vt}for(let pt=_e+1;pt<ot.length;pt++){const mt=ot[pt],vt=at?mt.getMaxWidth():mt.getMaxHeight();if(dt[pt]+ft<vt){dt[pt]+=ft;break}else ft-=vt-dt[pt],dt[pt]=vt}}else{let ht=tt-it,ft=0;dt[_e-1]+ht>ct?(ft=dt[_e-1]+ht-ct,dt[_e-1]=ct):dt[_e-1]+=ht;for(let pt=_e;pt<ot.length;pt++){const mt=ot[pt],vt=at?mt.getMinWidth():mt.getMinHeight();if(dt[pt]-ht>vt){dt[pt]-=ht;break}else ht-=dt[pt]-vt,dt[pt]=vt}for(let pt=_e-1;pt>=0;pt--){const mt=ot[pt],vt=at?mt.getMaxWidth():mt.getMaxHeight();if(dt[pt]+ft<vt){dt[pt]+=ft;break}else ft-=vt-dt[pt],dt[pt]=vt}}return dt.map(ht=>Math.max(.1,ht)*100/nt)}getMinSize(_e){return _e===Orientation.HORZ?this.getMinWidth():this.getMinHeight()}getMinWidth(){return this.minWidth}getMinHeight(){return this.minHeight}getMaxSize(_e){return _e===Orientation.HORZ?this.getMaxWidth():this.getMaxHeight()}getMaxWidth(){return this.maxWidth}getMaxHeight(){return this.maxHeight}calcMinMaxSize(){this.minHeight=DefaultMin,this.minWidth=DefaultMin,this.maxHeight=DefaultMax,this.maxWidth=DefaultMax;let _e=!0;for(const tt of this.children){const et=tt;et.calcMinMaxSize(),this.getOrientation()===Orientation.VERT?(this.minHeight+=et.getMinHeight(),this.maxHeight+=et.getMaxHeight(),_e||(this.minHeight+=this.model.getSplitterSize(),this.maxHeight+=this.model.getSplitterSize()),this.minWidth=Math.max(this.minWidth,et.getMinWidth()),this.maxWidth=Math.min(this.maxWidth,et.getMaxWidth())):(this.minWidth+=et.getMinWidth(),this.maxWidth+=et.getMaxWidth(),_e||(this.minWidth+=this.model.getSplitterSize(),this.maxWidth+=this.model.getSplitterSize()),this.minHeight=Math.max(this.minHeight,et.getMinHeight()),this.maxHeight=Math.min(this.maxHeight,et.getMaxHeight())),_e=!1}}tidy(){let _e=0;for(;_e<this.children.length;){const tt=this.children[_e];if(tt instanceof ar){tt.tidy();const et=tt.getChildren();if(et.length===0)this.removeChild(tt);else if(et.length===1){const nt=et[0];if(this.removeChild(tt),nt instanceof ar){let it=0;const at=nt.getChildren();for(const ot of at)it+=ot.getWeight();for(let ot=0;ot<at.length;ot++){const st=at[ot];st.setWeight(tt.getWeight()*st.getWeight()/it),this.addChild(st,_e+ot)}}else nt.setWeight(tt.getWeight()),this.addChild(nt,_e)}else _e++}else tt instanceof TabSetNode&&tt.getChildren().length===0&&tt.isEnableDeleteWhenEmpty()?(this.removeChild(tt),tt===this.model.getMaximizedTabset(this.windowId)&&this.model.setMaximizedTabset(void 0,this.windowId)):_e++}if(this===this.model.getRoot(this.windowId)&&this.children.length===0){const tt=this.model.getOnCreateTabSet();let et=tt?tt():{};et={...et,selected:-1};const nt=new TabSetNode(this.model,et);this.model.setActiveTabset(nt,this.windowId),this.addChild(nt)}}canDrop(_e,tt,et){const nt=et-this.rect.y,it=tt-this.rect.x,at=this.rect.width,ot=this.rect.height,st=10,ct=50;let dt;if(!(this.getWindowId()!==Model.MAIN_WINDOW_ID&&!canDockToWindow(_e))){if(this.model.isEnableEdgeDock()&&this.parent===void 0){if(tt<this.rect.x+st&&nt>ot/2-ct&&nt<ot/2+ct){const ut=DockLocation.LEFT,ht=ut.getDockRect(this.rect);ht.width=ht.width/2,dt=new DropInfo(this,ht,ut,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE)}else if(tt>this.rect.getRight()-st&&nt>ot/2-ct&&nt<ot/2+ct){const ut=DockLocation.RIGHT,ht=ut.getDockRect(this.rect);ht.width=ht.width/2,ht.x+=ht.width,dt=new DropInfo(this,ht,ut,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE)}else if(et<this.rect.y+st&&it>at/2-ct&&it<at/2+ct){const ut=DockLocation.TOP,ht=ut.getDockRect(this.rect);ht.height=ht.height/2,dt=new DropInfo(this,ht,ut,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE)}else if(et>this.rect.getBottom()-st&&it>at/2-ct&&it<at/2+ct){const ut=DockLocation.BOTTOM,ht=ut.getDockRect(this.rect);ht.height=ht.height/2,ht.y+=ht.height,dt=new DropInfo(this,ht,ut,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT_EDGE)}if(dt!==void 0&&!_e.canDockInto(_e,dt))return}return dt}}drop(_e,tt,et){const nt=tt,it=_e.getParent();it&&it.removeChild(_e),it!==void 0&&it instanceof TabSetNode&&it.setSelected(0),it!==void 0&&it instanceof BorderNode&&it.setSelected(-1);let at;if(_e instanceof TabSetNode||_e instanceof ar)at=_e,at instanceof ar&&at.getOrientation()===this.getOrientation()&&(tt.getOrientation()===this.getOrientation()||tt===DockLocation.CENTER)&&(at=new ar(this.model,this.windowId,{}),at.addChild(_e));else{const ct=this.model.getOnCreateTabSet();at=new TabSetNode(this.model,ct?ct(_e):{}),at.addChild(_e)}let ot=this.children.reduce((ct,dt)=>ct+dt.getWeight(),0);ot===0&&(ot=100),at.setWeight(ot/3);const st=!this.model.isRootOrientationVertical();if(nt===DockLocation.CENTER)et===-1?this.addChild(at,this.children.length):this.addChild(at,et);else if(st&&nt===DockLocation.LEFT||!st&&nt===DockLocation.TOP)this.addChild(at,0);else if(st&&nt===DockLocation.RIGHT||!st&&nt===DockLocation.BOTTOM)this.addChild(at);else if(st&&nt===DockLocation.TOP||!st&&nt===DockLocation.LEFT){const ct=new ar(this.model,this.windowId,{}),dt=new ar(this.model,this.windowId,{});dt.setWeight(75),at.setWeight(25);for(const ut of this.children)dt.addChild(ut);this.removeAll(),ct.addChild(at),ct.addChild(dt),this.addChild(ct)}else if(st&&nt===DockLocation.BOTTOM||!st&&nt===DockLocation.RIGHT){const ct=new ar(this.model,this.windowId,{}),dt=new ar(this.model,this.windowId,{});dt.setWeight(75),at.setWeight(25);for(const ut of this.children)dt.addChild(ut);this.removeAll(),ct.addChild(dt),ct.addChild(at),this.addChild(ct)}at instanceof TabSetNode&&this.model.setActiveTabset(at,this.windowId),this.model.tidy()}isEnableDrop(){return!0}getAttributeDefinitions(){return ar.attributeDefinitions}updateAttrs(_e){ar.attributeDefinitions.update(_e,this.attributes)}static getAttributeDefinitions(){return ar.attributeDefinitions}normalizeWeights(){let _e=0;for(const tt of this.children)_e+=tt.getWeight();_e===0&&(_e=1);for(const tt of this.children){const et=tt;et.setWeight(Math.max(.001,100*et.getWeight()/_e))}}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("type",ar.TYPE,!0).setType(Attribute.STRING).setFixed(),_e.add("id",void 0).setType(Attribute.STRING).setDescription("the unique id of the row, if left undefined a uuid will be assigned"),_e.add("weight",100).setType(Attribute.NUMBER).setDescription("relative weight for sizing of this row in parent row"),_e}};__publicField(_RowNode,"TYPE","row");__publicField(_RowNode,"attributeDefinitions",_RowNode.createAttributeDefinitions());let RowNode=_RowNode;class LayoutWindow{constructor(_e,tt){__publicField(this,"_windowId"),__publicField(this,"_layout"),__publicField(this,"_rect"),__publicField(this,"_window"),__publicField(this,"_root"),__publicField(this,"_maximizedTabSet"),__publicField(this,"_activeTabSet"),__publicField(this,"_toScreenRectFunction"),this._windowId=_e,this._rect=tt,this._toScreenRectFunction=et=>et}visitNodes(_e){this.root.forEachNode(_e,0)}get windowId(){return this._windowId}get rect(){return this._rect}get layout(){return this._layout}get window(){return this._window}get root(){return this._root}get maximizedTabSet(){return this._maximizedTabSet}get activeTabSet(){return this._activeTabSet}set rect(_e){this._rect=_e}set layout(_e){this._layout=_e}set window(_e){this._window=_e}set root(_e){this._root=_e}set maximizedTabSet(_e){this._maximizedTabSet=_e}set activeTabSet(_e){this._activeTabSet=_e}get toScreenRectFunction(){return this._toScreenRectFunction}set toScreenRectFunction(_e){this._toScreenRectFunction=_e}toJson(){return this._window&&this._window.screenTop>-1e4&&(this.rect=new Rect(this._window.screenLeft,this._window.screenTop,this._window.outerWidth,this._window.outerHeight)),{layout:this.root.toJson(),rect:this.rect.toJson()}}static fromJson(_e,tt,et){const nt=tt.getwindowsMap().size,it=_e.rect?Rect.fromJson(_e.rect):new Rect(50+50*nt,50+50*nt,600,400);it.snap(10);const at=new LayoutWindow(et,it);return at.root=RowNode.fromJson(_e.layout,tt,at),at}}const DefaultMin=0,DefaultMax=99999,_Model=class Kn{constructor(){__publicField(this,"attributes"),__publicField(this,"idMap"),__publicField(this,"changeListeners"),__publicField(this,"borders"),__publicField(this,"onAllowDrop"),__publicField(this,"onCreateTabSet"),__publicField(this,"windows"),__publicField(this,"rootWindow"),this.attributes={},this.idMap=new Map,this.borders=new BorderSet(this),this.windows=new Map,this.rootWindow=new LayoutWindow(Kn.MAIN_WINDOW_ID,Rect.empty()),this.windows.set(Kn.MAIN_WINDOW_ID,this.rootWindow),this.changeListeners=[]}doAction(_e){var tt;let et;switch(_e.type){case Actions.ADD_NODE:{const nt=new TabNode(this,_e.data.json,!0),it=this.idMap.get(_e.data.toNode);(it instanceof TabSetNode||it instanceof BorderNode||it instanceof RowNode)&&(it.drop(nt,DockLocation.getByName(_e.data.location),_e.data.index,_e.data.select),et=nt);break}case Actions.MOVE_NODE:{const nt=this.idMap.get(_e.data.fromNode);if(nt instanceof TabNode||nt instanceof TabSetNode||nt instanceof RowNode){if(nt===this.getMaximizedTabset(nt.getWindowId())){const at=this.windows.get(nt.getWindowId());at.maximizedTabSet=void 0}const it=this.idMap.get(_e.data.toNode);(it instanceof TabSetNode||it instanceof BorderNode||it instanceof RowNode)&&it.drop(nt,DockLocation.getByName(_e.data.location),_e.data.index,_e.data.select)}this.removeEmptyWindows();break}case Actions.DELETE_TAB:{const nt=this.idMap.get(_e.data.node);nt instanceof TabNode&&nt.delete(),this.removeEmptyWindows();break}case Actions.DELETE_TABSET:{const nt=this.idMap.get(_e.data.node);if(nt instanceof TabSetNode){const it=[...nt.getChildren()];for(let at=0;at<it.length;at++){const ot=it[at];ot.isEnableClose()&&ot.delete()}nt.getChildren().length===0&&nt.delete(),this.tidy()}this.removeEmptyWindows();break}case Actions.POPOUT_TABSET:{const nt=this.idMap.get(_e.data.node);if(nt instanceof TabSetNode){const it=nt.isMaximized(),at=this.windows.get(nt.getWindowId()),ot=randomUUID(),st=new LayoutWindow(ot,at.toScreenRectFunction(nt.getRect())),ct={type:"row",children:[]},dt=RowNode.fromJson(ct,this,st);st.root=dt,this.windows.set(ot,st),dt.drop(nt,DockLocation.CENTER,0),it&&(this.rootWindow.maximizedTabSet=void 0)}this.removeEmptyWindows();break}case Actions.POPOUT_TAB:{const nt=this.idMap.get(_e.data.node);if(nt instanceof TabNode){const it=randomUUID();let at=Rect.empty();nt.getParent()instanceof TabSetNode?at=nt.getParent().getRect():at=nt.getParent().getContentRect();const ot=this.windows.get(nt.getWindowId()),st=new LayoutWindow(it,ot.toScreenRectFunction(at)),ct=randomUUID(),dt={type:"row",children:[{type:"tabset",id:ct}]},ut=RowNode.fromJson(dt,this,st);st.root=ut,this.windows.set(it,st),this.idMap.get(ct).drop(nt,DockLocation.CENTER,0,!0)}this.removeEmptyWindows();break}case Actions.CLOSE_WINDOW:{const nt=this.windows.get(_e.data.windowId);nt&&((tt=this.rootWindow.root)==null||tt.drop(nt.root,DockLocation.CENTER,-1),this.rootWindow.visitNodes((it,at)=>{it instanceof RowNode&&it.setWindowId(Kn.MAIN_WINDOW_ID)}),this.windows.delete(_e.data.windowId));break}case Actions.CREATE_WINDOW:{const nt=randomUUID(),it=new LayoutWindow(nt,Rect.fromJson(_e.data.rect)),at=RowNode.fromJson(_e.data.layout,this,it);it.root=at,this.windows.set(nt,it),et=nt;break}case Actions.RENAME_TAB:{const nt=this.idMap.get(_e.data.node);nt instanceof TabNode&&nt.setName(_e.data.text);break}case Actions.SELECT_TAB:{const nt=this.idMap.get(_e.data.tabNode),it=_e.data.windowId?_e.data.windowId:Kn.MAIN_WINDOW_ID,at=this.windows.get(it);if(nt instanceof TabNode){const ot=nt.getParent(),st=ot.getChildren().indexOf(nt);ot instanceof BorderNode?ot.getSelected()===st?ot.setSelected(-1):ot.setSelected(st):ot instanceof TabSetNode&&(ot.getSelected()!==st&&ot.setSelected(st),at.activeTabSet=ot)}break}case Actions.SET_ACTIVE_TABSET:{const nt=_e.data.windowId?_e.data.windowId:Kn.MAIN_WINDOW_ID,it=this.windows.get(nt);if(_e.data.tabsetNode===void 0)it.activeTabSet=void 0;else{const at=this.idMap.get(_e.data.tabsetNode);at instanceof TabSetNode&&(it.activeTabSet=at)}break}case Actions.ADJUST_WEIGHTS:{const it=this.idMap.get(_e.data.nodeId).getChildren();for(let at=0;at<it.length;at++)it[at].setWeight(_e.data.weights[at]);break}case Actions.ADJUST_BORDER_SPLIT:{const nt=this.idMap.get(_e.data.node);nt instanceof BorderNode&&nt.setSize(_e.data.pos);break}case Actions.MAXIMIZE_TOGGLE:{const nt=_e.data.windowId?_e.data.windowId:Kn.MAIN_WINDOW_ID,it=this.windows.get(nt),at=this.idMap.get(_e.data.node);at instanceof TabSetNode&&(at===it.maximizedTabSet?it.maximizedTabSet=void 0:(it.maximizedTabSet=at,it.activeTabSet=at));break}case Actions.UPDATE_MODEL_ATTRIBUTES:{this.updateAttrs(_e.data.json);break}case Actions.UPDATE_NODE_ATTRIBUTES:{this.idMap.get(_e.data.node).updateAttrs(_e.data.json);break}}this.updateIdMap();for(const nt of this.changeListeners)nt(_e);return et}getActiveTabset(_e=Kn.MAIN_WINDOW_ID){const tt=this.windows.get(_e);if(tt&&tt.activeTabSet&&this.getNodeById(tt.activeTabSet.getId()))return tt.activeTabSet}getMaximizedTabset(_e=Kn.MAIN_WINDOW_ID){return this.windows.get(_e).maximizedTabSet}getRoot(_e=Kn.MAIN_WINDOW_ID){return this.windows.get(_e).root}isRootOrientationVertical(){return this.attributes.rootOrientationVertical}isEnableRotateBorderIcons(){return this.attributes.enableRotateBorderIcons}getBorderSet(){return this.borders}getwindowsMap(){return this.windows}visitNodes(_e){this.borders.forEachNode(_e);for(const[tt,et]of this.windows)et.root.forEachNode(_e,0)}visitWindowNodes(_e,tt){this.windows.has(_e)&&(_e===Kn.MAIN_WINDOW_ID&&this.borders.forEachNode(tt),this.windows.get(_e).visitNodes(tt))}getNodeById(_e){return this.idMap.get(_e)}getFirstTabSet(_e=this.windows.get(Kn.MAIN_WINDOW_ID).root){const tt=_e.getChildren()[0];return tt instanceof TabSetNode?tt:this.getFirstTabSet(tt)}static fromJson(_e){const tt=new Kn;if(Kn.attributeDefinitions.fromJson(_e.global,tt.attributes),_e.borders&&(tt.borders=BorderSet.fromJson(_e.borders,tt)),_e.popouts)for(const et in _e.popouts){const nt=_e.popouts[et],it=LayoutWindow.fromJson(nt,tt,et);tt.windows.set(et,it)}return tt.rootWindow.root=RowNode.fromJson(_e.layout,tt,tt.getwindowsMap().get(Kn.MAIN_WINDOW_ID)),tt.tidy(),tt}toJson(){const _e={};Kn.attributeDefinitions.toJson(_e,this.attributes),this.visitNodes(et=>{et.fireEvent("save",{})});const tt={};for(const[et,nt]of this.windows)et!==Kn.MAIN_WINDOW_ID&&(tt[et]=nt.toJson());return{global:_e,borders:this.borders.toJson(),layout:this.rootWindow.root.toJson(),popouts:tt}}getSplitterSize(){return this.attributes.splitterSize}getSplitterExtra(){return this.attributes.splitterExtra}isEnableEdgeDock(){return this.attributes.enableEdgeDock}isSplitterEnableHandle(){return this.attributes.splitterEnableHandle}setOnAllowDrop(_e){this.onAllowDrop=_e}setOnCreateTabSet(_e){this.onCreateTabSet=_e}addChangeListener(_e){this.changeListeners.push(_e)}removeChangeListener(_e){const tt=this.changeListeners.findIndex(et=>et===_e);tt!==-1&&this.changeListeners.splice(tt,1)}toString(){return JSON.stringify(this.toJson())}removeEmptyWindows(){const _e=new Set;for(const[tt]of this.windows)if(tt!==Kn.MAIN_WINDOW_ID){let et=0;this.visitWindowNodes(tt,nt=>{nt instanceof TabNode&&et++}),et===0&&_e.add(tt)}for(const tt of _e)this.windows.delete(tt)}setActiveTabset(_e,tt){const et=this.windows.get(tt);et&&(_e?et.activeTabSet=_e:et.activeTabSet=void 0)}setMaximizedTabset(_e,tt){const et=this.windows.get(tt);et&&(_e?et.maximizedTabSet=_e:et.maximizedTabSet=void 0)}updateIdMap(){this.idMap.clear(),this.visitNodes(_e=>{this.idMap.set(_e.getId(),_e)})}addNode(_e){const tt=_e.getId();if(this.idMap.has(tt))throw new Error(`Error: each node must have a unique id, duplicate id:${_e.getId()}`);this.idMap.set(tt,_e)}findDropTargetNode(_e,tt,et,nt){let it=this.windows.get(_e).root.findDropTargetNode(_e,tt,et,nt);return it===void 0&&_e===Kn.MAIN_WINDOW_ID&&(it=this.borders.findDropTargetNode(tt,et,nt)),it}tidy(){for(const[_e,tt]of this.windows)tt.root.tidy()}updateAttrs(_e){Kn.attributeDefinitions.update(_e,this.attributes)}nextUniqueId(){return"#"+randomUUID()}getAttribute(_e){return this.attributes[_e]}getOnAllowDrop(){return this.onAllowDrop}getOnCreateTabSet(){return this.onCreateTabSet}static toTypescriptInterfaces(){Kn.attributeDefinitions.pairAttributes("RowNode",RowNode.getAttributeDefinitions()),Kn.attributeDefinitions.pairAttributes("TabSetNode",TabSetNode.getAttributeDefinitions()),Kn.attributeDefinitions.pairAttributes("TabNode",TabNode.getAttributeDefinitions()),Kn.attributeDefinitions.pairAttributes("BorderNode",BorderNode.getAttributeDefinitions());const _e=[];_e.push(Kn.attributeDefinitions.toTypescriptInterface("Global",void 0)),_e.push(RowNode.getAttributeDefinitions().toTypescriptInterface("Row",Kn.attributeDefinitions)),_e.push(TabSetNode.getAttributeDefinitions().toTypescriptInterface("TabSet",Kn.attributeDefinitions)),_e.push(TabNode.getAttributeDefinitions().toTypescriptInterface("Tab",Kn.attributeDefinitions)),_e.push(BorderNode.getAttributeDefinitions().toTypescriptInterface("Border",Kn.attributeDefinitions)),console.log(_e.join(`
|
|
29238
|
-
`))}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("enableEdgeDock",!0).setType(Attribute.BOOLEAN).setDescription("enable docking to the edges of the layout, this will show the edge indicators"),_e.add("rootOrientationVertical",!1).setType(Attribute.BOOLEAN).setDescription("the top level 'row' will layout horizontally by default, set this option true to make it layout vertically"),_e.add("enableRotateBorderIcons",!0).setType(Attribute.BOOLEAN).setDescription("boolean indicating if tab icons should rotate with the text in the left and right borders"),_e.add("splitterSize",8).setType(Attribute.NUMBER).setDescription("width in pixels of all splitters between tabsets/borders"),_e.add("splitterExtra",0).setType(Attribute.NUMBER).setDescription("additional width in pixels of the splitter hit test area"),_e.add("splitterEnableHandle",!1).setType(Attribute.BOOLEAN).setDescription("enable a small centralized handle on all splitters"),_e.add("tabEnableClose",!0).setType(Attribute.BOOLEAN),_e.add("tabCloseType",1).setType("ICloseType"),_e.add("tabEnablePopout",!1).setType(Attribute.BOOLEAN).setAlias("tabEnableFloat"),_e.add("tabEnablePopoutIcon",!0).setType(Attribute.BOOLEAN),_e.add("tabEnablePopoutOverlay",!1).setType(Attribute.BOOLEAN),_e.add("tabEnableDrag",!0).setType(Attribute.BOOLEAN),_e.add("tabEnableRename",!0).setType(Attribute.BOOLEAN),_e.add("tabContentClassName",void 0).setType(Attribute.STRING),_e.add("tabClassName",void 0).setType(Attribute.STRING),_e.add("tabIcon",void 0).setType(Attribute.STRING),_e.add("tabEnableRenderOnDemand",!0).setType(Attribute.BOOLEAN),_e.add("tabDragSpeed",.3).setType(Attribute.NUMBER),_e.add("tabBorderWidth",-1).setType(Attribute.NUMBER),_e.add("tabBorderHeight",-1).setType(Attribute.NUMBER),_e.add("tabSetEnableDeleteWhenEmpty",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDrop",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDrag",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDivide",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableMaximize",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableClose",!1).setType(Attribute.BOOLEAN),_e.add("tabSetEnableSingleTabStretch",!1).setType(Attribute.BOOLEAN),_e.add("tabSetAutoSelectTab",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableActiveIcon",!1).setType(Attribute.BOOLEAN),_e.add("tabSetClassNameTabStrip",void 0).setType(Attribute.STRING),_e.add("tabSetEnableTabStrip",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableTabWrap",!1).setType(Attribute.BOOLEAN),_e.add("tabSetTabLocation","top").setType("ITabLocation"),_e.add("tabMinWidth",DefaultMin).setType(Attribute.NUMBER),_e.add("tabMinHeight",DefaultMin).setType(Attribute.NUMBER),_e.add("tabSetMinWidth",DefaultMin).setType(Attribute.NUMBER),_e.add("tabSetMinHeight",DefaultMin).setType(Attribute.NUMBER),_e.add("tabMaxWidth",DefaultMax).setType(Attribute.NUMBER),_e.add("tabMaxHeight",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetMaxWidth",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetMaxHeight",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetEnableTabScrollbar",!1).setType(Attribute.BOOLEAN),_e.add("borderSize",200).setType(Attribute.NUMBER),_e.add("borderMinSize",DefaultMin).setType(Attribute.NUMBER),_e.add("borderMaxSize",DefaultMax).setType(Attribute.NUMBER),_e.add("borderEnableDrop",!0).setType(Attribute.BOOLEAN),_e.add("borderAutoSelectTabWhenOpen",!0).setType(Attribute.BOOLEAN),_e.add("borderAutoSelectTabWhenClosed",!1).setType(Attribute.BOOLEAN),_e.add("borderClassName",void 0).setType(Attribute.STRING),_e.add("borderEnableAutoHide",!1).setType(Attribute.BOOLEAN),_e.add("borderEnableTabScrollbar",!1).setType(Attribute.BOOLEAN),_e}};__publicField(_Model,"MAIN_WINDOW_ID","__main_window_id__");__publicField(_Model,"attributeDefinitions",_Model.createAttributeDefinitions());let Model=_Model;const _BorderNode=class Dr extends Node$1{constructor(_e,tt,et){super(et),__publicField(this,"contentRect",Rect.empty()),__publicField(this,"tabHeaderRect",Rect.empty()),__publicField(this,"location"),this.location=_e,this.attributes.id=`border_${_e.getName()}`,Dr.attributeDefinitions.fromJson(tt,this.attributes),et.addNode(this)}static fromJson(_e,tt){const et=DockLocation.getByName(_e.location),nt=new Dr(et,_e,tt);return _e.children&&(nt.children=_e.children.map(it=>{const at=TabNode.fromJson(it,tt);return at.setParent(nt),at})),nt}getLocation(){return this.location}getClassName(){return this.getAttr("className")}isHorizontal(){return this.location.orientation===Orientation.HORZ}getSize(){const _e=this.getAttr("size"),tt=this.getSelected();if(tt===-1)return _e;{const et=this.children[tt],nt=this.isHorizontal()?et.getAttr("borderWidth"):et.getAttr("borderHeight");return nt===-1?_e:nt}}getMinSize(){const _e=this.getSelectedNode();let tt=this.getAttr("minSize");if(_e){const et=this.isHorizontal()?_e.getMinWidth():_e.getMinHeight();tt=Math.max(tt,et)}return tt}getMaxSize(){const _e=this.getSelectedNode();let tt=this.getAttr("maxSize");if(_e){const et=this.isHorizontal()?_e.getMaxWidth():_e.getMaxHeight();tt=Math.min(tt,et)}return tt}getSelected(){return this.attributes.selected}isAutoHide(){return this.getAttr("enableAutoHide")}getSelectedNode(){if(this.getSelected()!==-1)return this.children[this.getSelected()]}getOrientation(){return this.location.getOrientation()}getConfig(){return this.attributes.config}isMaximized(){return!1}isShowing(){return this.attributes.show}toJson(){const _e={};return Dr.attributeDefinitions.toJson(_e,this.attributes),_e.location=this.location.getName(),_e.children=this.children.map(tt=>tt.toJson()),_e}isAutoSelectTab(_e){return _e==null&&(_e=this.getSelected()!==-1),_e?this.getAttr("autoSelectTabWhenOpen"):this.getAttr("autoSelectTabWhenClosed")}isEnableTabScrollbar(){return this.getAttr("enableTabScrollbar")}setSelected(_e){this.attributes.selected=_e}getTabHeaderRect(){return this.tabHeaderRect}setTabHeaderRect(_e){this.tabHeaderRect=_e}getRect(){return this.tabHeaderRect}getContentRect(){return this.contentRect}setContentRect(_e){this.contentRect=_e}isEnableDrop(){return this.getAttr("enableDrop")}setSize(_e){const tt=this.getSelected();if(tt===-1)this.attributes.size=_e;else{const et=this.children[tt];(this.isHorizontal()?et.getAttr("borderWidth"):et.getAttr("borderHeight"))===-1?this.attributes.size=_e:this.isHorizontal()?et.setBorderWidth(_e):et.setBorderHeight(_e)}}updateAttrs(_e){Dr.attributeDefinitions.update(_e,this.attributes)}remove(_e){const tt=this.removeChild(_e);this.getSelected()!==-1&&adjustSelectedIndex(this,tt)}canDrop(_e,tt,et){if(!(_e instanceof TabNode))return;let nt;const it=DockLocation.CENTER;if(this.tabHeaderRect.contains(tt,et)){if(this.location.orientation===Orientation.VERT)if(this.children.length>0){let at=this.children[0],ot=at.getTabRect();const st=ot.y,ct=ot.height;let dt=this.tabHeaderRect.x,ut=0;for(let ht=0;ht<this.children.length;ht++){if(at=this.children[ht],ot=at.getTabRect(),ut=ot.x+ot.width/2,tt>=dt&&tt<ut){const ft=new Rect(ot.x-2,st,3,ct);nt=new DropInfo(this,ft,it,ht,CLASSES.FLEXLAYOUT__OUTLINE_RECT);break}dt=ut}if(nt==null){const ht=new Rect(ot.getRight()-2,st,3,ct);nt=new DropInfo(this,ht,it,this.children.length,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}}else{const at=new Rect(this.tabHeaderRect.x+1,this.tabHeaderRect.y+2,3,18);nt=new DropInfo(this,at,it,0,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}else if(this.children.length>0){let at=this.children[0],ot=at.getTabRect();const st=ot.x,ct=ot.width;let dt=this.tabHeaderRect.y,ut=0;for(let ht=0;ht<this.children.length;ht++){if(at=this.children[ht],ot=at.getTabRect(),ut=ot.y+ot.height/2,et>=dt&&et<ut){const ft=new Rect(st,ot.y-2,ct,3);nt=new DropInfo(this,ft,it,ht,CLASSES.FLEXLAYOUT__OUTLINE_RECT);break}dt=ut}if(nt==null){const ht=new Rect(st,ot.getBottom()-2,ct,3);nt=new DropInfo(this,ht,it,this.children.length,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}}else{const at=new Rect(this.tabHeaderRect.x+2,this.tabHeaderRect.y+1,18,3);nt=new DropInfo(this,at,it,0,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}if(!_e.canDockInto(_e,nt))return}else if(this.getSelected()!==-1&&this.contentRect.contains(tt,et)){const at=this.contentRect;if(nt=new DropInfo(this,at,it,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT),!_e.canDockInto(_e,nt))return}return nt}drop(_e,tt,et,nt){let it=0;const at=_e.getParent();at!==void 0&&(it=at.removeChild(_e),at!==this&&at instanceof Dr&&at.getSelected()===it?at.setSelected(-1):adjustSelectedIndex(at,it)),_e instanceof TabNode&&at===this&&it<et&&et>0&&et--;let ot=et;ot===-1&&(ot=this.children.length),_e instanceof TabNode&&this.addChild(_e,ot),(nt||nt!==!1&&this.isAutoSelectTab())&&this.setSelected(ot),this.model.tidy()}getSplitterBounds(_e,tt=!1){const et=[0,0],nt=tt?this.getMinSize():0,it=tt?this.getMaxSize():99999,at=this.model.getRoot(Model.MAIN_WINDOW_ID),ot=at.getRect(),st=this.model.getSplitterSize();if(this.location===DockLocation.TOP){et[0]=this.tabHeaderRect.getBottom()+nt;const ct=this.tabHeaderRect.getBottom()+it;et[1]=Math.max(et[0],ot.getBottom()-at.getMinHeight()-st),et[1]=Math.min(et[1],ct)}else if(this.location===DockLocation.LEFT){et[0]=this.tabHeaderRect.getRight()+nt;const ct=this.tabHeaderRect.getRight()+it;et[1]=Math.max(et[0],ot.getRight()-at.getMinWidth()-st),et[1]=Math.min(et[1],ct)}else if(this.location===DockLocation.BOTTOM){et[1]=this.tabHeaderRect.y-nt-st;const ct=this.tabHeaderRect.y-it-st;et[0]=Math.min(et[1],ot.y+at.getMinHeight()),et[0]=Math.max(et[0],ct)}else if(this.location===DockLocation.RIGHT){et[1]=this.tabHeaderRect.x-nt-st;const ct=this.tabHeaderRect.x-it-st;et[0]=Math.min(et[1],ot.x+at.getMinWidth()),et[0]=Math.max(et[0],ct)}return et}calculateSplit(_e,tt){const et=this.getSplitterBounds(tt);return this.location===DockLocation.BOTTOM||this.location===DockLocation.RIGHT?Math.max(0,et[1]-tt):Math.max(0,tt-et[0])}getAttributeDefinitions(){return Dr.attributeDefinitions}static getAttributeDefinitions(){return Dr.attributeDefinitions}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("type",Dr.TYPE,!0).setType(Attribute.STRING).setFixed(),_e.add("selected",-1).setType(Attribute.NUMBER).setDescription("index of selected/visible tab in border; -1 means no tab selected"),_e.add("show",!0).setType(Attribute.BOOLEAN).setDescription("show/hide this border"),_e.add("config",void 0).setType("any").setDescription("a place to hold json config used in your own code"),_e.addInherited("enableDrop","borderEnableDrop").setType(Attribute.BOOLEAN).setDescription("whether tabs can be dropped into this border"),_e.addInherited("className","borderClassName").setType(Attribute.STRING).setDescription("class applied to tab button"),_e.addInherited("autoSelectTabWhenOpen","borderAutoSelectTabWhenOpen").setType(Attribute.BOOLEAN).setDescription("whether to select new/moved tabs in border when the border is already open"),_e.addInherited("autoSelectTabWhenClosed","borderAutoSelectTabWhenClosed").setType(Attribute.BOOLEAN).setDescription("whether to select new/moved tabs in border when the border is currently closed"),_e.addInherited("size","borderSize").setType(Attribute.NUMBER).setDescription("size of the tab area when selected"),_e.addInherited("minSize","borderMinSize").setType(Attribute.NUMBER).setDescription("the minimum size of the tab area"),_e.addInherited("maxSize","borderMaxSize").setType(Attribute.NUMBER).setDescription("the maximum size of the tab area"),_e.addInherited("enableAutoHide","borderEnableAutoHide").setType(Attribute.BOOLEAN).setDescription("hide border if it has zero tabs"),_e.addInherited("enableTabScrollbar","borderEnableTabScrollbar").setType(Attribute.BOOLEAN).setDescription("whether to show a mini scrollbar for the tabs"),_e}};__publicField(_BorderNode,"TYPE","border");__publicField(_BorderNode,"attributeDefinitions",_BorderNode.createAttributeDefinitions());let BorderNode=_BorderNode,splitterDragging=!1;const Splitter=rt=>{const{layout:_e,node:tt,index:et,horizontal:nt}=rt,[it,at]=reactExports.useState(!1),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=reactExports.useRef([]),dt=reactExports.useRef(void 0),ut=reactExports.useRef(void 0),ht=reactExports.useRef(0),ft=reactExports.useRef(0),pt=reactExports.useRef({initialSizes:[],sum:0,startPosition:0}),mt=tt.getModel().getSplitterSize();let vt=tt.getModel().getSplitterExtra();isDesktop()||(vt=Math.max(20,vt+mt)-mt),reactExports.useEffect(()=>{var It,Ot;return(It=ot.current)==null||It.addEventListener("touchstart",_t,{passive:!1}),(Ot=st.current)==null||Ot.addEventListener("touchstart",_t,{passive:!1}),()=>{var Nt,Mt;(Nt=ot.current)==null||Nt.removeEventListener("touchstart",_t),(Mt=st.current)==null||Mt.removeEventListener("touchstart",_t)}},[]);const _t=It=>{It.preventDefault(),It.stopImmediatePropagation()},yt=It=>{var Ot;It.stopPropagation(),tt instanceof RowNode&&(pt.current=tt.getSplitterInitials(et)),enablePointerOnIFrames(!1,_e.getCurrentDocument()),startDrag(It.currentTarget.ownerDocument,It,Et,St,bt),ct.current=tt.getSplitterBounds(et,!0);const Nt=_e.getRootDiv();dt.current=_e.getCurrentDocument().createElement("div"),dt.current.style.flexDirection=nt?"row":"column",dt.current.className=_e.getClassName(CLASSES.FLEXLAYOUT__SPLITTER_DRAG),dt.current.style.cursor=tt.getOrientation()===Orientation.VERT?"ns-resize":"ew-resize",tt.getModel().isSplitterEnableHandle()&&(ut.current=_e.getCurrentDocument().createElement("div"),ut.current.className=Ct(CLASSES.FLEXLAYOUT__SPLITTER_HANDLE)+" "+Ct(nt?CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_HORZ:CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_VERT),dt.current.appendChild(ut.current));const Mt=(Ot=ot.current)==null?void 0:Ot.getBoundingClientRect(),Lt=new Rect(Mt.x-_e.getDomRect().x,Mt.y-_e.getDomRect().y,Mt.width,Mt.height);ht.current=It.clientX-Mt.x,ft.current=It.clientY-Mt.y,Lt.positionElement(dt.current),Nt&&Nt.appendChild(dt.current),at(!0),splitterDragging=!0},bt=()=>{const It=_e.getRootDiv();It&&dt.current&&It.removeChild(dt.current),dt.current=void 0,at(!1),splitterDragging=!1},Et=(It,Ot)=>{if(dt.current){const Nt=_e.getDomRect();if(!Nt)return;tt.getOrientation()===Orientation.VERT?dt.current.style.top=xt(Ot-Nt.y-ft.current)+"px":dt.current.style.left=xt(It-Nt.x-ht.current)+"px",_e.isRealtimeResize()&&At()}},St=()=>{if(dt.current){At();const It=_e.getRootDiv();It&&dt.current&&It.removeChild(dt.current),dt.current=void 0}enablePointerOnIFrames(!0,_e.getCurrentDocument()),at(!1),splitterDragging=!1},At=It=>{(()=>{if(dt.current){let Nt=0;if(tt.getOrientation()===Orientation.VERT?Nt=dt.current.offsetTop:Nt=dt.current.offsetLeft,tt instanceof BorderNode){const Mt=tt.calculateSplit(tt,Nt);_e.doAction(Actions.adjustBorderSplit(tt.getId(),Mt))}else{const Mt=pt.current,Lt=tt.calculateSplit(et,Nt,Mt.initialSizes,Mt.sum,Mt.startPosition);_e.doAction(Actions.adjustWeights(tt.getId(),Lt))}}})()},xt=It=>{const Ot=ct.current;let Nt=It;return It<Ot[0]&&(Nt=Ot[0]),It>Ot[1]&&(Nt=Ot[1]),Nt},Ct=_e.getClassName,Pt={cursor:nt?"ew-resize":"ns-resize",flexDirection:nt?"column":"row"};let Tt=Ct(CLASSES.FLEXLAYOUT__SPLITTER)+" "+Ct(CLASSES.FLEXLAYOUT__SPLITTER_+tt.getOrientation().getName());tt instanceof BorderNode?Tt+=" "+Ct(CLASSES.FLEXLAYOUT__SPLITTER_BORDER):tt.getModel().getMaximizedTabset(_e.getWindowId())!==void 0&&(Pt.display="none"),nt?(Pt.width=mt+"px",Pt.minWidth=mt+"px"):(Pt.height=mt+"px",Pt.minHeight=mt+"px");let wt;if(!it&&tt.getModel().isSplitterEnableHandle()&&(wt=jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__SPLITTER_HANDLE)+" "+Ct(nt?CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_HORZ:CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_VERT)})),vt===0)return jsxRuntimeExports.jsx("div",{className:Tt,style:Pt,ref:ot,"data-layout-path":tt.getPath()+"/s"+(et-1),onPointerDown:yt,children:wt});{const It={};tt.getOrientation()===Orientation.HORZ?(It.height="100%",It.width=mt+vt+"px",It.cursor="ew-resize"):(It.height=mt+vt+"px",It.width="100%",It.cursor="ns-resize");const Ot=Ct(CLASSES.FLEXLAYOUT__SPLITTER_EXTRA);return jsxRuntimeExports.jsx("div",{className:Tt,style:Pt,ref:ot,"data-layout-path":tt.getPath()+"/s"+(et-1),onPointerDown:yt,children:jsxRuntimeExports.jsx("div",{style:It,ref:st,className:Ot,onPointerDown:yt})})}};function BorderTab(rt){const{layout:_e,border:tt,show:et}=rt,nt=reactExports.useRef(null),it=reactExports.useRef(void 0);reactExports.useLayoutEffect(()=>{const ct=_e.getBoundingClientRect(nt.current);!isNaN(ct.x)&&ct.width>0&&(tt.getContentRect().equals(ct)||(tt.setContentRect(ct),splitterDragging?(it.current&&clearTimeout(it.current),it.current=setTimeout(()=>{_e.redrawInternal("border content rect "+ct),it.current=void 0},50)):_e.redrawInternal("border content rect "+ct)))});let at=!0;const ot={};tt.getOrientation()===Orientation.HORZ?(ot.width=tt.getSize(),ot.minWidth=tt.getMinSize(),ot.maxWidth=tt.getMaxSize()):(ot.height=tt.getSize(),ot.minHeight=tt.getMinSize(),ot.maxHeight=tt.getMaxSize(),at=!1),ot.display=et?"flex":"none";const st=_e.getClassName(CLASSES.FLEXLAYOUT__BORDER_TAB_CONTENTS);return tt.getLocation()===DockLocation.LEFT||tt.getLocation()===DockLocation.TOP?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{ref:nt,style:ot,className:st}),et&&jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:0,horizontal:at})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[et&&jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:0,horizontal:at}),jsxRuntimeExports.jsx("div",{ref:nt,style:ot,className:st})]})}var ICloseType=(rt=>(rt[rt.Visible=1]="Visible",rt[rt.Always=2]="Always",rt[rt.Selected=3]="Selected",rt))(ICloseType||{});const BorderButton=rt=>{const{layout:_e,node:tt,selected:et,border:nt,icons:it,path:at}=rt,ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=Pt=>{tt.isEnableDrag()?(Pt.stopPropagation(),_e.setDragNode(Pt.nativeEvent,tt)):Pt.preventDefault()},dt=Pt=>{Pt.stopPropagation(),_e.clearDragMain()},ut=Pt=>{isAuxMouseEvent(Pt)&&_e.auxMouseClick(tt,Pt)},ht=Pt=>{_e.showContextMenu(tt,Pt)},ft=()=>{_e.doAction(Actions.selectTab(tt.getId()))},pt=()=>{const Pt=tt.getCloseType();return!!(et||Pt===ICloseType.Always||Pt===ICloseType.Visible&&window.matchMedia&&window.matchMedia("(hover: hover) and (pointer: fine)").matches)},mt=Pt=>{pt()&&(_e.doAction(Actions.deleteTab(tt.getId())),Pt.stopPropagation())},vt=Pt=>{Pt.stopPropagation()};reactExports.useLayoutEffect(()=>{tt.setTabRect(_e.getBoundingClientRect(ot.current)),_e.getEditingTab()===tt&&st.current.select()});const _t=Pt=>{Pt.stopPropagation()},yt=Pt=>{Pt.code==="Escape"?_e.setEditingTab(void 0):(Pt.code==="Enter"||Pt.code==="NumpadEnter")&&(_e.setEditingTab(void 0),_e.doAction(Actions.renameTab(tt.getId(),Pt.target.value)))},bt=_e.getClassName;let Et=bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON)+" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_+nt);et?Et+=" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON__SELECTED):Et+=" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON__UNSELECTED),tt.getClassName()!==void 0&&(Et+=" "+tt.getClassName());let St=0;tt.getModel().isEnableRotateBorderIcons()===!1&&(nt==="left"?St=90:nt==="right"&&(St=-90));const At=getRenderStateEx(_e,tt,St);let xt=At.content?jsxRuntimeExports.jsx("div",{className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_CONTENT),children:At.content}):null;const Ct=At.leading?jsxRuntimeExports.jsx("div",{className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_LEADING),children:At.leading}):null;if(_e.getEditingTab()===tt&&(xt=jsxRuntimeExports.jsx("input",{ref:st,className:bt(CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX),"data-layout-path":at+"/textbox",type:"text",autoFocus:!0,defaultValue:tt.getName(),onKeyDown:yt,onPointerDown:_t})),tt.isEnableClose()){const Pt=_e.i18nName(I18nLabel.Close_Tab);At.buttons.push(jsxRuntimeExports.jsx("div",{"data-layout-path":at+"/button/close",title:Pt,className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_TRAILING),onPointerDown:vt,onClick:mt,children:typeof it.close=="function"?it.close(tt):it.close},"close"))}return jsxRuntimeExports.jsxs("div",{ref:ot,"data-layout-path":at,className:Et,onClick:ft,onAuxClick:ut,onContextMenu:ht,title:tt.getHelpText(),draggable:!0,onDragStart:ct,onDragEnd:dt,children:[Ct,xt,At.buttons]})},TabButtonStamp=rt=>{const{layout:_e,node:tt}=rt,et=_e.getClassName,nt=et(CLASSES.FLEXLAYOUT__TAB_BUTTON_STAMP),it=getRenderStateEx(_e,tt),at=it.content?jsxRuntimeExports.jsx("div",{className:et(CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT),children:it.content}):tt.getNameForOverflowMenu(),ot=it.leading?jsxRuntimeExports.jsx("div",{className:et(CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING),children:it.leading}):null;return jsxRuntimeExports.jsxs("div",{className:nt,title:tt.getHelpText(),children:[ot,at]})};function showPopup(rt,_e,tt,et,nt){const it=nt.getRootDiv(),at=nt.getClassName,ot=rt.ownerDocument,st=rt.getBoundingClientRect(),ct=(it==null?void 0:it.getBoundingClientRect())??new DOMRect(0,0,100,100),dt=ot.createElement("div");dt.className=at(CLASSES.FLEXLAYOUT__POPUP_MENU_CONTAINER),st.left<ct.left+ct.width/2?dt.style.left=st.left-ct.left+"px":dt.style.right=ct.right-st.right+"px",st.top<ct.top+ct.height/2?dt.style.top=st.top-ct.top+"px":dt.style.bottom=ct.bottom-st.bottom+"px",nt.showOverlay(!0),it&&it.appendChild(dt);const ut=()=>{nt.hideControlInPortal(),nt.showOverlay(!1),it&&it.removeChild(dt),dt.removeEventListener("pointerdown",ht),ot.removeEventListener("pointerdown",ft)},ht=pt=>{pt.stopPropagation()},ft=pt=>{ut()};dt.addEventListener("pointerdown",ht),ot.addEventListener("pointerdown",ft),nt.showControlInPortal(jsxRuntimeExports.jsx(PopupMenu,{currentDocument:ot,parentNode:_e,onSelect:et,onHide:ut,items:tt,classNameMapper:at,layout:nt}),dt)}const PopupMenu=rt=>{const{parentNode:_e,items:tt,onHide:et,onSelect:nt,classNameMapper:it,layout:at}=rt,ot=reactExports.useRef(null);reactExports.useEffect(()=>{ot.current&&ot.current.focus()},[]);const st=(ft,pt)=>{nt(ft),et(),pt.stopPropagation()},ct=(ft,pt)=>{ft.stopPropagation(),at.setDragNode(ft.nativeEvent,pt),setTimeout(()=>{et()},0)},dt=ft=>{at.clearDragMain()},ut=ft=>{ft.key==="Escape"&&et()},ht=tt.map((ft,pt)=>{let mt=it(CLASSES.FLEXLAYOUT__POPUP_MENU_ITEM);return _e.getSelected()===ft.index&&(mt+=" "+it(CLASSES.FLEXLAYOUT__POPUP_MENU_ITEM__SELECTED)),jsxRuntimeExports.jsx("div",{className:mt,"data-layout-path":"/popup-menu/tb"+pt,onClick:vt=>st(ft,vt),draggable:!0,onDragStart:vt=>ct(vt,ft.node),onDragEnd:dt,title:ft.node.getHelpText(),children:jsxRuntimeExports.jsx(TabButtonStamp,{node:ft.node,layout:at})},ft.index)});return jsxRuntimeExports.jsx("div",{className:it(CLASSES.FLEXLAYOUT__POPUP_MENU),ref:ot,tabIndex:0,onKeyDown:ut,"data-layout-path":"/popup-menu",children:ht})},useTabOverflow=(rt,_e,tt,et,nt,it)=>{const[at,ot]=reactExports.useState([]),[st,ct]=reactExports.useState(!1),[dt,ut]=reactExports.useState(!1),ht=reactExports.useRef(null),ft=reactExports.useRef(!1),pt=reactExports.useRef(void 0),mt=reactExports.useRef([]),vt=reactExports.useRef(0),_t=reactExports.useRef(!1);mt.current=at,reactExports.useLayoutEffect(()=>{et.current&&Bt(0)},[_e.getId()]),reactExports.useLayoutEffect(()=>{ft.current=!1},[_e.getSelectedNode(),_e.getRect().width,_e.getRect().height]),reactExports.useLayoutEffect(()=>{wt(),ft.current===!1&&bt(),Et(),St()}),reactExports.useEffect(()=>{var zt;return(zt=ht.current)==null||zt.addEventListener("wheel",yt,{passive:!1}),()=>{var Wt;(Wt=ht.current)==null||Wt.removeEventListener("wheel",yt)}},[ht.current]);const yt=zt=>{zt.preventDefault()};function bt(){const zt=_e.getSelectedNode();if(zt&&et.current){const Wt=rt.getBoundingClientRect(et.current),Qt=zt.getTabRect();let nn=Nt(Wt)-Nt(Qt);nn>0||$t(Qt)>$t(Wt)?(Bt(Gt(et.current)-nn),_t.current=!0):(nn=Mt(Qt)-Mt(Wt),nn>0&&(Bt(Gt(et.current)+nn),_t.current=!0))}}const Et=()=>{if(et.current&&nt.current){const zt=et.current,Wt=nt.current,Qt=Lt(zt),nn=Dt(zt),Yt=Gt(zt);if(nn>Qt&&nn>0){let tn=Qt*Qt/nn,sn=0;tn<20&&(sn=20-tn,tn=20);const dn=Yt*(Qt-sn)/nn;tt===Orientation.HORZ?(Wt.style.width=tn+"px",Wt.style.left=dn+"px"):(Wt.style.height=tn+"px",Wt.style.top=dn+"px"),Wt.style.display="block"}else Wt.style.display="none";tt===Orientation.HORZ?Wt.style.bottom="0px":Wt.style.right="0px"}},St=()=>{const Wt=It().length>0;Wt!==st&&ct(Wt),pt.current===void 0&&(pt.current=setTimeout(()=>{const Qt=It();arraysEqual(Qt,mt.current)||ot(Qt),pt.current=void 0},100))},At=()=>{_t.current||(ft.current=!0),_t.current=!1,Et(),St()},xt=zt=>{var Wt;zt.stopPropagation(),nt.current.setPointerCapture(zt.pointerId);const Qt=(Wt=nt.current)==null?void 0:Wt.getBoundingClientRect();tt===Orientation.HORZ?vt.current=zt.clientX-Qt.x:vt.current=zt.clientY-Qt.y,startDrag(zt.currentTarget.ownerDocument,zt,Ct,Pt,Tt)},Ct=(zt,Wt)=>{if(et.current&&nt.current){const Qt=et.current,nn=nt.current,Yt=Lt(Qt),tn=Dt(Qt),sn=Lt(nn),dn=Qt.getBoundingClientRect();let vn=0;if(tt===Orientation.HORZ?vn=zt-dn.x-vt.current:vn=Wt-dn.y-vt.current,vn=Math.max(0,Math.min(tn-sn,vn)),Yt>0){const mn=vn*tn/Yt;Bt(mn)}}},Pt=()=>{},Tt=()=>{},wt=()=>{if(et.current){const Wt=et.current.firstElementChild,Qt=dt?10:0,nn=Lt(Wt)+Qt>Lt(et.current);nn!==dt&&ut(nn)}},It=()=>{const zt=[];if(et.current){const Wt=et.current,Qt=Wt.getBoundingClientRect(),nn=Nt(Qt)-1,Yt=Mt(Qt)+1,tn=Wt.firstElementChild;let sn=0;Array.from(tn.children).forEach(dn=>{const vn=dn.getBoundingClientRect();dn.classList.contains(it)&&((Nt(vn)<nn||Mt(vn)>Yt)&&zt.push(sn),sn++)})}return zt},Ot=zt=>{if(et.current){if(_e.getChildren().length===0)return;let Wt=0;if(Math.abs(zt.deltaY)>0){Wt=-zt.deltaY,zt.deltaMode===1&&(Wt*=40);const Qt=Gt(et.current)-Wt,nn=Dt(et.current)-Lt(et.current),Yt=Math.max(0,Math.min(nn,Qt));Bt(Yt),zt.stopPropagation()}}},Nt=zt=>tt===Orientation.HORZ?zt.x:zt.y,Mt=zt=>tt===Orientation.HORZ?zt.right:zt.bottom,Lt=zt=>tt===Orientation.HORZ?zt.clientWidth:zt.clientHeight,$t=zt=>tt===Orientation.HORZ?zt.width:zt.height,Dt=zt=>tt===Orientation.HORZ?zt.scrollWidth:zt.scrollHeight,Bt=zt=>{tt===Orientation.HORZ?et.current.scrollLeft=zt:et.current.scrollTop=zt},Gt=zt=>tt===Orientation.HORZ?zt.scrollLeft:zt.scrollTop;return{selfRef:ht,userControlledPositionRef:ft,onScroll:At,onScrollPointerDown:xt,hiddenTabs:at,onMouseWheel:Ot,isDockStickyButtons:dt,isShowHiddenTabs:st}};function arraysEqual(rt,_e){return rt.length===_e.length&&rt.every((tt,et)=>tt===_e[et])}const BorderTabSet=rt=>{const{border:_e,layout:tt,size:et}=rt,nt=reactExports.useRef(null),it=reactExports.useRef(null),at=reactExports.useRef(null),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=tt.getIcons();reactExports.useLayoutEffect(()=>{_e.setTabHeaderRect(tt.getBoundingClientRect(dt.current))});const{selfRef:dt,userControlledPositionRef:ut,onScroll:ht,onScrollPointerDown:ft,hiddenTabs:pt,onMouseWheel:mt,isDockStickyButtons:vt,isShowHiddenTabs:_t}=useTabOverflow(tt,_e,Orientation.flip(_e.getOrientation()),st,it,tt.getClassName(CLASSES.FLEXLAYOUT__BORDER_BUTTON)),yt=Qt=>{isAuxMouseEvent(Qt)&&tt.auxMouseClick(_e,Qt)},bt=Qt=>{tt.showContextMenu(_e,Qt)},Et=Qt=>{Qt.stopPropagation()},St=Qt=>{const nn=tt.getShowOverflowMenu(),Yt=pt.map(tn=>({index:tn,node:_e.getChildren()[tn]}));if(nn!==void 0)nn(_e,Qt,Yt,At);else{const tn=at.current;showPopup(tn,_e,Yt,At,tt)}Qt.stopPropagation()},At=Qt=>{tt.doAction(Actions.selectTab(Qt.node.getId())),ut.current=!1},xt=Qt=>{const nn=_e.getChildren()[_e.getSelected()];nn!==void 0&&tt.doAction(Actions.popoutTab(nn.getId())),Qt.stopPropagation()},Ct=tt.getClassName,Pt=[],Tt=Qt=>{const nn=_e.getSelected()===Qt,Yt=_e.getChildren()[Qt];Pt.push(jsxRuntimeExports.jsx(BorderButton,{layout:tt,border:_e.getLocation().getName(),node:Yt,path:_e.getPath()+"/tb"+Qt,selected:nn,icons:ct},Yt.getId())),Qt<_e.getChildren().length-1&&Pt.push(jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__BORDER_TAB_DIVIDER)},"divider"+Qt))};for(let Qt=0;Qt<_e.getChildren().length;Qt++)Tt(Qt);let wt=Ct(CLASSES.FLEXLAYOUT__BORDER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_+_e.getLocation().getName());_e.getClassName()!==void 0&&(wt+=" "+_e.getClassName());let It,Ot=[],Nt=[];const Mt={leading:It,buttons:Ot,stickyButtons:Nt,overflowPosition:void 0};if(tt.customizeTabSet(_e,Mt),It=Mt.leading,Nt=Mt.stickyButtons,Ot=Mt.buttons,Mt.overflowPosition===void 0&&(Mt.overflowPosition=Nt.length),Nt.length>0&&(vt?Ot=[...Nt,...Ot]:Pt.push(jsxRuntimeExports.jsx("div",{ref:ot,onPointerDown:Et,onDragStart:Qt=>{Qt.preventDefault()},className:Ct(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER),children:Nt},"sticky_buttons_container"))),_t){const Qt=tt.i18nName(I18nLabel.Overflow_Menu_Tooltip);let nn;if(typeof ct.more=="function"){const Yt=pt.map(tn=>({index:tn,node:_e.getChildren()[tn]}));nn=ct.more(_e,Yt)}else nn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ct.more,jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT),children:pt.length>0?pt.length:""})]});Ot.splice(Math.min(Mt.overflowPosition,Ot.length),0,jsxRuntimeExports.jsx("button",{ref:at,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_+_e.getLocation().getName()),title:Qt,onClick:St,onPointerDown:Et,children:nn},"overflowbutton"))}const Lt=_e.getSelected();if(Lt!==-1){const Qt=_e.getChildren()[Lt];if(Qt!==void 0&&tt.isSupportsPopout()&&Qt.isEnablePopout()){const nn=tt.i18nName(I18nLabel.Popout_Tab);Ot.push(jsxRuntimeExports.jsx("button",{title:nn,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT),onClick:xt,onPointerDown:Et,children:typeof ct.popout=="function"?ct.popout(Qt):ct.popout},"popout"))}}const $t=jsxRuntimeExports.jsx("div",{ref:nt,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_+_e.getLocation().getName()),children:Ot},"toolbar");let Dt={},Bt={};const Gt=et-1;_e.getLocation()===DockLocation.LEFT?(Dt={right:"100%",top:0},Bt={width:Gt,overflowY:"auto"}):_e.getLocation()===DockLocation.RIGHT?(Dt={left:"100%",top:0},Bt={width:Gt,overflowY:"auto"}):(Dt={left:0},Bt={height:Gt,overflowX:"auto"});let zt;_e.isEnableTabScrollbar()&&(zt=jsxRuntimeExports.jsx("div",{ref:it,className:Ct(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR),onPointerDown:ft}));let Wt;return It&&(Wt=jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__BORDER_LEADING),children:It})),jsxRuntimeExports.jsxs("div",{ref:dt,style:{display:"flex",flexDirection:_e.getOrientation()===Orientation.VERT?"row":"column"},className:wt,"data-layout-path":_e.getPath(),onClick:yt,onAuxClick:yt,onContextMenu:bt,onWheel:mt,children:[Wt,jsxRuntimeExports.jsxs("div",{className:Ct(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER),children:[jsxRuntimeExports.jsx("div",{ref:st,className:Ct(CLASSES.FLEXLAYOUT__BORDER_INNER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_+_e.getLocation().getName()),style:Bt,onScroll:ht,children:jsxRuntimeExports.jsx("div",{style:Dt,className:Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_+_e.getLocation().getName()),children:Pt})}),zt]}),$t]})},DragContainer=rt=>{const{layout:_e,node:tt}=rt,et=reactExports.useRef(null);reactExports.useEffect(()=>{tt.setTabStamp(et.current)},[tt,et.current]);const nt=_e.getClassName,it=nt(CLASSES.FLEXLAYOUT__DRAG_RECT);return jsxRuntimeExports.jsx("div",{ref:et,className:it,children:jsxRuntimeExports.jsx(TabButtonStamp,{layout:_e,node:tt},tt.getId())})},PopoutWindow=rt=>{const{title:_e,layout:tt,layoutWindow:et,url:nt,onCloseWindow:it,onSetWindow:at,children:ot}=rt,st=reactExports.useRef(null),[ct,dt]=reactExports.useState(void 0),ut=new Map;return reactExports.useLayoutEffect(()=>{if(!st.current){const ht=et.windowId,ft=et.rect;st.current=window.open(nt,ht,`left=${ft.x},top=${ft.y},width=${ft.width},height=${ft.height}`),st.current?(et.window=st.current,at(et,st.current),window.addEventListener("beforeunload",()=>{if(st.current){const pt=st.current;st.current=null,pt.close()}}),st.current.addEventListener("load",()=>{if(st.current){st.current.focus(),st.current.resizeTo(ft.width,ft.height),st.current.moveTo(ft.x,ft.y);const pt=st.current.document;pt.title=_e;const mt=pt.createElement("div");mt.className=CLASSES.FLEXLAYOUT__FLOATING_WINDOW_CONTENT,pt.body.appendChild(mt),copyStyles(pt,ut).then(()=>{dt(mt)});const vt=new MutationObserver(_t=>handleStyleMutations(_t,pt,ut));vt.observe(document.head,{childList:!0}),st.current.addEventListener("beforeunload",()=>{st.current&&(it(et),st.current=null,vt.disconnect())})}})):(console.warn(`Unable to open window ${nt}`),it(et))}return()=>{var ht;tt.getModel().getwindowsMap().has(et.windowId)||((ht=st.current)==null||ht.close(),st.current=null)}},[]),ct!==void 0?reactDomExports.createPortal(ot,ct):null};function handleStyleMutations(rt,_e,tt){for(const et of rt)if(et.type==="childList"){for(const nt of et.addedNodes)(nt instanceof HTMLLinkElement||nt instanceof HTMLStyleElement)&©Style(_e,nt,tt);for(const nt of et.removedNodes)if(nt instanceof HTMLLinkElement||nt instanceof HTMLStyleElement){const it=tt.get(nt);it&&_e.head.removeChild(it)}}}function copyStyles(rt,_e){const tt=[],et=document.querySelectorAll('style, link[rel="stylesheet"]');for(const nt of et)copyStyle(rt,nt,_e,tt);return Promise.all(tt)}function copyStyle(rt,_e,tt,et){if(_e instanceof HTMLLinkElement){const nt=_e.cloneNode(!0);rt.head.appendChild(nt),tt.set(_e,nt),et&&et.push(new Promise(it=>{nt.onload=()=>it(!0)}))}else if(_e instanceof HTMLStyleElement)try{const nt=_e.cloneNode(!0);rt.head.appendChild(nt),tt.set(_e,nt)}catch{}}const style={width:"1em",height:"1em",display:"flex",alignItems:"center"},CloseIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",children:[jsxRuntimeExports.jsx("path",{fill:"none",d:"M0 0h24v24H0z"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",fill:"var(--color-icon)",d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]}),MaximizeIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"})]}),OverflowIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M7 10l5 5 5-5z"})]}),EdgeIcon=()=>jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",style:{display:"block",width:10,height:10},preserveAspectRatio:"none",viewBox:"0 0 100 100",children:jsxRuntimeExports.jsx("path",{fill:"var(--color-edge-icon)",stroke:"var(--color-edge-icon)",d:"M10 30 L90 30 l-40 40 Z"})}),PopoutIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 20 20",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"}),jsxRuntimeExports.jsx("path",{d:"M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"})]}),RestoreIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"})]}),AsterickIcon=()=>jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",style,height:"24px",viewBox:"0 -960 960 960",width:"24px",children:jsxRuntimeExports.jsx("path",{fill:"var(--color-icon)",stroke:"var(--color-icon)",d:"M440-120v-264L254-197l-57-57 187-186H120v-80h264L197-706l57-57 186 187v-264h80v264l186-187 57 57-187 186h264v80H576l187 186-57 57-186-187v264h-80Z"})}),Overlay=rt=>{const{layout:_e,show:tt}=rt;return jsxRuntimeExports.jsx("div",{className:_e.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_OVERLAY),style:{display:tt?"flex":"none"}})},TabButton=rt=>{const{layout:_e,node:tt,selected:et,path:nt}=rt,it=reactExports.useRef(null),at=reactExports.useRef(null),ot=_e.getIcons();reactExports.useLayoutEffect(()=>{tt.setTabRect(_e.getBoundingClientRect(it.current)),_e.getEditingTab()===tt&&at.current.select()});const st=Ot=>{tt.isEnableDrag()?(Ot.stopPropagation(),_e.setDragNode(Ot.nativeEvent,tt)):Ot.preventDefault()},ct=Ot=>{_e.clearDragMain()},dt=Ot=>{isAuxMouseEvent(Ot)&&_e.auxMouseClick(tt,Ot)},ut=Ot=>{_e.showContextMenu(tt,Ot)},ht=()=>{_e.doAction(Actions.selectTab(tt.getId()))},ft=Ot=>{tt.isEnableRename()&&(pt(),Ot.stopPropagation())},pt=()=>{_e.setEditingTab(tt),_e.getCurrentDocument().body.addEventListener("pointerdown",mt)},mt=Ot=>{Ot.target!==at.current&&(_e.getCurrentDocument().body.removeEventListener("pointerdown",mt),_e.setEditingTab(void 0))},vt=()=>{const Ot=tt.getCloseType();return!!(et||Ot===ICloseType.Always||Ot===ICloseType.Visible&&window.matchMedia&&window.matchMedia("(hover: hover) and (pointer: fine)").matches)},_t=Ot=>{vt()&&(_e.doAction(Actions.deleteTab(tt.getId())),Ot.stopPropagation())},yt=Ot=>{Ot.stopPropagation()},bt=Ot=>{Ot.stopPropagation()},Et=Ot=>{Ot.code==="Escape"?_e.setEditingTab(void 0):(Ot.code==="Enter"||Ot.code==="NumpadEnter")&&(_e.setEditingTab(void 0),_e.doAction(Actions.renameTab(tt.getId(),Ot.target.value)))},St=_e.getClassName,At=tt.getParent(),xt=At.isEnableSingleTabStretch()&&At.getChildren().length===1,Ct=xt?CLASSES.FLEXLAYOUT__TAB_BUTTON_STRETCH:CLASSES.FLEXLAYOUT__TAB_BUTTON;let Pt=St(Ct);Pt+=" "+St(Ct+"_"+At.getTabLocation()),xt||(et?Pt+=" "+St(Ct+"--selected"):Pt+=" "+St(Ct+"--unselected")),tt.getClassName()!==void 0&&(Pt+=" "+tt.getClassName());const Tt=getRenderStateEx(_e,tt);let wt=Tt.content?jsxRuntimeExports.jsx("div",{className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT),children:Tt.content}):null;const It=Tt.leading?jsxRuntimeExports.jsx("div",{className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING),children:Tt.leading}):null;if(_e.getEditingTab()===tt&&(wt=jsxRuntimeExports.jsx("input",{ref:at,className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX),"data-layout-path":nt+"/textbox",type:"text",autoFocus:!0,defaultValue:tt.getName(),onKeyDown:Et,onPointerDown:bt})),tt.isEnableClose()&&!xt){const Ot=_e.i18nName(I18nLabel.Close_Tab);Tt.buttons.push(jsxRuntimeExports.jsx("div",{"data-layout-path":nt+"/button/close",title:Ot,className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_TRAILING),onPointerDown:yt,onClick:_t,children:typeof ot.close=="function"?ot.close(tt):ot.close},"close"))}return jsxRuntimeExports.jsxs("div",{ref:it,"data-layout-path":nt,className:Pt,onClick:ht,onAuxClick:dt,onContextMenu:ut,title:tt.getHelpText(),draggable:!0,onDragStart:st,onDragEnd:ct,onDoubleClick:ft,children:[It,wt,Tt.buttons]})},TabSet=rt=>{const{node:_e,layout:tt}=rt,et=reactExports.useRef(null),nt=reactExports.useRef(null),it=reactExports.useRef(null),at=reactExports.useRef(null),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=reactExports.useRef(null),dt=reactExports.useRef(void 0),ut=tt.getIcons();reactExports.useLayoutEffect(()=>{_e.setRect(tt.getBoundingClientRect(ht.current)),et.current&&_e.setTabStripRect(tt.getBoundingClientRect(et.current));const fn=tt.getBoundingClientRect(at.current);!_e.getContentRect().equals(fn)&&!isNaN(fn.x)&&(_e.setContentRect(fn),splitterDragging?(dt.current&&clearTimeout(dt.current),dt.current=setTimeout(()=>{tt.redrawInternal("border content rect "+fn),dt.current=void 0},50)):tt.redrawInternal("border content rect "+fn))});const{selfRef:ht,userControlledPositionRef:ft,onScroll:pt,onScrollPointerDown:mt,hiddenTabs:vt,onMouseWheel:_t,isDockStickyButtons:yt,isShowHiddenTabs:bt}=useTabOverflow(tt,_e,Orientation.HORZ,it,nt,tt.getClassName(CLASSES.FLEXLAYOUT__TAB_BUTTON)),Et=fn=>{const Sn=tt.getShowOverflowMenu(),zn=vt.map(On=>({index:On,node:_e.getChildren()[On]}));if(Sn!==void 0)Sn(_e,fn,zn,St);else{const On=st.current;showPopup(On,_e,zn,St,tt)}fn.stopPropagation()},St=fn=>{tt.doAction(Actions.selectTab(fn.node.getId())),ft.current=!1},At=fn=>{tt.getEditingTab()?fn.preventDefault():_e.isEnableDrag()?(fn.stopPropagation(),tt.setDragNode(fn.nativeEvent,_e)):fn.preventDefault()},xt=fn=>{isAuxMouseEvent(fn)||tt.doAction(Actions.setActiveTabset(_e.getId(),tt.getWindowId()))},Ct=fn=>{isAuxMouseEvent(fn)&&tt.auxMouseClick(_e,fn)},Pt=fn=>{tt.showContextMenu(_e,fn)},Tt=fn=>{fn.stopPropagation()},wt=fn=>{_e.canMaximize()&&tt.maximize(_e),fn.stopPropagation()},It=fn=>{tt.doAction(Actions.deleteTabset(_e.getId())),fn.stopPropagation()},Ot=fn=>{tt.doAction(Actions.deleteTab(_e.getChildren()[0].getId())),fn.stopPropagation()},Nt=fn=>{$t!==void 0&&tt.doAction(Actions.popoutTab($t.getId())),fn.stopPropagation()},Mt=fn=>{_e.canMaximize()&&tt.maximize(_e)},Lt=tt.getClassName,$t=_e.getSelectedNode(),Dt=_e.getPath(),Bt=[];if(_e.isEnableTabStrip())for(let fn=0;fn<_e.getChildren().length;fn++){const Sn=_e.getChildren()[fn],zn=_e.getSelected()===fn;Bt.push(jsxRuntimeExports.jsx(TabButton,{layout:tt,node:Sn,path:Dt+"/tb"+fn,selected:zn},Sn.getId())),fn<_e.getChildren().length-1&&Bt.push(jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET_TAB_DIVIDER)},"divider"+fn))}let Gt,zt=[],Wt=[];const Qt={leading:Gt,stickyButtons:zt,buttons:Wt,overflowPosition:void 0};tt.customizeTabSet(_e,Qt),Gt=Qt.leading,zt=Qt.stickyButtons,Wt=Qt.buttons;const nn=_e.isEnableSingleTabStretch()&&_e.getChildren().length===1,Yt=nn&&_e.getChildren()[0].isEnableClose()||_e.isEnableClose();if(Qt.overflowPosition===void 0&&(Qt.overflowPosition=zt.length),zt.length>0&&(!_e.isEnableTabWrap()&&(yt||nn)?Wt=[...zt,...Wt]:Bt.push(jsxRuntimeExports.jsx("div",{ref:ct,onPointerDown:Tt,onDragStart:fn=>{fn.preventDefault()},className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER),children:zt},"sticky_buttons_container"))),!_e.isEnableTabWrap()&&bt){const fn=tt.i18nName(I18nLabel.Overflow_Menu_Tooltip);let Sn;if(typeof ut.more=="function"){const zn=vt.map(On=>({index:On,node:_e.getChildren()[On]}));Sn=ut.more(_e,zn)}else Sn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ut.more,jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT),children:vt.length>0?vt.length:""})]});Wt.splice(Math.min(Qt.overflowPosition,Wt.length),0,jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/overflow",ref:st,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW),title:fn,onClick:Et,onPointerDown:Tt,children:Sn},"overflowbutton"))}if($t!==void 0&&tt.isSupportsPopout()&&$t.isEnablePopout()&&$t.isEnablePopoutIcon()){const fn=tt.i18nName(I18nLabel.Popout_Tab);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/popout",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT),onClick:Nt,onPointerDown:Tt,children:typeof ut.popout=="function"?ut.popout($t):ut.popout},"popout"))}if(_e.canMaximize()){const fn=tt.i18nName(I18nLabel.Restore),Sn=tt.i18nName(I18nLabel.Maximize);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/max",title:_e.isMaximized()?fn:Sn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_+(_e.isMaximized()?"max":"min")),onClick:wt,onPointerDown:Tt,children:_e.isMaximized()?typeof ut.restore=="function"?ut.restore(_e):ut.restore:typeof ut.maximize=="function"?ut.maximize(_e):ut.maximize},"max"))}if(!_e.isMaximized()&&Yt){const fn=nn?tt.i18nName(I18nLabel.Close_Tab):tt.i18nName(I18nLabel.Close_Tabset);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/close",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE),onClick:nn?Ot:It,onPointerDown:Tt,children:typeof ut.closeTabset=="function"?ut.closeTabset(_e):ut.closeTabset},"close"))}if(_e.isActive()&&_e.isEnableActiveIcon()){const fn=tt.i18nName(I18nLabel.Active_Tabset);Wt.push(jsxRuntimeExports.jsx("div",{"data-layout-path":Dt+"/button/active",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_ICON),children:typeof ut.activeTabset=="function"?ut.activeTabset(_e):ut.activeTabset},"active"))}const tn=jsxRuntimeExports.jsx("div",{ref:ot,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR),onPointerDown:Tt,onDragStart:fn=>{fn.preventDefault()},children:Wt},"buttonbar");let sn,dn=Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER);if(_e.getClassNameTabStrip()!==void 0&&(dn+=" "+_e.getClassNameTabStrip()),dn+=" "+CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER_+_e.getTabLocation(),_e.isActive()&&(dn+=" "+Lt(CLASSES.FLEXLAYOUT__TABSET_SELECTED)),_e.isMaximized()&&(dn+=" "+Lt(CLASSES.FLEXLAYOUT__TABSET_MAXIMIZED)),nn){const fn=_e.getChildren()[0];fn.getTabSetClassName()!==void 0&&(dn+=" "+fn.getTabSetClassName())}let vn;if(Gt&&(vn=jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET_LEADING),children:Gt})),_e.isEnableTabWrap())_e.isEnableTabStrip()&&(sn=jsxRuntimeExports.jsxs("div",{className:dn,style:{flexWrap:"wrap",gap:"1px",marginTop:"2px"},ref:et,"data-layout-path":Dt+"/tabstrip",onPointerDown:xt,onDoubleClick:Mt,onContextMenu:Pt,onClick:Ct,onAuxClick:Ct,draggable:!0,onDragStart:At,children:[vn,Bt,jsxRuntimeExports.jsx("div",{style:{flexGrow:1}}),tn]}));else if(_e.isEnableTabStrip()){let fn;_e.isEnableTabScrollbar()&&(fn=jsxRuntimeExports.jsx("div",{ref:nt,className:Lt(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR),onPointerDown:mt})),sn=jsxRuntimeExports.jsxs("div",{className:dn,ref:et,"data-layout-path":Dt+"/tabstrip",onPointerDown:xt,onDoubleClick:Mt,onContextMenu:Pt,onClick:Ct,onAuxClick:Ct,draggable:!0,onWheel:_t,onDragStart:At,children:[vn,jsxRuntimeExports.jsxs("div",{className:Lt(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER),children:[jsxRuntimeExports.jsx("div",{ref:it,className:Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER)+" "+Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_+_e.getTabLocation()),style:{overflowX:"auto",overflowY:"hidden"},onScroll:pt,children:jsxRuntimeExports.jsx("div",{style:{width:nn?"100%":"none"},className:Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER)+" "+Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_+_e.getTabLocation()),children:Bt})}),fn]}),tn]})}let mn;if(_e.getChildren().length===0){const fn=tt.getTabSetPlaceHolderCallback();fn&&(mn=fn(_e))}let pn=jsxRuntimeExports.jsx("div",{ref:at,className:Lt(CLASSES.FLEXLAYOUT__TABSET_CONTENT),children:mn});_e.getTabLocation()==="top"?pn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[sn,pn]}):pn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[pn,sn]});const Cn={flexGrow:Math.max(1,_e.getWeight()*1e3),minWidth:_e.getMinWidth(),minHeight:_e.getMinHeight(),maxWidth:_e.getMaxWidth(),maxHeight:_e.getMaxHeight()};_e.getModel().getMaximizedTabset(tt.getWindowId())!==void 0&&!_e.isMaximized()&&(Cn.display="none");const Ln=jsxRuntimeExports.jsx("div",{ref:ht,className:Lt(CLASSES.FLEXLAYOUT__TABSET_CONTAINER),style:Cn,children:jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET),"data-layout-path":Dt,children:pn})});return _e.isMaximized()&&tt.getMainElement()?reactDomExports.createPortal(jsxRuntimeExports.jsx("div",{style:{position:"absolute",display:"flex",top:0,left:0,bottom:0,right:0},children:Ln}),tt.getMainElement()):Ln},Row=rt=>{const{layout:_e,node:tt}=rt,et=reactExports.useRef(null),nt=tt.getOrientation()===Orientation.HORZ;reactExports.useLayoutEffect(()=>{tt.setRect(_e.getBoundingClientRect(et.current))});const it=[];let at=0;for(const st of tt.getChildren())at>0&&it.push(jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:at,horizontal:nt},"splitter"+at)),st instanceof RowNode?it.push(jsxRuntimeExports.jsx(Row,{layout:_e,node:st},st.getId())):st instanceof TabSetNode&&it.push(jsxRuntimeExports.jsx(TabSet,{layout:_e,node:st},st.getId())),at++;const ot={flexGrow:Math.max(1,tt.getWeight()*1e3),minWidth:tt.getMinWidth(),minHeight:tt.getMinHeight(),maxWidth:tt.getMaxWidth(),maxHeight:tt.getMaxHeight()};return nt?ot.flexDirection="row":ot.flexDirection="column",jsxRuntimeExports.jsx("div",{ref:et,className:_e.getClassName(CLASSES.FLEXLAYOUT__ROW),style:ot,children:it})},Tab=rt=>{const{layout:_e,selected:tt,node:et,path:nt}=rt,it=reactExports.useRef(null),at=reactExports.useRef(!0),ot=et.getParent(),st=ot.getContentRect();reactExports.useLayoutEffect(()=>{const pt=et.getMoveableElement();it.current.appendChild(pt),et.setMoveableElement(pt);const mt=()=>{et.saveScrollPosition()};return pt.addEventListener("scroll",mt),it.current.addEventListener("pointerdown",ct),()=>{pt.removeEventListener("scroll",mt),it.current&&it.current.removeEventListener("pointerdown",ct),et.setVisible(!1)}},[]),reactExports.useEffect(()=>{et.isSelected()&&at.current&&(et.restoreScrollPosition(),at.current=!1)});const ct=()=>{const pt=et.getParent();pt instanceof TabSetNode&&(pt.isActive()||_e.doAction(Actions.setActiveTabset(pt.getId(),_e.getWindowId())))};et.setRect(st);const dt=_e.getClassName,ut={};st.styleWithPosition(ut);let ht=null;if(tt){if(et.setVisible(!0),document.hidden&&et.isEnablePopoutOverlay()){const pt={};st.styleWithPosition(pt),ht=jsxRuntimeExports.jsx("div",{style:pt,className:dt(CLASSES.FLEXLAYOUT__TAB_OVERLAY)})}}else ut.display="none",et.setVisible(!1);ot instanceof TabSetNode&&et.getModel().getMaximizedTabset(_e.getWindowId())!==void 0&&(ot.isMaximized()?ut.zIndex=10:ut.display="none"),ot instanceof BorderNode&&(ot.isShowing()||(ut.display="none"));let ft=dt(CLASSES.FLEXLAYOUT__TAB);return ot instanceof BorderNode&&(ft+=" "+dt(CLASSES.FLEXLAYOUT__TAB_BORDER),ft+=" "+dt(CLASSES.FLEXLAYOUT__TAB_BORDER_+ot.getLocation().getName())),et.getContentClassName()!==void 0&&(ft+=" "+et.getContentClassName()),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ht,jsxRuntimeExports.jsx("div",{ref:it,style:ut,className:ft,"data-layout-path":nt})]})};class ErrorBoundary extends reactExports.Component{constructor(_e){super(_e),__publicField(this,"retry",()=>{this.setState({hasError:!1})}),this.state={hasError:!1}}static getDerivedStateFromError(_e){return{hasError:!0}}componentDidCatch(_e,tt){console.debug(_e),console.debug(tt)}render(){return this.state.hasError?jsxRuntimeExports.jsx("div",{className:CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER,children:jsxRuntimeExports.jsx("div",{className:CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTENT,children:jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[this.props.message,jsxRuntimeExports.jsx("p",{children:jsxRuntimeExports.jsx("button",{onClick:this.retry,children:this.props.retryText})})]})})}):this.props.children}}const SizeTracker=reactExports.memo(({layout:rt,node:_e})=>jsxRuntimeExports.jsx(ErrorBoundary,{message:rt.i18nName(I18nLabel.Error_rendering_component),retryText:rt.i18nName(I18nLabel.Error_rendering_component_retry),children:rt.props.factory(_e)}),arePropsEqual);function arePropsEqual(rt,_e){return!(_e.visible&&(!rt.rect.equalSize(_e.rect)||rt.forceRevision!==_e.forceRevision||rt.tabsRevision!==_e.tabsRevision))}const _LayoutInternal=class _r extends reactExports.Component{constructor(_e){super(_e),__publicField(this,"selfRef"),__publicField(this,"moveablesRef"),__publicField(this,"findBorderBarSizeRef"),__publicField(this,"mainRef"),__publicField(this,"previousModel"),__publicField(this,"orderedTabIds"),__publicField(this,"orderedTabMoveableIds"),__publicField(this,"moveableElementMap",new Map),__publicField(this,"dropInfo"),__publicField(this,"outlineDiv"),__publicField(this,"currentDocument"),__publicField(this,"currentWindow"),__publicField(this,"supportsPopout"),__publicField(this,"popoutURL"),__publicField(this,"icons"),__publicField(this,"resizeObserver"),__publicField(this,"dragEnterCount",0),__publicField(this,"dragging",!1),__publicField(this,"windowId"),__publicField(this,"layoutWindow"),__publicField(this,"mainLayout"),__publicField(this,"isMainWindow"),__publicField(this,"isDraggingOverWindow"),__publicField(this,"styleObserver"),__publicField(this,"popoutWindowName"),__publicField(this,"updateLayoutMetrics",()=>{if(this.findBorderBarSizeRef.current){const tt=this.findBorderBarSizeRef.current.getBoundingClientRect().height;tt!==this.state.calculatedBorderBarSize&&this.setState({calculatedBorderBarSize:tt})}}),__publicField(this,"onModelChange",tt=>{this.redrawInternal("model change"),this.props.onModelChange&&this.props.onModelChange(this.props.model,tt)}),__publicField(this,"updateRect",()=>{if(this.selfRef.current){const tt=Rect.fromDomRect(this.selfRef.current.getBoundingClientRect());!tt.equals(this.state.rect)&&tt.width!==0&&tt.height!==0&&(this.setState({rect:tt}),this.windowId!==Model.MAIN_WINDOW_ID&&this.redrawInternal("rect updated"))}}),__publicField(this,"getClassName",tt=>this.props.classNameMapper===void 0?tt:this.props.classNameMapper(tt)),__publicField(this,"onCloseWindow",tt=>{this.doAction(Actions.closeWindow(tt.windowId))}),__publicField(this,"onSetWindow",(tt,et)=>{}),__publicField(this,"showControlInPortal",(tt,et)=>{const nt=reactDomExports.createPortal(tt,et);this.setState({portal:nt})}),__publicField(this,"hideControlInPortal",()=>{this.setState({portal:void 0})}),__publicField(this,"getIcons",()=>this.icons),__publicField(this,"setDragNode",(tt,et)=>{if(_r.dragState=new DragState(this.mainLayout,"internal",et,void 0,void 0),tt.dataTransfer.setData("text/plain","--flexlayout--"),tt.dataTransfer.effectAllowed="copyMove",tt.dataTransfer.dropEffect="move",this.dragEnterCount=0,et instanceof TabSetNode){let nt=!1,it=this.i18nName(I18nLabel.Move_Tabset);if(et.getChildren().length>0&&(it=this.i18nName(I18nLabel.Move_Tabs).replace("?",String(et.getChildren().length))),this.props.onRenderDragRect){const at=this.props.onRenderDragRect(it,et,void 0);at&&(this.setDragComponent(tt,at,10,10),nt=!0)}nt||this.setDragComponent(tt,it,10,10)}else{const it=tt.target.getBoundingClientRect(),at=tt.clientX-it.left,ot=tt.clientY-it.top,st=et==null?void 0:et.getParent(),ct=st instanceof BorderNode&&st.getOrientation()===Orientation.HORZ,dt=ct?10:at,ut=ct?10:ot;let ht=!1;if(this.props.onRenderDragRect){const ft=jsxRuntimeExports.jsx(TabButtonStamp,{layout:this,node:et},et.getId()),pt=this.props.onRenderDragRect(ft,et,void 0);pt&&(this.setDragComponent(tt,pt,dt,ut),ht=!0)}ht||(isSafari()?this.setDragComponent(tt,jsxRuntimeExports.jsx(TabButtonStamp,{node:et,layout:this}),dt,ut):tt.dataTransfer.setDragImage(et.getTabStamp(),dt,ut))}}),__publicField(this,"onDragEnterRaw",tt=>{this.dragEnterCount++,this.dragEnterCount===1&&this.onDragEnter(tt)}),__publicField(this,"onDragLeaveRaw",tt=>{this.dragEnterCount--,this.dragEnterCount===0&&this.onDragLeave(tt)}),__publicField(this,"onDragEnter",tt=>{if(!_r.dragState&&this.props.onExternalDrag){const et=this.props.onExternalDrag(tt);if(et){const nt=TabNode.fromJson(et.json,this.props.model,!1);_r.dragState=new DragState(this.mainLayout,"external",nt,et.json,et.onDrop)}}if(_r.dragState){if(this.windowId!==Model.MAIN_WINDOW_ID&&_r.dragState.mainLayout===this.mainLayout&&_r.dragState.mainLayout.setDraggingOverWindow(!0),_r.dragState.mainLayout!==this.mainLayout)return;tt.preventDefault(),this.dropInfo=void 0;const et=this.selfRef.current;this.outlineDiv=this.currentDocument.createElement("div"),this.outlineDiv.className=this.getClassName(CLASSES.FLEXLAYOUT__OUTLINE_RECT),this.outlineDiv.style.visibility="hidden";const nt=this.props.model.getAttribute("tabDragSpeed");this.outlineDiv.style.transition=`top ${nt}s, left ${nt}s, width ${nt}s, height ${nt}s`,et.appendChild(this.outlineDiv),this.dragging=!0,this.showOverlay(!0),!this.isDraggingOverWindow&&this.props.model.getMaximizedTabset(this.windowId)===void 0&&this.setState({showEdges:this.props.model.isEnableEdgeDock()});const it=this.selfRef.current.getBoundingClientRect();new Rect(tt.clientX-it.left,tt.clientY-it.top,1,1).positionElement(this.outlineDiv)}}),__publicField(this,"onDragOver",tt=>{var et;if(this.dragging&&!this.isDraggingOverWindow){tt.preventDefault();const nt=(et=this.selfRef.current)==null?void 0:et.getBoundingClientRect(),it={x:tt.clientX-((nt==null?void 0:nt.left)??0),y:tt.clientY-((nt==null?void 0:nt.top)??0)};this.checkForBorderToShow(it.x,it.y);const at=this.props.model.findDropTargetNode(this.windowId,_r.dragState.dragNode,it.x,it.y);at&&(this.dropInfo=at,this.outlineDiv&&(this.outlineDiv.className=this.getClassName(at.className),at.rect.positionElement(this.outlineDiv),this.outlineDiv.style.visibility="visible"))}}),__publicField(this,"onDragLeave",tt=>{this.dragging&&(this.windowId!==Model.MAIN_WINDOW_ID&&_r.dragState.mainLayout.setDraggingOverWindow(!1),this.clearDragLocal())}),__publicField(this,"onDrop",tt=>{if(this.dragging){tt.preventDefault();const et=_r.dragState;if(this.dropInfo)if(et.dragJson!==void 0){const nt=this.doAction(Actions.addNode(et.dragJson,this.dropInfo.node.getId(),this.dropInfo.location,this.dropInfo.index));et.fnNewNodeDropped!==void 0&&et.fnNewNodeDropped(nt,tt)}else et.dragNode!==void 0&&this.doAction(Actions.moveNode(et.dragNode.getId(),this.dropInfo.node.getId(),this.dropInfo.location,this.dropInfo.index));this.mainLayout.clearDragMain()}this.dragEnterCount=0}),this.orderedTabIds=[],this.orderedTabMoveableIds=[],this.selfRef=reactExports.createRef(),this.moveablesRef=reactExports.createRef(),this.mainRef=reactExports.createRef(),this.findBorderBarSizeRef=reactExports.createRef(),this.supportsPopout=_e.supportsPopout!==void 0?_e.supportsPopout:defaultSupportsPopout,this.popoutURL=_e.popoutURL?_e.popoutURL:"popout.html",this.icons={...defaultIcons,..._e.icons},this.windowId=_e.windowId?_e.windowId:Model.MAIN_WINDOW_ID,this.mainLayout=this.props.mainLayout?this.props.mainLayout:this,this.isDraggingOverWindow=!1,this.layoutWindow=this.props.model.getwindowsMap().get(this.windowId),this.layoutWindow.layout=this,this.popoutWindowName=this.props.popoutWindowName||"Popout Window",this.state={rect:Rect.empty(),editingTab:void 0,showEdges:!1,showOverlay:!1,calculatedBorderBarSize:29,layoutRevision:0,forceRevision:0,showHiddenBorder:DockLocation.CENTER},this.isMainWindow=this.windowId===Model.MAIN_WINDOW_ID}componentDidMount(){if(this.updateRect(),this.currentDocument=this.selfRef.current.ownerDocument,this.currentWindow=this.currentDocument.defaultView,this.layoutWindow.window=this.currentWindow,this.layoutWindow.toScreenRectFunction=_e=>this.getScreenRect(_e),this.resizeObserver=new ResizeObserver(_e=>{requestAnimationFrame(()=>{this.updateRect()})}),this.selfRef.current&&this.resizeObserver.observe(this.selfRef.current),this.isMainWindow)this.props.model.addChangeListener(this.onModelChange),this.updateLayoutMetrics();else{this.currentWindow.addEventListener("resize",()=>{this.updateRect()});const _e=this.props.mainLayout.getRootDiv(),tt=this.selfRef.current;copyInlineStyles(_e,tt),this.styleObserver=new MutationObserver(()=>{copyInlineStyles(_e,tt)&&this.redraw("mutation observer")}),this.styleObserver.observe(_e,{attributeFilter:["style"]})}document.addEventListener("visibilitychange",()=>{for(const[_e,tt]of this.props.model.getwindowsMap())tt.layout&&this.redraw("visibility change")})}componentDidUpdate(){this.currentDocument=this.selfRef.current.ownerDocument,this.currentWindow=this.currentDocument.defaultView,this.isMainWindow&&(this.props.model!==this.previousModel&&(this.previousModel!==void 0&&this.previousModel.removeChangeListener(this.onModelChange),this.props.model.getwindowsMap().get(this.windowId).layout=this,this.props.model.addChangeListener(this.onModelChange),this.layoutWindow=this.props.model.getwindowsMap().get(this.windowId),this.layoutWindow.layout=this,this.layoutWindow.toScreenRectFunction=_e=>this.getScreenRect(_e),this.previousModel=this.props.model,this.tidyMoveablesMap()),this.updateLayoutMetrics())}componentWillUnmount(){var _e,tt;this.selfRef.current&&((_e=this.resizeObserver)==null||_e.unobserve(this.selfRef.current)),this.isMainWindow&&this.props.model.removeChangeListener(this.onModelChange),(tt=this.styleObserver)==null||tt.disconnect()}render(){if(!this.selfRef.current)return jsxRuntimeExports.jsxs("div",{ref:this.selfRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT),children:[jsxRuntimeExports.jsx("div",{ref:this.moveablesRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MOVEABLES)},"__moveables__"),this.renderMetricsElements()]});const _e=this.props.model;_e.getRoot(this.windowId).calcMinMaxSize(),_e.getRoot(this.windowId).setPaths(""),_e.getBorderSet().setPaths();const tt=this.renderLayout(),et=this.renderBorders(tt),nt=this.renderTabs(),it=this.reorderComponents(nt,this.orderedTabIds);let at=null,ot=null,st=null,ct=null;if(this.isMainWindow){at=this.renderWindows(),ct=this.renderMetricsElements();const dt=this.renderTabMoveables();ot=this.reorderComponents(dt,this.orderedTabMoveableIds),st=jsxRuntimeExports.jsx("div",{className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_TAB_STAMPS),children:this.renderTabStamps()},"__tabStamps__")}return jsxRuntimeExports.jsxs("div",{ref:this.selfRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT),onDragEnter:this.onDragEnterRaw,onDragLeave:this.onDragLeaveRaw,onDragOver:this.onDragOver,onDrop:this.onDrop,children:[jsxRuntimeExports.jsx("div",{ref:this.moveablesRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MOVEABLES)},"__moveables__"),ct,jsxRuntimeExports.jsx(Overlay,{layout:this,show:this.state.showOverlay},"__overlay__"),et,it,ot,st,this.state.portal,at]})}renderBorders(_e){const tt=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MAIN),et=this.props.model.getBorderSet().getBorderMap();if(this.isMainWindow&&et.size>0){_e=jsxRuntimeExports.jsx("div",{className:tt,ref:this.mainRef,children:_e});const nt=new Map,it=new Map;for(const[st,ct]of DockLocation.values){const dt=et.get(ct);dt&&dt.isShowing()&&(!dt.isAutoHide()||dt.isAutoHide()&&(dt.getChildren().length>0||this.state.showHiddenBorder===ct))&&(nt.set(ct,jsxRuntimeExports.jsx(BorderTabSet,{layout:this,border:dt,size:this.state.calculatedBorderBarSize})),it.set(ct,jsxRuntimeExports.jsx(BorderTab,{layout:this,border:dt,show:dt.getSelected()!==-1})))}const at=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER),ot=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER_INNER);if(this.props.model.getBorderSet().getLayoutHorizontal()){const st=jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[it.get(DockLocation.TOP),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[it.get(DockLocation.LEFT),_e,it.get(DockLocation.RIGHT)]}),it.get(DockLocation.BOTTOM)]});return jsxRuntimeExports.jsxs("div",{className:at,style:{flexDirection:"column"},children:[nt.get(DockLocation.TOP),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[nt.get(DockLocation.LEFT),st,nt.get(DockLocation.RIGHT)]}),nt.get(DockLocation.BOTTOM)]})}else{const st=jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[it.get(DockLocation.LEFT),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[it.get(DockLocation.TOP),_e,it.get(DockLocation.BOTTOM)]}),it.get(DockLocation.RIGHT)]});return jsxRuntimeExports.jsxs("div",{className:at,style:{flexDirection:"row"},children:[nt.get(DockLocation.LEFT),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[nt.get(DockLocation.TOP),st,nt.get(DockLocation.BOTTOM)]}),nt.get(DockLocation.RIGHT)]})}}else return jsxRuntimeExports.jsx("div",{className:tt,ref:this.mainRef,style:{position:"absolute",top:0,left:0,bottom:0,right:0,display:"flex"},children:_e})}renderLayout(){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Row,{layout:this,node:this.props.model.getRoot(this.windowId)},"__row__"),this.renderEdgeIndicators()]})}renderEdgeIndicators(){const _e=[],tt=this.icons.edgeArrow;if(this.state.showEdges){const et=this.props.model.getRoot(this.windowId).getRect(),nt=edgeRectLength,it=edgeRectWidth,at=edgeRectLength/2,ot=this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT),st=50;_e.push(jsxRuntimeExports.jsx("div",{style:{top:0,left:et.width/2-at,width:nt,height:it,borderBottomLeftRadius:st,borderBottomRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_TOP),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(180deg)"},children:tt})},"North")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height/2-at,left:0,width:it,height:nt,borderTopRightRadius:st,borderBottomRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_LEFT),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(90deg)"},children:tt})},"West")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height-it,left:et.width/2-at,width:nt,height:it,borderTopLeftRadius:st,borderTopRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_BOTTOM),children:jsxRuntimeExports.jsx("div",{children:tt})},"South")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height/2-at,left:et.width-it,width:it,height:nt,borderTopLeftRadius:st,borderBottomLeftRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_RIGHT),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(-90deg)"},children:tt})},"East"))}return _e}renderWindows(){const _e=[];if(this.supportsPopout){const tt=this.props.model.getwindowsMap();let et=1;for(const[nt,it]of tt)nt!==Model.MAIN_WINDOW_ID&&(_e.push(jsxRuntimeExports.jsx(PopoutWindow,{layout:this,title:this.popoutWindowName+" "+et,layoutWindow:it,url:this.popoutURL+"?id="+nt,onSetWindow:this.onSetWindow,onCloseWindow:this.onCloseWindow,children:jsxRuntimeExports.jsx("div",{className:this.props.popoutClassName,children:jsxRuntimeExports.jsx(_r,{...this.props,windowId:nt,mainLayout:this})})},nt)),et++)}return _e}renderTabMoveables(){const _e=new Map;return this.props.model.visitNodes(tt=>{if(tt instanceof TabNode){const et=tt,nt=this.getMoveableElement(et.getId());et.setMoveableElement(nt);const it=et.isSelected(),at=et.getParent().getContentRect(),ot=it||!et.isEnableRenderOnDemand(),st=et.isRendered()||ot&&at.width>0&&at.height>0;if(st){const ct=et.getId()+(et.isEnableWindowReMount()?et.getWindowId():"");_e.set(tt.getId(),reactDomExports.createPortal(jsxRuntimeExports.jsx(SizeTracker,{layout:this,node:et,rect:at,visible:ot,forceRevision:this.state.forceRevision,tabsRevision:this.props.renderRevision},ct),nt,ct)),et.setRendered(st)}}}),_e}renderTabStamps(){const _e=[];return this.props.model.visitNodes(tt=>{if(tt instanceof TabNode){const et=tt;_e.push(jsxRuntimeExports.jsx(DragContainer,{layout:this,node:et},et.getId()))}}),_e}renderTabs(){const _e=new Map;return this.props.model.visitWindowNodes(this.windowId,tt=>{if(tt instanceof TabNode){const et=tt,nt=et.isSelected(),it=et.getPath();(et.isRendered()||nt||!et.isEnableRenderOnDemand())&&_e.set(et.getId(),jsxRuntimeExports.jsx(Tab,{layout:this,path:it,node:et,selected:nt},et.getId()))}}),_e}renderMetricsElements(){return jsxRuntimeExports.jsx("div",{ref:this.findBorderBarSizeRef,className:this.getClassName(CLASSES.FLEXLAYOUT__BORDER_SIZER),children:"FindBorderBarSize"},"findBorderBarSize")}checkForBorderToShow(_e,tt){const et=this.getBoundingClientRect(this.mainRef.current),nt=et.getCenter(),it=edgeRectWidth,at=edgeRectLength/2;let ot=!1;this.props.model.isEnableEdgeDock()&&this.state.showHiddenBorder===DockLocation.CENTER&&(tt>nt.y-at&&tt<nt.y+at||_e>nt.x-at&&_e<nt.x+at)&&(ot=!0);let st=DockLocation.CENTER;ot||(_e<=et.x+it?st=DockLocation.LEFT:_e>=et.getRight()-it?st=DockLocation.RIGHT:tt<=et.y+it?st=DockLocation.TOP:tt>=et.getBottom()-it&&(st=DockLocation.BOTTOM)),st!==this.state.showHiddenBorder&&this.setState({showHiddenBorder:st})}tidyMoveablesMap(){const _e=new Map;this.props.model.visitNodes((tt,et)=>{tt instanceof TabNode&&_e.set(tt.getId(),tt)});for(const[tt,et]of this.moveableElementMap)_e.has(tt)||(et.remove(),this.moveableElementMap.delete(tt))}reorderComponents(_e,tt){const et=[],nt=new Set;let it=[];for(const at of tt)_e.get(at)&&(et.push(at),nt.add(at));tt.splice(0,tt.length,...et);for(const[at,ot]of _e)nt.has(at)||tt.push(at);return it=tt.map(at=>_e.get(at)),it}redraw(_e){this.mainLayout.setState((tt,et)=>({forceRevision:tt.forceRevision+1}))}redrawInternal(_e){this.mainLayout.setState((tt,et)=>({layoutRevision:tt.layoutRevision+1}))}doAction(_e){if(this.props.onAction!==void 0){const tt=this.props.onAction(_e);return tt!==void 0?this.props.model.doAction(tt):void 0}else return this.props.model.doAction(_e)}getBoundingClientRect(_e){const tt=this.getDomRect();return tt?Rect.getBoundingClientRect(_e).relativeTo(tt):Rect.empty()}getMoveableContainer(){return this.moveablesRef.current}getMoveableElement(_e){let tt=this.moveableElementMap.get(_e);return tt===void 0&&(tt=document.createElement("div"),this.moveablesRef.current.appendChild(tt),tt.className=CLASSES.FLEXLAYOUT__TAB_MOVEABLE,this.moveableElementMap.set(_e,tt)),tt}getMainLayout(){return this.mainLayout}getCurrentDocument(){return this.currentDocument}getDomRect(){return this.selfRef.current?Rect.fromDomRect(this.selfRef.current.getBoundingClientRect()):Rect.empty()}getWindowId(){return this.windowId}getRootDiv(){return this.selfRef.current}getMainElement(){return this.mainRef.current}getFactory(){return this.props.factory}isSupportsPopout(){return this.supportsPopout}isRealtimeResize(){return this.props.realtimeResize??!1}getPopoutURL(){return this.popoutURL}setEditingTab(_e){this.setState({editingTab:_e})}getEditingTab(){return this.state.editingTab}getModel(){return this.props.model}getScreenRect(_e){const tt=_e.clone(),et=this.getDomRect(),nt=60,it=2;return tt.x=this.currentWindow.screenX+this.currentWindow.scrollX+it/2+et.x+tt.x,tt.y=this.currentWindow.screenY+this.currentWindow.scrollY+(nt-it/2)+et.y+tt.y,tt.height+=nt,tt.width+=it,tt}addTabToTabSet(_e,tt){if(this.props.model.getNodeById(_e)!==void 0)return this.doAction(Actions.addNode(tt,_e,DockLocation.CENTER,-1))}addTabToActiveTabSet(_e){const tt=this.props.model.getActiveTabset(this.windowId);if(tt!==void 0)return this.doAction(Actions.addNode(_e,tt.getId(),DockLocation.CENTER,-1))}maximize(_e){this.doAction(Actions.maximizeToggle(_e.getId(),this.getWindowId()))}customizeTab(_e,tt){this.props.onRenderTab&&this.props.onRenderTab(_e,tt)}customizeTabSet(_e,tt){this.props.onRenderTabSet&&this.props.onRenderTabSet(_e,tt)}i18nName(_e,tt){let et;return this.props.i18nMapper&&(et=this.props.i18nMapper(_e,tt)),et===void 0&&(et=_e+(tt===void 0?"":tt)),et}getShowOverflowMenu(){return this.props.onShowOverflowMenu}getTabSetPlaceHolderCallback(){return this.props.onTabSetPlaceHolder}showContextMenu(_e,tt){this.props.onContextMenu&&this.props.onContextMenu(_e,tt)}auxMouseClick(_e,tt){this.props.onAuxMouseClick&&this.props.onAuxMouseClick(_e,tt)}showOverlay(_e){this.setState({showOverlay:_e}),enablePointerOnIFrames(!_e,this.currentDocument)}addTabWithDragAndDrop(_e,tt,et){const nt=TabNode.fromJson(tt,this.props.model,!1);_r.dragState=new DragState(this.mainLayout,"add",nt,tt,et)}moveTabWithDragAndDrop(_e,tt){this.setDragNode(_e,tt)}setDragComponent(_e,tt,et,nt){const it=jsxRuntimeExports.jsx("div",{style:{position:"unset"},className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT)+" "+this.getClassName(CLASSES.FLEXLAYOUT__DRAG_RECT),children:tt}),at=this.currentDocument.createElement("div");at.setAttribute("data-layout-path","/drag-rectangle"),at.style.position="absolute",at.style.left="-10000px",at.style.top="-10000px",this.currentDocument.body.appendChild(at),createRoot(at).render(it),_e.dataTransfer.setDragImage(at,et,nt),setTimeout(()=>{this.currentDocument.body.removeChild(at)},0)}setDraggingOverWindow(_e){this.isDraggingOverWindow!==_e&&(this.outlineDiv&&(this.outlineDiv.style.visibility=_e?"hidden":"visible"),_e?this.setState({showEdges:!1}):this.props.model.getMaximizedTabset(this.windowId)===void 0&&this.setState({showEdges:this.props.model.isEnableEdgeDock()}),this.isDraggingOverWindow=_e)}clearDragMain(){_r.dragState=void 0,this.windowId===Model.MAIN_WINDOW_ID&&(this.isDraggingOverWindow=!1);for(const[,_e]of this.props.model.getwindowsMap())_e.layout.clearDragLocal()}clearDragLocal(){this.setState({showEdges:!1}),this.showOverlay(!1),this.dragEnterCount=0,this.dragging=!1,this.outlineDiv&&(this.selfRef.current.removeChild(this.outlineDiv),this.outlineDiv=void 0)}};__publicField(_LayoutInternal,"dragState");const defaultIcons={close:jsxRuntimeExports.jsx(CloseIcon,{}),closeTabset:jsxRuntimeExports.jsx(CloseIcon,{}),popout:jsxRuntimeExports.jsx(PopoutIcon,{}),maximize:jsxRuntimeExports.jsx(MaximizeIcon,{}),restore:jsxRuntimeExports.jsx(RestoreIcon,{}),more:jsxRuntimeExports.jsx(OverflowIcon,{}),edgeArrow:jsxRuntimeExports.jsx(EdgeIcon,{}),activeTabset:jsxRuntimeExports.jsx(AsterickIcon,{})},defaultSupportsPopout=isDesktop(),edgeRectLength=100,edgeRectWidth=10;class DragState{constructor(_e,tt,et,nt,it){__publicField(this,"mainLayout"),__publicField(this,"dragSource"),__publicField(this,"dragNode"),__publicField(this,"dragJson"),__publicField(this,"fnNewNodeDropped"),this.mainLayout=_e,this.dragSource=tt,this.dragNode=et,this.dragJson=nt,this.fnNewNodeDropped=it}}const log=logger$2("layout");class LayoutSystem extends RootStore{constructor(tt){super(tt);Rt(this,"CACHE_LAYOUT_KEY","galacean-layoutFile");Rt(this,"CACHE_SIDEBAR_KEY","galacean-sidebar");Rt(this,"CACHE_SIDEBAR_POSITION_KEY","galacean-sidebar-position");Rt(this,"CUSTOM_LAYOUT_KEY","galacean-custom-layoutFile");Rt(this,"EDITOR_MODE_KEY","galacean-editor-mode");Rt(this,"sidebarVisible",!0);Rt(this,"sidebarPosition","left");Rt(this,"editorMode","professional");Rt(this,"activePanel","");Rt(this,"flexLayoutModel",null);Rt(this,"controller");Rt(this,"tabs",null);Rt(this,"panels",[]);Rt(this,"panelContents",new Map);Rt(this,"customLayouts",[]);Rt(this,"initTabs",tt=>{this.tabs=tt});Rt(this,"activeTab",tt=>{const{flexLayoutModel:et}=this;et.doAction(Actions.selectTab(tt))});Rt(this,"saveController",tt=>{this.controller=tt});Rt(this,"setModel",tt=>{this.flexLayoutModel=tt});Rt(this,"addPanel",(tt,et)=>{this.panelContents.set(tt.id,et),this.panels.push(tt)});Rt(this,"closePanel",tt=>{const et=this.panels.findIndex(nt=>nt.id===tt);et>-1&&this.panels.splice(et,1)});Rt(this,"removePanel",tt=>{this.panelContents.delete(tt)});Rt(this,"resizePanel",(tt,et)=>{const nt=this.panels.find(it=>it.id===tt);nt&&(nt.size=et)});Rt(this,"toggleSidebar",tt=>{if(tt!==void 0){this.sidebarVisible=tt;return}this.sidebarVisible=!this.sidebarVisible,set(this.CACHE_SIDEBAR_KEY,this.sidebarVisible)});Rt(this,"setSidebarPosition",tt=>{this.sidebarPosition=tt,set(this.CACHE_SIDEBAR_POSITION_KEY,tt)});Rt(this,"setActivePanel",tt=>{this.activePanel=tt});Rt(this,"toggleEditorMode",tt=>{tt!==void 0?this.editorMode=tt:this.editorMode=this.editorMode==="simple"?"professional":"simple",set(this.EDITOR_MODE_KEY,this.editorMode)});Rt(this,"toggleTabVisibility",(tt,et)=>{const{flexLayoutModel:nt,tabs:it,controller:at}=this,ot=nt.getNodeById(tt),st=nt.getNodeById(it.Viewport.id),ct=["Assets","AnimatorController","AnimationClip"],dt=["Hierarchy"],ut=["Inspector"];if(ot&&et===!1){nt.doAction(Actions.deleteTab(ot.getId()));return}if(ot){if(ot.isVisible()&&nt.doAction(Actions.selectTab(tt)),et!==!1){const mt=it[tt];mt!=null&&mt.onVisibilityChange&&mt.onVisibilityChange(mt.id,!0)}return}let ht=nt.getRoot().getId(),ft=DockLocation.BOTTOM;function pt(mt,vt,_t){const yt=mt.find(bt=>nt.getNodeById(it[bt].id));if(yt){_t=nt.getNodeById(it[yt].id).getParent().getId(),at.addTabToTabSet(_t,it[tt]);return}nt.doAction(Actions.addNode(it[tt],_t,vt,0))}if(dt.includes(tt))return ft=DockLocation.LEFT,pt(dt,ft,ht);if(ut.includes(tt))return ft=DockLocation.RIGHT,pt(ut,ft,ht);if(ct.includes(tt))return ht=st.getParent().getId(),ft=DockLocation.BOTTOM,pt(ct,ft,ht)});Rt(this,"toggleSceneMaximize",()=>{const{flexLayoutModel:tt,tabs:et}=this,it=tt.getNodeById(et.Viewport.id).getParent();tt.doAction(Actions.maximizeToggle(it.getId()))});Rt(this,"cache",tt=>{log.info("save layout","verbose");const et=tt||this.flexLayoutModel;et&&set(this.CACHE_LAYOUT_KEY,et.toJson())});Rt(this,"addCustomLayout",async tt=>{const et={name:tt,layout:this.flexLayoutModel.toJson()};await get(this.CUSTOM_LAYOUT_KEY)?update$1(this.CUSTOM_LAYOUT_KEY,it=>[...it,et]):set(this.CUSTOM_LAYOUT_KEY,[et]),this.customLayouts.push(et)});Rt(this,"deleteCustomLayout",tt=>{update$1(this.CUSTOM_LAYOUT_KEY,et=>et.filter(nt=>nt.name!==tt)),this.customLayouts=this.customLayouts.filter(et=>et.name!==tt)});Rt(this,"clearCacheLayout",async()=>{await del(this.CACHE_LAYOUT_KEY),await del(this.CACHE_SIDEBAR_KEY),location.reload()});makeObservable(this,{sidebarVisible:observable,sidebarPosition:observable,editorMode:observable,activePanel:observable,customLayouts:observable.shallow,toggleSidebar:action,setSidebarPosition:action,toggleEditorMode:action,setActivePanel:action,flexLayoutModel:observable.ref,panels:observable,panelContents:observable.ref,removePanel:observable.ref})}async getCustomLayoutFromLocal(){const tt=await get(this.CUSTOM_LAYOUT_KEY);this.customLayouts=tt||[]}async initLayout(tt,et,nt){this.CACHE_LAYOUT_KEY=`${this.CACHE_LAYOUT_KEY}-${et}`,this.CACHE_SIDEBAR_KEY=`${this.CACHE_SIDEBAR_KEY}-${et}`,this.CACHE_SIDEBAR_POSITION_KEY=`${this.CACHE_SIDEBAR_POSITION_KEY}-${et}`,this.CUSTOM_LAYOUT_KEY=`${this.CUSTOM_LAYOUT_KEY}-${nt}`,this.EDITOR_MODE_KEY=`${this.EDITOR_MODE_KEY}-${et}`;const it=await this.loadCacheLayout(),at=await this.loadCacheSidebar(),ot=await this.loadCacheSidebarPosition(),st=await this.loadCacheEditorMode(),ct=it?{...it,global:tt.global}:tt;this.flexLayoutModel=Model.fromJson(ct),this.sidebarVisible=at??!0,this.sidebarPosition=ot??"left",this.editorMode=st??"professional",await this.getCustomLayoutFromLocal()}async loadCacheLayout(){try{return await get(this.CACHE_LAYOUT_KEY)}catch{return console.warn("Failed to load and parse layout from cache."),null}}async loadCacheSidebar(){try{return await get(this.CACHE_SIDEBAR_KEY)}catch{console.warn("Failed to load and parse layout from cache.");return}}async loadCacheSidebarPosition(){try{return await get(this.CACHE_SIDEBAR_POSITION_KEY)}catch{console.warn("Failed to load sidebar position from cache.");return}}async loadCacheEditorMode(){try{return await get(this.EDITOR_MODE_KEY)}catch{console.warn("Failed to load editor mode from cache.");return}}replaceLayout(tt){this.flexLayoutModel=Model.fromJson(tt),this.cache()}}class SelectionStore extends RootStore{constructor(tt){super(tt);Rt(this,"_logger",new TraceLogger("SelectionStore"));Rt(this,"_fallbackContext","scene");Rt(this,"_listeners",new Set);Rt(this,"_snapshot",null);Rt(this,"_sceneDisposer",null);Rt(this,"_assetDisposer",null);Rt(this,"_disposed",!1)}subscribe(tt){return this._disposed?()=>{}:(this._ensureSelectionBridge(),this._listeners.add(tt),()=>{this._listeners.delete(tt)})}getSnapshot(){return this._disposed?this._buildSnapshot():(this._ensureSelectionBridge(),this._snapshot||(this._snapshot=this._buildSnapshot()),this._snapshot)}get context(){return this.assetIds.size||this.lastSelectedAssetId?"asset":this.entityIds.size||this.lastSelectedEntityId?"entity":this._fallbackContext}get entityIds(){var tt;return new Set(Array.from(((tt=this.root.sceneUIStore)==null?void 0:tt.selectedKeys)??[]))}get assetIds(){var tt;return new Set(((tt=this.root.assetUIStore)==null?void 0:tt.pickedAssets)??[])}get lastSelectedEntityId(){var tt;return((tt=this.root.sceneUIStore)==null?void 0:tt.lastSelectedId)??null}get lastSelectedAssetId(){var tt;return((tt=this.root.assetUIStore)==null?void 0:tt.selectedAssetId)??null}_buildSnapshot(){return{context:this.context,entityIds:Array.from(this.entityIds),assetIds:Array.from(this.assetIds),lastSelectedEntityId:this.lastSelectedEntityId,lastSelectedAssetId:this.lastSelectedAssetId}}_notify(){this._snapshot=null,this._logger.info("_notify",{listeners:this._listeners.size,lastEntityId:this.lastSelectedEntityId});for(const tt of this._listeners)tt()}_ensureSelectionBridge(){this._disposed||this._sceneDisposer||(this.root.sceneUIStore&&(this._sceneDisposer=this.root.sceneUIStore.onSelectionChange(()=>this._notify())),this.root.assetUIStore&&(this._assetDisposer=this.root.assetUIStore.onSelectionChange(()=>this._notify())))}_disposeSelectionBridge(){var tt,et;(tt=this._sceneDisposer)==null||tt.call(this),(et=this._assetDisposer)==null||et.call(this),this._sceneDisposer=null,this._assetDisposer=null}dispose(){this._disposed||(this._disposed=!0,this._listeners.clear(),this._snapshot=null,this._disposeSelectionBridge())}get selectedEntities(){return this.root.sceneStore?Array.from(this.entityIds).map(tt=>this.root.sceneStore.getEntityModel(tt)).filter(Boolean):[]}get selectedAssets(){return this.root.assetStore?Array.from(this.assetIds).map(tt=>this.root.assetStore.assets[tt]).filter(Boolean):[]}get lastSelectedEntity(){return!this.lastSelectedEntityId||!this.root.sceneStore?null:this.root.sceneStore.getEntityModel(this.lastSelectedEntityId)??null}get selectedEntityReadModels(){return this.root.readModelStore?Array.from(this.entityIds).map(tt=>this.root.readModelStore.getEntity(tt)).filter(tt=>tt!==void 0):[]}get lastSelectedEntityReadModel(){return!this.lastSelectedEntityId||!this.root.readModelStore?null:this.root.readModelStore.getEntity(this.lastSelectedEntityId)??null}get lastSelectedAsset(){return!this.lastSelectedAssetId||!this.root.assetStore?null:this.root.assetStore.assets[this.lastSelectedAssetId]??null}selectEntity(tt,et=!1){var nt;this._fallbackContext="entity",typeof((nt=this.root.sceneStore)==null?void 0:nt.selectEntity)=="function"?this.root.sceneStore.selectEntity(tt,et):this.root.sceneUIStore&&(et||this.root.sceneUIStore.clearSelection(),this.root.sceneUIStore.selectEntity(tt,!0))}deselectEntity(tt){var et;(et=this.root.sceneUIStore)==null||et.deselectEntity(tt)}selectAsset(tt,et=!1){var nt,it,at,ot,st;if(this._fallbackContext="asset",et){const ct=[...((nt=this.root.assetUIStore)==null?void 0:nt.pickedAssets)??[]];ct.includes(tt)||ct.push(tt),(at=(it=this.root.assetStore)==null?void 0:it.selectAsset)==null||at.call(it,ct);return}(st=(ot=this.root.assetStore)==null?void 0:ot.selectAsset)==null||st.call(ot,tt)}deselectAsset(tt){if(!this.root.assetUIStore)return;const et=this.root.assetUIStore.pickedAssets.filter(it=>it!==tt),nt=this.root.assetUIStore.selectedAssetId===tt?et.at(-1)??null:this.root.assetUIStore.selectedAssetId;this.root.assetUIStore.setSelection(et,nt)}clearSelection(){var tt,et;(tt=this.root.sceneUIStore)==null||tt.clearSelection(),(et=this.root.assetUIStore)==null||et.clearSelect(),this._fallbackContext="scene",this._notify()}setContext(tt){this._fallbackContext=tt,this._notify()}}class EditorError extends Error{constructor(_e,tt,et,nt,it){super(nt),this.domain=_e,this.severity=tt,this.code=et,this.details=it,this.name="EditorError"}}var ProjectionErrorCode=(rt=>(rt.PARENT_NOT_FOUND="PROJECTION_PARENT_NOT_FOUND",rt.ENTITY_NOT_FOUND="PROJECTION_ENTITY_NOT_FOUND",rt.ROLLBACK_FAILED="PROJECTION_ROLLBACK_FAILED",rt.REBUILD_FAILED="PROJECTION_REBUILD_FAILED",rt))(ProjectionErrorCode||{});class ProjectionError extends EditorError{constructor(_e,tt,et){super("projection","recoverable",_e,tt,et),this.name="ProjectionError"}}var EffectsErrorCode=(rt=>(rt.DELETE_FAILED="EFFECTS_DELETE_FAILED",rt.CREATE_FAILED="EFFECTS_CREATE_FAILED",rt.UPDATE_FAILED="EFFECTS_UPDATE_FAILED",rt))(EffectsErrorCode||{});class EffectsError extends EditorError{constructor(_e,tt,et){super("effects","warning",_e,tt,et),this.name="EffectsError"}}const defaultComponentFactory=()=>null;function assertNeverEvent$2(rt){throw new Error(`EngineProjection: unhandled event ${rt.type}`)}class EngineProjection{constructor(_e,tt,et){Rt(this,"entityMap",new Map);Rt(this,"entityReverseMap",new WeakMap);Rt(this,"componentMap",new Map);Rt(this,"assetMap",new Map);Rt(this,"externalEntityIds",new Set);Rt(this,"graveyardEntities",new Map);Rt(this,"graveyardComponents",new Map);Rt(this,"componentFactory");Rt(this,"assetResolver",null);Rt(this,"sceneSettingAppliers",{"ambient/diffuseMode":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.diffuseMode=tt)},"ambient/diffuseSolidColor":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&this.applyStructuredValue(et,"diffuseSolidColor",tt)},"ambient/diffuseIntensity":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.diffuseIntensity=tt)},"ambient/specularMode":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.specularMode=tt)},"ambient/specularIntensity":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.specularIntensity=tt)},"background/mode":(_e,tt)=>{const et=this.getBackground(_e);et&&(et.mode=tt)},"background/color":(_e,tt)=>{const et=this.getBackground(_e);et&&this.applyStructuredValue(et,"solidColor",tt)},"background/texture":(_e,tt)=>{const et=this.getBackground(_e);et&&this.applyResolvedReference(et,"texture",tt)},"background/skyMaterial":(_e,tt)=>{const et=this.getBackgroundSky(_e);et&&this.applyResolvedReference(et,"material",tt)},"background/skyMesh":(_e,tt)=>{const et=this.getBackgroundSky(_e);et&&this.applyResolvedReference(et,"mesh",tt)},"background/textureFillMode":(_e,tt)=>{const et=this.getBackground(_e);et&&(et.textureFillMode=tt)},"shadow/castShadows":(_e,tt)=>{_e.castShadows=tt},"shadow/enableTransparentShadow":(_e,tt)=>{_e.enableTransparentShadow=tt},"shadow/shadowResolution":(_e,tt)=>{_e.shadowResolution=tt},"shadow/shadowDistance":(_e,tt)=>{_e.shadowDistance=tt},"shadow/shadowCascades":(_e,tt)=>{_e.shadowCascades=tt},"shadow/shadowTwoCascadeSplits":(_e,tt)=>{_e.shadowTwoCascadeSplits=tt},"shadow/shadowFourCascadeSplits":(_e,tt)=>{this.applyStructuredValue(_e,"shadowFourCascadeSplits",tt)},"shadow/shadowFadeBorder":(_e,tt)=>{_e.shadowFadeBorder=tt},"fog/mode":(_e,tt)=>{_e.fogMode=tt},"fog/color":(_e,tt)=>{this.applyStructuredValue(_e,"fogColor",tt)},"fog/density":(_e,tt)=>{_e.fogDensity=tt},"fog/start":(_e,tt)=>{_e.fogStart=tt},"fog/end":(_e,tt)=>{_e.fogEnd=tt},"ambientOcclusion/enabled":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.enabled=tt)},"ambientOcclusion/quality":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.quality=tt)},"ambientOcclusion/intensity":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.intensity=tt)},"ambientOcclusion/radius":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.radius=tt)},"ambientOcclusion/bias":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.bias=tt)},"ambientOcclusion/power":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.power=tt)},"ambientOcclusion/bilateralThreshold":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.bilateralThreshold=tt)},"ambientOcclusion/minHorizonAngle":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.minHorizonAngle=tt)}});Rt(this,"_canRedo");this._scene=_e,this.componentFactory=tt??defaultComponentFactory,this._canRedo=et??(()=>!1)}get scene(){return this._scene}setComponentFactory(_e){this.componentFactory=_e}flushDeferredComponentProps(){var _e,tt;(tt=(_e=this.componentFactory).flushDeferred)==null||tt.call(_e)}rebindAssetReferences(_e){var tt,et,nt,it;(et=(tt=this.componentFactory).rebindAssetReferences)==null||et.call(tt,_e),(it=(nt=this.componentFactory).flushDeferred)==null||it.call(nt)}setAssetResolver(_e){this.assetResolver=_e}resolveRef(_e){if(_e==null||typeof _e!="object"||!("refId"in _e))return _e;if(!this.assetResolver)return;const tt=_e,et=tt.key?`${tt.refId}-${tt.key}`:tt.refId,nt=this.assetResolver(et);return nt!==null?nt:void 0}setScene(_e){if(this._scene===_e)return;this._scene=_e;const tt=[];for(const et of this.entityMap.values())et.parent||tt.push(et);for(const et of tt)_e.addRootEntity(et)}apply(_e,tt){tt&&!isUndoRedoCommand(tt)&&!this._canRedo()&&this.clearGraveyard(),_e!=null&&_e.length&&this.applyEvents(_e)}applyEvents(_e){for(const tt of _e)switch(tt.type){case"EntityCreated":this.createEngineEntity(tt.entityId,tt.entity);break;case"EntityUpdated":this.applyEntityUpdatedEvent(tt);break;case"EntityMoved":this.applyEntityMovedEvent(tt);break;case"EntityDeleted":this.applyEntityDeletedEvent(tt);break;case"ComponentAdded":this.applyComponentAddedEvent(tt);break;case"ComponentUpdated":this.applyComponentUpdatedEvent(tt);break;case"ComponentRemoved":this.destroyEngineComponent(tt.componentId);break;case"SceneSettingUpdated":this.applySceneSettingEvent(tt.settingPath,tt.value);break;case"AssetCreated":this.assetMap.set(tt.assetId,tt.asset);break;case"AssetUpdated":this.applyAssetUpdatedEvent(tt);break;case"AssetDeleted":this.assetMap.delete(tt.assetId);break;case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":case"PrefabOverrideChanged":break;default:assertNeverEvent$2(tt)}}applyEntityUpdatedEvent(_e){const tt=this.entityMap.get(_e.entityId);if(!tt)return;const{changes:et}=_e;if(et.name!==void 0&&(tt.name=et.name),et.isActive!==void 0&&(tt.isActive=et.isActive),et.layer!==void 0&&(tt.layer=et.layer),et.transform){const nt=et.transform;nt.position&&this.updateTransformProperty(tt,["position"],{x:nt.position.x??tt.transform.position.x,y:nt.position.y??tt.transform.position.y,z:nt.position.z??tt.transform.position.z}),nt.rotation&&this.updateTransformProperty(tt,["rotation"],{x:nt.rotation.x??tt.transform.rotation.x,y:nt.rotation.y??tt.transform.rotation.y,z:nt.rotation.z??tt.transform.rotation.z}),nt.scale&&this.updateTransformProperty(tt,["scale"],{x:nt.scale.x??tt.transform.scale.x,y:nt.scale.y??tt.transform.scale.y,z:nt.scale.z??tt.transform.scale.z})}}applyEntityMovedEvent(_e){const tt=this.entityMap.get(_e.entityId);tt&&(this.reparentEntity(tt,_e.parentId),tt.siblingIndex=_e.index)}applyEntityDeletedEvent(_e){for(const tt of[..._e.subtreeIds].reverse())this.destroyEngineEntity(tt)}applyComponentAddedEvent(_e){const tt=this.entityMap.get(_e.entityId);tt&&this.createEngineComponent(tt,_e.componentId,_e.component)}applyComponentUpdatedEvent(_e){for(const[tt,et]of Object.entries(_e.changes))this.updateComponentProperty(_e.componentId,tt,et)}applyAssetUpdatedEvent(_e){this.assetMap.set(_e.assetId,_e.asset);const tt=_e.previousAsset.meta??{},et=_e.asset.meta??{},nt=new Set([...Object.keys(tt),...Object.keys(et)]);for(const it of nt){const at=tt[it],ot=et[it];JSON.stringify(at)!==JSON.stringify(ot)&&this.projectAssetMetaToEngine(_e.assetId,it,ot)}}createEngineEntity(_e,tt){const et=this.graveyardEntities.get(_e);et&&(this.entityMap.set(_e,et),this.entityReverseMap.set(et,_e),this.externalEntityIds.add(_e),this.graveyardEntities.delete(_e));const nt=this.resolveParentEntity(_e,tt.parentId),it=this.entityMap.get(_e);if(it){if(this.externalEntityIds.has(_e)){const ot=it;ot.__editorExternalComponentClaimRevision=(ot.__editorExternalComponentClaimRevision??0)+1}if(nt)it.parent!==nt&&nt.addChild(it);else{const ot=!!it.parent;ot&&(it.parent=null),(ot||!it.scene||it.scene!==this.scene)&&this.scene.addRootEntity(it)}if(this.applyEntityState(it,tt),tt.components)for(const[ot,st]of Object.entries(tt.components))this.componentMap.has(ot)||this.createEngineComponent(it,ot,st);return}const at=nt?nt.createChild(tt.name):this.scene.createRootEntity(tt.name);if(this.applyEntityState(at,tt),this.entityMap.set(_e,at),this.entityReverseMap.set(at,_e),tt.components)for(const[ot,st]of Object.entries(tt.components))this.createEngineComponent(at,ot,st)}resolveParentEntity(_e,tt){if(!tt)return null;const et=this.entityMap.get(tt);if(!et)throw new ProjectionError(ProjectionErrorCode.PARENT_NOT_FOUND,`EngineProjection: parent entity "${tt}" not found when creating "${_e}".`,{entityId:_e,parentId:tt});return et}applyEntityState(_e,tt){_e.name=tt.name,_e.isActive=tt.isActive,_e.layer=tt.layer;const{position:et,rotation:nt,scale:it}=tt.transform;_e.transform.position.set(et.x,et.y,et.z),_e.transform.rotation.set(nt.x,nt.y,nt.z),_e.transform.scale.set(it.x,it.y,it.z)}destroyEngineEntity(_e){var nt,it;const tt=this.entityMap.get(_e);if(!tt)return;const et=this.externalEntityIds.has(_e);for(const[at,ot]of this.componentMap)ot.entity===tt&&((it=(nt=this.componentFactory).forgetComponentAssetReferences)==null||it.call(nt,ot),et&&this.addToGraveyard(_e,at,ot),this.componentMap.delete(at));if(et)tt.parent=null,tt.scene===this.scene&&this.scene.removeRootEntity(tt),this.graveyardEntities.set(_e,tt);else try{tt.destroy()}catch(at){console.warn("[EngineProjection] destroyEngineEntity failed:",at)}this.entityMap.delete(_e),this.externalEntityIds.delete(_e),tt&&this.entityReverseMap.delete(tt)}createEngineComponent(_e,tt,et){var at,ot;const nt=this.findEntityId(_e);if(nt){const st=this.graveyardComponents.get(nt);if(st!=null&&st.has(tt)){const ct=st.get(tt);ct.__editorComponentType=et.type;for(const[dt,ut]of Object.entries(et.props))(ot=(at=this.componentFactory).trackAssetReference)==null||ot.call(at,ct,et.type,dt,ut);this.componentMap.set(tt,ct),st.delete(tt),st.size===0&&this.graveyardComponents.delete(nt);return}}const it=this.componentFactory(_e,et.type,et.props);it&&(it.__editorComponentType=et.type,this.componentMap.set(tt,it))}findEntityId(_e){return this.entityReverseMap.get(_e)}destroyEngineComponent(_e){var nt,it;const tt=this.componentMap.get(_e);if(!tt)return;(it=(nt=this.componentFactory).forgetComponentAssetReferences)==null||it.call(nt,tt);const et=this.findEntityId(tt.entity);if(et&&this.externalEntityIds.has(et)){this.addToGraveyard(et,_e,tt),this.componentMap.delete(_e);return}tt.destroy(),this.componentMap.delete(_e)}addToGraveyard(_e,tt,et){let nt=this.graveyardComponents.get(_e);nt||(nt=new Map,this.graveyardComponents.set(_e,nt)),nt.set(tt,et)}clearGraveyard(){if(!(this.graveyardEntities.size===0&&this.graveyardComponents.size===0)){for(const _e of this.graveyardEntities.values())try{_e.destroy()}catch{}for(const _e of this.graveyardComponents.values())for(const tt of _e.values())try{tt.destroy()}catch{}this.graveyardEntities.clear(),this.graveyardComponents.clear()}}updateComponentProperty(_e,tt,et){var st,ct,dt,ut,ht;const nt=this.componentMap.get(_e);if(!nt)return;const it=nt.__editorComponentType;it&&((ct=(st=this.componentFactory).trackAssetReference)==null||ct.call(st,nt,it,tt,et));const at=et===void 0?void 0:this.resolveRef(et);if(et!==void 0&&at===void 0)return;const ot=it?(ht=(ut=(dt=this.componentFactory).getProxyMap)==null?void 0:ut.call(dt,it))==null?void 0:ht[tt]:void 0;if(ot&&typeof nt[ot]=="function"){nt[ot](at);return}if(tt in nt)try{nt[tt]=at}catch{}}reparentEntity(_e,tt){if(tt){const et=this.entityMap.get(tt);if(!et)throw new ProjectionError(ProjectionErrorCode.PARENT_NOT_FOUND,`EngineProjection: new parent "${tt}" not found for reparent.`,{parentId:tt});_e.parent=et}else _e.parent=null,this.scene.addRootEntity(_e)}updateTransformProperty(_e,tt,et){if(tt.length===0){const ot=et;_e.transform.position.set(ot.position.x,ot.position.y,ot.position.z),_e.transform.rotation.set(ot.rotation.x,ot.rotation.y,ot.rotation.z),_e.transform.scale.set(ot.scale.x,ot.scale.y,ot.scale.z);return}if(tt.length===1){const[ot]=tt,st=et;_e.transform[ot].set(st.x,st.y,st.z);return}const[nt,it]=tt,at=_e.transform[nt];if(at&&it in at){const ot={x:at.x,y:at.y,z:at.z};ot[it]=et,at.set(ot.x,ot.y,ot.z)}}projectAssetMetaToEngine(_e,tt,et){if(!this.assetResolver)return;const nt=this.assetResolver(_e);if(!(!nt||typeof nt!="object")&&tt in nt)try{nt[tt]=et}catch{}}applySceneSettingEvent(_e,tt){if(!isEngineProjectionSceneSettingPath(_e))return;const et=this.sceneSettingAppliers[_e];et(this._scene,tt)}applyStructuredValue(_e,tt,et){if(!et||typeof et!="object"){_e[tt]=et;return}const nt=_e[tt];if(nt&&typeof nt=="object"&&"set"in nt){const it=nt.set,at=et;"r"in at?it.call(nt,at.r,at.g,at.b,at.a):"x"in at&&it.call(nt,at.x,at.y,at.z)}else _e[tt]=et}applyResolvedReference(_e,tt,et){if(et==null){_e[tt]=et;return}const nt=this.resolveRef(et);nt!==void 0&&(_e[tt]=nt)}getAmbientLight(_e){return _e.ambientLight}getBackground(_e){return _e.background}getBackgroundSky(_e){var tt;return(tt=this.getBackground(_e))==null?void 0:tt.sky}getAmbientOcclusion(_e){return _e.ambientOcclusion}checkHealth(_e){const tt=new Set(Object.keys(_e.entities)),et=new Set(this.entityMap.keys()),nt=new Set(Object.keys(_e.assets)),it=new Set(this.assetMap.keys()),at=Array.from(tt).filter(dt=>!et.has(dt)),ot=Array.from(et).filter(dt=>!tt.has(dt)),st=Array.from(nt).filter(dt=>!it.has(dt)),ct=Array.from(it).filter(dt=>!nt.has(dt));return at.sort(),ot.sort(),st.sort(),ct.sort(),{healthy:at.length===0&&ot.length===0&&st.length===0&&ct.length===0,missingInEngine:at,orphanInEngine:ot,missingAssets:st,orphanAssets:ct}}getEntity(_e){return this.entityMap.get(_e)}getAsset(_e){return this.assetMap.get(_e)}getComponent(_e){return this.componentMap.get(_e)}setEntityRuntimeActive(_e,tt){const et=this.entityMap.get(_e);et&&(et.isActive=tt)}addEntityChild(_e,tt,et){const nt=this.entityMap.get(_e),it=this.entityMap.get(tt);nt&&it&&(et!==void 0?nt.addChild(et,it):nt.addChild(it))}removeEntityChild(_e,tt){const et=this.entityMap.get(_e),nt=this.entityMap.get(tt);et&&nt&&et.removeChild(nt)}getEntityIdByEngineObject(_e){return this.entityReverseMap.get(_e)}registerExternalEntity(_e,tt){this.entityMap.set(_e,tt),this.entityReverseMap.set(tt,_e),this.externalEntityIds.add(_e),tt.__editorExternalEntity=!0}reset(){var tt,et;for(const nt of this.componentMap.values()){const it=this.findEntityId(nt.entity);if(!(it&&this.externalEntityIds.has(it)))try{nt.destroy()}catch{}}this.componentMap.clear();const _e=new Map;for(const[nt,it]of this.entityMap){if(this.externalEntityIds.has(nt)){_e.set(nt,it);continue}try{it.destroy()}catch{}}this.entityMap=_e;for(const nt of this.graveyardEntities.values())try{nt.destroy()}catch{}this.graveyardEntities.clear(),this.graveyardComponents.clear(),this.assetMap.clear(),(et=(tt=this.componentFactory).clearAssetReferenceTracking)==null||et.call(tt)}rebuildFromState(_e){this.reset();const tt=new Set,et=nt=>{if(tt.has(nt))return;const it=_e.entities[nt];it&&(it.parentId&&!tt.has(it.parentId)&&et(it.parentId),this.createEngineEntity(nt,it),tt.add(nt))};for(const nt of _e.scene.rootEntityIds)et(nt);for(const nt of Object.keys(_e.entities))et(nt);for(const[nt,it]of Object.entries(_e.assets))this.assetMap.set(nt,it)}}function assertNeverEvent$1(rt){throw new Error(`EntityModelProjection: unhandled event ${rt.type}`)}const ENTITY_TRANSFORM_COMPONENT_TYPES=new Set(["Transform","UITransform"]);class EntityModelProjection{constructor(_e,tt){Rt(this,"_logger",new TraceLogger("EntityModelProjection"));this._getScene=_e,this._getEP=tt}apply(_e,tt){const et=this._getScene();et&&_e!=null&&_e.length&&this._applyEvents(_e,tt,et)}_applyEvents(_e,tt,et){for(const nt of _e)switch(nt.type){case"EntityCreated":this._handleEntityCreatedEvent(nt,et);break;case"EntityDeleted":for(const it of nt.subtreeIds)et.deleteEntityModel(it);break;case"EntityUpdated":this._handleEntityUpdatedEvent(nt,tt,et);break;case"ComponentAdded":this._applyComponentAdd(nt.entityId,nt.componentId,nt.component,et);break;case"ComponentUpdated":this._handleComponentUpdatedEvent(nt,et);break;case"ComponentRemoved":this._handleComponentRemovedEvent(nt.entityId,nt.componentId,et);break;case"EntityMoved":case"SceneSettingUpdated":case"AssetCreated":case"AssetUpdated":case"AssetDeleted":case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":break;case"PrefabOverrideChanged":this._handlePrefabOverrideChangedEvent(nt,et);break;default:assertNeverEvent$1(nt)}}_handleEntityCreatedEvent(_e,tt){const et=tt.getEntityModel(_e.entityId);if(et){this._logger.info("EntityCreated re-set existing",{entityId:_e.entityId}),tt.setEntityModel(_e.entityId,et),_e.entity.parentId&&tt.addEntityToParent&&tt.addEntityToParent(et,_e.entity.parentId);return}if(!tt.createEntity)return;this._logger.info("EntityCreated createEntity",{entityId:_e.entityId,name:_e.entity.name});const nt=tt.createEntity(_e.entity.name,_e.entityId);nt&&_e.entity.parentId&&tt.addEntityToParent&&tt.addEntityToParent(nt,_e.entity.parentId),nt&&this._initCreatedEntityModel(nt,_e.entityId)}_handleEntityUpdatedEvent(_e,tt,et){const nt=et.getEntityModel(_e.entityId);nt&&this._applyEntityUpdate(nt,_e,tt)}_applyComponentAdd(_e,tt,et,nt){const it=nt.getEntityModel(_e);it&&this._addComponentToModel(it,tt,et)}_handleComponentRemovedEvent(_e,tt,et){const nt=et.getEntityModel(_e);nt&&this._removeComponentFromModel(nt,tt)}_handleComponentUpdatedEvent(_e,tt){const et=tt.getEntityModel(_e.entityId);et&&this._applyComponentUpdate(et,_e)}_handlePrefabOverrideChangedEvent(_e,tt){var nt,it,at;if(!_e.entityId)return;const et=tt.getEntityModel(_e.entityId);if(et){if((nt=et.invalidateFromDomain)==null||nt.call(et),_e.bucket==="entityProps"){this._invalidateTransformComponents(et);return}if(!(_e.bucket!=="componentProps"&&_e.bucket!=="removedComponents"&&_e.bucket!=="addedComponents")){_e.bucket==="removedComponents"&&((it=et.syncRemovedComponentPlaceholdersFromDomain)==null||it.call(et));for(const ot of et.components??[])(at=ot.invalidateFromDomain)==null||at.call(ot)}}}_invalidateTransformComponents(_e){var tt;for(const et of _e.components??[])et.type&&ENTITY_TRANSFORM_COMPONENT_TYPES.has(et.type)&&((tt=et.invalidateFromDomain)==null||tt.call(et))}_addComponentToModel(_e,tt,et){var it,at,ot;const nt=(it=_e.getComponentByTypeName)==null?void 0:it.call(_e,et.type);nt&&nt.id!==tt&&((at=_e.removeComponentFromDomain)==null||at.call(_e,nt.id)),(ot=_e.addComponentFromDomain)==null||ot.call(_e,tt,et)}_removeComponentFromModel(_e,tt){var et;(et=_e.removeComponentFromDomain)==null||et.call(_e,tt)}_applyComponentUpdate(_e,tt){var nt,it,at;const et=(nt=_e.getComponentById)==null?void 0:nt.call(_e,tt.componentId);if(et){for(const[ot,st]of Object.entries(tt.changes))(it=et.applyPropertyFromDomain)==null||it.call(et,ot,st);(at=et.invalidateFromDomain)==null||at.call(et)}}_initCreatedEntityModel(_e,tt){var nt,it;const et=(nt=this._getEP())==null?void 0:nt.getEntity(tt);et&&((it=_e.initImmediate)==null||it.call(_e,et))}_applyEntityUpdate(_e,tt,et){var nt,it,at,ot;(nt=_e.invalidateFromDomain)==null||nt.call(_e),tt.changes.isLocked!==void 0&&((it=_e.applyLockedFromDomain)==null||it.call(_e,tt.changes.isLocked)),tt.changes.transform&&!et.has(tt.entityId)&&((ot=(at=_e.transform)==null?void 0:at.syncEngineToEditor)==null||ot.call(at))}}function assertNeverEvent(rt){throw new Error(`RuntimeProjection: unhandled event ${rt.type}`)}class RuntimeEntityCache{constructor(){Rt(this,"_models",new Map)}stash(_e,tt){this._models.set(_e,tt)}restore(_e){const tt=this._models.get(_e);return tt&&this._models.delete(_e),tt}clear(){this._models.clear()}}const NOOP_RUNTIME_BINDER_REGISTRY={detachEntityBinder:()=>{},restoreEntityBinder:()=>null,clearDetachedEntityBinders:()=>{}};class RuntimeProjection{constructor(_e,tt,et=NOOP_RUNTIME_BINDER_REGISTRY,nt=()=>!1){Rt(this,"_entityCache",new RuntimeEntityCache);Rt(this,"_logger",new TraceLogger("RuntimeProjection"));this._getScene=_e,this._getEP=tt,this._runtimeBinderRegistry=et,this._canRedo=nt}apply(_e,tt){const et=this._getScene(),nt=new Set;if(!et)return nt;const it=isUndoRedoCommand(tt);!it&&!this._canRedo()&&(this._entityCache.clear(),this._runtimeBinderRegistry.clearDetachedEntityBinders());const at=it?this._getEP():null;if(!(_e!=null&&_e.length))return nt;for(const ot of _e)switch(ot.type){case"EntityCreated":this._handleEntityCreated(ot.entityId,ot.entity,et,it,at,nt);break;case"EntityDeleted":for(const st of[...ot.subtreeIds].reverse())this._handleEntityDeleted(st,et);break;case"EntityUpdated":case"EntityMoved":case"ComponentAdded":case"ComponentUpdated":case"ComponentRemoved":case"SceneSettingUpdated":case"AssetCreated":case"AssetUpdated":case"AssetDeleted":case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":case"PrefabOverrideChanged":break;default:assertNeverEvent(ot)}return nt}reset(){this._entityCache.clear(),this._runtimeBinderRegistry.clearDetachedEntityBinders()}_handleEntityCreated(_e,tt,et,nt,it,at){nt&&this._restoreOrMaterialize(_e,tt,et,it,at)}_handleEntityDeleted(_e,tt){this._stashAndDetach(_e,tt)}_stashAndDetach(_e,tt){const et=tt.getEntityModel(_e);et&&(this._entityCache.stash(_e,et),this._runtimeBinderRegistry.detachEntityBinder(_e)),tt.deleteEntityModel(_e)}_restoreOrMaterialize(_e,tt,et,nt,it){var ct,dt,ut,ht;if(et.hasEntityModel(_e))return;const at=this._entityCache.restore(_e);if(at){this._runtimeBinderRegistry.restoreEntityBinder(_e),et.setEntityModel(_e,at),nt&&this._rebindRestoredEntity(at,nt),(ct=at.applyLockedFromDomain)==null||ct.call(at,tt.isLocked??!1),it.add(_e);return}this._runtimeBinderRegistry.restoreEntityBinder(_e);const ot=nt==null?void 0:nt.getEntity(_e);if(!ot){this._logger.warn("Skip cache-miss runtime restore: engine entity not found",{entityId:_e});return}if(!et.createEntity){this._logger.warn("Skip cache-miss runtime restore: scene.createEntity unavailable",{entityId:_e});return}const st=et.createEntity(tt.name,_e);if(this._hydrateCacheMissModel(st,tt),(dt=st.initImmediate)==null||dt.call(st,ot),tt.components)for(const[ft,pt]of Object.entries(tt.components))(ut=st.addComponentFromDomain)==null||ut.call(st,ft,pt);(ht=st.applyLockedFromDomain)==null||ht.call(st,tt.isLocked??!1),it.add(_e)}_rebindRestoredEntity(_e,tt){var nt,it,at,ot,st;const et=tt.getEntity(_e.id);et&&((nt=_e.rebindEngineObject)==null||nt.call(_e,et),_e.transform&&((at=(it=_e.transform).rebindEngineObject)==null||at.call(it,et.transform),(st=(ot=_e.transform).syncEngineToEditor)==null||st.call(ot)))}_hydrateCacheMissModel(_e,tt){_e.name=tt.name,_e.isActive=tt.isActive??!0}}class UIProjection{constructor(_e,tt){Rt(this,"_logger",new TraceLogger("UIProjection"));Rt(this,"unsubscribe",null);Rt(this,"assetStore",null);Rt(this,"_sceneStore",null);Rt(this,"prefabOverrideBucketCounts",new Map);Rt(this,"contentApplier",null);Rt(this,"pendingContentReplayByAssetId",new Map);this.readModelStore=tt,this.rebuildFromState(_e.state),this.unsubscribe=_e.subscribe((et,nt)=>{var it;if(et.commandName==="reset"){this.rebuildFromState(nt);return}(it=et.events)!=null&&it.length&&this.applyEvents(et.events,nt)})}setContentApplier(_e){this.contentApplier=_e}async awaitContentReplay(_e){const tt=this.pendingContentReplayByAssetId.get(_e);if(tt)try{await tt}catch{}}setAssetStore(_e){this.assetStore=_e}setSceneStore(_e){this._sceneStore=_e}warnDev(_e,tt){this._logger.warn(_e,tt)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.assetStore=null,this._sceneStore=null,this.contentApplier=null,this.prefabOverrideBucketCounts.clear(),this.pendingContentReplayByAssetId.clear()}rebuildFromState(_e){var nt,it;this.readModelStore.beginBatch(),this.readModelStore.clear(),this.prefabOverrideBucketCounts.clear();for(const[at,ot]of Object.entries(_e.entities)){const st=this.createEntityReadModel(at,ot);this.readModelStore.setEntity(at,st)}const tt=new Map,et=[];for(const[at,ot]of Object.entries(_e.assets)){const st=this.createAssetReadModel(at,ot);if(this.readModelStore.setAsset(at,st),this.assetStore&&!this.assetStore.assets[at]&&((it=(nt=this.assetStore).createEditorAssetFromState)==null||it.call(nt,at,ot)),ot.parentFolderId){const ct=tt.get(ot.parentFolderId)??[];ct.push(at),tt.set(ot.parentFolderId,ct)}else et.push(at)}for(const[at,ot]of tt)this.readModelStore.setFolderChildren(at,ot);if(this.readModelStore.setRootAssetIds(et),this.readModelStore.setScene({rootEntityIds:[..._e.scene.rootEntityIds]}),_e.prefab){for(const[at,ot]of Object.entries(_e.prefab.bindings))this.setPrefabBindingReadModel(at,ot);for(const[at,ot]of Object.entries(_e.prefab.byAssetId))this.readModelStore.setAssetBindingIds(at,[...ot])}this.readModelStore.endBatch()}applyEvents(_e,tt){for(const et of _e)switch(et.type){case"EntityCreated":this._logger.info("EntityCreated",{entityId:et.entityId,parentId:et.parentId}),this.refreshEntityFromState(et.entityId,tt),et.parentId&&this.refreshEntityFromState(et.parentId,tt),this.refreshSceneFromState(tt);break;case"EntityUpdated":this.refreshEntityFromState(et.entityId,tt);break;case"EntityMoved":this.refreshEntityFromState(et.entityId,tt),et.previousParentId&&this.refreshEntityFromState(et.previousParentId,tt),et.parentId&&et.parentId!==et.previousParentId&&this.refreshEntityFromState(et.parentId,tt),this.refreshSceneFromState(tt);break;case"EntityDeleted":for(const nt of et.subtreeIds)this.readModelStore.deleteEntity(nt);et.snapshot.parentId&&this.refreshEntityFromState(et.snapshot.parentId,tt),this.refreshSceneFromState(tt);break;case"ComponentAdded":case"ComponentUpdated":case"ComponentRemoved":this.refreshEntityFromState(et.entityId,tt);break;case"SceneSettingUpdated":this.applySceneSettingValueToStore(et.settingPath,et.value);break;case"AssetCreated":this.applyAssetCreatedEvent(et);break;case"AssetUpdated":this.applyAssetUpdatedEvent(et);break;case"AssetDeleted":this.applyAssetDeletedEvent(et);break;case"PrefabBindingCreated":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;case"PrefabBindingRetargeted":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.previousAssetId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;case"PrefabOverrideChanged":{const nt=tt.prefab.bindings[et.bindingId];nt?this.readModelStore.prefabBindings.get(et.bindingId)?this.updatePrefabBindingOverrideCount(et.bindingId,nt,et.bucket):this.setPrefabBindingReadModel(et.bindingId,nt):this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break}case"PrefabBindingRemoved":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;default:return et}}refreshEntityFromState(_e,tt){const et=tt.entities[_e];if(!et){this.readModelStore.deleteEntity(_e);return}this.readModelStore.setEntity(_e,this.createEntityReadModel(_e,et))}refreshSceneFromState(_e){this.readModelStore.setScene({rootEntityIds:[..._e.scene.rootEntityIds]})}refreshPrefabBindingFromState(_e,tt){const et=tt.prefab.bindings[_e];et?this.setPrefabBindingReadModel(_e,et):(this.prefabOverrideBucketCounts.delete(_e),this.readModelStore.deletePrefabBinding(_e))}refreshAssetBindingIdsFromState(_e,tt){const et=tt.prefab.byAssetId[_e];this.readModelStore.setAssetBindingIds(_e,et?[...et]:[])}replayAssetContent(_e,tt,et,nt){if(this.contentApplier)try{const it=this.contentApplier(_e,tt,et);if(it&&typeof it.then=="function"){const at=Promise.resolve(it).catch(ot=>{this.warnDev(`[UIProjection] contentApplier failed for asset: ${_e}`,{error:ot,details:nt})}).finally(()=>{this.pendingContentReplayByAssetId.get(_e)===at&&this.pendingContentReplayByAssetId.delete(_e)});this.pendingContentReplayByAssetId.set(_e,at)}else this.pendingContentReplayByAssetId.delete(_e)}catch(it){this.warnDev(`[UIProjection] contentApplier threw for asset: ${_e}`,{error:it,details:nt})}}isSerializableEqual(_e,tt){return JSON.stringify(_e)===JSON.stringify(tt)}syncAssetPropsFromSnapshots(_e,tt,et){var it,at,ot;const nt=(it=this.assetStore)==null?void 0:it.assets[_e];if(nt){for(const st of Object.keys(tt??{}))(!et||!(st in et))&&((at=nt.resetPropertyToDefaultFromDomain)==null||at.call(nt,st));for(const[st,ct]of Object.entries(et??{}))(!tt||!this.isSerializableEqual(tt[st],ct))&&((ot=nt.applyPropertyFromDomain)==null||ot.call(nt,st,ct))}}syncAssetStoreFromSnapshots(_e,tt,et){var it,at,ot,st;const nt=(it=this.assetStore)==null?void 0:it.assets[_e];nt&&((!tt||tt.name!==et.name)&&((at=nt.applyNameFromDomain)==null||at.call(nt,et.name)),(!tt||tt.parentFolderId!==et.parentFolderId)&&((ot=nt.applyParentFolderFromDomain)==null||ot.call(nt,et.parentFolderId)),(!tt||!this.isSerializableEqual(tt.meta??{},et.meta??{}))&&((st=nt.applyMetaFromDomain)==null||st.call(nt,{...et.meta??{}})),this.syncAssetPropsFromSnapshots(_e,tt==null?void 0:tt.props,et.props)),(!tt||!this.isSerializableEqual(tt.content,et.content))&&et.content&&this.replayAssetContent(_e,et.type,et.content,{event:"AssetUpdated"})}applyAssetCreatedEvent(_e){var tt,et;this.readModelStore.setAsset(_e.assetId,this.createAssetReadModel(_e.assetId,_e.asset)),this.updateFolderChildrenOnAdd(_e.assetId,_e.asset.parentFolderId),this.assetStore&&(this.assetStore.assets[_e.assetId]?this.syncAssetStoreFromSnapshots(_e.assetId,void 0,_e.asset):(et=(tt=this.assetStore).createEditorAssetFromState)==null||et.call(tt,_e.assetId,_e.asset))}applyAssetUpdatedEvent(_e){this.readModelStore.setAsset(_e.assetId,this.createAssetReadModel(_e.assetId,_e.asset)),_e.previousAsset.parentFolderId!==_e.asset.parentFolderId&&this.updateFolderChildrenOnMove(_e.assetId,_e.previousAsset.parentFolderId,_e.asset.parentFolderId),this.syncAssetStoreFromSnapshots(_e.assetId,_e.previousAsset,_e.asset)}applyAssetDeletedEvent(_e){var tt,et,nt;this.updateFolderChildrenOnRemove(_e.assetId,_e.snapshot.parentFolderId),this.readModelStore.deleteAsset(_e.assetId),(tt=this.assetStore)!=null&&tt.assets[_e.assetId]&&((nt=(et=this.assetStore).deleteEditorAsset)==null||nt.call(et,_e.assetId))}updateFolderChildrenOnAdd(_e,tt){if(tt){const et=this.readModelStore.folderChildren.get(tt)??[];et.includes(_e)||(et.push(_e),this.readModelStore.setFolderChildren(tt,et))}else this.readModelStore.rootAssetIds.includes(_e)||this.readModelStore.rootAssetIds.push(_e)}updateFolderChildrenOnRemove(_e,tt){if(tt){const et=this.readModelStore.folderChildren.get(tt)??[],nt=et.indexOf(_e);nt!==-1&&(et.splice(nt,1),this.readModelStore.setFolderChildren(tt,et))}else{const et=this.readModelStore.rootAssetIds.indexOf(_e);et!==-1&&this.readModelStore.rootAssetIds.splice(et,1)}}updateFolderChildrenOnMove(_e,tt,et){this.updateFolderChildrenOnRemove(_e,tt),this.updateFolderChildrenOnAdd(_e,et)}applySceneSettingValueToStore(_e,tt){var et,nt;(nt=(et=this._sceneStore)==null?void 0:et.applySettingFromDomain)==null||nt.call(et,_e,tt)}measureOverrideBucketCounts(_e){return{entityProps:Object.keys(_e.entityProps).length,componentProps:Object.keys(_e.componentProps).length,removedEntities:Object.keys(_e.removedEntities).length,removedComponents:Object.keys(_e.removedComponents).length,addedEntities:Object.keys(_e.addedEntities).length,addedComponents:Object.keys(_e.addedComponents).length}}sumOverrideBucketCounts(_e){return _e.entityProps+_e.componentProps+_e.removedEntities+_e.removedComponents+_e.addedEntities+_e.addedComponents}setPrefabBindingReadModel(_e,tt){const et=this.measureOverrideBucketCounts(tt.overrides),nt={};for(const[it,at]of Object.entries(tt.sourceEntitySnapshots??{}))at.instanceAssetKind&&(nt[it]=at.instanceAssetKind);this.prefabOverrideBucketCounts.set(_e,et),this.readModelStore.setPrefabBinding(_e,{id:_e,assetId:tt.assetId,assetKind:tt.assetKind,instanceRootEntityId:tt.instanceRootEntityId,sourceRevision:tt.sourceRevision,overrideCount:this.sumOverrideBucketCounts(et),addedEntityIds:Object.keys(tt.overrides.addedEntities),sourceEntityAssetKinds:nt})}updatePrefabBindingOverrideCount(_e,tt,et){const nt=this.readModelStore.prefabBindings.get(_e);if(!nt)return;const it=this.prefabOverrideBucketCounts.get(_e)??this.measureOverrideBucketCounts(tt.overrides),at=et?{...it,[et]:Object.keys(tt.overrides[et]).length}:this.measureOverrideBucketCounts(tt.overrides);this.prefabOverrideBucketCounts.set(_e,at),this.readModelStore.setPrefabBinding(_e,{...nt,overrideCount:this.sumOverrideBucketCounts(at),addedEntityIds:et===null||et==="addedEntities"?Object.keys(tt.overrides.addedEntities):nt.addedEntityIds})}createEntityReadModel(_e,tt){var nt;const et=new Map;for(const[it,at]of Object.entries(tt.components))et.set(it,{id:it,type:at.type,enabled:((nt=at.props)==null?void 0:nt.enabled)??!0,props:{...at.props}});return{id:_e,name:tt.name,isActive:tt.isActive,layer:tt.layer??0,isLocked:tt.isLocked??!1,parentId:tt.parentId,children:[...tt.children],isStripped:tt.isStripped===!0,transform:{position:{...tt.transform.position},rotation:{...tt.transform.rotation},scale:{...tt.transform.scale}},components:et,instance:tt.instance??null,instanceRef:this.resolveEntityInstanceRef(tt)}}resolveEntityInstanceRef(_e){return resolveEntityInstanceRef(_e)}createAssetReadModel(_e,tt){return{id:_e,name:tt.name,type:tt.type,parentFolderId:tt.parentFolderId,url:tt.url,meta:tt.meta?{...tt.meta}:void 0,props:tt.props&&Object.keys(tt.props).length>0?{...tt.props}:void 0,content:tt.content?{...tt.content}:void 0}}}function isNonPojoObject(rt){return!rt||typeof rt!="object"?!1:"constructor"in rt&&rt.constructor!==Object}function isUICanvasRenderCameraReady(rt){if(!rt||typeof rt!="object")return!0;const _e=rt.entity;return _e?!!_e._updateFlagManager:!0}function createComponentFactory(rt){const _e=new WeakMap,tt=[],et=new Map;let nt=new WeakMap;function it(ft){if(!ft||typeof ft!="object"||!("refId"in ft)||typeof ft.refId!="string")return null;const pt=ft;return pt.key?`${pt.refId}-${pt.key}`:pt.refId}function at(ft,pt){const mt=nt.get(ft),vt=mt==null?void 0:mt.get(pt);if(!vt)return;const _t=it(vt.value);if(_t){const yt=et.get(_t);yt==null||yt.delete(vt),(yt==null?void 0:yt.size)===0&&et.delete(_t)}mt==null||mt.delete(pt),(mt==null?void 0:mt.size)===0&&nt.delete(ft)}function ot(ft,pt,mt,vt){at(ft,mt);const _t=it(vt);if(!_t)return;const yt={component:ft,type:pt,key:mt,value:vt};let bt=nt.get(ft);bt||(bt=new Map,nt.set(ft,bt)),bt.set(mt,yt);let Et=et.get(_t);Et||(Et=new Set,et.set(_t,Et)),Et.add(yt)}function st(ft,pt){for(let mt=tt.length-1;mt>=0;mt--){const vt=tt[mt];vt.component===ft&&(pt===void 0||vt.key===pt)&&tt.splice(mt,1)}}function ct(ft,pt,mt,vt){var At,xt;const _t=getComponentSemantics(pt),yt=(At=_t==null?void 0:_t.proxyMap)==null?void 0:At[mt],bt=yt&&typeof ft[yt]=="function";if(!!yt&&((xt=_t==null?void 0:_t.methodKeys)==null?void 0:xt.has(mt))&&!yt.startsWith("set")||!(mt in ft)&&!bt||mt in ft&&isNonPojoObject(ft[mt]))return"applied";let St=vt;if(rt){const Ct=it(St);if(Ct){const Pt=rt(Ct);if(Pt===null)return"await-asset";isTraceEnabled()&&console.log(`[ComponentFactory] resolved ref ${Ct} → ${(Pt==null?void 0:Pt.name)??Pt}`),St=Pt}}if(pt==="UICanvas"&&mt==="renderCamera"&&!isUICanvasRenderCameraReady(St))return"needs-defer";try{return bt?(isTraceEnabled()&&console.log(`[ComponentFactory] ${pt}.${yt}(${St})`),ft[yt](St)):(isTraceEnabled()&&console.log(`[ComponentFactory] ${pt}.${mt} = ${St}`),ft[mt]=St),"applied"}catch(Ct){return console.warn(`[ComponentFactory] Failed to set prop "${mt}" on ${pt}:`,Ct),"needs-defer"}}function dt(ft){const pt=ft.__editorExternalComponentClaimRevision,mt=typeof pt=="number"?pt:0,vt=_e.get(ft);if(vt&&vt.revision===mt)return vt.components;const _t={revision:mt,components:new Set};return _e.set(ft,_t),_t.components}function ut(ft,pt){var bt;const mt=dt(ft),vt=[],_t=ft;if(_t.getComponents){_t.getComponents(pt,vt);for(const Et of vt)if(!mt.has(Et))return mt.add(Et),Et}const yt=((bt=_t.getComponent)==null?void 0:bt.call(_t,pt))??null;return yt&&!mt.has(yt)?(mt.add(yt),yt):null}const ht=(ft,pt,mt)=>{const vt=EditorComponent.getEngineComponent(pt);if(!vt)return console.warn(`[ComponentFactory] Unknown component type: ${pt}`),null;const _t=!!ft.__editorExternalEntity;let yt=null;if(_t){const Et=ut(ft,vt);Et&&(yt=Et)}yt||(yt=ft.addComponent(vt),_t&&dt(ft).add(yt)),isTraceEnabled()&&console.log(`[ComponentFactory] create ${pt} on entity ${ft.name}`);const bt=yt;for(const Et of Object.keys(mt)){const St=mt[Et];it(St)?ot(bt,pt,Et,St):at(bt,Et),ct(bt,pt,Et,St)==="needs-defer"&&tt.push({component:bt,type:pt,key:Et,value:St})}return yt};return ht.getProxyMap=ft=>{var pt;return(pt=getComponentSemantics(ft))==null?void 0:pt.proxyMap},ht.flushDeferred=()=>{if(tt.length===0)return;const ft=[];for(let pt=0,mt=tt.length;pt<mt;pt++){const vt=tt[pt];if(vt.type==="UICanvas"&&vt.key==="renderCamera"&&!isUICanvasRenderCameraReady(vt.value)){ft.push(vt);continue}ct(vt.component,vt.type,vt.key,vt.value)!=="applied"&&ft.push(vt)}tt.length=0,tt.push(...ft)},ht.trackAssetReference=(ft,pt,mt,vt)=>{if(it(vt)){ot(ft,pt,mt,vt);return}at(ft,mt)},ht.forgetComponentAssetReferences=ft=>{const pt=nt.get(ft);if(pt)for(const mt of Array.from(pt.keys()))at(ft,mt);st(ft)},ht.rebindAssetReferences=ft=>{const pt=et.get(ft);if(pt!=null&&pt.size)for(const mt of Array.from(pt))ct(mt.component,mt.type,mt.key,mt.value)==="applied"&&st(mt.component,mt.key)},ht.clearAssetReferenceTracking=()=>{tt.length=0,et.clear(),nt=new WeakMap},ht}function rebindEntityModels(rt,_e){for(const[tt,et]of rt.iterateEntityModels()){const nt=_e.getEntity(tt);if(!(!nt||et.engineObject===nt)){et.rebindEngineObject(nt);for(const it of et.components){const at=_e.getComponent(it.id);at&&it.engineObject!==at&&it.rebindEngineObject(at)}}}}class ReadModelStore{constructor(){Rt(this,"_logger",new TraceLogger("ReadModelStore"));Rt(this,"entities",new Map);Rt(this,"assets",new Map);Rt(this,"scene",{rootEntityIds:[]});Rt(this,"folderChildren",new Map);Rt(this,"prefabBindings",new Map);Rt(this,"instanceRootBindingIds",new Map);Rt(this,"assetBindingIds",new Map);Rt(this,"rootAssetIds",[]);Rt(this,"_globalListeners",new Set);Rt(this,"_entityListeners",new Map);Rt(this,"_batching",!1);Rt(this,"_batchedEntityIds",new Set)}subscribe(_e){return this._globalListeners.add(_e),()=>this._globalListeners.delete(_e)}subscribeEntity(_e,tt){let et=this._entityListeners.get(_e);return et||(et=new Set,this._entityListeners.set(_e,et)),et.add(tt),()=>{et.delete(tt),et.size===0&&this._entityListeners.delete(_e)}}_notifyGlobal(){if(!this._batching)for(const _e of this._globalListeners)_e()}_notifyEntity(_e){if(this._batching)return;const tt=this._entityListeners.get(_e);if(tt)for(const et of tt)et()}getEntity(_e){return this.entities.get(_e)}getEntityName(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.name)??""}getEntityChildren(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.children)??[]}getEntityParent(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.parentId)??null}getRootEntities(){return this.scene.rootEntityIds.map(_e=>this.entities.get(_e)).filter(_e=>_e!==void 0)}isEntityLocked(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.isLocked)??!1}isEntityActive(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.isActive)??!0}getAsset(_e){return this.assets.get(_e)}getAssetName(_e){var tt;return((tt=this.assets.get(_e))==null?void 0:tt.name)??""}getAssetType(_e){var tt;return((tt=this.assets.get(_e))==null?void 0:tt.type)??""}getFolderChildren(_e){return _e===null?this.rootAssetIds:this.folderChildren.get(_e)??[]}getRootAssets(){return this.rootAssetIds.map(_e=>this.assets.get(_e)).filter(_e=>_e!==void 0)}getComponent(_e,tt){var et;return(et=this.entities.get(_e))==null?void 0:et.components.get(tt)}getComponentsByEntity(_e){const tt=this.entities.get(_e);return tt?Array.from(tt.components.values()):[]}getComponentByType(_e,tt){const et=this.entities.get(_e);if(et){for(const nt of et.components.values())if(nt.type===tt)return nt}}getBindingByEntity(_e){const tt=this.entities.get(_e);if(tt!=null&&tt.instance)return this.prefabBindings.get(tt.instance.bindingId)}getInstanceRootBindingByEntity(_e){const et=(this.instanceRootBindingIds.get(_e)??[]).map(nt=>this.prefabBindings.get(nt)).filter(nt=>!!nt);return et.find(nt=>nt.assetKind==="glTF")??et[0]}getBindingsByAsset(_e){return(this.assetBindingIds.get(_e)??[]).map(et=>this.prefabBindings.get(et)).filter(et=>et!==void 0)}setEntity(_e,tt){if(this._logger.info("setEntity",{id:_e,name:tt.name}),this.entities.set(_e,tt),this._batching){this._batchedEntityIds.add(_e);return}this._notifyEntity(_e),this._notifyGlobal()}deleteEntity(_e){this.entities.delete(_e),this._notifyEntity(_e),this._notifyGlobal()}setAsset(_e,tt){this.assets.set(_e,tt),this._notifyGlobal()}deleteAsset(_e){this.assets.delete(_e),this._notifyGlobal()}setScene(_e){this._logger.info("setScene",{rootEntityIds:_e.rootEntityIds}),this.scene=_e,this._notifyGlobal()}setFolderChildren(_e,tt){this.folderChildren.set(_e,tt),this._notifyGlobal()}setRootAssetIds(_e){this.rootAssetIds=_e,this._notifyGlobal()}setPrefabBinding(_e,tt){const et=this.prefabBindings.get(_e);et&&this.removeInstanceRootBindingIndex(_e,et.instanceRootEntityId),this.prefabBindings.set(_e,tt),this.addInstanceRootBindingIndex(_e,tt.instanceRootEntityId),this._notifyGlobal()}deletePrefabBinding(_e){const tt=this.prefabBindings.get(_e);tt&&this.removeInstanceRootBindingIndex(_e,tt.instanceRootEntityId),this.prefabBindings.delete(_e),this._notifyGlobal()}setAssetBindingIds(_e,tt){tt.length===0?this.assetBindingIds.delete(_e):this.assetBindingIds.set(_e,tt),this._notifyGlobal()}beginBatch(){this._batching=!0,this._batchedEntityIds.clear()}endBatch(){this._batching=!1;for(const _e of this._batchedEntityIds)this._notifyEntity(_e);this._batchedEntityIds.clear(),this._notifyGlobal()}clear(){if(this._batching)for(const tt of this.entities.keys())this._batchedEntityIds.add(tt);const _e=this._batching?[]:Array.from(this.entities.keys());if(this.entities.clear(),this.assets.clear(),this.folderChildren.clear(),this.prefabBindings.clear(),this.instanceRootBindingIds.clear(),this.assetBindingIds.clear(),this.rootAssetIds=[],this.scene={rootEntityIds:[]},!this._batching){for(const tt of _e)this._notifyEntity(tt);this._notifyGlobal()}}addInstanceRootBindingIndex(_e,tt){const et=this.instanceRootBindingIds.get(tt)??[];et.includes(_e)||et.push(_e),this.instanceRootBindingIds.set(tt,et)}removeInstanceRootBindingIndex(_e,tt){const et=this.instanceRootBindingIds.get(tt);if(!et)return;const nt=et.filter(it=>it!==_e);nt.length===0?this.instanceRootBindingIds.delete(tt):this.instanceRootBindingIds.set(tt,nt)}}function parseUploadMeta(rt){if(!(typeof rt!="string"||rt.length===0))try{const _e=JSON.parse(rt);if(_e&&typeof _e=="object"&&!Array.isArray(_e))return _e}catch{}}class UploadService{constructor(_e){this.root=_e}async upload(_e){const{file:tt,name:et,projectId:nt,assetId:it,assetType:at,meta:ot,parentFolderId:st,isFBX:ct=!1,onProgress:dt}=_e,ut=await this.root.storage.assets.create({blob:tt,name:et,projectId:nt,uuid:it,type:at,meta:ot,parentId:st,options:{useCache:!ct,onProgress:dt}});return{serverId:ut.id,url:ut.url,meta:parseUploadMeta(ut.meta)}}async uploadAndUpdateState(_e,tt){try{const et=await this.upload(tt);return this.root.assetFacade.markAssetReady(_e,et.serverId,et.url),et}catch(et){throw this.root.assetFacade.markAssetError(_e,et instanceof Error?et.message:String(et)),et}}}function buildCreateAssetRequest(rt){const{assetId:_e,projectId:tt,state:et}=rt;return{blob:null,name:et.name,projectId:tt,uuid:_e,type:et.type==="Folder"?EProjectAssetType.Directory:EProjectAssetType.File,meta:JSON.stringify(et.meta),parentId:et.parentFolderId??void 0,url:et.url}}const to=class to{constructor(_e,tt,et,nt){Rt(this,"_sessionToken",0);Rt(this,"unsubscribe",null);Rt(this,"revisions",new Map);Rt(this,"assetChains",new Map);Rt(this,"pendingDeletes",[]);Rt(this,"workSet",new Set);Rt(this,"trackedPersistenceTasks",new WeakSet);Rt(this,"_lastError",null);Rt(this,"idleResolvers",[]);Rt(this,"statusListeners",new Set);this.domainStore=_e,this.projectIdOrGetter=tt,this.api=et,this.onError=nt}start(){this.unsubscribe||(this._sessionToken++,this.unsubscribe=this.domainStore.subscribe(_e=>this.handleTransaction(_e)))}stop(){var _e;this._sessionToken++,(_e=this.unsubscribe)==null||_e.call(this),this.unsubscribe=null,this.assetChains.clear()}get pendingCount(){return this.workSet.size}get lastError(){return this._lastError}clearLastError(){this._lastError&&(this._lastError=null,this.notifyStatusChange())}waitForIdle(){return this.pendingCount===0?Promise.resolve():new Promise(_e=>{this.idleResolvers.push(_e)})}onStatusChange(_e){return this.statusListeners.add(_e),()=>{this.statusListeners.delete(_e)}}trackPersistenceTask(_e,tt){_e&&(this.trackedPersistenceTasks.has(_e)||(this.trackedPersistenceTasks.add(_e),this.runTask((async()=>{try{await _e}catch(et){this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,"Asset persistence task failed",{...tt,originalError:et}))}})())))}get projectId(){return typeof this.projectIdOrGetter=="function"?this.projectIdOrGetter():this.projectIdOrGetter}handleTransaction(_e){if(_e.commandName==="system"||_e.commandName==="remote"||_e.commandName==="asset.init"||_e.commandName==="reset")return;const tt=this._sessionToken,et=this.projectId,nt=_e.commandName??"",it=nt.startsWith("undo:")||nt==="redo:asset.create"||nt==="asset.copy",at=new Map;for(const ot of _e.operations){const st=this.parsePropertyPath(ot.path);if(st&&ot.op==="replace"&&"value"in ot){const ut=at.get(st.assetId)??{hasParentId:!1};st.property==="name"?ut.name=ot.value:(ut.hasParentId=!0,ut.parentId=ot.value),at.set(st.assetId,ut);continue}const ct=this.extractRootAssetId(ot.path);if(!ct)continue;const dt=(this.revisions.get(ct)??0)+1;if(this.revisions.set(ct,dt),ot.op==="remove"){const ut=ot.oldValue;ut!=null&&ut.serverId&&this.scheduleAssetTask(ct,()=>this.executeDelete([ut.serverId],et),tt)}else if(ot.op==="add"&&it&&"value"in ot){const ut=ot.value;ut.url&&this.scheduleAssetTask(ct,()=>this.handleCreate(ct,ut,dt,et,tt),tt)}}for(const[ot,st]of at)this.scheduleAssetTask(ot,async()=>{var ut;let ct=(ut=this.domainStore.state.assets[ot])==null?void 0:ut.serverId;if(ct||(ct=await this.waitForServerId(ot,3e4,tt)),!ct)return;const dt={};st.name!==void 0&&(dt.name=st.name),st.hasParentId&&(dt.parentId=st.parentId),await this.executeUpdate(ct,dt)},tt)}async executeDelete(_e,tt){const{error:et}=await this.retryOnce(()=>this.api.assets.delete(_e,tt));et&&(this.pendingDeletes.push(..._e),console.warn("[AssetEffectsRunner] delete failed:",et.retryError),this.reportError(new EffectsError(EffectsErrorCode.DELETE_FAILED,"Asset delete side effects failed",{serverIds:_e,originalError:et.originalError,retryError:et.retryError})))}async executeUpdate(_e,tt){const{error:et}=await this.retryOnce(()=>this.api.assets.update(_e,tt));et&&(console.warn("[AssetEffectsRunner] update failed:",et.retryError),this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,`Asset update side effects failed: ${_e}`,{serverId:_e,data:tt,originalError:et.originalError,retryError:et.retryError})))}async retryOnce(_e){try{return await _e(),{}}catch(tt){await new Promise(et=>setTimeout(et,to.RETRY_DELAY_MS));try{return await _e(),{}}catch(et){return{error:{originalError:tt,retryError:et}}}}}getPendingDeletes(){return[...this.pendingDeletes]}async retryPendingDeletes(){const _e=this.pendingDeletes.splice(0);_e.length!==0&&await this.runTask(this.executeDelete(_e,this.projectId))}async handleCreate(_e,tt,et,nt,it){try{const at=await this.api.assets.create(buildCreateAssetRequest({assetId:_e,projectId:nt,state:tt}));if(this._sessionToken!==it){this.runTask(this.executeDelete([at.id],nt));return}const ot=this.domainStore.state.assets[_e];if(this.revisions.get(_e)!==et||!ot){this.runTask(this.executeDelete([at.id],nt));return}const st=Object.prototype.hasOwnProperty.call(ot,"serverId")?"replace":"add";try{this.domainStore.applySystem([{op:st,path:`/assets/${_e}/serverId`,value:at.id}])}catch(ct){throw this.runTask(this.executeDelete([at.id],nt)),ct}}catch(at){console.warn("[AssetEffectsRunner] recreate failed:",at),this.reportError(new EffectsError(EffectsErrorCode.CREATE_FAILED,`Asset create side effects failed: ${_e}`,{assetId:_e,originalError:at}))}}runTask(_e){const tt=this.beginWork();return _e.finally(()=>{this.endWork(tt)})}scheduleAssetTask(_e,tt,et){const nt=this.beginWork(),it=async()=>{this._sessionToken===et&&await tt()},at=this.assetChains.get(_e),ot=(at?at.catch(()=>{}).then(it):Promise.resolve(it())).catch(st=>{this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,`Asset side effects scheduler failed: ${_e}`,{assetId:_e,originalError:st}))}).finally(()=>{this.endWork(nt),this.assetChains.get(_e)===ot&&this.assetChains.delete(_e)});this.assetChains.set(_e,ot)}beginWork(){const _e=Symbol("asset-effects-work");return this.workSet.size===0&&(this._lastError=null),this.workSet.add(_e),this.notifyStatusChange(),_e}endWork(_e){this.workSet.delete(_e)&&this.notifyStatusChange()}notifyStatusChange(){const _e=this.pendingCount;for(const tt of this.statusListeners)tt(_e,_e===0?this._lastError:null);if(_e===0){const tt=this.idleResolvers.splice(0);for(const et of tt)et()}}reportError(_e){var tt;this._lastError=_e,(tt=this.onError)==null||tt.call(this,_e)}parsePropertyPath(_e){const tt=_e.match(/^\/assets\/([^/]+)\/(name|parentFolderId)$/);return tt?{assetId:tt[1],property:tt[2]}:null}extractRootAssetId(_e){if(!_e.startsWith("/assets/"))return null;const tt=_e.slice(8);return!tt||tt.includes("/")?null:tt}waitForServerId(_e,tt,et){const nt=this.domainStore.state.assets[_e];return nt?nt.serverId?Promise.resolve(nt.serverId):this._sessionToken!==et?Promise.resolve(null):new Promise(it=>{let at=!1;const ot=dt=>{at||(at=!0,clearTimeout(st),ct(),it(dt))},st=setTimeout(()=>ot(null),tt),ct=this.domainStore.subscribe(()=>{if(this._sessionToken!==et)return ot(null);const dt=this.domainStore.state.assets[_e];if(!dt)return ot(null);dt.serverId&&ot(dt.serverId)})}):Promise.resolve(null)}};Rt(to,"RETRY_DELAY_MS",500);let AssetEffectsRunner=to;const SKIP_COMMANDS=new Set(["system","remote","asset.init","reset"]);class ScenePersistenceRunner{constructor(_e,tt){Rt(this,"_unsubscribe",null);this.domainStore=_e,this.config=tt}start(){this._unsubscribe||(this._unsubscribe=this.domainStore.subscribe(_e=>this.handleTransaction(_e)))}stop(){var _e;(_e=this._unsubscribe)==null||_e.call(this),this._unsubscribe=null}handleTransaction(_e){if(this.domainStore.isHistoryPaused)return;const tt=_e.commandName??"";SKIP_COMMANDS.has(tt)||!_e.operations.some(nt=>nt.path.startsWith("/entities/")||nt.path.startsWith("/scene/"))||this.config.persistSceneDebounced(tt||"unknown")}}class InspectorSelectionService{constructor(_e){this.root=_e}getSelectedEntityId(){var tt;const _e=((tt=this.root.sceneUIStore)==null?void 0:tt.lastSelectedId)??null;return!_e||_e===DEFAULT_SCENE?null:_e}getSelectedEntityModel(){const _e=this.getSelectedEntityId();return _e?this.root.sceneStore.getEntityModel(_e)??null:null}getSelectedEntityReadModel(){const _e=this.getSelectedEntityId();return _e?this.root.readModelStore.getEntity(_e)??null:null}getSelectedComponents(){var _e;return((_e=this.getSelectedEntityModel())==null?void 0:_e.components)??[]}}function disposeReloadState(rt,_e){var tt,et,nt,it,at,ot,st;(tt=rt.assetEffectsRunner)==null||tt.stop(),(et=rt.scenePersistenceRunner)==null||et.stop(),(nt=rt.selectionStore)==null||nt.dispose(),(it=rt.domainStateReactive)==null||it.dispose(),(at=rt.uiProjection)==null||at.dispose(),(ot=rt.runtimeBinderRegistry)==null||ot.dispose(),(st=rt.runtimeAssetStore)==null||st.dispose(),_e==null||_e()}function createRuntimeAssetResolver(rt){return _e=>{const tt=rt.get(_e);return(tt==null?void 0:tt.status)==="ready"?tt.engineObject??null:null}}function bindAssetRuntimeReadyToProjection(rt,_e,tt){return rt.subscribe((et,nt)=>{var it,at,ot;(nt==null?void 0:nt.status)==="ready"&&((it=_e())==null||it.rebindAssetReferences(et),(ot=(at=tt==null?void 0:tt())==null?void 0:at.rebindAssetReferences)==null||ot.call(at,et,!1))})}const Mr=class Mr{constructor(){Rt(this,"projectStore");Rt(this,"configDataStore");Rt(this,"layoutStore");Rt(this,"assetStore");Rt(this,"animationClipStore");Rt(this,"animatorControllerStore");Rt(this,"snapshot");Rt(this,"inspectorStore",inspectorStore);Rt(this,"selectionStore");Rt(this,"sceneUIStore");Rt(this,"assetUIStore");Rt(this,"assetService");Rt(this,"assetRegistry");Rt(this,"domainStore");Rt(this,"commandBus");Rt(this,"engineProjection",null);Rt(this,"_lastProjectionRebuildTime",0);Rt(this,"_projectionRebuildTimer",null);Rt(this,"_disposeAssetRuntimeReadySubscription",null);Rt(this,"domainStateReactive");Rt(this,"entityModelProjection");Rt(this,"runtimeProjection");Rt(this,"readModelStore");Rt(this,"uiProjection");Rt(this,"entityFacade");Rt(this,"assetFacade");Rt(this,"componentFacade");Rt(this,"sceneFacade");Rt(this,"inspectorFacade");Rt(this,"prefabFacade");Rt(this,"uploadService");Rt(this,"_logger",new TraceLogger("Root"));Rt(this,"assetEffectsRunner");Rt(this,"scenePersistenceRunner");Rt(this,"inspectorSelectionService");Rt(this,"runtimeBinderRegistry");Rt(this,"runtimeAssetStore");Rt(this,"storage");Rt(this,"esbuildInstancePromise",Mr.getEsbuildInstancePromise());Rt(this,"reload",()=>{disposeReloadState(this,()=>{var _e;(_e=this._disposeAssetRuntimeReadySubscription)==null||_e.call(this),this._disposeAssetRuntimeReadySubscription=null,this._projectionRebuildTimer&&(clearTimeout(this._projectionRebuildTimer),this._projectionRebuildTimer=null)}),this.configDataStore=new ConfigDataCenter,this.projectStore=new Project(this),this.layoutStore=new LayoutSystem(this),this.snapshot=snapshotStore,this.assetUIStore=new AssetUIStore,this.assetService=new AssetService(this),this.assetRegistry=new AssetRegistry,this.assetStore=new AssetManager(this),this.animationClipStore=new AnimationClipStore(this),this.animatorControllerStore=new AnimatorControllerStore(this),this.selectionStore=new SelectionStore(this),this.sceneUIStore=new SceneUIStore(this),this.domainStore=new DomainStore,this.domainStore.pauseHistory(),this.commandBus=new CommandBus(this.domainStore),this.domainStateReactive=new DomainStateReactive(this.domainStore),this.readModelStore=new ReadModelStore,this.runtimeAssetStore=new RuntimeAssetStore,this.runtimeBinderRegistry=new RuntimeBinderRegistry,this.uiProjection=new UIProjection(this.domainStore,this.readModelStore),this.uiProjection.setAssetStore(this.assetStore),this.runtimeProjection=new RuntimeProjection(()=>this.sceneStore,()=>this.engineProjection,this.runtimeBinderRegistry,()=>this.domainStore.canRedo),this.entityModelProjection=new EntityModelProjection(()=>this.sceneStore,()=>this.engineProjection),this.domainStore.subscribe(_e=>{if(this.engineProjection){if(_e.commandName==="reset"){this.runtimeProjection.reset();try{this.engineProjection.rebuildFromState(this.domainStore.state),this._rebindAllEntityModels()}catch(nt){console.error("EngineProjection rebuild failed:",nt),this._requestEngineProjectionRebuild(nt)}return}try{this.engineProjection.apply(_e.events,_e.commandName)}catch(nt){console.error("EngineProjection apply failed:",nt),this._requestEngineProjectionRebuild(nt)}}const tt=this.runtimeProjection.apply(_e.events,_e.commandName);this.entityModelProjection.apply(_e.events,tt),isUndoRedoCommand(_e.commandName)&&this._syncUploadingAssetIds(_e.operations),this._resumeCreateByAddAfterRedo(_e.operations,_e.commandName)}),this.entityFacade=new EntityFacade(this),this.assetFacade=new AssetFacade(this),this.componentFacade=new ComponentFacade(this),this.sceneFacade=new SceneFacade(this.domainStore,this.commandBus),this.inspectorFacade=new InspectorFacade(this),this.prefabFacade=new PrefabFacade(this),isTraceEnabled()&&(instrumentCommandBus(this.commandBus),instrumentDomainStore(this.domainStore),wrapFacadeWithTrace(this.entityFacade,"EntityFacade"),wrapFacadeWithTrace(this.componentFacade,"ComponentFacade"),wrapFacadeWithTrace(this.assetFacade,"AssetFacade"),wrapFacadeWithTrace(this.inspectorFacade,"InspectorFacade")),this.uploadService=new UploadService(this),this.assetEffectsRunner=new AssetEffectsRunner(this.domainStore,()=>this.projectStore.id,{assets:{delete:(..._e)=>this.storage.assets.delete(..._e),create:_e=>this.storage.assets.create(_e),update:(_e,tt)=>this.storage.assets.update(_e,tt).then(()=>{})}}),this.scenePersistenceRunner=new ScenePersistenceRunner(this.domainStore,{persistSceneDebounced:_e=>this.projectStore.persistSceneDebounced(_e)}),this.inspectorSelectionService=new InspectorSelectionService(this)});this.reload()}static getEsbuildInstancePromise(){return Mr.esbuildInstancePromiseSingleton||(Mr.esbuildInstancePromiseSingleton=browserExports.initialize({worker:!0,wasmURL:"https://gw.alipayobjects.com/os/lib/esbuild-wasm/0.25.8/esbuild.wasm"})),Mr.esbuildInstancePromiseSingleton}createLogger(_e){return new TraceLogger(_e)}get sceneStore(){return this.projectStore.currentScene}get viewportStore(){return this.projectStore.currentViewport}get currentSceneId(){var _e;return((_e=this.projectStore.currentScene)==null?void 0:_e.refId)??null}async switchActiveScene(_e){await this.projectStore.setActiveEditorScene(_e)}undo(){isTraceEnabled()&&beginTrace();try{return this.domainStore.undo()!==null}finally{isTraceEnabled()&&endTrace()}}redo(){isTraceEnabled()&&beginTrace();try{return this.domainStore.redo()!==null}finally{isTraceEnabled()&&endTrace()}}get canUndo(){return this.domainStore.canUndo}get canRedo(){return this.domainStore.canRedo}runInUndoGroup(_e,tt){this.domainStore.beginUndoGroup();const et=()=>{this.domainStore.endUndoGroup(_e)};try{const nt=tt();return nt&&typeof nt.then=="function"?nt.finally(et):(et(),nt)}catch(nt){throw et(),nt}}resumeHistoryCapture(){this.domainStore.resumeHistory.bind(this.domainStore)()}setStorage(_e){if(!(_e!=null&&_e.project)||!(_e!=null&&_e.assets)||!(_e!=null&&_e.schema))throw new Error("setStorage: storage must implement project, assets, and schema");this.storage=_e}initEngineProjection(_e){var et;(et=this._disposeAssetRuntimeReadySubscription)==null||et.call(this),this._disposeAssetRuntimeReadySubscription=null,this.engineProjection=new EngineProjection(_e,void 0,()=>this.domainStore.canRedo);const tt=createRuntimeAssetResolver(this.runtimeAssetStore);this.engineProjection.setAssetResolver(tt),this.engineProjection.setComponentFactory(createComponentFactory(tt)),this._disposeAssetRuntimeReadySubscription=bindAssetRuntimeReadyToProjection(this.runtimeAssetStore,()=>this.engineProjection,()=>this.sceneStore),this.sceneStore&&this.uiProjection.setSceneStore(this.sceneStore)}_requestEngineProjectionRebuild(_e){if(!this.engineProjection)return;const nt=Date.now()-this._lastProjectionRebuildTime;if(nt>=Mr.PROJECTION_REBUILD_THROTTLE_MS){this._runEngineProjectionRebuild(_e);return}if(this._projectionRebuildTimer)return;const it=Mr.PROJECTION_REBUILD_THROTTLE_MS-nt;this._projectionRebuildTimer=setTimeout(()=>{this._projectionRebuildTimer=null,this._runEngineProjectionRebuild(_e)},it)}_resumeCreateByAddAfterRedo(_e,tt){const et=collectCreateByAddResumeCandidates({commandName:tt,operations:_e,assets:this.domainStore.state.assets});for(const nt of et)this.assetStore.resumeCreateAssetByAddFromState(nt).catch(it=>{console.warn("[Root] resumeCreateAssetByAddFromState failed:",{assetId:nt,error:it})})}_runEngineProjectionRebuild(_e){const tt=this.engineProjection;if(tt){this._lastProjectionRebuildTime=Date.now();try{tt.rebuildFromState(this.domainStore.state),this._rebindAllEntityModels()}catch(et){console.error("EngineProjection rebuild failed:",et,"reason:",_e);try{tt.reset()}catch(nt){console.error("EngineProjection reset failed:",nt)}}}}_rebindAllEntityModels(){const _e=this.sceneStore;!_e||!this.engineProjection||rebindEntityModels(_e,this.engineProjection)}_syncUploadingAssetIds(_e){const tt=this.assetUIStore;if(!tt)return;const et=/^\/assets\/([^/]+)$/;for(const it of _e){const at=et.exec(it.path);if(!at)continue;const ot=at[1];it.op==="add"&&it.value&&typeof it.value=="object"&&it.value.status==="uploading"?tt.markAssetUploading(ot):it.op==="remove"&&tt.clearAssetUploading(ot)}const nt=/^\/assets\/([^/]+)\/status$/;for(const it of _e){const at=nt.exec(it.path);if(!at)continue;const ot=at[1];it.op!=="remove"&&"value"in it&&it.value==="uploading"?tt.markAssetUploading(ot):tt.clearAssetUploading(ot)}}};Rt(Mr,"esbuildInstancePromiseSingleton",null),Rt(Mr,"PROJECTION_REBUILD_THROTTLE_MS",3e3);let Root=Mr;async function initProjectReadRuntime({root:rt,storage:_e,projectId:tt,canvas:et,projectInfo:nt,onStage:it,viewport:at}){var ut;rt.setStorage(_e);const ot=nt??await(async()=>(it==null||it("query-project"),_e.project.query(tt)))(),st=rt.projectStore,ct=[...ot.assets??[]];it==null||it("init-project"),await st.init(ot),it==null||it("init-engine"),await st.initEngine(et),it==null||it("init-assets"),await st.initAssets(ct),it==null||it("init-scene"),await st.initScene(),it==null||it("run-engine"),st.runEngine(at);const dt=(ut=rt.sceneStore)!=null&&ut.iterateEntityModels?Array.from(rt.sceneStore.iterateEntityModels()).flatMap(([,ht])=>ht.components):[];return it==null||it("replay-bindings"),await Promise.all(dt.map(ht=>{var ft;return((ft=ht.replaySerializedBindings)==null?void 0:ft.call(ht))??Promise.resolve()})),it==null||it("resume-history"),rt.resumeHistoryCapture(),{root:rt,projectInfo:ot,projectStore:st,viewportStore:st.currentViewport}}function collectAssetPickerMatches(rt,_e){if(!rt)return[];const tt=[],et=getPropertyConfigs(rt);for(const nt in et){const it=et[nt];if(!it||it.type!==ComponentType.AssetPicker)continue;const at=rt[nt];at&&typeof at=="object"&&"refId"in at&&at.refId===_e&&tt.push({target:rt,key:nt})}return tt}function refreshAssetReferenceMatch(rt){var dt,ut,ht,ft,pt,mt,vt;const{target:_e,key:tt}=rt,et=(dt=getPropertyConfigs(_e))==null?void 0:dt[tt];(ut=_e.triggerPropertyChange)==null||ut.call(_e,tt,!1);const nt=((ht=_e==null?void 0:_e[storedPropertyProxySymbol])==null?void 0:ht[tt])??((ft=getPropertyProxyConfigs(_e))==null?void 0:ft[tt]),it=nt==null?void 0:nt.engineKey;if(!!(et!=null&&et.bindPath||et!=null&&et.onChange)||!it)return;const ot=_e==null?void 0:_e.engineObject;if(!ot||typeof ot[it]!="function")return;const st=_e[tt],ct=st!=null&&st.refId?((vt=(mt=(pt=_e==null?void 0:_e.root)==null?void 0:pt.assetStore)==null?void 0:mt.assets)==null?void 0:vt[st.refId])??null:null;ot[it]((ct==null?void 0:ct.engineObject)??null)}async function reloadSceneStateFromAsset(rt){const _e=createEmptyDomainState();_e.version=rt.preserveVersion,_e.assets=rt.preserveAssets,rt.domainStore.reset(_e),await rt.sceneStore.init(rt.sceneAsset),rt.sceneFacade.initSettingsSystem(collectSceneSettings(rt.sceneStore))}const TEXT_ASSET_TYPES=new Set(["Scene","Prefab","script","Shader","ShaderChunk","StateMachineScript"]);function parseAssetMeta(rt,_e){if(!rt)return{};try{const tt=JSON.parse(rt);if(!tt||typeof tt!="object"||Array.isArray(tt))throw new Error("asset meta is not an object");return tt}catch(tt){return console.warn(`[applyProjectReadRefresh] invalid asset meta for ${_e}, fallback to empty meta`,tt),{}}}function toDomainAssetState(rt){const _e=parseAssetMeta(rt.meta,rt.uuid);return{id:rt.uuid,name:rt.name,type:_e.type??"Unknown",serverId:rt.id??null,parentFolderId:rt.parentId||null,url:rt.url||void 0,meta:_e,status:"ready"}}function isSerializableEqual(rt,_e){return JSON.stringify(rt)===JSON.stringify(_e)}async function fetchAssetPayload(rt,_e){const tt=await fetch(rt);if(!tt.ok)throw new Error(`asset fetch failed: ${tt.status}`);const et=await tt.blob(),nt=TEXT_ASSET_TYPES.has(_e)?await et.text():void 0;return{blob:et,text:nt}}function refreshSceneAssetPickerReferences(rt,_e){var it,at;const tt=rt.sceneStore;if(!tt)return;const et=ot=>{for(const st of collectAssetPickerMatches(ot,_e))refreshAssetReferenceMatch(st)};et(tt);const nt=typeof tt.iterateEntityModels=="function"?Array.from(tt.iterateEntityModels(),([,ot])=>ot):[];for(const ot of nt)for(const st of ot.components??[])et(st);for(const ot of((at=(it=tt.strippedEntities)==null?void 0:it.values)==null?void 0:at.call(it))??[])for(const st of ot.components??[])et(st)}function syncDomainAssetState(rt,_e){const tt=_e.id,et=rt.domainStore.state.assets[tt];if(et&&isSerializableEqual(et,_e))return;const nt=encodeJsonPointerSegment(tt),it=et?{op:"replace",path:`/assets/${nt}`,value:_e}:{op:"add",path:`/assets/${nt}`,value:_e};rt.domainStore.applyRemote([it])}function normalizeAssetBatchChanges(rt){const _e=new Map;for(const tt of rt){const et=_e.get(tt.assetId);if(!et){_e.set(tt.assetId,{assetId:tt.assetId,reason:tt.reason});continue}et.reason!=="main"&&tt.reason==="main"&&_e.set(tt.assetId,{assetId:tt.assetId,reason:"main"})}return Array.from(_e.values())}function isRuntimeOnlyAssetState(rt){var _e;return(rt==null?void 0:rt.serverId)==null&&((_e=rt==null?void 0:rt.meta)==null?void 0:_e.locked)===!0}function removeDomainAssetState(rt,_e){var et,nt;const tt=encodeJsonPointerSegment(_e);rt.domainStore.applyRemote([{op:"remove",path:`/assets/${tt}`}]),(nt=(et=rt.assetStore).deleteEditorAsset)==null||nt.call(et,_e)}function resolveRefreshSceneId(rt,_e){var nt;const tt=(nt=rt.content)==null?void 0:nt.scene;if(tt&&rt.assets.some(it=>it.uuid===tt))return tt;const et=rt.assets.find(it=>parseAssetMeta(it.meta,it.uuid).type==="Scene");return et?et.uuid:_e&&rt.assets.some(it=>it.uuid===_e)?_e:null}function assertRefreshSceneAvailable(rt,_e){if(!(rt||!_e))throw new Error(`[applyProjectReadFullRefresh] active scene ${_e} was removed and no replacement Scene asset is available`)}function syncProjectContent(rt,_e){!rt.projectStore||!_e.content||(rt.projectStore.content={...rt.projectStore.content??{},..._e.content,platform:_e.platform})}async function fetchAndLoadMainFile(rt,_e){var it;const tt=_e.url;if(!tt||typeof rt.reloadMainFileFromRemote!="function")return;const{blob:et,text:nt}=await fetchAssetPayload(tt,_e.type);return(it=rt.setUrl)==null||it.call(rt,tt),await rt.reloadMainFileFromRemote({blob:et,url:tt}),_e.type==="ShaderChunk"&&typeof nt=="string"&&typeof rt.updateCode=="function"&&rt.updateCode(nt),nt}async function reloadRuntimeAsset(rt,_e,tt,et){var nt;if(!rt){const it=tt.assetStore.initAsset(et);if(!it)return;let at;try{at=await fetchAndLoadMainFile(it,_e)}catch(ot){console.warn(`[applyProjectReadRefresh] initial main file load failed for ${et.uuid}`,ot)}try{await((nt=it.collectDependencies)==null?void 0:nt.call(it))}catch(ot){console.warn(`[applyProjectReadRefresh] collectDependencies failed for ${et.uuid}`,ot)}return at}return fetchAndLoadMainFile(rt,_e)}async function refreshCurrentScene(rt,_e){!rt.sceneStore||!_e||await reloadSceneStateFromAsset({sceneStore:rt.sceneStore,sceneFacade:rt.sceneFacade,domainStore:rt.domainStore,sceneAsset:_e,preserveAssets:rt.domainStore.state.assets,preserveVersion:rt.domainStore.state.version})}async function applyProjectReadFullRefresh(rt){var ct;const{root:_e,storage:tt,projectId:et}=rt,nt=rt.projectInfo??await tt.project.query(et),it=_e.domainStore.state.assets??{},at=((ct=_e.sceneStore)==null?void 0:ct.refId)??null,ot=resolveRefreshSceneId(nt,at),st=new Set(nt.assets.map(dt=>dt.uuid));assertRefreshSceneAvailable(ot,at),await EditorAsset.runWithGlobalAutoSaveSuspended(async()=>{await _e.domainStore.runAsRemote(async()=>{var ut,ht,ft,pt,mt;syncProjectContent(_e,nt),ot&&((ut=_e.projectStore)!=null&&ut.content)&&(_e.projectStore.content.scene=ot);for(const[vt,_t]of Object.entries(it))st.has(vt)||isRuntimeOnlyAssetState(_t)||removeDomainAssetState(_e,vt);let dt=ot?((ht=_e.assetStore.assets)==null?void 0:ht[ot])??null:null;for(const vt of nt.assets){const _t=toDomainAssetState(vt),yt=it[vt.uuid],bt=(ft=_e.assetStore.assets)==null?void 0:ft[vt.uuid],Et=vt.uuid===ot;if(Et&&(dt=bt??dt),!(!Et&&yt&&isSerializableEqual(yt,_t))){syncDomainAssetState(_e,_t);try{await reloadRuntimeAsset(bt,_t,_e,vt),Et&&(dt=((pt=_e.assetStore.assets)==null?void 0:pt[vt.uuid])??bt??dt)}catch(St){const At=Et?`[applyProjectReadFullRefresh] reload active scene asset failed for ${vt.uuid}, aborting full refresh`:`[applyProjectReadFullRefresh] reload runtime asset failed for ${vt.uuid}, skipping`;if(console.warn(At,St),Et)throw St}Et||refreshSceneAssetPickerReferences(_e,vt.uuid)}}if(dt||ot){const vt=dt??((mt=_e.assetStore.assets)==null?void 0:mt[ot]);await refreshCurrentScene(_e,vt)}})})}async function applyProjectReadAssetBatchRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,changes:nt}){const it=et??await _e.project.query(tt),at=normalizeAssetBatchChanges(nt);await EditorAsset.runWithGlobalAutoSaveSuspended(async()=>{await rt.domainStore.runAsRemote(async()=>{var st;const ot=new Map(it.assets.map(ct=>[ct.uuid,ct]));for(const ct of at){const dt=ot.get(ct.assetId);if(!dt){console.warn(`[applyProjectReadAssetBatchRefresh] asset missing from latest project detail, skipping ${ct.assetId}`);continue}const ut=toDomainAssetState(dt),ht=(st=rt.assetStore.assets)==null?void 0:st[ct.assetId];syncDomainAssetState(rt,ut),ct.reason==="main"&&(await reloadRuntimeAsset(ht,ut,rt,dt),refreshSceneAssetPickerReferences(rt,ct.assetId))}})})}async function applyProjectReadRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,change:nt}){if(nt.type==="scene-changed"){await applyProjectReadFullRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et});return}await applyProjectReadAssetBatchRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,changes:[{assetId:nt.assetId,reason:nt.reason}]})}function mountEngineCanvas(rt,_e){var et;const tt=_e.canvas;if(!tt)throw new Error("projectStore.canvas is missing");return tt.style.width="100%",tt.style.height="100%",tt.oncontextmenu=nt=>{nt.preventDefault()},tt.parentElement!==rt&&rt.appendChild(tt),(et=_e.engine)==null||et.dispatch("onReady"),tt}function unique(rt){return Array.from(new Set(rt))}function createRuntimeBootstrapPlan({projectInfo:rt,sceneData:_e}){const tt=Array.from(collectAssetTypes(rt.assets)).sort(),et=Array.from(collectComponentTypes(_e)).sort(),nt=tt.filter(at=>!ASSET_MODULE_KEYS_BY_TYPE[at]),it=et.filter(at=>!COMPONENT_MODULE_KEYS_BY_TYPE[at]);return!_e||nt.length>0||it.length>0?{mode:"full",assetTypes:tt,componentTypes:et,unknownAssetTypes:nt,unknownComponentTypes:it,assetModuleKeys:[...FULL_ASSET_MODULE_KEYS],componentModuleKeys:[...FULL_COMPONENT_MODULE_KEYS],shouldInitGlTFIO:!0}:{mode:"selective",assetTypes:tt,componentTypes:et,unknownAssetTypes:nt,unknownComponentTypes:it,assetModuleKeys:unique([...tt.map(at=>ASSET_MODULE_KEYS_BY_TYPE[at]).filter(Boolean),"ambient-light"]).sort(),componentModuleKeys:unique(et.map(at=>COMPONENT_MODULE_KEYS_BY_TYPE[at]).filter(Boolean)).sort(),shouldInitGlTFIO:tt.includes("glTF")}}async function loadRuntimeBootstrapContext({storage:rt,projectId:_e,fetchImpl:tt=fetch}){const et=await rt.project.query(_e),nt=await loadCurrentSceneData(et,tt);return{projectInfo:et,currentSceneData:nt,plan:createRuntimeBootstrapPlan({projectInfo:et,sceneData:nt})}}async function loadCurrentSceneData(rt,_e){var nt;const tt=(nt=rt.content)==null?void 0:nt.scene,et=resolveCurrentSceneAsset(rt.assets,tt);if(!(et!=null&&et.url))return null;try{const it=await _e(et.url);if(!it.ok)return null;const at=await it.json();return at&&typeof at=="object"?at:null}catch{return null}}function resolveCurrentSceneAsset(rt,_e){if(_e){const tt=rt.find(et=>et.uuid===_e);if(tt)return tt}return rt.find(tt=>parseAssetType(tt.meta)==="Scene")}function collectAssetTypes(rt){const _e=new Set;for(const tt of rt){const et=parseAssetType(tt.meta);et&&!NON_RUNTIME_ASSET_TYPES.has(et)&&_e.add(et)}return _e}function parseAssetType(rt){try{const _e=JSON.parse(rt);return typeof _e.type=="string"&&_e.type.length>0?_e.type:null}catch{return null}}function collectComponentTypes(rt){var nt;const _e=new Set,tt=rt==null?void 0:rt.components;if(Array.isArray(tt))for(const it of tt){if(!it||typeof it!="object")continue;const at=readString(it.type)??readString(it.class);at&&_e.add(at)}const et=rt==null?void 0:rt.entities;if(!Array.isArray(et))return _e;for(const it of et){if(!it||typeof it!="object")continue;const at=readString((nt=it.transform)==null?void 0:nt.class);at&&_e.add(at);const ot=it.components;if(Array.isArray(ot))for(const st of ot){const ct=readString(st==null?void 0:st.class);ct&&_e.add(ct)}}return _e}function readString(rt){return typeof rt=="string"&&rt.length>0?rt:null}class PreviewRuntime{constructor(){Rt(this,"root",null);Rt(this,"projectStore",null);Rt(this,"viewportStore",null);Rt(this,"container",null);Rt(this,"storage",null);Rt(this,"projectId",null);Rt(this,"taskQueue",Promise.resolve());Rt(this,"resizeObserver",null)}get engine(){var _e;return((_e=this.projectStore)==null?void 0:_e.engine)??null}async init(_e,tt,et,nt={}){this.container=_e,this.storage=tt,this.projectId=et,await this.enqueueBootstrap(_e,tt,et,!1,nt.onStage,nt.projectInfo)}async reload(_e=this.storage,tt=this.projectId){if(!_e)throw new Error("storage is required");if(!tt)throw new Error("projectId is required");if(this.storage=_e,this.projectId=tt,this.root){await this.enqueueTask(async()=>{await this.runRefreshWithBootstrap(async et=>{await applyProjectReadFullRefresh({root:this.root,storage:_e,projectId:tt,projectInfo:et==null?void 0:et.projectInfo})})});return}if(!this.container)throw new Error("container is required");await this.enqueueBootstrap(this.container,_e,tt,!0)}async applyChange(_e){if(_e.type==="project-changed"){await this.reload();return}await this.enqueueTask(async()=>{const tt=this.root,et=this.storage,nt=this.projectId;if(!tt)throw new Error("runtime root is required");if(!et)throw new Error("storage is required");if(!nt)throw new Error("projectId is required");await this.runRefreshWithBootstrap(async it=>{await applyProjectReadRefresh({root:tt,storage:et,projectId:nt,projectInfo:it==null?void 0:it.projectInfo,change:{type:_e.type,assetId:_e.assetId,reason:_e.reason}})})})}async applyAssetBatchChange({changes:_e}){await this.enqueueTask(async()=>{const tt=this.root,et=this.storage,nt=this.projectId;if(!tt)throw new Error("runtime root is required");if(!et)throw new Error("storage is required");if(!nt)throw new Error("projectId is required");await this.runRefreshWithBootstrap(async it=>{await applyProjectReadAssetBatchRefresh({root:tt,storage:et,projectId:nt,projectInfo:it==null?void 0:it.projectInfo,changes:_e})})})}async runRefreshWithBootstrap(_e){var et,nt;const tt=await this.ensureBootstrapForCurrentProject();await _e(tt),(nt=(et=this.viewportStore)==null?void 0:et.reapplySceneCameraIfUntouched)==null||nt.call(et)}async ensureBootstrapForCurrentProject(){const _e=this.storage,tt=this.projectId;if(!_e||!tt)return null;try{const et=await loadRuntimeBootstrapContext({storage:_e,projectId:tt});return await bootstrapEditorRuntime({plan:et.plan}),et}catch(et){throw console.warn("[PreviewRuntime] ensureBootstrapForCurrentProject failed:",et),et}}async setEntityTransform(_e,tt,et={}){await this.enqueueTask(async()=>{const{root:nt,projectStore:it}=this.requireRuntimeHandles();nt.entityFacade.setTransform(_e,tt),await this.persistSceneIfRequested(it,et.persist)})}async saveScene(){await this.enqueueTask(async()=>{const{projectStore:_e}=this.requireRuntimeHandles();await this.persistScene(_e)})}async undo(_e={}){return this.enqueueTask(async()=>{const{root:tt,projectStore:et}=this.requireRuntimeHandles(),nt=tt.undo();return nt&&await this.persistSceneIfRequested(et,_e.persist),nt})}async redo(_e={}){return this.enqueueTask(async()=>{const{root:tt,projectStore:et}=this.requireRuntimeHandles(),nt=tt.redo();return nt&&await this.persistSceneIfRequested(et,_e.persist),nt})}dispose(){this.disposeRuntime(),this.container=null,this.storage=null,this.projectId=null}enqueueBootstrap(_e,tt,et,nt=!1,it,at){return this.enqueueTask(async()=>{nt&&this.disposeRuntime(),await this.bootstrap(_e,tt,et,it,at)})}enqueueTask(_e){const tt=this.taskQueue.then(_e,_e);return this.taskQueue=tt.then(()=>{},()=>{}),tt}async bootstrap(_e,tt,et,nt,it){const at=new Root,ot=document.createElement("canvas"),st=await initProjectReadRuntime({root:at,storage:tt,projectId:et,canvas:ot,projectInfo:it,onStage:nt,viewport:{mode:"editor",useSceneCameraAsFallback:!0}});this.root=st.root,this.projectStore=st.projectStore,this.viewportStore=st.viewportStore,mountEngineCanvas(_e,this.projectStore),this.attachResizeSync(_e)}disposeRuntime(){var tt,et,nt,it;(tt=this.resizeObserver)==null||tt.disconnect(),this.resizeObserver=null;const _e=(et=this.projectStore)==null?void 0:et.canvas;_e!=null&&_e.parentElement&&_e.parentElement.removeChild(_e),(it=(nt=this.projectStore)==null?void 0:nt.reset)==null||it.call(nt),this.root=null,this.projectStore=null,this.viewportStore=null}attachResizeSync(_e){var et,nt,it;if((et=this.resizeObserver)==null||et.disconnect(),this.resizeObserver=null,(it=(nt=this.viewportStore)==null?void 0:nt.handleContainerResize)==null||it.call(nt),typeof ResizeObserver>"u")return;const tt=new ResizeObserver(()=>{var at,ot;(ot=(at=this.viewportStore)==null?void 0:at.handleContainerResize)==null||ot.call(at)});tt.observe(_e),this.resizeObserver=tt}requireRuntimeHandles(){const _e=this.root,tt=this.projectStore;if(!_e)throw new Error("runtime root is required");if(!tt)throw new Error("projectStore is required");return{root:_e,projectStore:tt}}async persistSceneIfRequested(_e,tt=!1){tt&&await this.persistScene(_e)}async persistScene(_e){var et;const tt=(et=_e.updateSceneAsset)==null?void 0:et.bind(_e);if(!tt)throw new Error("projectStore.updateSceneAsset is required");await tt()}}class HttpStorage{constructor(_e){Rt(this,"project");Rt(this,"assets");Rt(this,"schema");this.project={query:tt=>_e.project.query(tt),modifyProjectName:(tt,et)=>_e.project.modifyProjectName(tt,et).then(()=>{}),updateThumbnail:(tt,et)=>_e.project.updateThumbnail(tt,et),updateMetaInfo:(tt,et,nt)=>_e.project.updateMetaInfo(tt,et,nt).then(()=>{}),updateSetting:(tt,et)=>_e.project.updateSetting(tt,et).then(()=>{})},this.assets={create:async tt=>{const{id:et,url:nt,meta:it}=await _e.assets.create(tt);return{id:et,url:nt,meta:typeof it=="string"?it:void 0}},update:(tt,et)=>_e.assets.update(tt,et),delete:(tt,et)=>_e.assets.delete(tt,et),duplicate:async tt=>(await _e.assets.duplicateTo(tt)).data},this.schema={update:(tt,et)=>_e.schema.update(tt,et)}}}function createStorage(rt,_e=fetch){const tt={project:{query:async et=>{const nt=await _e(`${rt}/api/project/${et}`);if(!nt.ok)throw new Error(`project query failed: ${nt.status}`);return nt.json()},modifyProjectName:async()=>({}),updateThumbnail:async()=>({thumbnail:""}),updateMetaInfo:async()=>({}),updateSetting:async()=>({})},assets:{create:async()=>({id:"",url:""}),update:async(et,nt)=>{const it=await serializeAssetUpdate(nt),at=await _e(`${rt}/api/assets/${encodeURIComponent(et)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(it)});if(!at.ok)throw new Error(`asset update failed: ${at.status}`);return at.json()},delete:async()=>{},duplicateTo:async()=>({data:[]})},schema:{update:async()=>{}}};return new HttpStorage(tt)}async function serializeAssetUpdate(rt){return{file:rt.file?await serializeBlob(rt.file):void 0,meta:rt.meta,name:rt.name,parentId:rt.parentId,url:rt.url}}async function serializeBlob(rt){const _e=await rt.arrayBuffer();return{base64:encodeBase64(_e),type:rt.type}}function encodeBase64(rt){if(typeof Buffer<"u")return Buffer.from(rt).toString("base64");let _e="";const tt=new Uint8Array(rt);for(let et=0;et<tt.length;et++)_e+=String.fromCharCode(tt[et]);return btoa(_e)}async function loadRuntimeProjectId(rt,_e=fetch){const tt=normalizeBaseUrl(rt),et=await _e(`${tt}/healthz`);if(!et.ok)throw new Error(`project id query failed: ${et.status}`);const nt=await et.json();return typeof nt.projectId=="string"&&nt.projectId.length>0?nt.projectId:"local"}async function loadRuntimeProjectContext(rt,_e={}){var ot,st;const tt=normalizeBaseUrl(rt),et=_e.fetchImpl??fetch;(ot=_e.onStage)==null||ot.call(_e,"resolve-project-id");const nt=await loadRuntimeProjectId(tt,et),it=createStorage(tt,et);(st=_e.onStage)==null||st.call(_e,"query-project");const at=await loadRuntimeBootstrapContext({storage:it,projectId:nt,fetchImpl:et});return{storage:it,projectId:nt,...at}}function normalizeBaseUrl(rt){return rt.replace(/\/$/,"")}async function main(){const rt=document.getElementById("app"),_e=document.getElementById("status");if(!rt)throw new Error("preview container not found");const tt=(ct,dt="busy")=>{_e&&(_e.textContent=ct,_e.setAttribute("data-state",dt))},et=createStartupStatusReporter({setStatus:tt});let nt=!1;const it=(ct,dt="busy")=>{if(ct==="hot reload disconnected, retrying..."){nt=!0,tt(ct,dt);return}if(ct==="hot reload connected"){if(!nt)return;nt=!1}tt(ct,dt)},at="",ot=new PreviewRuntime;let st=null;try{const{storage:ct,projectId:dt,projectInfo:ut,plan:ht}=await loadRuntimeProjectContext(at,{onStage:et.reportStage});et.reportStage("boot-runtime"),await bootstrapEditorRuntime({onStage:et.reportStage,plan:ht}),await ot.init(rt,ct,dt,{onStage:et.reportStage,projectInfo:ut}),window.__runtime=ot,Object.defineProperty(window,"__engine",{configurable:!0,enumerable:!0,get:()=>ot.engine}),et.finish(),st=attachSceneHotReload({runtime:ot,onStatus:it});const ft=()=>{st==null||st(),ot.dispose()};window.addEventListener("beforeunload",ft)}catch(ct){console.error(ct),tt(ct instanceof Error?ct.message:String(ct))}}main();export{Sprite$1 as $,AntiAliasing as A,BoundingBox as B,ComponentType as C,DepthTextureMode as D,EditorComponent as E,Vector2 as F,resourceLoader as G,Loader as H,Renderer$1 as I,ignoreClone as J,Entity as K,LayerSetting as L,MSAASamples as M,SpriteRenderer as N,TextRenderer as O,PhysicsMaterialCombineMode as P,Font as Q,RenderFace as R,Script as S,TextureWrapMode$1 as T,Logger as U,Vector4 as V,Engine as W,AssetPromise as X,Utils$3 as Y,AssetType as Z,EngineObject as _,Layer as a,TextureFormat as a$,SubPrimitive as a0,BlendFactor as a1,BlendOperation as a2,VertexElement as a3,VertexElementFormat as a4,Buffer$3 as a5,BufferBindFlag as a6,BufferUsage as a7,IndexBufferBinding as a8,IndexFormat as a9,SpriteMaskLayer as aA,SpriteMaskInteraction as aB,action as aC,hdrColorSerializer as aD,ValueTypeEnum as aE,SpriteDrawMode as aF,resolveSceneChangeUpdate as aG,styled as aH,Flex as aI,observer as aJ,useTranslation as aK,ActionButton as aL,reactExports as aM,Collapsible as aN,InspectorForm as aO,Button$2 as aP,AnimatorController as aQ,AnimatorControllerLayer as aR,AnimatorLayerBlendingMode as aS,meta as aT,override as aU,AnimatorStateTransition as aV,parseSourceV2SceneFileJson as aW,stringifySourceV2SceneFile as aX,reportSavingWhileDestroy as aY,buildSourceSceneFile as aZ,Texture2D as a_,assignmentClone as aa,deepClone as ab,ReferResource as ac,TextureFilterMode as ad,Shader as ae,CullMode as af,RenderQueueType as ag,Material as ah,Vector3 as ai,Primitive as aj,VertexBufferBinding as ak,XRManager as al,decoder as am,Ray as an,Plane as ao,decode as ap,CameraType$1 as aq,Matrix as ar,Signal as as,Rect$1 as at,Quaternion as au,jsxRuntimeExports as av,FormItem as aw,extractFormItemProps as ax,StyledText as ay,angleSerializer as az,CameraClearFlags as b,Root as b$,AUDIO_EXT_LIST as b0,ShaderProperty as b1,ShaderPropertyType as b2,Color$1 as b3,createCollection$1 as b4,createContextScope$4 as b5,createCollapsibleScope as b6,React$1 as b7,useControllableState as b8,useComposedRefs$6 as b9,FormItemAssetPicker$1 as bA,createReactComponent$1 as bB,IconPlus$1 as bC,PrimitiveMesh as bD,ParticleRenderer as bE,reaction as bF,extendObservable as bG,BlendMode as bH,cloneDeep$1 as bI,isObservableProp as bJ,virtualPropertyManually as bK,InterpolationType as bL,addPropertyProxyConfig as bM,ModelMesh as bN,BlendShape as bO,MeshTopology as bP,BlinnPhongMaterial as bQ,ensureUploadMainFile as bR,AssetPreviewer as bS,Select as bT,SelectItem as bU,v4 as bV,collectDependenciesFromMeta as bW,n as bX,extname$1 as bY,basename$1 as bZ,assetService as b_,useDirection as ba,composeEventHandlers$6 as bb,Primitive$8 as bc,useId as bd,Root$d as be,Trigger$5 as bf,Content$5 as bg,keyframes$2 as bh,IconChevronRight as bi,Spin as bj,FormItemSelect as bk,normalizeToDomainValueRecord as bl,FormItemVector3 as bm,EntityPicker$1 as bn,Transform as bo,AnimatorCullingMode as bp,BaseScript as bq,Animator as br,viewport as bs,ViewportPlugin as bt,MathUtil as bu,VertexAttribute as bv,ContentRestorer as bw,BufferMesh as bx,RenderTarget as by,Separator as bz,Downsampling as c,isSubProperty as c$,assetIconMap as c0,showEditorUiToastError as c1,computed as c2,getBoundingBox as c3,FormItemButton as c4,toJS as c5,normalizeToDomainValue as c6,api as c7,ParticleCurve as c8,CurveKey as c9,StaticCollider as cA,CharacterController as cB,SpringJoint as cC,FixedJoint as cD,HingeJoint as cE,AudioSource as cF,PostProcess as cG,AnimationFloatCurve as cH,AnimationFloatArrayCurve as cI,AnimationVector2Curve as cJ,AnimationVector3Curve as cK,AnimationVector4Curve as cL,AnimationQuaternionCurve as cM,AnimationColorCurve as cN,AnimationRefCurve as cO,AnimationRectCurve as cP,AnimationBoolCurve as cQ,AnimationStringCurve as cR,AnimationArrayCurve as cS,PropertyType as cT,getPropertyProxyConfigs as cU,TangentMode as cV,TangentType as cW,openAnimatorStateReport as cX,AnimationClip as cY,getPropertyUniquePath as cZ,getPropertyConfigs as c_,denormalizeColor as ca,ColorPicker as cb,normalizeColor as cc,ParticleGradient as cd,GradientColorKey as ce,GradientAlphaKey as cf,TrailTextureMode as cg,TextVerticalAlignment as ch,TextHorizontalAlignment as ci,FontStyle as cj,OverflowMode as ck,FormItemInput as cl,FormItemInputNumber as cm,DirectLight as cn,Camera as co,SkinnedMeshRenderer as cp,PointLight as cq,SpotLight as cr,SpriteMask$1 as cs,UITransform as ct,UICanvas as cu,UIGroup as cv,Button$1 as cw,Image$3 as cx,Text as cy,DynamicCollider as cz,decomposeLayersByBitwise as d,assertSourceV2PrefabFileStructure as d$,storedPropertyProxySymbol as d0,Keyframe$1 as d1,useEscapeKeydown as d2,useCallbackRef$1 as d3,dispatchDiscreteCustomEvent$1 as d4,useLayoutEffect2 as d5,$1CM7W$reactdom as d6,composeRefs$7 as d7,createPopperScope$1 as d8,Anchor$2 as d9,toBuffer as dA,toBufferKTX2 as dB,SphericalHarmonics3 as dC,AmbientLight as dD,DiffuseMode as dE,FileHeader as dF,createStore as dG,get as dH,set as dI,__vitePreload as dJ,md5 as dK,logger$2 as dL,ReturnableObjectPool as dM,ClearableObjectPool as dN,ShaderLanguage as dO,CompareFunction as dP,StencilOperation as dQ,ColorWriteMask as dR,RenderStateElementKey as dS,shaders as dT,browserExports as dU,Group$2 as dV,resolve$2 as dW,ShaderFactory as dX,openCodeEditor as dY,openScriptReport as dZ,mergeSourceValueRecords as d_,Presence$2 as da,Content$3 as db,Arrow$2 as dc,Root2$6 as dd,Checkbox as de,PostProcessEffectParameter as df,PostProcessEffectVector4Parameter as dg,FormItemVector4 as dh,PostProcessEffectVector3Parameter as di,PostProcessEffectVector2Parameter as dj,FormItemVector2 as dk,PostProcessEffectTextureParameter as dl,PostProcessEffectColorParameter as dm,FormItemColor as dn,PostProcessEffectEnumParameter as dp,PostProcessEffectBoolParameter as dq,FormItemToggle as dr,PostProcessEffectFloatParameter as ds,TonemappingEffect as dt,BloomEffect as du,TextureCubeFace as dv,BakerResolution as dw,DecodeMode as dx,IBLBaker as dy,isValidFileHeader as dz,t$7 as e,CameraModifyFlags as e$,isPlainRecord as e0,FormItemGroup as e1,ParticleStopMode as e2,isSourceInstanceBoundary as e3,resolveSourceInstanceRootOverrideTarget as e4,readSourceEntityResolvedState as e5,isTraceEnabled as e6,beginTrace as e7,endTrace as e8,EntityManager as e9,getTextureInformation as eA,resolveLocalWorkspaceRelativePath as eB,Galacean as eC,ColliderShapeUpAxis$1 as eD,SphereColliderShape as eE,PlaneColliderShape as eF,CapsuleColliderShape as eG,BoxColliderShape as eH,FormItemToggleGroup as eI,DynamicColliderConstraints as eJ,CollisionDetectionMode as eK,ControllerNonWalkableMode as eL,FormItemEntityPicker as eM,EditorDependentMode as eN,JointLimits as eO,JointMotor as eP,ScaleTransition as eQ,ColorTransition as eR,SpriteTransition as eS,HorizontalAlignmentMode as eT,VerticalAlignmentMode as eU,css$1 as eV,InputNumber as eW,EntityModifyFlags as eX,debounce$2 as eY,CanvasRenderMode as eZ,ResolutionAdaptationMode as e_,parseSourceV2PrefabFileJson as ea,stringifySourceV2PrefabFile as eb,normalizePrefabRootInstanceOverrides as ec,SerializeContext as ed,createSourceRefCodec as ee,convertAssetRefsToDomainRefs as ef,assertCanonicalSourceRef as eg,readComponentSourceProps as eh,readComponentSourcePropsWithEditorValues as ei,diffSourceValueRecord as ej,combineLayersByBitwise as ek,buildSourceIdIndex as el,encodeJsonPointerSegment as em,sourceValuesEqual as en,getSerializeConfigs as eo,buildInitialComponentProps as ep,showAlert as eq,PrefabResource as er,TraceLogger as es,GLTFResource as et,MessageCenter as eu,reactDomExports as ev,FormItemSlider as ew,LineDrawer as ex,TextureCube as ey,replaceExtname as ez,propertyProxy as f,PopoverCloseTrigger as f$,createReactComponent$3 as f0,clamp$2 as f1,mergeRefs as f2,ActionButtonGroup as f3,Popover as f4,getDefaultExportFromCjs as f5,Input as f6,autorun as f7,buildGlTFDomainInstanceBindingSync as f8,Component as f9,Title as fA,Description$1 as fB,IconX as fC,Root$4 as fD,Portal$3 as fE,lightTheme as fF,darkTheme as fG,Badge as fH,Breadcrumbs as fI,BreadcrumbItem as fJ,CascadeSlider as fK,useColorSpaceConversion as fL,createDisplayColorSpaceToggle as fM,toNormalizeHexStr as fN,isEqual$1 as fO,blendParticleStops as fP,generateLinearGradient as fQ,generateHDR as fR,generatePreviewColor as fS,srgbColorToLinear as fT,linearColorToSRGB as fU,GradientSlider as fV,ParticleSlider as fW,HDRSlider as fX,EyeDropperIcon as fY,IconRightBottomCorner as fZ,IconPendingFile$1 as f_,ParticleShapeArcMode as fa,ConeEmitType as fb,MeshShape as fc,SphereShape as fd,HemisphereShape as fe,ConeShape as ff,CircleShape as fg,BoxShape as fh,ParticleCurveMode as fi,FormItemTable as fj,ParticleCompositeCurve as fk,Burst as fl,ParticleGradientMode as fm,ParticleRenderMode as fn,ParticleSimulationSpace as fo,ParticleScaleMode as fp,Ie as fq,useDrop as fr,Overlay$2 as fs,overlayFadeIn as ft,Content$1 as fu,contentShow as fv,contentFadeIn as fw,contentFadeOut as fx,DialogClose as fy,Trigger$2 as fz,getMultipleLayerOptions as g,createRovingFocusGroupScope as g$,SegmentControl as g0,SegmentControlItem as g1,Slider as g2,StyledTextarea as g3,ToggleGroup$1 as g4,ToggleGroupItem as g5,StyledBold as g6,StyledLink as g7,StyledTitle$1 as g8,TreeItemRoot as g9,Slot as gA,useSize as gB,useFloating as gC,autoUpdate as gD,offset$2 as gE,shift as gF,limitShift as gG,flip as gH,size as gI,arrow as gJ,hide as gK,hideOthers as gL,useFocusGuards as gM,FocusScope as gN,DismissableLayer$1 as gO,RemoveScroll as gP,Portal$6 as gQ,createSidecarMedium as gR,__rest$r as gS,useMergeRefs as gT,__assign as gU,fullWidthClassName as gV,zeroRightClassName as gW,styleSingleton as gX,__spreadArray as gY,RemoveScrollBar as gZ,exportSidecar as g_,TreeItemContent as ga,TreeItemIcon as gb,TreeItemPreview as gc,TreeGroup$1 as gd,AlertDialog as ge,AssetItem as gf,HoverCard as gg,resetStyle as gh,globalCss as gi,theme as gj,getCssText as gk,createTheme as gl,recipes as gm,keyframes$1 as gn,DragContext as go,DragDropContextProvider as gp,useDrag as gq,domainWhiteList as gr,Env as gs,EQueryKeys as gt,EventBus as gu,reloadSceneStateFromAsset as gv,Scene as gw,storedMainSymbol as gx,FormItemRect as gy,SpriteAtlas as gz,layerProxy as h,Root$7 as h0,Item$1 as h1,clamp$3 as h2,radioGroupStyle as h3,labelStyle as h4,basicItemStyle as h5,contentStyle as h6,contextMenuContentStyle as h7,subMenuItemStyle as h8,separatorStyle as h9,checkboxItemStyle as ha,radioItemStyle as hb,indicatorStyle as hc,dropdownMenuContentStyle as hd,IconCheck as he,ShadowType as i,EditorAsset as j,PhysicsMaterial as k,layerSerializer as l,main$1 as m,asset as n,AssetsImportType as o,propertyField as p,DragLayer as q,runInAction as r,serialize as s,transformEnumToOptions as t,makeObservable as u,virtualProperty as v,openMarkdownEditor as w,observable as x,MeshRenderer as y,PBRMaterial as z};
|
|
29238
|
+
`))}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("enableEdgeDock",!0).setType(Attribute.BOOLEAN).setDescription("enable docking to the edges of the layout, this will show the edge indicators"),_e.add("rootOrientationVertical",!1).setType(Attribute.BOOLEAN).setDescription("the top level 'row' will layout horizontally by default, set this option true to make it layout vertically"),_e.add("enableRotateBorderIcons",!0).setType(Attribute.BOOLEAN).setDescription("boolean indicating if tab icons should rotate with the text in the left and right borders"),_e.add("splitterSize",8).setType(Attribute.NUMBER).setDescription("width in pixels of all splitters between tabsets/borders"),_e.add("splitterExtra",0).setType(Attribute.NUMBER).setDescription("additional width in pixels of the splitter hit test area"),_e.add("splitterEnableHandle",!1).setType(Attribute.BOOLEAN).setDescription("enable a small centralized handle on all splitters"),_e.add("tabEnableClose",!0).setType(Attribute.BOOLEAN),_e.add("tabCloseType",1).setType("ICloseType"),_e.add("tabEnablePopout",!1).setType(Attribute.BOOLEAN).setAlias("tabEnableFloat"),_e.add("tabEnablePopoutIcon",!0).setType(Attribute.BOOLEAN),_e.add("tabEnablePopoutOverlay",!1).setType(Attribute.BOOLEAN),_e.add("tabEnableDrag",!0).setType(Attribute.BOOLEAN),_e.add("tabEnableRename",!0).setType(Attribute.BOOLEAN),_e.add("tabContentClassName",void 0).setType(Attribute.STRING),_e.add("tabClassName",void 0).setType(Attribute.STRING),_e.add("tabIcon",void 0).setType(Attribute.STRING),_e.add("tabEnableRenderOnDemand",!0).setType(Attribute.BOOLEAN),_e.add("tabDragSpeed",.3).setType(Attribute.NUMBER),_e.add("tabBorderWidth",-1).setType(Attribute.NUMBER),_e.add("tabBorderHeight",-1).setType(Attribute.NUMBER),_e.add("tabSetEnableDeleteWhenEmpty",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDrop",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDrag",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableDivide",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableMaximize",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableClose",!1).setType(Attribute.BOOLEAN),_e.add("tabSetEnableSingleTabStretch",!1).setType(Attribute.BOOLEAN),_e.add("tabSetAutoSelectTab",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableActiveIcon",!1).setType(Attribute.BOOLEAN),_e.add("tabSetClassNameTabStrip",void 0).setType(Attribute.STRING),_e.add("tabSetEnableTabStrip",!0).setType(Attribute.BOOLEAN),_e.add("tabSetEnableTabWrap",!1).setType(Attribute.BOOLEAN),_e.add("tabSetTabLocation","top").setType("ITabLocation"),_e.add("tabMinWidth",DefaultMin).setType(Attribute.NUMBER),_e.add("tabMinHeight",DefaultMin).setType(Attribute.NUMBER),_e.add("tabSetMinWidth",DefaultMin).setType(Attribute.NUMBER),_e.add("tabSetMinHeight",DefaultMin).setType(Attribute.NUMBER),_e.add("tabMaxWidth",DefaultMax).setType(Attribute.NUMBER),_e.add("tabMaxHeight",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetMaxWidth",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetMaxHeight",DefaultMax).setType(Attribute.NUMBER),_e.add("tabSetEnableTabScrollbar",!1).setType(Attribute.BOOLEAN),_e.add("borderSize",200).setType(Attribute.NUMBER),_e.add("borderMinSize",DefaultMin).setType(Attribute.NUMBER),_e.add("borderMaxSize",DefaultMax).setType(Attribute.NUMBER),_e.add("borderEnableDrop",!0).setType(Attribute.BOOLEAN),_e.add("borderAutoSelectTabWhenOpen",!0).setType(Attribute.BOOLEAN),_e.add("borderAutoSelectTabWhenClosed",!1).setType(Attribute.BOOLEAN),_e.add("borderClassName",void 0).setType(Attribute.STRING),_e.add("borderEnableAutoHide",!1).setType(Attribute.BOOLEAN),_e.add("borderEnableTabScrollbar",!1).setType(Attribute.BOOLEAN),_e}};__publicField(_Model,"MAIN_WINDOW_ID","__main_window_id__");__publicField(_Model,"attributeDefinitions",_Model.createAttributeDefinitions());let Model=_Model;const _BorderNode=class Dr extends Node$1{constructor(_e,tt,et){super(et),__publicField(this,"contentRect",Rect.empty()),__publicField(this,"tabHeaderRect",Rect.empty()),__publicField(this,"location"),this.location=_e,this.attributes.id=`border_${_e.getName()}`,Dr.attributeDefinitions.fromJson(tt,this.attributes),et.addNode(this)}static fromJson(_e,tt){const et=DockLocation.getByName(_e.location),nt=new Dr(et,_e,tt);return _e.children&&(nt.children=_e.children.map(it=>{const at=TabNode.fromJson(it,tt);return at.setParent(nt),at})),nt}getLocation(){return this.location}getClassName(){return this.getAttr("className")}isHorizontal(){return this.location.orientation===Orientation.HORZ}getSize(){const _e=this.getAttr("size"),tt=this.getSelected();if(tt===-1)return _e;{const et=this.children[tt],nt=this.isHorizontal()?et.getAttr("borderWidth"):et.getAttr("borderHeight");return nt===-1?_e:nt}}getMinSize(){const _e=this.getSelectedNode();let tt=this.getAttr("minSize");if(_e){const et=this.isHorizontal()?_e.getMinWidth():_e.getMinHeight();tt=Math.max(tt,et)}return tt}getMaxSize(){const _e=this.getSelectedNode();let tt=this.getAttr("maxSize");if(_e){const et=this.isHorizontal()?_e.getMaxWidth():_e.getMaxHeight();tt=Math.min(tt,et)}return tt}getSelected(){return this.attributes.selected}isAutoHide(){return this.getAttr("enableAutoHide")}getSelectedNode(){if(this.getSelected()!==-1)return this.children[this.getSelected()]}getOrientation(){return this.location.getOrientation()}getConfig(){return this.attributes.config}isMaximized(){return!1}isShowing(){return this.attributes.show}toJson(){const _e={};return Dr.attributeDefinitions.toJson(_e,this.attributes),_e.location=this.location.getName(),_e.children=this.children.map(tt=>tt.toJson()),_e}isAutoSelectTab(_e){return _e==null&&(_e=this.getSelected()!==-1),_e?this.getAttr("autoSelectTabWhenOpen"):this.getAttr("autoSelectTabWhenClosed")}isEnableTabScrollbar(){return this.getAttr("enableTabScrollbar")}setSelected(_e){this.attributes.selected=_e}getTabHeaderRect(){return this.tabHeaderRect}setTabHeaderRect(_e){this.tabHeaderRect=_e}getRect(){return this.tabHeaderRect}getContentRect(){return this.contentRect}setContentRect(_e){this.contentRect=_e}isEnableDrop(){return this.getAttr("enableDrop")}setSize(_e){const tt=this.getSelected();if(tt===-1)this.attributes.size=_e;else{const et=this.children[tt];(this.isHorizontal()?et.getAttr("borderWidth"):et.getAttr("borderHeight"))===-1?this.attributes.size=_e:this.isHorizontal()?et.setBorderWidth(_e):et.setBorderHeight(_e)}}updateAttrs(_e){Dr.attributeDefinitions.update(_e,this.attributes)}remove(_e){const tt=this.removeChild(_e);this.getSelected()!==-1&&adjustSelectedIndex(this,tt)}canDrop(_e,tt,et){if(!(_e instanceof TabNode))return;let nt;const it=DockLocation.CENTER;if(this.tabHeaderRect.contains(tt,et)){if(this.location.orientation===Orientation.VERT)if(this.children.length>0){let at=this.children[0],ot=at.getTabRect();const st=ot.y,ct=ot.height;let dt=this.tabHeaderRect.x,ut=0;for(let ht=0;ht<this.children.length;ht++){if(at=this.children[ht],ot=at.getTabRect(),ut=ot.x+ot.width/2,tt>=dt&&tt<ut){const ft=new Rect(ot.x-2,st,3,ct);nt=new DropInfo(this,ft,it,ht,CLASSES.FLEXLAYOUT__OUTLINE_RECT);break}dt=ut}if(nt==null){const ht=new Rect(ot.getRight()-2,st,3,ct);nt=new DropInfo(this,ht,it,this.children.length,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}}else{const at=new Rect(this.tabHeaderRect.x+1,this.tabHeaderRect.y+2,3,18);nt=new DropInfo(this,at,it,0,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}else if(this.children.length>0){let at=this.children[0],ot=at.getTabRect();const st=ot.x,ct=ot.width;let dt=this.tabHeaderRect.y,ut=0;for(let ht=0;ht<this.children.length;ht++){if(at=this.children[ht],ot=at.getTabRect(),ut=ot.y+ot.height/2,et>=dt&&et<ut){const ft=new Rect(st,ot.y-2,ct,3);nt=new DropInfo(this,ft,it,ht,CLASSES.FLEXLAYOUT__OUTLINE_RECT);break}dt=ut}if(nt==null){const ht=new Rect(st,ot.getBottom()-2,ct,3);nt=new DropInfo(this,ht,it,this.children.length,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}}else{const at=new Rect(this.tabHeaderRect.x+2,this.tabHeaderRect.y+1,18,3);nt=new DropInfo(this,at,it,0,CLASSES.FLEXLAYOUT__OUTLINE_RECT)}if(!_e.canDockInto(_e,nt))return}else if(this.getSelected()!==-1&&this.contentRect.contains(tt,et)){const at=this.contentRect;if(nt=new DropInfo(this,at,it,-1,CLASSES.FLEXLAYOUT__OUTLINE_RECT),!_e.canDockInto(_e,nt))return}return nt}drop(_e,tt,et,nt){let it=0;const at=_e.getParent();at!==void 0&&(it=at.removeChild(_e),at!==this&&at instanceof Dr&&at.getSelected()===it?at.setSelected(-1):adjustSelectedIndex(at,it)),_e instanceof TabNode&&at===this&&it<et&&et>0&&et--;let ot=et;ot===-1&&(ot=this.children.length),_e instanceof TabNode&&this.addChild(_e,ot),(nt||nt!==!1&&this.isAutoSelectTab())&&this.setSelected(ot),this.model.tidy()}getSplitterBounds(_e,tt=!1){const et=[0,0],nt=tt?this.getMinSize():0,it=tt?this.getMaxSize():99999,at=this.model.getRoot(Model.MAIN_WINDOW_ID),ot=at.getRect(),st=this.model.getSplitterSize();if(this.location===DockLocation.TOP){et[0]=this.tabHeaderRect.getBottom()+nt;const ct=this.tabHeaderRect.getBottom()+it;et[1]=Math.max(et[0],ot.getBottom()-at.getMinHeight()-st),et[1]=Math.min(et[1],ct)}else if(this.location===DockLocation.LEFT){et[0]=this.tabHeaderRect.getRight()+nt;const ct=this.tabHeaderRect.getRight()+it;et[1]=Math.max(et[0],ot.getRight()-at.getMinWidth()-st),et[1]=Math.min(et[1],ct)}else if(this.location===DockLocation.BOTTOM){et[1]=this.tabHeaderRect.y-nt-st;const ct=this.tabHeaderRect.y-it-st;et[0]=Math.min(et[1],ot.y+at.getMinHeight()),et[0]=Math.max(et[0],ct)}else if(this.location===DockLocation.RIGHT){et[1]=this.tabHeaderRect.x-nt-st;const ct=this.tabHeaderRect.x-it-st;et[0]=Math.min(et[1],ot.x+at.getMinWidth()),et[0]=Math.max(et[0],ct)}return et}calculateSplit(_e,tt){const et=this.getSplitterBounds(tt);return this.location===DockLocation.BOTTOM||this.location===DockLocation.RIGHT?Math.max(0,et[1]-tt):Math.max(0,tt-et[0])}getAttributeDefinitions(){return Dr.attributeDefinitions}static getAttributeDefinitions(){return Dr.attributeDefinitions}static createAttributeDefinitions(){const _e=new AttributeDefinitions;return _e.add("type",Dr.TYPE,!0).setType(Attribute.STRING).setFixed(),_e.add("selected",-1).setType(Attribute.NUMBER).setDescription("index of selected/visible tab in border; -1 means no tab selected"),_e.add("show",!0).setType(Attribute.BOOLEAN).setDescription("show/hide this border"),_e.add("config",void 0).setType("any").setDescription("a place to hold json config used in your own code"),_e.addInherited("enableDrop","borderEnableDrop").setType(Attribute.BOOLEAN).setDescription("whether tabs can be dropped into this border"),_e.addInherited("className","borderClassName").setType(Attribute.STRING).setDescription("class applied to tab button"),_e.addInherited("autoSelectTabWhenOpen","borderAutoSelectTabWhenOpen").setType(Attribute.BOOLEAN).setDescription("whether to select new/moved tabs in border when the border is already open"),_e.addInherited("autoSelectTabWhenClosed","borderAutoSelectTabWhenClosed").setType(Attribute.BOOLEAN).setDescription("whether to select new/moved tabs in border when the border is currently closed"),_e.addInherited("size","borderSize").setType(Attribute.NUMBER).setDescription("size of the tab area when selected"),_e.addInherited("minSize","borderMinSize").setType(Attribute.NUMBER).setDescription("the minimum size of the tab area"),_e.addInherited("maxSize","borderMaxSize").setType(Attribute.NUMBER).setDescription("the maximum size of the tab area"),_e.addInherited("enableAutoHide","borderEnableAutoHide").setType(Attribute.BOOLEAN).setDescription("hide border if it has zero tabs"),_e.addInherited("enableTabScrollbar","borderEnableTabScrollbar").setType(Attribute.BOOLEAN).setDescription("whether to show a mini scrollbar for the tabs"),_e}};__publicField(_BorderNode,"TYPE","border");__publicField(_BorderNode,"attributeDefinitions",_BorderNode.createAttributeDefinitions());let BorderNode=_BorderNode,splitterDragging=!1;const Splitter=rt=>{const{layout:_e,node:tt,index:et,horizontal:nt}=rt,[it,at]=reactExports.useState(!1),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=reactExports.useRef([]),dt=reactExports.useRef(void 0),ut=reactExports.useRef(void 0),ht=reactExports.useRef(0),ft=reactExports.useRef(0),pt=reactExports.useRef({initialSizes:[],sum:0,startPosition:0}),mt=tt.getModel().getSplitterSize();let vt=tt.getModel().getSplitterExtra();isDesktop()||(vt=Math.max(20,vt+mt)-mt),reactExports.useEffect(()=>{var It,Ot;return(It=ot.current)==null||It.addEventListener("touchstart",_t,{passive:!1}),(Ot=st.current)==null||Ot.addEventListener("touchstart",_t,{passive:!1}),()=>{var Nt,Mt;(Nt=ot.current)==null||Nt.removeEventListener("touchstart",_t),(Mt=st.current)==null||Mt.removeEventListener("touchstart",_t)}},[]);const _t=It=>{It.preventDefault(),It.stopImmediatePropagation()},yt=It=>{var Ot;It.stopPropagation(),tt instanceof RowNode&&(pt.current=tt.getSplitterInitials(et)),enablePointerOnIFrames(!1,_e.getCurrentDocument()),startDrag(It.currentTarget.ownerDocument,It,Et,St,bt),ct.current=tt.getSplitterBounds(et,!0);const Nt=_e.getRootDiv();dt.current=_e.getCurrentDocument().createElement("div"),dt.current.style.flexDirection=nt?"row":"column",dt.current.className=_e.getClassName(CLASSES.FLEXLAYOUT__SPLITTER_DRAG),dt.current.style.cursor=tt.getOrientation()===Orientation.VERT?"ns-resize":"ew-resize",tt.getModel().isSplitterEnableHandle()&&(ut.current=_e.getCurrentDocument().createElement("div"),ut.current.className=Ct(CLASSES.FLEXLAYOUT__SPLITTER_HANDLE)+" "+Ct(nt?CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_HORZ:CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_VERT),dt.current.appendChild(ut.current));const Mt=(Ot=ot.current)==null?void 0:Ot.getBoundingClientRect(),Lt=new Rect(Mt.x-_e.getDomRect().x,Mt.y-_e.getDomRect().y,Mt.width,Mt.height);ht.current=It.clientX-Mt.x,ft.current=It.clientY-Mt.y,Lt.positionElement(dt.current),Nt&&Nt.appendChild(dt.current),at(!0),splitterDragging=!0},bt=()=>{const It=_e.getRootDiv();It&&dt.current&&It.removeChild(dt.current),dt.current=void 0,at(!1),splitterDragging=!1},Et=(It,Ot)=>{if(dt.current){const Nt=_e.getDomRect();if(!Nt)return;tt.getOrientation()===Orientation.VERT?dt.current.style.top=xt(Ot-Nt.y-ft.current)+"px":dt.current.style.left=xt(It-Nt.x-ht.current)+"px",_e.isRealtimeResize()&&At()}},St=()=>{if(dt.current){At();const It=_e.getRootDiv();It&&dt.current&&It.removeChild(dt.current),dt.current=void 0}enablePointerOnIFrames(!0,_e.getCurrentDocument()),at(!1),splitterDragging=!1},At=It=>{(()=>{if(dt.current){let Nt=0;if(tt.getOrientation()===Orientation.VERT?Nt=dt.current.offsetTop:Nt=dt.current.offsetLeft,tt instanceof BorderNode){const Mt=tt.calculateSplit(tt,Nt);_e.doAction(Actions.adjustBorderSplit(tt.getId(),Mt))}else{const Mt=pt.current,Lt=tt.calculateSplit(et,Nt,Mt.initialSizes,Mt.sum,Mt.startPosition);_e.doAction(Actions.adjustWeights(tt.getId(),Lt))}}})()},xt=It=>{const Ot=ct.current;let Nt=It;return It<Ot[0]&&(Nt=Ot[0]),It>Ot[1]&&(Nt=Ot[1]),Nt},Ct=_e.getClassName,Pt={cursor:nt?"ew-resize":"ns-resize",flexDirection:nt?"column":"row"};let Tt=Ct(CLASSES.FLEXLAYOUT__SPLITTER)+" "+Ct(CLASSES.FLEXLAYOUT__SPLITTER_+tt.getOrientation().getName());tt instanceof BorderNode?Tt+=" "+Ct(CLASSES.FLEXLAYOUT__SPLITTER_BORDER):tt.getModel().getMaximizedTabset(_e.getWindowId())!==void 0&&(Pt.display="none"),nt?(Pt.width=mt+"px",Pt.minWidth=mt+"px"):(Pt.height=mt+"px",Pt.minHeight=mt+"px");let wt;if(!it&&tt.getModel().isSplitterEnableHandle()&&(wt=jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__SPLITTER_HANDLE)+" "+Ct(nt?CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_HORZ:CLASSES.FLEXLAYOUT__SPLITTER_HANDLE_VERT)})),vt===0)return jsxRuntimeExports.jsx("div",{className:Tt,style:Pt,ref:ot,"data-layout-path":tt.getPath()+"/s"+(et-1),onPointerDown:yt,children:wt});{const It={};tt.getOrientation()===Orientation.HORZ?(It.height="100%",It.width=mt+vt+"px",It.cursor="ew-resize"):(It.height=mt+vt+"px",It.width="100%",It.cursor="ns-resize");const Ot=Ct(CLASSES.FLEXLAYOUT__SPLITTER_EXTRA);return jsxRuntimeExports.jsx("div",{className:Tt,style:Pt,ref:ot,"data-layout-path":tt.getPath()+"/s"+(et-1),onPointerDown:yt,children:jsxRuntimeExports.jsx("div",{style:It,ref:st,className:Ot,onPointerDown:yt})})}};function BorderTab(rt){const{layout:_e,border:tt,show:et}=rt,nt=reactExports.useRef(null),it=reactExports.useRef(void 0);reactExports.useLayoutEffect(()=>{const ct=_e.getBoundingClientRect(nt.current);!isNaN(ct.x)&&ct.width>0&&(tt.getContentRect().equals(ct)||(tt.setContentRect(ct),splitterDragging?(it.current&&clearTimeout(it.current),it.current=setTimeout(()=>{_e.redrawInternal("border content rect "+ct),it.current=void 0},50)):_e.redrawInternal("border content rect "+ct)))});let at=!0;const ot={};tt.getOrientation()===Orientation.HORZ?(ot.width=tt.getSize(),ot.minWidth=tt.getMinSize(),ot.maxWidth=tt.getMaxSize()):(ot.height=tt.getSize(),ot.minHeight=tt.getMinSize(),ot.maxHeight=tt.getMaxSize(),at=!1),ot.display=et?"flex":"none";const st=_e.getClassName(CLASSES.FLEXLAYOUT__BORDER_TAB_CONTENTS);return tt.getLocation()===DockLocation.LEFT||tt.getLocation()===DockLocation.TOP?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{ref:nt,style:ot,className:st}),et&&jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:0,horizontal:at})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[et&&jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:0,horizontal:at}),jsxRuntimeExports.jsx("div",{ref:nt,style:ot,className:st})]})}var ICloseType=(rt=>(rt[rt.Visible=1]="Visible",rt[rt.Always=2]="Always",rt[rt.Selected=3]="Selected",rt))(ICloseType||{});const BorderButton=rt=>{const{layout:_e,node:tt,selected:et,border:nt,icons:it,path:at}=rt,ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=Pt=>{tt.isEnableDrag()?(Pt.stopPropagation(),_e.setDragNode(Pt.nativeEvent,tt)):Pt.preventDefault()},dt=Pt=>{Pt.stopPropagation(),_e.clearDragMain()},ut=Pt=>{isAuxMouseEvent(Pt)&&_e.auxMouseClick(tt,Pt)},ht=Pt=>{_e.showContextMenu(tt,Pt)},ft=()=>{_e.doAction(Actions.selectTab(tt.getId()))},pt=()=>{const Pt=tt.getCloseType();return!!(et||Pt===ICloseType.Always||Pt===ICloseType.Visible&&window.matchMedia&&window.matchMedia("(hover: hover) and (pointer: fine)").matches)},mt=Pt=>{pt()&&(_e.doAction(Actions.deleteTab(tt.getId())),Pt.stopPropagation())},vt=Pt=>{Pt.stopPropagation()};reactExports.useLayoutEffect(()=>{tt.setTabRect(_e.getBoundingClientRect(ot.current)),_e.getEditingTab()===tt&&st.current.select()});const _t=Pt=>{Pt.stopPropagation()},yt=Pt=>{Pt.code==="Escape"?_e.setEditingTab(void 0):(Pt.code==="Enter"||Pt.code==="NumpadEnter")&&(_e.setEditingTab(void 0),_e.doAction(Actions.renameTab(tt.getId(),Pt.target.value)))},bt=_e.getClassName;let Et=bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON)+" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_+nt);et?Et+=" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON__SELECTED):Et+=" "+bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON__UNSELECTED),tt.getClassName()!==void 0&&(Et+=" "+tt.getClassName());let St=0;tt.getModel().isEnableRotateBorderIcons()===!1&&(nt==="left"?St=90:nt==="right"&&(St=-90));const At=getRenderStateEx(_e,tt,St);let xt=At.content?jsxRuntimeExports.jsx("div",{className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_CONTENT),children:At.content}):null;const Ct=At.leading?jsxRuntimeExports.jsx("div",{className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_LEADING),children:At.leading}):null;if(_e.getEditingTab()===tt&&(xt=jsxRuntimeExports.jsx("input",{ref:st,className:bt(CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX),"data-layout-path":at+"/textbox",type:"text",autoFocus:!0,defaultValue:tt.getName(),onKeyDown:yt,onPointerDown:_t})),tt.isEnableClose()){const Pt=_e.i18nName(I18nLabel.Close_Tab);At.buttons.push(jsxRuntimeExports.jsx("div",{"data-layout-path":at+"/button/close",title:Pt,className:bt(CLASSES.FLEXLAYOUT__BORDER_BUTTON_TRAILING),onPointerDown:vt,onClick:mt,children:typeof it.close=="function"?it.close(tt):it.close},"close"))}return jsxRuntimeExports.jsxs("div",{ref:ot,"data-layout-path":at,className:Et,onClick:ft,onAuxClick:ut,onContextMenu:ht,title:tt.getHelpText(),draggable:!0,onDragStart:ct,onDragEnd:dt,children:[Ct,xt,At.buttons]})},TabButtonStamp=rt=>{const{layout:_e,node:tt}=rt,et=_e.getClassName,nt=et(CLASSES.FLEXLAYOUT__TAB_BUTTON_STAMP),it=getRenderStateEx(_e,tt),at=it.content?jsxRuntimeExports.jsx("div",{className:et(CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT),children:it.content}):tt.getNameForOverflowMenu(),ot=it.leading?jsxRuntimeExports.jsx("div",{className:et(CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING),children:it.leading}):null;return jsxRuntimeExports.jsxs("div",{className:nt,title:tt.getHelpText(),children:[ot,at]})};function showPopup(rt,_e,tt,et,nt){const it=nt.getRootDiv(),at=nt.getClassName,ot=rt.ownerDocument,st=rt.getBoundingClientRect(),ct=(it==null?void 0:it.getBoundingClientRect())??new DOMRect(0,0,100,100),dt=ot.createElement("div");dt.className=at(CLASSES.FLEXLAYOUT__POPUP_MENU_CONTAINER),st.left<ct.left+ct.width/2?dt.style.left=st.left-ct.left+"px":dt.style.right=ct.right-st.right+"px",st.top<ct.top+ct.height/2?dt.style.top=st.top-ct.top+"px":dt.style.bottom=ct.bottom-st.bottom+"px",nt.showOverlay(!0),it&&it.appendChild(dt);const ut=()=>{nt.hideControlInPortal(),nt.showOverlay(!1),it&&it.removeChild(dt),dt.removeEventListener("pointerdown",ht),ot.removeEventListener("pointerdown",ft)},ht=pt=>{pt.stopPropagation()},ft=pt=>{ut()};dt.addEventListener("pointerdown",ht),ot.addEventListener("pointerdown",ft),nt.showControlInPortal(jsxRuntimeExports.jsx(PopupMenu,{currentDocument:ot,parentNode:_e,onSelect:et,onHide:ut,items:tt,classNameMapper:at,layout:nt}),dt)}const PopupMenu=rt=>{const{parentNode:_e,items:tt,onHide:et,onSelect:nt,classNameMapper:it,layout:at}=rt,ot=reactExports.useRef(null);reactExports.useEffect(()=>{ot.current&&ot.current.focus()},[]);const st=(ft,pt)=>{nt(ft),et(),pt.stopPropagation()},ct=(ft,pt)=>{ft.stopPropagation(),at.setDragNode(ft.nativeEvent,pt),setTimeout(()=>{et()},0)},dt=ft=>{at.clearDragMain()},ut=ft=>{ft.key==="Escape"&&et()},ht=tt.map((ft,pt)=>{let mt=it(CLASSES.FLEXLAYOUT__POPUP_MENU_ITEM);return _e.getSelected()===ft.index&&(mt+=" "+it(CLASSES.FLEXLAYOUT__POPUP_MENU_ITEM__SELECTED)),jsxRuntimeExports.jsx("div",{className:mt,"data-layout-path":"/popup-menu/tb"+pt,onClick:vt=>st(ft,vt),draggable:!0,onDragStart:vt=>ct(vt,ft.node),onDragEnd:dt,title:ft.node.getHelpText(),children:jsxRuntimeExports.jsx(TabButtonStamp,{node:ft.node,layout:at})},ft.index)});return jsxRuntimeExports.jsx("div",{className:it(CLASSES.FLEXLAYOUT__POPUP_MENU),ref:ot,tabIndex:0,onKeyDown:ut,"data-layout-path":"/popup-menu",children:ht})},useTabOverflow=(rt,_e,tt,et,nt,it)=>{const[at,ot]=reactExports.useState([]),[st,ct]=reactExports.useState(!1),[dt,ut]=reactExports.useState(!1),ht=reactExports.useRef(null),ft=reactExports.useRef(!1),pt=reactExports.useRef(void 0),mt=reactExports.useRef([]),vt=reactExports.useRef(0),_t=reactExports.useRef(!1);mt.current=at,reactExports.useLayoutEffect(()=>{et.current&&Bt(0)},[_e.getId()]),reactExports.useLayoutEffect(()=>{ft.current=!1},[_e.getSelectedNode(),_e.getRect().width,_e.getRect().height]),reactExports.useLayoutEffect(()=>{wt(),ft.current===!1&&bt(),Et(),St()}),reactExports.useEffect(()=>{var zt;return(zt=ht.current)==null||zt.addEventListener("wheel",yt,{passive:!1}),()=>{var Wt;(Wt=ht.current)==null||Wt.removeEventListener("wheel",yt)}},[ht.current]);const yt=zt=>{zt.preventDefault()};function bt(){const zt=_e.getSelectedNode();if(zt&&et.current){const Wt=rt.getBoundingClientRect(et.current),Qt=zt.getTabRect();let nn=Nt(Wt)-Nt(Qt);nn>0||$t(Qt)>$t(Wt)?(Bt(Gt(et.current)-nn),_t.current=!0):(nn=Mt(Qt)-Mt(Wt),nn>0&&(Bt(Gt(et.current)+nn),_t.current=!0))}}const Et=()=>{if(et.current&&nt.current){const zt=et.current,Wt=nt.current,Qt=Lt(zt),nn=Dt(zt),Yt=Gt(zt);if(nn>Qt&&nn>0){let tn=Qt*Qt/nn,sn=0;tn<20&&(sn=20-tn,tn=20);const dn=Yt*(Qt-sn)/nn;tt===Orientation.HORZ?(Wt.style.width=tn+"px",Wt.style.left=dn+"px"):(Wt.style.height=tn+"px",Wt.style.top=dn+"px"),Wt.style.display="block"}else Wt.style.display="none";tt===Orientation.HORZ?Wt.style.bottom="0px":Wt.style.right="0px"}},St=()=>{const Wt=It().length>0;Wt!==st&&ct(Wt),pt.current===void 0&&(pt.current=setTimeout(()=>{const Qt=It();arraysEqual(Qt,mt.current)||ot(Qt),pt.current=void 0},100))},At=()=>{_t.current||(ft.current=!0),_t.current=!1,Et(),St()},xt=zt=>{var Wt;zt.stopPropagation(),nt.current.setPointerCapture(zt.pointerId);const Qt=(Wt=nt.current)==null?void 0:Wt.getBoundingClientRect();tt===Orientation.HORZ?vt.current=zt.clientX-Qt.x:vt.current=zt.clientY-Qt.y,startDrag(zt.currentTarget.ownerDocument,zt,Ct,Pt,Tt)},Ct=(zt,Wt)=>{if(et.current&&nt.current){const Qt=et.current,nn=nt.current,Yt=Lt(Qt),tn=Dt(Qt),sn=Lt(nn),dn=Qt.getBoundingClientRect();let vn=0;if(tt===Orientation.HORZ?vn=zt-dn.x-vt.current:vn=Wt-dn.y-vt.current,vn=Math.max(0,Math.min(tn-sn,vn)),Yt>0){const mn=vn*tn/Yt;Bt(mn)}}},Pt=()=>{},Tt=()=>{},wt=()=>{if(et.current){const Wt=et.current.firstElementChild,Qt=dt?10:0,nn=Lt(Wt)+Qt>Lt(et.current);nn!==dt&&ut(nn)}},It=()=>{const zt=[];if(et.current){const Wt=et.current,Qt=Wt.getBoundingClientRect(),nn=Nt(Qt)-1,Yt=Mt(Qt)+1,tn=Wt.firstElementChild;let sn=0;Array.from(tn.children).forEach(dn=>{const vn=dn.getBoundingClientRect();dn.classList.contains(it)&&((Nt(vn)<nn||Mt(vn)>Yt)&&zt.push(sn),sn++)})}return zt},Ot=zt=>{if(et.current){if(_e.getChildren().length===0)return;let Wt=0;if(Math.abs(zt.deltaY)>0){Wt=-zt.deltaY,zt.deltaMode===1&&(Wt*=40);const Qt=Gt(et.current)-Wt,nn=Dt(et.current)-Lt(et.current),Yt=Math.max(0,Math.min(nn,Qt));Bt(Yt),zt.stopPropagation()}}},Nt=zt=>tt===Orientation.HORZ?zt.x:zt.y,Mt=zt=>tt===Orientation.HORZ?zt.right:zt.bottom,Lt=zt=>tt===Orientation.HORZ?zt.clientWidth:zt.clientHeight,$t=zt=>tt===Orientation.HORZ?zt.width:zt.height,Dt=zt=>tt===Orientation.HORZ?zt.scrollWidth:zt.scrollHeight,Bt=zt=>{tt===Orientation.HORZ?et.current.scrollLeft=zt:et.current.scrollTop=zt},Gt=zt=>tt===Orientation.HORZ?zt.scrollLeft:zt.scrollTop;return{selfRef:ht,userControlledPositionRef:ft,onScroll:At,onScrollPointerDown:xt,hiddenTabs:at,onMouseWheel:Ot,isDockStickyButtons:dt,isShowHiddenTabs:st}};function arraysEqual(rt,_e){return rt.length===_e.length&&rt.every((tt,et)=>tt===_e[et])}const BorderTabSet=rt=>{const{border:_e,layout:tt,size:et}=rt,nt=reactExports.useRef(null),it=reactExports.useRef(null),at=reactExports.useRef(null),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=tt.getIcons();reactExports.useLayoutEffect(()=>{_e.setTabHeaderRect(tt.getBoundingClientRect(dt.current))});const{selfRef:dt,userControlledPositionRef:ut,onScroll:ht,onScrollPointerDown:ft,hiddenTabs:pt,onMouseWheel:mt,isDockStickyButtons:vt,isShowHiddenTabs:_t}=useTabOverflow(tt,_e,Orientation.flip(_e.getOrientation()),st,it,tt.getClassName(CLASSES.FLEXLAYOUT__BORDER_BUTTON)),yt=Qt=>{isAuxMouseEvent(Qt)&&tt.auxMouseClick(_e,Qt)},bt=Qt=>{tt.showContextMenu(_e,Qt)},Et=Qt=>{Qt.stopPropagation()},St=Qt=>{const nn=tt.getShowOverflowMenu(),Yt=pt.map(tn=>({index:tn,node:_e.getChildren()[tn]}));if(nn!==void 0)nn(_e,Qt,Yt,At);else{const tn=at.current;showPopup(tn,_e,Yt,At,tt)}Qt.stopPropagation()},At=Qt=>{tt.doAction(Actions.selectTab(Qt.node.getId())),ut.current=!1},xt=Qt=>{const nn=_e.getChildren()[_e.getSelected()];nn!==void 0&&tt.doAction(Actions.popoutTab(nn.getId())),Qt.stopPropagation()},Ct=tt.getClassName,Pt=[],Tt=Qt=>{const nn=_e.getSelected()===Qt,Yt=_e.getChildren()[Qt];Pt.push(jsxRuntimeExports.jsx(BorderButton,{layout:tt,border:_e.getLocation().getName(),node:Yt,path:_e.getPath()+"/tb"+Qt,selected:nn,icons:ct},Yt.getId())),Qt<_e.getChildren().length-1&&Pt.push(jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__BORDER_TAB_DIVIDER)},"divider"+Qt))};for(let Qt=0;Qt<_e.getChildren().length;Qt++)Tt(Qt);let wt=Ct(CLASSES.FLEXLAYOUT__BORDER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_+_e.getLocation().getName());_e.getClassName()!==void 0&&(wt+=" "+_e.getClassName());let It,Ot=[],Nt=[];const Mt={leading:It,buttons:Ot,stickyButtons:Nt,overflowPosition:void 0};if(tt.customizeTabSet(_e,Mt),It=Mt.leading,Nt=Mt.stickyButtons,Ot=Mt.buttons,Mt.overflowPosition===void 0&&(Mt.overflowPosition=Nt.length),Nt.length>0&&(vt?Ot=[...Nt,...Ot]:Pt.push(jsxRuntimeExports.jsx("div",{ref:ot,onPointerDown:Et,onDragStart:Qt=>{Qt.preventDefault()},className:Ct(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER),children:Nt},"sticky_buttons_container"))),_t){const Qt=tt.i18nName(I18nLabel.Overflow_Menu_Tooltip);let nn;if(typeof ct.more=="function"){const Yt=pt.map(tn=>({index:tn,node:_e.getChildren()[tn]}));nn=ct.more(_e,Yt)}else nn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ct.more,jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT),children:pt.length>0?pt.length:""})]});Ot.splice(Math.min(Mt.overflowPosition,Ot.length),0,jsxRuntimeExports.jsx("button",{ref:at,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_OVERFLOW_+_e.getLocation().getName()),title:Qt,onClick:St,onPointerDown:Et,children:nn},"overflowbutton"))}const Lt=_e.getSelected();if(Lt!==-1){const Qt=_e.getChildren()[Lt];if(Qt!==void 0&&tt.isSupportsPopout()&&Qt.isEnablePopout()){const nn=tt.i18nName(I18nLabel.Popout_Tab);Ot.push(jsxRuntimeExports.jsx("button",{title:nn,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_BUTTON_FLOAT),onClick:xt,onPointerDown:Et,children:typeof ct.popout=="function"?ct.popout(Qt):ct.popout},"popout"))}}const $t=jsxRuntimeExports.jsx("div",{ref:nt,className:Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_TOOLBAR_+_e.getLocation().getName()),children:Ot},"toolbar");let Dt={},Bt={};const Gt=et-1;_e.getLocation()===DockLocation.LEFT?(Dt={right:"100%",top:0},Bt={width:Gt,overflowY:"auto"}):_e.getLocation()===DockLocation.RIGHT?(Dt={left:"100%",top:0},Bt={width:Gt,overflowY:"auto"}):(Dt={left:0},Bt={height:Gt,overflowX:"auto"});let zt;_e.isEnableTabScrollbar()&&(zt=jsxRuntimeExports.jsx("div",{ref:it,className:Ct(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR),onPointerDown:ft}));let Wt;return It&&(Wt=jsxRuntimeExports.jsx("div",{className:Ct(CLASSES.FLEXLAYOUT__BORDER_LEADING),children:It})),jsxRuntimeExports.jsxs("div",{ref:dt,style:{display:"flex",flexDirection:_e.getOrientation()===Orientation.VERT?"row":"column"},className:wt,"data-layout-path":_e.getPath(),onClick:yt,onAuxClick:yt,onContextMenu:bt,onWheel:mt,children:[Wt,jsxRuntimeExports.jsxs("div",{className:Ct(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER),children:[jsxRuntimeExports.jsx("div",{ref:st,className:Ct(CLASSES.FLEXLAYOUT__BORDER_INNER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_+_e.getLocation().getName()),style:Bt,onScroll:ht,children:jsxRuntimeExports.jsx("div",{style:Dt,className:Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER)+" "+Ct(CLASSES.FLEXLAYOUT__BORDER_INNER_TAB_CONTAINER_+_e.getLocation().getName()),children:Pt})}),zt]}),$t]})},DragContainer=rt=>{const{layout:_e,node:tt}=rt,et=reactExports.useRef(null);reactExports.useEffect(()=>{tt.setTabStamp(et.current)},[tt,et.current]);const nt=_e.getClassName,it=nt(CLASSES.FLEXLAYOUT__DRAG_RECT);return jsxRuntimeExports.jsx("div",{ref:et,className:it,children:jsxRuntimeExports.jsx(TabButtonStamp,{layout:_e,node:tt},tt.getId())})},PopoutWindow=rt=>{const{title:_e,layout:tt,layoutWindow:et,url:nt,onCloseWindow:it,onSetWindow:at,children:ot}=rt,st=reactExports.useRef(null),[ct,dt]=reactExports.useState(void 0),ut=new Map;return reactExports.useLayoutEffect(()=>{if(!st.current){const ht=et.windowId,ft=et.rect;st.current=window.open(nt,ht,`left=${ft.x},top=${ft.y},width=${ft.width},height=${ft.height}`),st.current?(et.window=st.current,at(et,st.current),window.addEventListener("beforeunload",()=>{if(st.current){const pt=st.current;st.current=null,pt.close()}}),st.current.addEventListener("load",()=>{if(st.current){st.current.focus(),st.current.resizeTo(ft.width,ft.height),st.current.moveTo(ft.x,ft.y);const pt=st.current.document;pt.title=_e;const mt=pt.createElement("div");mt.className=CLASSES.FLEXLAYOUT__FLOATING_WINDOW_CONTENT,pt.body.appendChild(mt),copyStyles(pt,ut).then(()=>{dt(mt)});const vt=new MutationObserver(_t=>handleStyleMutations(_t,pt,ut));vt.observe(document.head,{childList:!0}),st.current.addEventListener("beforeunload",()=>{st.current&&(it(et),st.current=null,vt.disconnect())})}})):(console.warn(`Unable to open window ${nt}`),it(et))}return()=>{var ht;tt.getModel().getwindowsMap().has(et.windowId)||((ht=st.current)==null||ht.close(),st.current=null)}},[]),ct!==void 0?reactDomExports.createPortal(ot,ct):null};function handleStyleMutations(rt,_e,tt){for(const et of rt)if(et.type==="childList"){for(const nt of et.addedNodes)(nt instanceof HTMLLinkElement||nt instanceof HTMLStyleElement)&©Style(_e,nt,tt);for(const nt of et.removedNodes)if(nt instanceof HTMLLinkElement||nt instanceof HTMLStyleElement){const it=tt.get(nt);it&&_e.head.removeChild(it)}}}function copyStyles(rt,_e){const tt=[],et=document.querySelectorAll('style, link[rel="stylesheet"]');for(const nt of et)copyStyle(rt,nt,_e,tt);return Promise.all(tt)}function copyStyle(rt,_e,tt,et){if(_e instanceof HTMLLinkElement){const nt=_e.cloneNode(!0);rt.head.appendChild(nt),tt.set(_e,nt),et&&et.push(new Promise(it=>{nt.onload=()=>it(!0)}))}else if(_e instanceof HTMLStyleElement)try{const nt=_e.cloneNode(!0);rt.head.appendChild(nt),tt.set(_e,nt)}catch{}}const style={width:"1em",height:"1em",display:"flex",alignItems:"center"},CloseIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",children:[jsxRuntimeExports.jsx("path",{fill:"none",d:"M0 0h24v24H0z"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",fill:"var(--color-icon)",d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]}),MaximizeIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"})]}),OverflowIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M7 10l5 5 5-5z"})]}),EdgeIcon=()=>jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",style:{display:"block",width:10,height:10},preserveAspectRatio:"none",viewBox:"0 0 100 100",children:jsxRuntimeExports.jsx("path",{fill:"var(--color-edge-icon)",stroke:"var(--color-edge-icon)",d:"M10 30 L90 30 l-40 40 Z"})}),PopoutIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 20 20",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"}),jsxRuntimeExports.jsx("path",{d:"M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"})]}),RestoreIcon=()=>jsxRuntimeExports.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",style,viewBox:"0 0 24 24",fill:"var(--color-icon)",children:[jsxRuntimeExports.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntimeExports.jsx("path",{stroke:"var(--color-icon)",d:"M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"})]}),AsterickIcon=()=>jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",style,height:"24px",viewBox:"0 -960 960 960",width:"24px",children:jsxRuntimeExports.jsx("path",{fill:"var(--color-icon)",stroke:"var(--color-icon)",d:"M440-120v-264L254-197l-57-57 187-186H120v-80h264L197-706l57-57 186 187v-264h80v264l186-187 57 57-187 186h264v80H576l187 186-57 57-186-187v264h-80Z"})}),Overlay=rt=>{const{layout:_e,show:tt}=rt;return jsxRuntimeExports.jsx("div",{className:_e.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_OVERLAY),style:{display:tt?"flex":"none"}})},TabButton=rt=>{const{layout:_e,node:tt,selected:et,path:nt}=rt,it=reactExports.useRef(null),at=reactExports.useRef(null),ot=_e.getIcons();reactExports.useLayoutEffect(()=>{tt.setTabRect(_e.getBoundingClientRect(it.current)),_e.getEditingTab()===tt&&at.current.select()});const st=Ot=>{tt.isEnableDrag()?(Ot.stopPropagation(),_e.setDragNode(Ot.nativeEvent,tt)):Ot.preventDefault()},ct=Ot=>{_e.clearDragMain()},dt=Ot=>{isAuxMouseEvent(Ot)&&_e.auxMouseClick(tt,Ot)},ut=Ot=>{_e.showContextMenu(tt,Ot)},ht=()=>{_e.doAction(Actions.selectTab(tt.getId()))},ft=Ot=>{tt.isEnableRename()&&(pt(),Ot.stopPropagation())},pt=()=>{_e.setEditingTab(tt),_e.getCurrentDocument().body.addEventListener("pointerdown",mt)},mt=Ot=>{Ot.target!==at.current&&(_e.getCurrentDocument().body.removeEventListener("pointerdown",mt),_e.setEditingTab(void 0))},vt=()=>{const Ot=tt.getCloseType();return!!(et||Ot===ICloseType.Always||Ot===ICloseType.Visible&&window.matchMedia&&window.matchMedia("(hover: hover) and (pointer: fine)").matches)},_t=Ot=>{vt()&&(_e.doAction(Actions.deleteTab(tt.getId())),Ot.stopPropagation())},yt=Ot=>{Ot.stopPropagation()},bt=Ot=>{Ot.stopPropagation()},Et=Ot=>{Ot.code==="Escape"?_e.setEditingTab(void 0):(Ot.code==="Enter"||Ot.code==="NumpadEnter")&&(_e.setEditingTab(void 0),_e.doAction(Actions.renameTab(tt.getId(),Ot.target.value)))},St=_e.getClassName,At=tt.getParent(),xt=At.isEnableSingleTabStretch()&&At.getChildren().length===1,Ct=xt?CLASSES.FLEXLAYOUT__TAB_BUTTON_STRETCH:CLASSES.FLEXLAYOUT__TAB_BUTTON;let Pt=St(Ct);Pt+=" "+St(Ct+"_"+At.getTabLocation()),xt||(et?Pt+=" "+St(Ct+"--selected"):Pt+=" "+St(Ct+"--unselected")),tt.getClassName()!==void 0&&(Pt+=" "+tt.getClassName());const Tt=getRenderStateEx(_e,tt);let wt=Tt.content?jsxRuntimeExports.jsx("div",{className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_CONTENT),children:Tt.content}):null;const It=Tt.leading?jsxRuntimeExports.jsx("div",{className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_LEADING),children:Tt.leading}):null;if(_e.getEditingTab()===tt&&(wt=jsxRuntimeExports.jsx("input",{ref:at,className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_TEXTBOX),"data-layout-path":nt+"/textbox",type:"text",autoFocus:!0,defaultValue:tt.getName(),onKeyDown:Et,onPointerDown:bt})),tt.isEnableClose()&&!xt){const Ot=_e.i18nName(I18nLabel.Close_Tab);Tt.buttons.push(jsxRuntimeExports.jsx("div",{"data-layout-path":nt+"/button/close",title:Ot,className:St(CLASSES.FLEXLAYOUT__TAB_BUTTON_TRAILING),onPointerDown:yt,onClick:_t,children:typeof ot.close=="function"?ot.close(tt):ot.close},"close"))}return jsxRuntimeExports.jsxs("div",{ref:it,"data-layout-path":nt,className:Pt,onClick:ht,onAuxClick:dt,onContextMenu:ut,title:tt.getHelpText(),draggable:!0,onDragStart:st,onDragEnd:ct,onDoubleClick:ft,children:[It,wt,Tt.buttons]})},TabSet=rt=>{const{node:_e,layout:tt}=rt,et=reactExports.useRef(null),nt=reactExports.useRef(null),it=reactExports.useRef(null),at=reactExports.useRef(null),ot=reactExports.useRef(null),st=reactExports.useRef(null),ct=reactExports.useRef(null),dt=reactExports.useRef(void 0),ut=tt.getIcons();reactExports.useLayoutEffect(()=>{_e.setRect(tt.getBoundingClientRect(ht.current)),et.current&&_e.setTabStripRect(tt.getBoundingClientRect(et.current));const fn=tt.getBoundingClientRect(at.current);!_e.getContentRect().equals(fn)&&!isNaN(fn.x)&&(_e.setContentRect(fn),splitterDragging?(dt.current&&clearTimeout(dt.current),dt.current=setTimeout(()=>{tt.redrawInternal("border content rect "+fn),dt.current=void 0},50)):tt.redrawInternal("border content rect "+fn))});const{selfRef:ht,userControlledPositionRef:ft,onScroll:pt,onScrollPointerDown:mt,hiddenTabs:vt,onMouseWheel:_t,isDockStickyButtons:yt,isShowHiddenTabs:bt}=useTabOverflow(tt,_e,Orientation.HORZ,it,nt,tt.getClassName(CLASSES.FLEXLAYOUT__TAB_BUTTON)),Et=fn=>{const Sn=tt.getShowOverflowMenu(),zn=vt.map(On=>({index:On,node:_e.getChildren()[On]}));if(Sn!==void 0)Sn(_e,fn,zn,St);else{const On=st.current;showPopup(On,_e,zn,St,tt)}fn.stopPropagation()},St=fn=>{tt.doAction(Actions.selectTab(fn.node.getId())),ft.current=!1},At=fn=>{tt.getEditingTab()?fn.preventDefault():_e.isEnableDrag()?(fn.stopPropagation(),tt.setDragNode(fn.nativeEvent,_e)):fn.preventDefault()},xt=fn=>{isAuxMouseEvent(fn)||tt.doAction(Actions.setActiveTabset(_e.getId(),tt.getWindowId()))},Ct=fn=>{isAuxMouseEvent(fn)&&tt.auxMouseClick(_e,fn)},Pt=fn=>{tt.showContextMenu(_e,fn)},Tt=fn=>{fn.stopPropagation()},wt=fn=>{_e.canMaximize()&&tt.maximize(_e),fn.stopPropagation()},It=fn=>{tt.doAction(Actions.deleteTabset(_e.getId())),fn.stopPropagation()},Ot=fn=>{tt.doAction(Actions.deleteTab(_e.getChildren()[0].getId())),fn.stopPropagation()},Nt=fn=>{$t!==void 0&&tt.doAction(Actions.popoutTab($t.getId())),fn.stopPropagation()},Mt=fn=>{_e.canMaximize()&&tt.maximize(_e)},Lt=tt.getClassName,$t=_e.getSelectedNode(),Dt=_e.getPath(),Bt=[];if(_e.isEnableTabStrip())for(let fn=0;fn<_e.getChildren().length;fn++){const Sn=_e.getChildren()[fn],zn=_e.getSelected()===fn;Bt.push(jsxRuntimeExports.jsx(TabButton,{layout:tt,node:Sn,path:Dt+"/tb"+fn,selected:zn},Sn.getId())),fn<_e.getChildren().length-1&&Bt.push(jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET_TAB_DIVIDER)},"divider"+fn))}let Gt,zt=[],Wt=[];const Qt={leading:Gt,stickyButtons:zt,buttons:Wt,overflowPosition:void 0};tt.customizeTabSet(_e,Qt),Gt=Qt.leading,zt=Qt.stickyButtons,Wt=Qt.buttons;const nn=_e.isEnableSingleTabStretch()&&_e.getChildren().length===1,Yt=nn&&_e.getChildren()[0].isEnableClose()||_e.isEnableClose();if(Qt.overflowPosition===void 0&&(Qt.overflowPosition=zt.length),zt.length>0&&(!_e.isEnableTabWrap()&&(yt||nn)?Wt=[...zt,...Wt]:Bt.push(jsxRuntimeExports.jsx("div",{ref:ct,onPointerDown:Tt,onDragStart:fn=>{fn.preventDefault()},className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_STICKY_BUTTONS_CONTAINER),children:zt},"sticky_buttons_container"))),!_e.isEnableTabWrap()&&bt){const fn=tt.i18nName(I18nLabel.Overflow_Menu_Tooltip);let Sn;if(typeof ut.more=="function"){const zn=vt.map(On=>({index:On,node:_e.getChildren()[On]}));Sn=ut.more(_e,zn)}else Sn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ut.more,jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW_COUNT),children:vt.length>0?vt.length:""})]});Wt.splice(Math.min(Qt.overflowPosition,Wt.length),0,jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/overflow",ref:st,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_BUTTON_OVERFLOW),title:fn,onClick:Et,onPointerDown:Tt,children:Sn},"overflowbutton"))}if($t!==void 0&&tt.isSupportsPopout()&&$t.isEnablePopout()&&$t.isEnablePopoutIcon()){const fn=tt.i18nName(I18nLabel.Popout_Tab);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/popout",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_FLOAT),onClick:Nt,onPointerDown:Tt,children:typeof ut.popout=="function"?ut.popout($t):ut.popout},"popout"))}if(_e.canMaximize()){const fn=tt.i18nName(I18nLabel.Restore),Sn=tt.i18nName(I18nLabel.Maximize);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/max",title:_e.isMaximized()?fn:Sn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_+(_e.isMaximized()?"max":"min")),onClick:wt,onPointerDown:Tt,children:_e.isMaximized()?typeof ut.restore=="function"?ut.restore(_e):ut.restore:typeof ut.maximize=="function"?ut.maximize(_e):ut.maximize},"max"))}if(!_e.isMaximized()&&Yt){const fn=nn?tt.i18nName(I18nLabel.Close_Tab):tt.i18nName(I18nLabel.Close_Tabset);Wt.push(jsxRuntimeExports.jsx("button",{"data-layout-path":Dt+"/button/close",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON)+" "+Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_BUTTON_CLOSE),onClick:nn?Ot:It,onPointerDown:Tt,children:typeof ut.closeTabset=="function"?ut.closeTabset(_e):ut.closeTabset},"close"))}if(_e.isActive()&&_e.isEnableActiveIcon()){const fn=tt.i18nName(I18nLabel.Active_Tabset);Wt.push(jsxRuntimeExports.jsx("div",{"data-layout-path":Dt+"/button/active",title:fn,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR_ICON),children:typeof ut.activeTabset=="function"?ut.activeTabset(_e):ut.activeTabset},"active"))}const tn=jsxRuntimeExports.jsx("div",{ref:ot,className:Lt(CLASSES.FLEXLAYOUT__TAB_TOOLBAR),onPointerDown:Tt,onDragStart:fn=>{fn.preventDefault()},children:Wt},"buttonbar");let sn,dn=Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER);if(_e.getClassNameTabStrip()!==void 0&&(dn+=" "+_e.getClassNameTabStrip()),dn+=" "+CLASSES.FLEXLAYOUT__TABSET_TABBAR_OUTER_+_e.getTabLocation(),_e.isActive()&&(dn+=" "+Lt(CLASSES.FLEXLAYOUT__TABSET_SELECTED)),_e.isMaximized()&&(dn+=" "+Lt(CLASSES.FLEXLAYOUT__TABSET_MAXIMIZED)),nn){const fn=_e.getChildren()[0];fn.getTabSetClassName()!==void 0&&(dn+=" "+fn.getTabSetClassName())}let vn;if(Gt&&(vn=jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET_LEADING),children:Gt})),_e.isEnableTabWrap())_e.isEnableTabStrip()&&(sn=jsxRuntimeExports.jsxs("div",{className:dn,style:{flexWrap:"wrap",gap:"1px",marginTop:"2px"},ref:et,"data-layout-path":Dt+"/tabstrip",onPointerDown:xt,onDoubleClick:Mt,onContextMenu:Pt,onClick:Ct,onAuxClick:Ct,draggable:!0,onDragStart:At,children:[vn,Bt,jsxRuntimeExports.jsx("div",{style:{flexGrow:1}}),tn]}));else if(_e.isEnableTabStrip()){let fn;_e.isEnableTabScrollbar()&&(fn=jsxRuntimeExports.jsx("div",{ref:nt,className:Lt(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR),onPointerDown:mt})),sn=jsxRuntimeExports.jsxs("div",{className:dn,ref:et,"data-layout-path":Dt+"/tabstrip",onPointerDown:xt,onDoubleClick:Mt,onContextMenu:Pt,onClick:Ct,onAuxClick:Ct,draggable:!0,onWheel:_t,onDragStart:At,children:[vn,jsxRuntimeExports.jsxs("div",{className:Lt(CLASSES.FLEXLAYOUT__MINI_SCROLLBAR_CONTAINER),children:[jsxRuntimeExports.jsx("div",{ref:it,className:Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER)+" "+Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_+_e.getTabLocation()),style:{overflowX:"auto",overflowY:"hidden"},onScroll:pt,children:jsxRuntimeExports.jsx("div",{style:{width:nn?"100%":"none"},className:Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER)+" "+Lt(CLASSES.FLEXLAYOUT__TABSET_TABBAR_INNER_TAB_CONTAINER_+_e.getTabLocation()),children:Bt})}),fn]}),tn]})}let mn;if(_e.getChildren().length===0){const fn=tt.getTabSetPlaceHolderCallback();fn&&(mn=fn(_e))}let pn=jsxRuntimeExports.jsx("div",{ref:at,className:Lt(CLASSES.FLEXLAYOUT__TABSET_CONTENT),children:mn});_e.getTabLocation()==="top"?pn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[sn,pn]}):pn=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[pn,sn]});const Cn={flexGrow:Math.max(1,_e.getWeight()*1e3),minWidth:_e.getMinWidth(),minHeight:_e.getMinHeight(),maxWidth:_e.getMaxWidth(),maxHeight:_e.getMaxHeight()};_e.getModel().getMaximizedTabset(tt.getWindowId())!==void 0&&!_e.isMaximized()&&(Cn.display="none");const Ln=jsxRuntimeExports.jsx("div",{ref:ht,className:Lt(CLASSES.FLEXLAYOUT__TABSET_CONTAINER),style:Cn,children:jsxRuntimeExports.jsx("div",{className:Lt(CLASSES.FLEXLAYOUT__TABSET),"data-layout-path":Dt,children:pn})});return _e.isMaximized()&&tt.getMainElement()?reactDomExports.createPortal(jsxRuntimeExports.jsx("div",{style:{position:"absolute",display:"flex",top:0,left:0,bottom:0,right:0},children:Ln}),tt.getMainElement()):Ln},Row=rt=>{const{layout:_e,node:tt}=rt,et=reactExports.useRef(null),nt=tt.getOrientation()===Orientation.HORZ;reactExports.useLayoutEffect(()=>{tt.setRect(_e.getBoundingClientRect(et.current))});const it=[];let at=0;for(const st of tt.getChildren())at>0&&it.push(jsxRuntimeExports.jsx(Splitter,{layout:_e,node:tt,index:at,horizontal:nt},"splitter"+at)),st instanceof RowNode?it.push(jsxRuntimeExports.jsx(Row,{layout:_e,node:st},st.getId())):st instanceof TabSetNode&&it.push(jsxRuntimeExports.jsx(TabSet,{layout:_e,node:st},st.getId())),at++;const ot={flexGrow:Math.max(1,tt.getWeight()*1e3),minWidth:tt.getMinWidth(),minHeight:tt.getMinHeight(),maxWidth:tt.getMaxWidth(),maxHeight:tt.getMaxHeight()};return nt?ot.flexDirection="row":ot.flexDirection="column",jsxRuntimeExports.jsx("div",{ref:et,className:_e.getClassName(CLASSES.FLEXLAYOUT__ROW),style:ot,children:it})},Tab=rt=>{const{layout:_e,selected:tt,node:et,path:nt}=rt,it=reactExports.useRef(null),at=reactExports.useRef(!0),ot=et.getParent(),st=ot.getContentRect();reactExports.useLayoutEffect(()=>{const pt=et.getMoveableElement();it.current.appendChild(pt),et.setMoveableElement(pt);const mt=()=>{et.saveScrollPosition()};return pt.addEventListener("scroll",mt),it.current.addEventListener("pointerdown",ct),()=>{pt.removeEventListener("scroll",mt),it.current&&it.current.removeEventListener("pointerdown",ct),et.setVisible(!1)}},[]),reactExports.useEffect(()=>{et.isSelected()&&at.current&&(et.restoreScrollPosition(),at.current=!1)});const ct=()=>{const pt=et.getParent();pt instanceof TabSetNode&&(pt.isActive()||_e.doAction(Actions.setActiveTabset(pt.getId(),_e.getWindowId())))};et.setRect(st);const dt=_e.getClassName,ut={};st.styleWithPosition(ut);let ht=null;if(tt){if(et.setVisible(!0),document.hidden&&et.isEnablePopoutOverlay()){const pt={};st.styleWithPosition(pt),ht=jsxRuntimeExports.jsx("div",{style:pt,className:dt(CLASSES.FLEXLAYOUT__TAB_OVERLAY)})}}else ut.display="none",et.setVisible(!1);ot instanceof TabSetNode&&et.getModel().getMaximizedTabset(_e.getWindowId())!==void 0&&(ot.isMaximized()?ut.zIndex=10:ut.display="none"),ot instanceof BorderNode&&(ot.isShowing()||(ut.display="none"));let ft=dt(CLASSES.FLEXLAYOUT__TAB);return ot instanceof BorderNode&&(ft+=" "+dt(CLASSES.FLEXLAYOUT__TAB_BORDER),ft+=" "+dt(CLASSES.FLEXLAYOUT__TAB_BORDER_+ot.getLocation().getName())),et.getContentClassName()!==void 0&&(ft+=" "+et.getContentClassName()),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ht,jsxRuntimeExports.jsx("div",{ref:it,style:ut,className:ft,"data-layout-path":nt})]})};class ErrorBoundary extends reactExports.Component{constructor(_e){super(_e),__publicField(this,"retry",()=>{this.setState({hasError:!1})}),this.state={hasError:!1}}static getDerivedStateFromError(_e){return{hasError:!0}}componentDidCatch(_e,tt){console.debug(_e),console.debug(tt)}render(){return this.state.hasError?jsxRuntimeExports.jsx("div",{className:CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTAINER,children:jsxRuntimeExports.jsx("div",{className:CLASSES.FLEXLAYOUT__ERROR_BOUNDARY_CONTENT,children:jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center"},children:[this.props.message,jsxRuntimeExports.jsx("p",{children:jsxRuntimeExports.jsx("button",{onClick:this.retry,children:this.props.retryText})})]})})}):this.props.children}}const SizeTracker=reactExports.memo(({layout:rt,node:_e})=>jsxRuntimeExports.jsx(ErrorBoundary,{message:rt.i18nName(I18nLabel.Error_rendering_component),retryText:rt.i18nName(I18nLabel.Error_rendering_component_retry),children:rt.props.factory(_e)}),arePropsEqual);function arePropsEqual(rt,_e){return!(_e.visible&&(!rt.rect.equalSize(_e.rect)||rt.forceRevision!==_e.forceRevision||rt.tabsRevision!==_e.tabsRevision))}const _LayoutInternal=class _r extends reactExports.Component{constructor(_e){super(_e),__publicField(this,"selfRef"),__publicField(this,"moveablesRef"),__publicField(this,"findBorderBarSizeRef"),__publicField(this,"mainRef"),__publicField(this,"previousModel"),__publicField(this,"orderedTabIds"),__publicField(this,"orderedTabMoveableIds"),__publicField(this,"moveableElementMap",new Map),__publicField(this,"dropInfo"),__publicField(this,"outlineDiv"),__publicField(this,"currentDocument"),__publicField(this,"currentWindow"),__publicField(this,"supportsPopout"),__publicField(this,"popoutURL"),__publicField(this,"icons"),__publicField(this,"resizeObserver"),__publicField(this,"dragEnterCount",0),__publicField(this,"dragging",!1),__publicField(this,"windowId"),__publicField(this,"layoutWindow"),__publicField(this,"mainLayout"),__publicField(this,"isMainWindow"),__publicField(this,"isDraggingOverWindow"),__publicField(this,"styleObserver"),__publicField(this,"popoutWindowName"),__publicField(this,"updateLayoutMetrics",()=>{if(this.findBorderBarSizeRef.current){const tt=this.findBorderBarSizeRef.current.getBoundingClientRect().height;tt!==this.state.calculatedBorderBarSize&&this.setState({calculatedBorderBarSize:tt})}}),__publicField(this,"onModelChange",tt=>{this.redrawInternal("model change"),this.props.onModelChange&&this.props.onModelChange(this.props.model,tt)}),__publicField(this,"updateRect",()=>{if(this.selfRef.current){const tt=Rect.fromDomRect(this.selfRef.current.getBoundingClientRect());!tt.equals(this.state.rect)&&tt.width!==0&&tt.height!==0&&(this.setState({rect:tt}),this.windowId!==Model.MAIN_WINDOW_ID&&this.redrawInternal("rect updated"))}}),__publicField(this,"getClassName",tt=>this.props.classNameMapper===void 0?tt:this.props.classNameMapper(tt)),__publicField(this,"onCloseWindow",tt=>{this.doAction(Actions.closeWindow(tt.windowId))}),__publicField(this,"onSetWindow",(tt,et)=>{}),__publicField(this,"showControlInPortal",(tt,et)=>{const nt=reactDomExports.createPortal(tt,et);this.setState({portal:nt})}),__publicField(this,"hideControlInPortal",()=>{this.setState({portal:void 0})}),__publicField(this,"getIcons",()=>this.icons),__publicField(this,"setDragNode",(tt,et)=>{if(_r.dragState=new DragState(this.mainLayout,"internal",et,void 0,void 0),tt.dataTransfer.setData("text/plain","--flexlayout--"),tt.dataTransfer.effectAllowed="copyMove",tt.dataTransfer.dropEffect="move",this.dragEnterCount=0,et instanceof TabSetNode){let nt=!1,it=this.i18nName(I18nLabel.Move_Tabset);if(et.getChildren().length>0&&(it=this.i18nName(I18nLabel.Move_Tabs).replace("?",String(et.getChildren().length))),this.props.onRenderDragRect){const at=this.props.onRenderDragRect(it,et,void 0);at&&(this.setDragComponent(tt,at,10,10),nt=!0)}nt||this.setDragComponent(tt,it,10,10)}else{const it=tt.target.getBoundingClientRect(),at=tt.clientX-it.left,ot=tt.clientY-it.top,st=et==null?void 0:et.getParent(),ct=st instanceof BorderNode&&st.getOrientation()===Orientation.HORZ,dt=ct?10:at,ut=ct?10:ot;let ht=!1;if(this.props.onRenderDragRect){const ft=jsxRuntimeExports.jsx(TabButtonStamp,{layout:this,node:et},et.getId()),pt=this.props.onRenderDragRect(ft,et,void 0);pt&&(this.setDragComponent(tt,pt,dt,ut),ht=!0)}ht||(isSafari()?this.setDragComponent(tt,jsxRuntimeExports.jsx(TabButtonStamp,{node:et,layout:this}),dt,ut):tt.dataTransfer.setDragImage(et.getTabStamp(),dt,ut))}}),__publicField(this,"onDragEnterRaw",tt=>{this.dragEnterCount++,this.dragEnterCount===1&&this.onDragEnter(tt)}),__publicField(this,"onDragLeaveRaw",tt=>{this.dragEnterCount--,this.dragEnterCount===0&&this.onDragLeave(tt)}),__publicField(this,"onDragEnter",tt=>{if(!_r.dragState&&this.props.onExternalDrag){const et=this.props.onExternalDrag(tt);if(et){const nt=TabNode.fromJson(et.json,this.props.model,!1);_r.dragState=new DragState(this.mainLayout,"external",nt,et.json,et.onDrop)}}if(_r.dragState){if(this.windowId!==Model.MAIN_WINDOW_ID&&_r.dragState.mainLayout===this.mainLayout&&_r.dragState.mainLayout.setDraggingOverWindow(!0),_r.dragState.mainLayout!==this.mainLayout)return;tt.preventDefault(),this.dropInfo=void 0;const et=this.selfRef.current;this.outlineDiv=this.currentDocument.createElement("div"),this.outlineDiv.className=this.getClassName(CLASSES.FLEXLAYOUT__OUTLINE_RECT),this.outlineDiv.style.visibility="hidden";const nt=this.props.model.getAttribute("tabDragSpeed");this.outlineDiv.style.transition=`top ${nt}s, left ${nt}s, width ${nt}s, height ${nt}s`,et.appendChild(this.outlineDiv),this.dragging=!0,this.showOverlay(!0),!this.isDraggingOverWindow&&this.props.model.getMaximizedTabset(this.windowId)===void 0&&this.setState({showEdges:this.props.model.isEnableEdgeDock()});const it=this.selfRef.current.getBoundingClientRect();new Rect(tt.clientX-it.left,tt.clientY-it.top,1,1).positionElement(this.outlineDiv)}}),__publicField(this,"onDragOver",tt=>{var et;if(this.dragging&&!this.isDraggingOverWindow){tt.preventDefault();const nt=(et=this.selfRef.current)==null?void 0:et.getBoundingClientRect(),it={x:tt.clientX-((nt==null?void 0:nt.left)??0),y:tt.clientY-((nt==null?void 0:nt.top)??0)};this.checkForBorderToShow(it.x,it.y);const at=this.props.model.findDropTargetNode(this.windowId,_r.dragState.dragNode,it.x,it.y);at&&(this.dropInfo=at,this.outlineDiv&&(this.outlineDiv.className=this.getClassName(at.className),at.rect.positionElement(this.outlineDiv),this.outlineDiv.style.visibility="visible"))}}),__publicField(this,"onDragLeave",tt=>{this.dragging&&(this.windowId!==Model.MAIN_WINDOW_ID&&_r.dragState.mainLayout.setDraggingOverWindow(!1),this.clearDragLocal())}),__publicField(this,"onDrop",tt=>{if(this.dragging){tt.preventDefault();const et=_r.dragState;if(this.dropInfo)if(et.dragJson!==void 0){const nt=this.doAction(Actions.addNode(et.dragJson,this.dropInfo.node.getId(),this.dropInfo.location,this.dropInfo.index));et.fnNewNodeDropped!==void 0&&et.fnNewNodeDropped(nt,tt)}else et.dragNode!==void 0&&this.doAction(Actions.moveNode(et.dragNode.getId(),this.dropInfo.node.getId(),this.dropInfo.location,this.dropInfo.index));this.mainLayout.clearDragMain()}this.dragEnterCount=0}),this.orderedTabIds=[],this.orderedTabMoveableIds=[],this.selfRef=reactExports.createRef(),this.moveablesRef=reactExports.createRef(),this.mainRef=reactExports.createRef(),this.findBorderBarSizeRef=reactExports.createRef(),this.supportsPopout=_e.supportsPopout!==void 0?_e.supportsPopout:defaultSupportsPopout,this.popoutURL=_e.popoutURL?_e.popoutURL:"popout.html",this.icons={...defaultIcons,..._e.icons},this.windowId=_e.windowId?_e.windowId:Model.MAIN_WINDOW_ID,this.mainLayout=this.props.mainLayout?this.props.mainLayout:this,this.isDraggingOverWindow=!1,this.layoutWindow=this.props.model.getwindowsMap().get(this.windowId),this.layoutWindow.layout=this,this.popoutWindowName=this.props.popoutWindowName||"Popout Window",this.state={rect:Rect.empty(),editingTab:void 0,showEdges:!1,showOverlay:!1,calculatedBorderBarSize:29,layoutRevision:0,forceRevision:0,showHiddenBorder:DockLocation.CENTER},this.isMainWindow=this.windowId===Model.MAIN_WINDOW_ID}componentDidMount(){if(this.updateRect(),this.currentDocument=this.selfRef.current.ownerDocument,this.currentWindow=this.currentDocument.defaultView,this.layoutWindow.window=this.currentWindow,this.layoutWindow.toScreenRectFunction=_e=>this.getScreenRect(_e),this.resizeObserver=new ResizeObserver(_e=>{requestAnimationFrame(()=>{this.updateRect()})}),this.selfRef.current&&this.resizeObserver.observe(this.selfRef.current),this.isMainWindow)this.props.model.addChangeListener(this.onModelChange),this.updateLayoutMetrics();else{this.currentWindow.addEventListener("resize",()=>{this.updateRect()});const _e=this.props.mainLayout.getRootDiv(),tt=this.selfRef.current;copyInlineStyles(_e,tt),this.styleObserver=new MutationObserver(()=>{copyInlineStyles(_e,tt)&&this.redraw("mutation observer")}),this.styleObserver.observe(_e,{attributeFilter:["style"]})}document.addEventListener("visibilitychange",()=>{for(const[_e,tt]of this.props.model.getwindowsMap())tt.layout&&this.redraw("visibility change")})}componentDidUpdate(){this.currentDocument=this.selfRef.current.ownerDocument,this.currentWindow=this.currentDocument.defaultView,this.isMainWindow&&(this.props.model!==this.previousModel&&(this.previousModel!==void 0&&this.previousModel.removeChangeListener(this.onModelChange),this.props.model.getwindowsMap().get(this.windowId).layout=this,this.props.model.addChangeListener(this.onModelChange),this.layoutWindow=this.props.model.getwindowsMap().get(this.windowId),this.layoutWindow.layout=this,this.layoutWindow.toScreenRectFunction=_e=>this.getScreenRect(_e),this.previousModel=this.props.model,this.tidyMoveablesMap()),this.updateLayoutMetrics())}componentWillUnmount(){var _e,tt;this.selfRef.current&&((_e=this.resizeObserver)==null||_e.unobserve(this.selfRef.current)),this.isMainWindow&&this.props.model.removeChangeListener(this.onModelChange),(tt=this.styleObserver)==null||tt.disconnect()}render(){if(!this.selfRef.current)return jsxRuntimeExports.jsxs("div",{ref:this.selfRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT),children:[jsxRuntimeExports.jsx("div",{ref:this.moveablesRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MOVEABLES)},"__moveables__"),this.renderMetricsElements()]});const _e=this.props.model;_e.getRoot(this.windowId).calcMinMaxSize(),_e.getRoot(this.windowId).setPaths(""),_e.getBorderSet().setPaths();const tt=this.renderLayout(),et=this.renderBorders(tt),nt=this.renderTabs(),it=this.reorderComponents(nt,this.orderedTabIds);let at=null,ot=null,st=null,ct=null;if(this.isMainWindow){at=this.renderWindows(),ct=this.renderMetricsElements();const dt=this.renderTabMoveables();ot=this.reorderComponents(dt,this.orderedTabMoveableIds),st=jsxRuntimeExports.jsx("div",{className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_TAB_STAMPS),children:this.renderTabStamps()},"__tabStamps__")}return jsxRuntimeExports.jsxs("div",{ref:this.selfRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT),onDragEnter:this.onDragEnterRaw,onDragLeave:this.onDragLeaveRaw,onDragOver:this.onDragOver,onDrop:this.onDrop,children:[jsxRuntimeExports.jsx("div",{ref:this.moveablesRef,className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MOVEABLES)},"__moveables__"),ct,jsxRuntimeExports.jsx(Overlay,{layout:this,show:this.state.showOverlay},"__overlay__"),et,it,ot,st,this.state.portal,at]})}renderBorders(_e){const tt=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_MAIN),et=this.props.model.getBorderSet().getBorderMap();if(this.isMainWindow&&et.size>0){_e=jsxRuntimeExports.jsx("div",{className:tt,ref:this.mainRef,children:_e});const nt=new Map,it=new Map;for(const[st,ct]of DockLocation.values){const dt=et.get(ct);dt&&dt.isShowing()&&(!dt.isAutoHide()||dt.isAutoHide()&&(dt.getChildren().length>0||this.state.showHiddenBorder===ct))&&(nt.set(ct,jsxRuntimeExports.jsx(BorderTabSet,{layout:this,border:dt,size:this.state.calculatedBorderBarSize})),it.set(ct,jsxRuntimeExports.jsx(BorderTab,{layout:this,border:dt,show:dt.getSelected()!==-1})))}const at=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER),ot=this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT_BORDER_CONTAINER_INNER);if(this.props.model.getBorderSet().getLayoutHorizontal()){const st=jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[it.get(DockLocation.TOP),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[it.get(DockLocation.LEFT),_e,it.get(DockLocation.RIGHT)]}),it.get(DockLocation.BOTTOM)]});return jsxRuntimeExports.jsxs("div",{className:at,style:{flexDirection:"column"},children:[nt.get(DockLocation.TOP),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[nt.get(DockLocation.LEFT),st,nt.get(DockLocation.RIGHT)]}),nt.get(DockLocation.BOTTOM)]})}else{const st=jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"row"},children:[it.get(DockLocation.LEFT),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[it.get(DockLocation.TOP),_e,it.get(DockLocation.BOTTOM)]}),it.get(DockLocation.RIGHT)]});return jsxRuntimeExports.jsxs("div",{className:at,style:{flexDirection:"row"},children:[nt.get(DockLocation.LEFT),jsxRuntimeExports.jsxs("div",{className:ot,style:{flexDirection:"column"},children:[nt.get(DockLocation.TOP),st,nt.get(DockLocation.BOTTOM)]}),nt.get(DockLocation.RIGHT)]})}}else return jsxRuntimeExports.jsx("div",{className:tt,ref:this.mainRef,style:{position:"absolute",top:0,left:0,bottom:0,right:0,display:"flex"},children:_e})}renderLayout(){return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Row,{layout:this,node:this.props.model.getRoot(this.windowId)},"__row__"),this.renderEdgeIndicators()]})}renderEdgeIndicators(){const _e=[],tt=this.icons.edgeArrow;if(this.state.showEdges){const et=this.props.model.getRoot(this.windowId).getRect(),nt=edgeRectLength,it=edgeRectWidth,at=edgeRectLength/2,ot=this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT),st=50;_e.push(jsxRuntimeExports.jsx("div",{style:{top:0,left:et.width/2-at,width:nt,height:it,borderBottomLeftRadius:st,borderBottomRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_TOP),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(180deg)"},children:tt})},"North")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height/2-at,left:0,width:it,height:nt,borderTopRightRadius:st,borderBottomRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_LEFT),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(90deg)"},children:tt})},"West")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height-it,left:et.width/2-at,width:nt,height:it,borderTopLeftRadius:st,borderTopRightRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_BOTTOM),children:jsxRuntimeExports.jsx("div",{children:tt})},"South")),_e.push(jsxRuntimeExports.jsx("div",{style:{top:et.height/2-at,left:et.width-it,width:it,height:nt,borderTopLeftRadius:st,borderBottomLeftRadius:st},className:ot+" "+this.getClassName(CLASSES.FLEXLAYOUT__EDGE_RECT_RIGHT),children:jsxRuntimeExports.jsx("div",{style:{transform:"rotate(-90deg)"},children:tt})},"East"))}return _e}renderWindows(){const _e=[];if(this.supportsPopout){const tt=this.props.model.getwindowsMap();let et=1;for(const[nt,it]of tt)nt!==Model.MAIN_WINDOW_ID&&(_e.push(jsxRuntimeExports.jsx(PopoutWindow,{layout:this,title:this.popoutWindowName+" "+et,layoutWindow:it,url:this.popoutURL+"?id="+nt,onSetWindow:this.onSetWindow,onCloseWindow:this.onCloseWindow,children:jsxRuntimeExports.jsx("div",{className:this.props.popoutClassName,children:jsxRuntimeExports.jsx(_r,{...this.props,windowId:nt,mainLayout:this})})},nt)),et++)}return _e}renderTabMoveables(){const _e=new Map;return this.props.model.visitNodes(tt=>{if(tt instanceof TabNode){const et=tt,nt=this.getMoveableElement(et.getId());et.setMoveableElement(nt);const it=et.isSelected(),at=et.getParent().getContentRect(),ot=it||!et.isEnableRenderOnDemand(),st=et.isRendered()||ot&&at.width>0&&at.height>0;if(st){const ct=et.getId()+(et.isEnableWindowReMount()?et.getWindowId():"");_e.set(tt.getId(),reactDomExports.createPortal(jsxRuntimeExports.jsx(SizeTracker,{layout:this,node:et,rect:at,visible:ot,forceRevision:this.state.forceRevision,tabsRevision:this.props.renderRevision},ct),nt,ct)),et.setRendered(st)}}}),_e}renderTabStamps(){const _e=[];return this.props.model.visitNodes(tt=>{if(tt instanceof TabNode){const et=tt;_e.push(jsxRuntimeExports.jsx(DragContainer,{layout:this,node:et},et.getId()))}}),_e}renderTabs(){const _e=new Map;return this.props.model.visitWindowNodes(this.windowId,tt=>{if(tt instanceof TabNode){const et=tt,nt=et.isSelected(),it=et.getPath();(et.isRendered()||nt||!et.isEnableRenderOnDemand())&&_e.set(et.getId(),jsxRuntimeExports.jsx(Tab,{layout:this,path:it,node:et,selected:nt},et.getId()))}}),_e}renderMetricsElements(){return jsxRuntimeExports.jsx("div",{ref:this.findBorderBarSizeRef,className:this.getClassName(CLASSES.FLEXLAYOUT__BORDER_SIZER),children:"FindBorderBarSize"},"findBorderBarSize")}checkForBorderToShow(_e,tt){const et=this.getBoundingClientRect(this.mainRef.current),nt=et.getCenter(),it=edgeRectWidth,at=edgeRectLength/2;let ot=!1;this.props.model.isEnableEdgeDock()&&this.state.showHiddenBorder===DockLocation.CENTER&&(tt>nt.y-at&&tt<nt.y+at||_e>nt.x-at&&_e<nt.x+at)&&(ot=!0);let st=DockLocation.CENTER;ot||(_e<=et.x+it?st=DockLocation.LEFT:_e>=et.getRight()-it?st=DockLocation.RIGHT:tt<=et.y+it?st=DockLocation.TOP:tt>=et.getBottom()-it&&(st=DockLocation.BOTTOM)),st!==this.state.showHiddenBorder&&this.setState({showHiddenBorder:st})}tidyMoveablesMap(){const _e=new Map;this.props.model.visitNodes((tt,et)=>{tt instanceof TabNode&&_e.set(tt.getId(),tt)});for(const[tt,et]of this.moveableElementMap)_e.has(tt)||(et.remove(),this.moveableElementMap.delete(tt))}reorderComponents(_e,tt){const et=[],nt=new Set;let it=[];for(const at of tt)_e.get(at)&&(et.push(at),nt.add(at));tt.splice(0,tt.length,...et);for(const[at,ot]of _e)nt.has(at)||tt.push(at);return it=tt.map(at=>_e.get(at)),it}redraw(_e){this.mainLayout.setState((tt,et)=>({forceRevision:tt.forceRevision+1}))}redrawInternal(_e){this.mainLayout.setState((tt,et)=>({layoutRevision:tt.layoutRevision+1}))}doAction(_e){if(this.props.onAction!==void 0){const tt=this.props.onAction(_e);return tt!==void 0?this.props.model.doAction(tt):void 0}else return this.props.model.doAction(_e)}getBoundingClientRect(_e){const tt=this.getDomRect();return tt?Rect.getBoundingClientRect(_e).relativeTo(tt):Rect.empty()}getMoveableContainer(){return this.moveablesRef.current}getMoveableElement(_e){let tt=this.moveableElementMap.get(_e);return tt===void 0&&(tt=document.createElement("div"),this.moveablesRef.current.appendChild(tt),tt.className=CLASSES.FLEXLAYOUT__TAB_MOVEABLE,this.moveableElementMap.set(_e,tt)),tt}getMainLayout(){return this.mainLayout}getCurrentDocument(){return this.currentDocument}getDomRect(){return this.selfRef.current?Rect.fromDomRect(this.selfRef.current.getBoundingClientRect()):Rect.empty()}getWindowId(){return this.windowId}getRootDiv(){return this.selfRef.current}getMainElement(){return this.mainRef.current}getFactory(){return this.props.factory}isSupportsPopout(){return this.supportsPopout}isRealtimeResize(){return this.props.realtimeResize??!1}getPopoutURL(){return this.popoutURL}setEditingTab(_e){this.setState({editingTab:_e})}getEditingTab(){return this.state.editingTab}getModel(){return this.props.model}getScreenRect(_e){const tt=_e.clone(),et=this.getDomRect(),nt=60,it=2;return tt.x=this.currentWindow.screenX+this.currentWindow.scrollX+it/2+et.x+tt.x,tt.y=this.currentWindow.screenY+this.currentWindow.scrollY+(nt-it/2)+et.y+tt.y,tt.height+=nt,tt.width+=it,tt}addTabToTabSet(_e,tt){if(this.props.model.getNodeById(_e)!==void 0)return this.doAction(Actions.addNode(tt,_e,DockLocation.CENTER,-1))}addTabToActiveTabSet(_e){const tt=this.props.model.getActiveTabset(this.windowId);if(tt!==void 0)return this.doAction(Actions.addNode(_e,tt.getId(),DockLocation.CENTER,-1))}maximize(_e){this.doAction(Actions.maximizeToggle(_e.getId(),this.getWindowId()))}customizeTab(_e,tt){this.props.onRenderTab&&this.props.onRenderTab(_e,tt)}customizeTabSet(_e,tt){this.props.onRenderTabSet&&this.props.onRenderTabSet(_e,tt)}i18nName(_e,tt){let et;return this.props.i18nMapper&&(et=this.props.i18nMapper(_e,tt)),et===void 0&&(et=_e+(tt===void 0?"":tt)),et}getShowOverflowMenu(){return this.props.onShowOverflowMenu}getTabSetPlaceHolderCallback(){return this.props.onTabSetPlaceHolder}showContextMenu(_e,tt){this.props.onContextMenu&&this.props.onContextMenu(_e,tt)}auxMouseClick(_e,tt){this.props.onAuxMouseClick&&this.props.onAuxMouseClick(_e,tt)}showOverlay(_e){this.setState({showOverlay:_e}),enablePointerOnIFrames(!_e,this.currentDocument)}addTabWithDragAndDrop(_e,tt,et){const nt=TabNode.fromJson(tt,this.props.model,!1);_r.dragState=new DragState(this.mainLayout,"add",nt,tt,et)}moveTabWithDragAndDrop(_e,tt){this.setDragNode(_e,tt)}setDragComponent(_e,tt,et,nt){const it=jsxRuntimeExports.jsx("div",{style:{position:"unset"},className:this.getClassName(CLASSES.FLEXLAYOUT__LAYOUT)+" "+this.getClassName(CLASSES.FLEXLAYOUT__DRAG_RECT),children:tt}),at=this.currentDocument.createElement("div");at.setAttribute("data-layout-path","/drag-rectangle"),at.style.position="absolute",at.style.left="-10000px",at.style.top="-10000px",this.currentDocument.body.appendChild(at),createRoot(at).render(it),_e.dataTransfer.setDragImage(at,et,nt),setTimeout(()=>{this.currentDocument.body.removeChild(at)},0)}setDraggingOverWindow(_e){this.isDraggingOverWindow!==_e&&(this.outlineDiv&&(this.outlineDiv.style.visibility=_e?"hidden":"visible"),_e?this.setState({showEdges:!1}):this.props.model.getMaximizedTabset(this.windowId)===void 0&&this.setState({showEdges:this.props.model.isEnableEdgeDock()}),this.isDraggingOverWindow=_e)}clearDragMain(){_r.dragState=void 0,this.windowId===Model.MAIN_WINDOW_ID&&(this.isDraggingOverWindow=!1);for(const[,_e]of this.props.model.getwindowsMap())_e.layout.clearDragLocal()}clearDragLocal(){this.setState({showEdges:!1}),this.showOverlay(!1),this.dragEnterCount=0,this.dragging=!1,this.outlineDiv&&(this.selfRef.current.removeChild(this.outlineDiv),this.outlineDiv=void 0)}};__publicField(_LayoutInternal,"dragState");const defaultIcons={close:jsxRuntimeExports.jsx(CloseIcon,{}),closeTabset:jsxRuntimeExports.jsx(CloseIcon,{}),popout:jsxRuntimeExports.jsx(PopoutIcon,{}),maximize:jsxRuntimeExports.jsx(MaximizeIcon,{}),restore:jsxRuntimeExports.jsx(RestoreIcon,{}),more:jsxRuntimeExports.jsx(OverflowIcon,{}),edgeArrow:jsxRuntimeExports.jsx(EdgeIcon,{}),activeTabset:jsxRuntimeExports.jsx(AsterickIcon,{})},defaultSupportsPopout=isDesktop(),edgeRectLength=100,edgeRectWidth=10;class DragState{constructor(_e,tt,et,nt,it){__publicField(this,"mainLayout"),__publicField(this,"dragSource"),__publicField(this,"dragNode"),__publicField(this,"dragJson"),__publicField(this,"fnNewNodeDropped"),this.mainLayout=_e,this.dragSource=tt,this.dragNode=et,this.dragJson=nt,this.fnNewNodeDropped=it}}const log=logger$2("layout");class LayoutSystem extends RootStore{constructor(tt){super(tt);Rt(this,"CACHE_LAYOUT_KEY","galacean-layoutFile");Rt(this,"CACHE_SIDEBAR_KEY","galacean-sidebar");Rt(this,"CACHE_SIDEBAR_POSITION_KEY","galacean-sidebar-position");Rt(this,"CUSTOM_LAYOUT_KEY","galacean-custom-layoutFile");Rt(this,"EDITOR_MODE_KEY","galacean-editor-mode");Rt(this,"sidebarVisible",!0);Rt(this,"sidebarPosition","left");Rt(this,"editorMode","professional");Rt(this,"activePanel","");Rt(this,"flexLayoutModel",null);Rt(this,"controller");Rt(this,"tabs",null);Rt(this,"panels",[]);Rt(this,"panelContents",new Map);Rt(this,"customLayouts",[]);Rt(this,"initTabs",tt=>{this.tabs=tt});Rt(this,"activeTab",tt=>{const{flexLayoutModel:et}=this;et.doAction(Actions.selectTab(tt))});Rt(this,"saveController",tt=>{this.controller=tt});Rt(this,"setModel",tt=>{this.flexLayoutModel=tt});Rt(this,"addPanel",(tt,et)=>{this.panelContents.set(tt.id,et),this.panels.push(tt)});Rt(this,"closePanel",tt=>{const et=this.panels.findIndex(nt=>nt.id===tt);et>-1&&this.panels.splice(et,1)});Rt(this,"removePanel",tt=>{this.panelContents.delete(tt)});Rt(this,"resizePanel",(tt,et)=>{const nt=this.panels.find(it=>it.id===tt);nt&&(nt.size=et)});Rt(this,"toggleSidebar",tt=>{if(tt!==void 0){this.sidebarVisible=tt;return}this.sidebarVisible=!this.sidebarVisible,set(this.CACHE_SIDEBAR_KEY,this.sidebarVisible)});Rt(this,"setSidebarPosition",tt=>{this.sidebarPosition=tt,set(this.CACHE_SIDEBAR_POSITION_KEY,tt)});Rt(this,"setActivePanel",tt=>{this.activePanel=tt});Rt(this,"toggleEditorMode",tt=>{tt!==void 0?this.editorMode=tt:this.editorMode=this.editorMode==="simple"?"professional":"simple",set(this.EDITOR_MODE_KEY,this.editorMode)});Rt(this,"toggleTabVisibility",(tt,et)=>{const{flexLayoutModel:nt,tabs:it,controller:at}=this,ot=nt.getNodeById(tt),st=nt.getNodeById(it.Viewport.id),ct=["Assets","AnimatorController","AnimationClip"],dt=["Hierarchy"],ut=["Inspector"];if(ot&&et===!1){nt.doAction(Actions.deleteTab(ot.getId()));return}if(ot){if(ot.isVisible()&&nt.doAction(Actions.selectTab(tt)),et!==!1){const mt=it[tt];mt!=null&&mt.onVisibilityChange&&mt.onVisibilityChange(mt.id,!0)}return}let ht=nt.getRoot().getId(),ft=DockLocation.BOTTOM;function pt(mt,vt,_t){const yt=mt.find(bt=>nt.getNodeById(it[bt].id));if(yt){_t=nt.getNodeById(it[yt].id).getParent().getId(),at.addTabToTabSet(_t,it[tt]);return}nt.doAction(Actions.addNode(it[tt],_t,vt,0))}if(dt.includes(tt))return ft=DockLocation.LEFT,pt(dt,ft,ht);if(ut.includes(tt))return ft=DockLocation.RIGHT,pt(ut,ft,ht);if(ct.includes(tt))return ht=st.getParent().getId(),ft=DockLocation.BOTTOM,pt(ct,ft,ht)});Rt(this,"toggleSceneMaximize",()=>{const{flexLayoutModel:tt,tabs:et}=this,it=tt.getNodeById(et.Viewport.id).getParent();tt.doAction(Actions.maximizeToggle(it.getId()))});Rt(this,"cache",tt=>{log.info("save layout","verbose");const et=tt||this.flexLayoutModel;et&&set(this.CACHE_LAYOUT_KEY,et.toJson())});Rt(this,"addCustomLayout",async tt=>{const et={name:tt,layout:this.flexLayoutModel.toJson()};await get(this.CUSTOM_LAYOUT_KEY)?update$1(this.CUSTOM_LAYOUT_KEY,it=>[...it,et]):set(this.CUSTOM_LAYOUT_KEY,[et]),this.customLayouts.push(et)});Rt(this,"deleteCustomLayout",tt=>{update$1(this.CUSTOM_LAYOUT_KEY,et=>et.filter(nt=>nt.name!==tt)),this.customLayouts=this.customLayouts.filter(et=>et.name!==tt)});Rt(this,"clearCacheLayout",async()=>{await del(this.CACHE_LAYOUT_KEY),await del(this.CACHE_SIDEBAR_KEY),location.reload()});makeObservable(this,{sidebarVisible:observable,sidebarPosition:observable,editorMode:observable,activePanel:observable,customLayouts:observable.shallow,toggleSidebar:action,setSidebarPosition:action,toggleEditorMode:action,setActivePanel:action,flexLayoutModel:observable.ref,panels:observable,panelContents:observable.ref,removePanel:observable.ref})}async getCustomLayoutFromLocal(){const tt=await get(this.CUSTOM_LAYOUT_KEY);this.customLayouts=tt||[]}async initLayout(tt,et,nt){this.CACHE_LAYOUT_KEY=`${this.CACHE_LAYOUT_KEY}-${et}`,this.CACHE_SIDEBAR_KEY=`${this.CACHE_SIDEBAR_KEY}-${et}`,this.CACHE_SIDEBAR_POSITION_KEY=`${this.CACHE_SIDEBAR_POSITION_KEY}-${et}`,this.CUSTOM_LAYOUT_KEY=`${this.CUSTOM_LAYOUT_KEY}-${nt}`,this.EDITOR_MODE_KEY=`${this.EDITOR_MODE_KEY}-${et}`;const it=await this.loadCacheLayout(),at=await this.loadCacheSidebar(),ot=await this.loadCacheSidebarPosition(),st=await this.loadCacheEditorMode(),ct=it?{...it,global:tt.global}:tt;this.flexLayoutModel=Model.fromJson(ct),this.sidebarVisible=at??!0,this.sidebarPosition=ot??"left",this.editorMode=st??"professional",await this.getCustomLayoutFromLocal()}async loadCacheLayout(){try{return await get(this.CACHE_LAYOUT_KEY)}catch{return console.warn("Failed to load and parse layout from cache."),null}}async loadCacheSidebar(){try{return await get(this.CACHE_SIDEBAR_KEY)}catch{console.warn("Failed to load and parse layout from cache.");return}}async loadCacheSidebarPosition(){try{return await get(this.CACHE_SIDEBAR_POSITION_KEY)}catch{console.warn("Failed to load sidebar position from cache.");return}}async loadCacheEditorMode(){try{return await get(this.EDITOR_MODE_KEY)}catch{console.warn("Failed to load editor mode from cache.");return}}replaceLayout(tt){this.flexLayoutModel=Model.fromJson(tt),this.cache()}}class SelectionStore extends RootStore{constructor(tt){super(tt);Rt(this,"_logger",new TraceLogger("SelectionStore"));Rt(this,"_fallbackContext","scene");Rt(this,"_listeners",new Set);Rt(this,"_snapshot",null);Rt(this,"_sceneDisposer",null);Rt(this,"_assetDisposer",null);Rt(this,"_disposed",!1)}subscribe(tt){return this._disposed?()=>{}:(this._ensureSelectionBridge(),this._listeners.add(tt),()=>{this._listeners.delete(tt)})}getSnapshot(){return this._disposed?this._buildSnapshot():(this._ensureSelectionBridge(),this._snapshot||(this._snapshot=this._buildSnapshot()),this._snapshot)}get context(){return this.assetIds.size||this.lastSelectedAssetId?"asset":this.entityIds.size||this.lastSelectedEntityId?"entity":this._fallbackContext}get entityIds(){var tt;return new Set(Array.from(((tt=this.root.sceneUIStore)==null?void 0:tt.selectedKeys)??[]))}get assetIds(){var tt;return new Set(((tt=this.root.assetUIStore)==null?void 0:tt.pickedAssets)??[])}get lastSelectedEntityId(){var tt;return((tt=this.root.sceneUIStore)==null?void 0:tt.lastSelectedId)??null}get lastSelectedAssetId(){var tt;return((tt=this.root.assetUIStore)==null?void 0:tt.selectedAssetId)??null}_buildSnapshot(){return{context:this.context,entityIds:Array.from(this.entityIds),assetIds:Array.from(this.assetIds),lastSelectedEntityId:this.lastSelectedEntityId,lastSelectedAssetId:this.lastSelectedAssetId}}_notify(){this._snapshot=null,this._logger.info("_notify",{listeners:this._listeners.size,lastEntityId:this.lastSelectedEntityId});for(const tt of this._listeners)tt()}_ensureSelectionBridge(){this._disposed||this._sceneDisposer||(this.root.sceneUIStore&&(this._sceneDisposer=this.root.sceneUIStore.onSelectionChange(()=>this._notify())),this.root.assetUIStore&&(this._assetDisposer=this.root.assetUIStore.onSelectionChange(()=>this._notify())))}_disposeSelectionBridge(){var tt,et;(tt=this._sceneDisposer)==null||tt.call(this),(et=this._assetDisposer)==null||et.call(this),this._sceneDisposer=null,this._assetDisposer=null}dispose(){this._disposed||(this._disposed=!0,this._listeners.clear(),this._snapshot=null,this._disposeSelectionBridge())}get selectedEntities(){return this.root.sceneStore?Array.from(this.entityIds).map(tt=>this.root.sceneStore.getEntityModel(tt)).filter(Boolean):[]}get selectedAssets(){return this.root.assetStore?Array.from(this.assetIds).map(tt=>this.root.assetStore.assets[tt]).filter(Boolean):[]}get lastSelectedEntity(){return!this.lastSelectedEntityId||!this.root.sceneStore?null:this.root.sceneStore.getEntityModel(this.lastSelectedEntityId)??null}get selectedEntityReadModels(){return this.root.readModelStore?Array.from(this.entityIds).map(tt=>this.root.readModelStore.getEntity(tt)).filter(tt=>tt!==void 0):[]}get lastSelectedEntityReadModel(){return!this.lastSelectedEntityId||!this.root.readModelStore?null:this.root.readModelStore.getEntity(this.lastSelectedEntityId)??null}get lastSelectedAsset(){return!this.lastSelectedAssetId||!this.root.assetStore?null:this.root.assetStore.assets[this.lastSelectedAssetId]??null}selectEntity(tt,et=!1){var nt;this._fallbackContext="entity",typeof((nt=this.root.sceneStore)==null?void 0:nt.selectEntity)=="function"?this.root.sceneStore.selectEntity(tt,et):this.root.sceneUIStore&&(et||this.root.sceneUIStore.clearSelection(),this.root.sceneUIStore.selectEntity(tt,!0))}deselectEntity(tt){var et;(et=this.root.sceneUIStore)==null||et.deselectEntity(tt)}selectAsset(tt,et=!1){var nt,it,at,ot,st;if(this._fallbackContext="asset",et){const ct=[...((nt=this.root.assetUIStore)==null?void 0:nt.pickedAssets)??[]];ct.includes(tt)||ct.push(tt),(at=(it=this.root.assetStore)==null?void 0:it.selectAsset)==null||at.call(it,ct);return}(st=(ot=this.root.assetStore)==null?void 0:ot.selectAsset)==null||st.call(ot,tt)}deselectAsset(tt){if(!this.root.assetUIStore)return;const et=this.root.assetUIStore.pickedAssets.filter(it=>it!==tt),nt=this.root.assetUIStore.selectedAssetId===tt?et.at(-1)??null:this.root.assetUIStore.selectedAssetId;this.root.assetUIStore.setSelection(et,nt)}clearSelection(){var tt,et;(tt=this.root.sceneUIStore)==null||tt.clearSelection(),(et=this.root.assetUIStore)==null||et.clearSelect(),this._fallbackContext="scene",this._notify()}setContext(tt){this._fallbackContext=tt,this._notify()}}class EditorError extends Error{constructor(_e,tt,et,nt,it){super(nt),this.domain=_e,this.severity=tt,this.code=et,this.details=it,this.name="EditorError"}}var ProjectionErrorCode=(rt=>(rt.PARENT_NOT_FOUND="PROJECTION_PARENT_NOT_FOUND",rt.ENTITY_NOT_FOUND="PROJECTION_ENTITY_NOT_FOUND",rt.ROLLBACK_FAILED="PROJECTION_ROLLBACK_FAILED",rt.REBUILD_FAILED="PROJECTION_REBUILD_FAILED",rt))(ProjectionErrorCode||{});class ProjectionError extends EditorError{constructor(_e,tt,et){super("projection","recoverable",_e,tt,et),this.name="ProjectionError"}}var EffectsErrorCode=(rt=>(rt.DELETE_FAILED="EFFECTS_DELETE_FAILED",rt.CREATE_FAILED="EFFECTS_CREATE_FAILED",rt.UPDATE_FAILED="EFFECTS_UPDATE_FAILED",rt))(EffectsErrorCode||{});class EffectsError extends EditorError{constructor(_e,tt,et){super("effects","warning",_e,tt,et),this.name="EffectsError"}}const defaultComponentFactory=()=>null;function assertNeverEvent$2(rt){throw new Error(`EngineProjection: unhandled event ${rt.type}`)}class EngineProjection{constructor(_e,tt,et){Rt(this,"entityMap",new Map);Rt(this,"entityReverseMap",new WeakMap);Rt(this,"componentMap",new Map);Rt(this,"assetMap",new Map);Rt(this,"externalEntityIds",new Set);Rt(this,"graveyardEntities",new Map);Rt(this,"graveyardComponents",new Map);Rt(this,"componentFactory");Rt(this,"assetResolver",null);Rt(this,"sceneSettingAppliers",{"ambient/diffuseMode":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.diffuseMode=tt)},"ambient/diffuseSolidColor":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&this.applyStructuredValue(et,"diffuseSolidColor",tt)},"ambient/diffuseIntensity":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.diffuseIntensity=tt)},"ambient/specularMode":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.specularMode=tt)},"ambient/specularIntensity":(_e,tt)=>{const et=this.getAmbientLight(_e);et&&(et.specularIntensity=tt)},"background/mode":(_e,tt)=>{const et=this.getBackground(_e);et&&(et.mode=tt)},"background/color":(_e,tt)=>{const et=this.getBackground(_e);et&&this.applyStructuredValue(et,"solidColor",tt)},"background/texture":(_e,tt)=>{const et=this.getBackground(_e);et&&this.applyResolvedReference(et,"texture",tt)},"background/skyMaterial":(_e,tt)=>{const et=this.getBackgroundSky(_e);et&&this.applyResolvedReference(et,"material",tt)},"background/skyMesh":(_e,tt)=>{const et=this.getBackgroundSky(_e);et&&this.applyResolvedReference(et,"mesh",tt)},"background/textureFillMode":(_e,tt)=>{const et=this.getBackground(_e);et&&(et.textureFillMode=tt)},"shadow/castShadows":(_e,tt)=>{_e.castShadows=tt},"shadow/enableTransparentShadow":(_e,tt)=>{_e.enableTransparentShadow=tt},"shadow/shadowResolution":(_e,tt)=>{_e.shadowResolution=tt},"shadow/shadowDistance":(_e,tt)=>{_e.shadowDistance=tt},"shadow/shadowCascades":(_e,tt)=>{_e.shadowCascades=tt},"shadow/shadowTwoCascadeSplits":(_e,tt)=>{_e.shadowTwoCascadeSplits=tt},"shadow/shadowFourCascadeSplits":(_e,tt)=>{this.applyStructuredValue(_e,"shadowFourCascadeSplits",tt)},"shadow/shadowFadeBorder":(_e,tt)=>{_e.shadowFadeBorder=tt},"fog/mode":(_e,tt)=>{_e.fogMode=tt},"fog/color":(_e,tt)=>{this.applyStructuredValue(_e,"fogColor",tt)},"fog/density":(_e,tt)=>{_e.fogDensity=tt},"fog/start":(_e,tt)=>{_e.fogStart=tt},"fog/end":(_e,tt)=>{_e.fogEnd=tt},"ambientOcclusion/enabled":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.enabled=tt)},"ambientOcclusion/quality":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.quality=tt)},"ambientOcclusion/intensity":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.intensity=tt)},"ambientOcclusion/radius":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.radius=tt)},"ambientOcclusion/bias":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.bias=tt)},"ambientOcclusion/power":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.power=tt)},"ambientOcclusion/bilateralThreshold":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.bilateralThreshold=tt)},"ambientOcclusion/minHorizonAngle":(_e,tt)=>{const et=this.getAmbientOcclusion(_e);et&&(et.minHorizonAngle=tt)}});Rt(this,"_canRedo");this._scene=_e,this.componentFactory=tt??defaultComponentFactory,this._canRedo=et??(()=>!1)}get scene(){return this._scene}setComponentFactory(_e){this.componentFactory=_e}flushDeferredComponentProps(){var _e,tt;(tt=(_e=this.componentFactory).flushDeferred)==null||tt.call(_e)}rebindAssetReferences(_e){var tt,et,nt,it;(et=(tt=this.componentFactory).rebindAssetReferences)==null||et.call(tt,_e),(it=(nt=this.componentFactory).flushDeferred)==null||it.call(nt)}setAssetResolver(_e){this.assetResolver=_e}resolveRef(_e){if(_e==null||typeof _e!="object"||!("refId"in _e))return _e;if(!this.assetResolver)return;const tt=_e,et=tt.key?`${tt.refId}-${tt.key}`:tt.refId,nt=this.assetResolver(et);return nt!==null?nt:void 0}setScene(_e){if(this._scene===_e)return;this._scene=_e;const tt=[];for(const et of this.entityMap.values())et.parent||tt.push(et);for(const et of tt)_e.addRootEntity(et)}apply(_e,tt){tt&&!isUndoRedoCommand(tt)&&!this._canRedo()&&this.clearGraveyard(),_e!=null&&_e.length&&this.applyEvents(_e)}applyEvents(_e){for(const tt of _e)switch(tt.type){case"EntityCreated":this.createEngineEntity(tt.entityId,tt.entity);break;case"EntityUpdated":this.applyEntityUpdatedEvent(tt);break;case"EntityMoved":this.applyEntityMovedEvent(tt);break;case"EntityDeleted":this.applyEntityDeletedEvent(tt);break;case"ComponentAdded":this.applyComponentAddedEvent(tt);break;case"ComponentUpdated":this.applyComponentUpdatedEvent(tt);break;case"ComponentRemoved":this.destroyEngineComponent(tt.componentId);break;case"SceneSettingUpdated":this.applySceneSettingEvent(tt.settingPath,tt.value);break;case"AssetCreated":this.assetMap.set(tt.assetId,tt.asset);break;case"AssetUpdated":this.applyAssetUpdatedEvent(tt);break;case"AssetDeleted":this.assetMap.delete(tt.assetId);break;case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":case"PrefabOverrideChanged":break;default:assertNeverEvent$2(tt)}}applyEntityUpdatedEvent(_e){const tt=this.entityMap.get(_e.entityId);if(!tt)return;const{changes:et}=_e;if(et.name!==void 0&&(tt.name=et.name),et.isActive!==void 0&&(tt.isActive=et.isActive),et.layer!==void 0&&(tt.layer=et.layer),et.transform){const nt=et.transform;nt.position&&this.updateTransformProperty(tt,["position"],{x:nt.position.x??tt.transform.position.x,y:nt.position.y??tt.transform.position.y,z:nt.position.z??tt.transform.position.z}),nt.rotation&&this.updateTransformProperty(tt,["rotation"],{x:nt.rotation.x??tt.transform.rotation.x,y:nt.rotation.y??tt.transform.rotation.y,z:nt.rotation.z??tt.transform.rotation.z}),nt.scale&&this.updateTransformProperty(tt,["scale"],{x:nt.scale.x??tt.transform.scale.x,y:nt.scale.y??tt.transform.scale.y,z:nt.scale.z??tt.transform.scale.z})}}applyEntityMovedEvent(_e){const tt=this.entityMap.get(_e.entityId);tt&&(this.reparentEntity(tt,_e.parentId),tt.siblingIndex=_e.index)}applyEntityDeletedEvent(_e){for(const tt of[..._e.subtreeIds].reverse())this.destroyEngineEntity(tt)}applyComponentAddedEvent(_e){const tt=this.entityMap.get(_e.entityId);tt&&this.createEngineComponent(tt,_e.componentId,_e.component)}applyComponentUpdatedEvent(_e){for(const[tt,et]of Object.entries(_e.changes))this.updateComponentProperty(_e.componentId,tt,et)}applyAssetUpdatedEvent(_e){this.assetMap.set(_e.assetId,_e.asset);const tt=_e.previousAsset.meta??{},et=_e.asset.meta??{},nt=new Set([...Object.keys(tt),...Object.keys(et)]);for(const it of nt){const at=tt[it],ot=et[it];JSON.stringify(at)!==JSON.stringify(ot)&&this.projectAssetMetaToEngine(_e.assetId,it,ot)}}createEngineEntity(_e,tt){const et=this.graveyardEntities.get(_e);et&&(this.entityMap.set(_e,et),this.entityReverseMap.set(et,_e),this.externalEntityIds.add(_e),this.graveyardEntities.delete(_e));const nt=this.resolveParentEntity(_e,tt.parentId),it=this.entityMap.get(_e);if(it){if(this.externalEntityIds.has(_e)){const ot=it;ot.__editorExternalComponentClaimRevision=(ot.__editorExternalComponentClaimRevision??0)+1}if(nt)it.parent!==nt&&nt.addChild(it);else{const ot=!!it.parent;ot&&(it.parent=null),(ot||!it.scene||it.scene!==this.scene)&&this.scene.addRootEntity(it)}if(this.applyEntityState(it,tt),tt.components)for(const[ot,st]of Object.entries(tt.components))this.componentMap.has(ot)||this.createEngineComponent(it,ot,st);return}const at=nt?nt.createChild(tt.name):this.scene.createRootEntity(tt.name);if(this.applyEntityState(at,tt),this.entityMap.set(_e,at),this.entityReverseMap.set(at,_e),tt.components)for(const[ot,st]of Object.entries(tt.components))this.createEngineComponent(at,ot,st)}resolveParentEntity(_e,tt){if(!tt)return null;const et=this.entityMap.get(tt);if(!et)throw new ProjectionError(ProjectionErrorCode.PARENT_NOT_FOUND,`EngineProjection: parent entity "${tt}" not found when creating "${_e}".`,{entityId:_e,parentId:tt});return et}applyEntityState(_e,tt){_e.name=tt.name,_e.isActive=tt.isActive,_e.layer=tt.layer;const{position:et,rotation:nt,scale:it}=tt.transform;_e.transform.position.set(et.x,et.y,et.z),_e.transform.rotation.set(nt.x,nt.y,nt.z),_e.transform.scale.set(it.x,it.y,it.z)}destroyEngineEntity(_e){var nt,it;const tt=this.entityMap.get(_e);if(!tt)return;const et=this.externalEntityIds.has(_e);for(const[at,ot]of this.componentMap)ot.entity===tt&&((it=(nt=this.componentFactory).forgetComponentAssetReferences)==null||it.call(nt,ot),et&&this.addToGraveyard(_e,at,ot),this.componentMap.delete(at));if(et)tt.parent=null,tt.scene===this.scene&&this.scene.removeRootEntity(tt),this.graveyardEntities.set(_e,tt);else try{tt.destroy()}catch(at){console.warn("[EngineProjection] destroyEngineEntity failed:",at)}this.entityMap.delete(_e),this.externalEntityIds.delete(_e),tt&&this.entityReverseMap.delete(tt)}createEngineComponent(_e,tt,et){var at,ot;const nt=this.findEntityId(_e);if(nt){const st=this.graveyardComponents.get(nt);if(st!=null&&st.has(tt)){const ct=st.get(tt);ct.__editorComponentType=et.type;for(const[dt,ut]of Object.entries(et.props))(ot=(at=this.componentFactory).trackAssetReference)==null||ot.call(at,ct,et.type,dt,ut);this.componentMap.set(tt,ct),st.delete(tt),st.size===0&&this.graveyardComponents.delete(nt);return}}const it=this.componentFactory(_e,et.type,et.props);it&&(it.__editorComponentType=et.type,this.componentMap.set(tt,it))}findEntityId(_e){return this.entityReverseMap.get(_e)}destroyEngineComponent(_e){var nt,it;const tt=this.componentMap.get(_e);if(!tt)return;(it=(nt=this.componentFactory).forgetComponentAssetReferences)==null||it.call(nt,tt);const et=this.findEntityId(tt.entity);if(et&&this.externalEntityIds.has(et)){this.addToGraveyard(et,_e,tt),this.componentMap.delete(_e);return}tt.destroy(),this.componentMap.delete(_e)}addToGraveyard(_e,tt,et){let nt=this.graveyardComponents.get(_e);nt||(nt=new Map,this.graveyardComponents.set(_e,nt)),nt.set(tt,et)}clearGraveyard(){if(!(this.graveyardEntities.size===0&&this.graveyardComponents.size===0)){for(const _e of this.graveyardEntities.values())try{_e.destroy()}catch{}for(const _e of this.graveyardComponents.values())for(const tt of _e.values())try{tt.destroy()}catch{}this.graveyardEntities.clear(),this.graveyardComponents.clear()}}updateComponentProperty(_e,tt,et){var st,ct,dt,ut,ht;const nt=this.componentMap.get(_e);if(!nt)return;const it=nt.__editorComponentType;it&&((ct=(st=this.componentFactory).trackAssetReference)==null||ct.call(st,nt,it,tt,et));const at=et===void 0?void 0:this.resolveRef(et);if(et!==void 0&&at===void 0)return;const ot=it?(ht=(ut=(dt=this.componentFactory).getProxyMap)==null?void 0:ut.call(dt,it))==null?void 0:ht[tt]:void 0;if(ot&&typeof nt[ot]=="function"){nt[ot](at);return}if(tt in nt)try{nt[tt]=at}catch{}}reparentEntity(_e,tt){if(tt){const et=this.entityMap.get(tt);if(!et)throw new ProjectionError(ProjectionErrorCode.PARENT_NOT_FOUND,`EngineProjection: new parent "${tt}" not found for reparent.`,{parentId:tt});_e.parent=et}else _e.parent=null,this.scene.addRootEntity(_e)}updateTransformProperty(_e,tt,et){if(tt.length===0){const ot=et;_e.transform.position.set(ot.position.x,ot.position.y,ot.position.z),_e.transform.rotation.set(ot.rotation.x,ot.rotation.y,ot.rotation.z),_e.transform.scale.set(ot.scale.x,ot.scale.y,ot.scale.z);return}if(tt.length===1){const[ot]=tt,st=et;_e.transform[ot].set(st.x,st.y,st.z);return}const[nt,it]=tt,at=_e.transform[nt];if(at&&it in at){const ot={x:at.x,y:at.y,z:at.z};ot[it]=et,at.set(ot.x,ot.y,ot.z)}}projectAssetMetaToEngine(_e,tt,et){if(!this.assetResolver)return;const nt=this.assetResolver(_e);if(!(!nt||typeof nt!="object")&&tt in nt)try{nt[tt]=et}catch{}}applySceneSettingEvent(_e,tt){if(!isEngineProjectionSceneSettingPath(_e))return;const et=this.sceneSettingAppliers[_e];et(this._scene,tt)}applyStructuredValue(_e,tt,et){if(!et||typeof et!="object"){_e[tt]=et;return}const nt=_e[tt];if(nt&&typeof nt=="object"&&"set"in nt){const it=nt.set,at=et;"r"in at?it.call(nt,at.r,at.g,at.b,at.a):"x"in at&&it.call(nt,at.x,at.y,at.z)}else _e[tt]=et}applyResolvedReference(_e,tt,et){if(et==null){_e[tt]=et;return}const nt=this.resolveRef(et);nt!==void 0&&(_e[tt]=nt)}getAmbientLight(_e){return _e.ambientLight}getBackground(_e){return _e.background}getBackgroundSky(_e){var tt;return(tt=this.getBackground(_e))==null?void 0:tt.sky}getAmbientOcclusion(_e){return _e.ambientOcclusion}checkHealth(_e){const tt=new Set(Object.keys(_e.entities)),et=new Set(this.entityMap.keys()),nt=new Set(Object.keys(_e.assets)),it=new Set(this.assetMap.keys()),at=Array.from(tt).filter(dt=>!et.has(dt)),ot=Array.from(et).filter(dt=>!tt.has(dt)),st=Array.from(nt).filter(dt=>!it.has(dt)),ct=Array.from(it).filter(dt=>!nt.has(dt));return at.sort(),ot.sort(),st.sort(),ct.sort(),{healthy:at.length===0&&ot.length===0&&st.length===0&&ct.length===0,missingInEngine:at,orphanInEngine:ot,missingAssets:st,orphanAssets:ct}}getEntity(_e){return this.entityMap.get(_e)}getAsset(_e){return this.assetMap.get(_e)}getComponent(_e){return this.componentMap.get(_e)}setEntityRuntimeActive(_e,tt){const et=this.entityMap.get(_e);et&&(et.isActive=tt)}addEntityChild(_e,tt,et){const nt=this.entityMap.get(_e),it=this.entityMap.get(tt);nt&&it&&(et!==void 0?nt.addChild(et,it):nt.addChild(it))}removeEntityChild(_e,tt){const et=this.entityMap.get(_e),nt=this.entityMap.get(tt);et&&nt&&et.removeChild(nt)}getEntityIdByEngineObject(_e){return this.entityReverseMap.get(_e)}registerExternalEntity(_e,tt){this.entityMap.set(_e,tt),this.entityReverseMap.set(tt,_e),this.externalEntityIds.add(_e),tt.__editorExternalEntity=!0}reset(){var tt,et;for(const nt of this.componentMap.values()){const it=this.findEntityId(nt.entity);if(!(it&&this.externalEntityIds.has(it)))try{nt.destroy()}catch{}}this.componentMap.clear();const _e=new Map;for(const[nt,it]of this.entityMap){if(this.externalEntityIds.has(nt)){_e.set(nt,it);continue}try{it.destroy()}catch{}}this.entityMap=_e;for(const nt of this.graveyardEntities.values())try{nt.destroy()}catch{}this.graveyardEntities.clear(),this.graveyardComponents.clear(),this.assetMap.clear(),(et=(tt=this.componentFactory).clearAssetReferenceTracking)==null||et.call(tt)}rebuildFromState(_e){this.reset();const tt=new Set,et=nt=>{if(tt.has(nt))return;const it=_e.entities[nt];it&&(it.parentId&&!tt.has(it.parentId)&&et(it.parentId),this.createEngineEntity(nt,it),tt.add(nt))};for(const nt of _e.scene.rootEntityIds)et(nt);for(const nt of Object.keys(_e.entities))et(nt);for(const[nt,it]of Object.entries(_e.assets))this.assetMap.set(nt,it)}}function assertNeverEvent$1(rt){throw new Error(`EntityModelProjection: unhandled event ${rt.type}`)}const ENTITY_TRANSFORM_COMPONENT_TYPES=new Set(["Transform","UITransform"]);class EntityModelProjection{constructor(_e,tt){Rt(this,"_logger",new TraceLogger("EntityModelProjection"));this._getScene=_e,this._getEP=tt}apply(_e,tt){const et=this._getScene();et&&_e!=null&&_e.length&&this._applyEvents(_e,tt,et)}_applyEvents(_e,tt,et){for(const nt of _e)switch(nt.type){case"EntityCreated":this._handleEntityCreatedEvent(nt,et);break;case"EntityDeleted":for(const it of nt.subtreeIds)et.deleteEntityModel(it);break;case"EntityUpdated":this._handleEntityUpdatedEvent(nt,tt,et);break;case"ComponentAdded":this._applyComponentAdd(nt.entityId,nt.componentId,nt.component,et);break;case"ComponentUpdated":this._handleComponentUpdatedEvent(nt,et);break;case"ComponentRemoved":this._handleComponentRemovedEvent(nt.entityId,nt.componentId,et);break;case"EntityMoved":case"SceneSettingUpdated":case"AssetCreated":case"AssetUpdated":case"AssetDeleted":case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":break;case"PrefabOverrideChanged":this._handlePrefabOverrideChangedEvent(nt,et);break;default:assertNeverEvent$1(nt)}}_handleEntityCreatedEvent(_e,tt){const et=tt.getEntityModel(_e.entityId);if(et){this._logger.info("EntityCreated re-set existing",{entityId:_e.entityId}),tt.setEntityModel(_e.entityId,et),_e.entity.parentId&&tt.addEntityToParent&&tt.addEntityToParent(et,_e.entity.parentId);return}if(!tt.createEntity)return;this._logger.info("EntityCreated createEntity",{entityId:_e.entityId,name:_e.entity.name});const nt=tt.createEntity(_e.entity.name,_e.entityId);nt&&_e.entity.parentId&&tt.addEntityToParent&&tt.addEntityToParent(nt,_e.entity.parentId),nt&&this._initCreatedEntityModel(nt,_e.entityId)}_handleEntityUpdatedEvent(_e,tt,et){const nt=et.getEntityModel(_e.entityId);nt&&this._applyEntityUpdate(nt,_e,tt)}_applyComponentAdd(_e,tt,et,nt){const it=nt.getEntityModel(_e);it&&this._addComponentToModel(it,tt,et)}_handleComponentRemovedEvent(_e,tt,et){const nt=et.getEntityModel(_e);nt&&this._removeComponentFromModel(nt,tt)}_handleComponentUpdatedEvent(_e,tt){const et=tt.getEntityModel(_e.entityId);et&&this._applyComponentUpdate(et,_e)}_handlePrefabOverrideChangedEvent(_e,tt){var nt,it,at;if(!_e.entityId)return;const et=tt.getEntityModel(_e.entityId);if(et){if((nt=et.invalidateFromDomain)==null||nt.call(et),_e.bucket==="entityProps"){this._invalidateTransformComponents(et);return}if(!(_e.bucket!=="componentProps"&&_e.bucket!=="removedComponents"&&_e.bucket!=="addedComponents")){_e.bucket==="removedComponents"&&((it=et.syncRemovedComponentPlaceholdersFromDomain)==null||it.call(et));for(const ot of et.components??[])(at=ot.invalidateFromDomain)==null||at.call(ot)}}}_invalidateTransformComponents(_e){var tt;for(const et of _e.components??[])et.type&&ENTITY_TRANSFORM_COMPONENT_TYPES.has(et.type)&&((tt=et.invalidateFromDomain)==null||tt.call(et))}_addComponentToModel(_e,tt,et){var it,at,ot;const nt=(it=_e.getComponentByTypeName)==null?void 0:it.call(_e,et.type);nt&&nt.id!==tt&&((at=_e.removeComponentFromDomain)==null||at.call(_e,nt.id)),(ot=_e.addComponentFromDomain)==null||ot.call(_e,tt,et)}_removeComponentFromModel(_e,tt){var et;(et=_e.removeComponentFromDomain)==null||et.call(_e,tt)}_applyComponentUpdate(_e,tt){var nt,it,at;const et=(nt=_e.getComponentById)==null?void 0:nt.call(_e,tt.componentId);if(et){for(const[ot,st]of Object.entries(tt.changes))(it=et.applyPropertyFromDomain)==null||it.call(et,ot,st);(at=et.invalidateFromDomain)==null||at.call(et)}}_initCreatedEntityModel(_e,tt){var nt,it;const et=(nt=this._getEP())==null?void 0:nt.getEntity(tt);et&&((it=_e.initImmediate)==null||it.call(_e,et))}_applyEntityUpdate(_e,tt,et){var nt,it,at,ot;(nt=_e.invalidateFromDomain)==null||nt.call(_e),tt.changes.isLocked!==void 0&&((it=_e.applyLockedFromDomain)==null||it.call(_e,tt.changes.isLocked)),tt.changes.transform&&!et.has(tt.entityId)&&((ot=(at=_e.transform)==null?void 0:at.syncEngineToEditor)==null||ot.call(at))}}function assertNeverEvent(rt){throw new Error(`RuntimeProjection: unhandled event ${rt.type}`)}class RuntimeEntityCache{constructor(){Rt(this,"_models",new Map)}stash(_e,tt){this._models.set(_e,tt)}restore(_e){const tt=this._models.get(_e);return tt&&this._models.delete(_e),tt}clear(){this._models.clear()}}const NOOP_RUNTIME_BINDER_REGISTRY={detachEntityBinder:()=>{},restoreEntityBinder:()=>null,clearDetachedEntityBinders:()=>{}};class RuntimeProjection{constructor(_e,tt,et=NOOP_RUNTIME_BINDER_REGISTRY,nt=()=>!1){Rt(this,"_entityCache",new RuntimeEntityCache);Rt(this,"_logger",new TraceLogger("RuntimeProjection"));this._getScene=_e,this._getEP=tt,this._runtimeBinderRegistry=et,this._canRedo=nt}apply(_e,tt){const et=this._getScene(),nt=new Set;if(!et)return nt;const it=isUndoRedoCommand(tt);!it&&!this._canRedo()&&(this._entityCache.clear(),this._runtimeBinderRegistry.clearDetachedEntityBinders());const at=it?this._getEP():null;if(!(_e!=null&&_e.length))return nt;for(const ot of _e)switch(ot.type){case"EntityCreated":this._handleEntityCreated(ot.entityId,ot.entity,et,it,at,nt);break;case"EntityDeleted":for(const st of[...ot.subtreeIds].reverse())this._handleEntityDeleted(st,et);break;case"EntityUpdated":case"EntityMoved":case"ComponentAdded":case"ComponentUpdated":case"ComponentRemoved":case"SceneSettingUpdated":case"AssetCreated":case"AssetUpdated":case"AssetDeleted":case"PrefabBindingCreated":case"PrefabBindingRemoved":case"PrefabBindingRetargeted":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":case"PrefabOverrideChanged":break;default:assertNeverEvent(ot)}return nt}reset(){this._entityCache.clear(),this._runtimeBinderRegistry.clearDetachedEntityBinders()}_handleEntityCreated(_e,tt,et,nt,it,at){nt&&this._restoreOrMaterialize(_e,tt,et,it,at)}_handleEntityDeleted(_e,tt){this._stashAndDetach(_e,tt)}_stashAndDetach(_e,tt){const et=tt.getEntityModel(_e);et&&(this._entityCache.stash(_e,et),this._runtimeBinderRegistry.detachEntityBinder(_e)),tt.deleteEntityModel(_e)}_restoreOrMaterialize(_e,tt,et,nt,it){var ct,dt,ut,ht;if(et.hasEntityModel(_e))return;const at=this._entityCache.restore(_e);if(at){this._runtimeBinderRegistry.restoreEntityBinder(_e),et.setEntityModel(_e,at),nt&&this._rebindRestoredEntity(at,nt),(ct=at.applyLockedFromDomain)==null||ct.call(at,tt.isLocked??!1),it.add(_e);return}this._runtimeBinderRegistry.restoreEntityBinder(_e);const ot=nt==null?void 0:nt.getEntity(_e);if(!ot){this._logger.warn("Skip cache-miss runtime restore: engine entity not found",{entityId:_e});return}if(!et.createEntity){this._logger.warn("Skip cache-miss runtime restore: scene.createEntity unavailable",{entityId:_e});return}const st=et.createEntity(tt.name,_e);if(this._hydrateCacheMissModel(st,tt),(dt=st.initImmediate)==null||dt.call(st,ot),tt.components)for(const[ft,pt]of Object.entries(tt.components))(ut=st.addComponentFromDomain)==null||ut.call(st,ft,pt);(ht=st.applyLockedFromDomain)==null||ht.call(st,tt.isLocked??!1),it.add(_e)}_rebindRestoredEntity(_e,tt){var nt,it,at,ot,st;const et=tt.getEntity(_e.id);et&&((nt=_e.rebindEngineObject)==null||nt.call(_e,et),_e.transform&&((at=(it=_e.transform).rebindEngineObject)==null||at.call(it,et.transform),(st=(ot=_e.transform).syncEngineToEditor)==null||st.call(ot)))}_hydrateCacheMissModel(_e,tt){_e.name=tt.name,_e.isActive=tt.isActive??!0}}class UIProjection{constructor(_e,tt){Rt(this,"_logger",new TraceLogger("UIProjection"));Rt(this,"unsubscribe",null);Rt(this,"assetStore",null);Rt(this,"_sceneStore",null);Rt(this,"prefabOverrideBucketCounts",new Map);Rt(this,"contentApplier",null);Rt(this,"pendingContentReplayByAssetId",new Map);this.readModelStore=tt,this.rebuildFromState(_e.state),this.unsubscribe=_e.subscribe((et,nt)=>{var it;if(et.commandName==="reset"){this.rebuildFromState(nt);return}(it=et.events)!=null&&it.length&&this.applyEvents(et.events,nt)})}setContentApplier(_e){this.contentApplier=_e}async awaitContentReplay(_e){const tt=this.pendingContentReplayByAssetId.get(_e);if(tt)try{await tt}catch{}}setAssetStore(_e){this.assetStore=_e}setSceneStore(_e){this._sceneStore=_e}warnDev(_e,tt){this._logger.warn(_e,tt)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.assetStore=null,this._sceneStore=null,this.contentApplier=null,this.prefabOverrideBucketCounts.clear(),this.pendingContentReplayByAssetId.clear()}rebuildFromState(_e){var nt,it;this.readModelStore.beginBatch(),this.readModelStore.clear(),this.prefabOverrideBucketCounts.clear();for(const[at,ot]of Object.entries(_e.entities)){const st=this.createEntityReadModel(at,ot);this.readModelStore.setEntity(at,st)}const tt=new Map,et=[];for(const[at,ot]of Object.entries(_e.assets)){const st=this.createAssetReadModel(at,ot);if(this.readModelStore.setAsset(at,st),this.assetStore&&!this.assetStore.assets[at]&&((it=(nt=this.assetStore).createEditorAssetFromState)==null||it.call(nt,at,ot)),ot.parentFolderId){const ct=tt.get(ot.parentFolderId)??[];ct.push(at),tt.set(ot.parentFolderId,ct)}else et.push(at)}for(const[at,ot]of tt)this.readModelStore.setFolderChildren(at,ot);if(this.readModelStore.setRootAssetIds(et),this.readModelStore.setScene({rootEntityIds:[..._e.scene.rootEntityIds]}),_e.prefab){for(const[at,ot]of Object.entries(_e.prefab.bindings))this.setPrefabBindingReadModel(at,ot);for(const[at,ot]of Object.entries(_e.prefab.byAssetId))this.readModelStore.setAssetBindingIds(at,[...ot])}this.readModelStore.endBatch()}applyEvents(_e,tt){for(const et of _e)switch(et.type){case"EntityCreated":this._logger.info("EntityCreated",{entityId:et.entityId,parentId:et.parentId}),this.refreshEntityFromState(et.entityId,tt),et.parentId&&this.refreshEntityFromState(et.parentId,tt),this.refreshSceneFromState(tt);break;case"EntityUpdated":this.refreshEntityFromState(et.entityId,tt);break;case"EntityMoved":this.refreshEntityFromState(et.entityId,tt),et.previousParentId&&this.refreshEntityFromState(et.previousParentId,tt),et.parentId&&et.parentId!==et.previousParentId&&this.refreshEntityFromState(et.parentId,tt),this.refreshSceneFromState(tt);break;case"EntityDeleted":for(const nt of et.subtreeIds)this.readModelStore.deleteEntity(nt);et.snapshot.parentId&&this.refreshEntityFromState(et.snapshot.parentId,tt),this.refreshSceneFromState(tt);break;case"ComponentAdded":case"ComponentUpdated":case"ComponentRemoved":this.refreshEntityFromState(et.entityId,tt);break;case"SceneSettingUpdated":this.applySceneSettingValueToStore(et.settingPath,et.value);break;case"AssetCreated":this.applyAssetCreatedEvent(et);break;case"AssetUpdated":this.applyAssetUpdatedEvent(et);break;case"AssetDeleted":this.applyAssetDeletedEvent(et);break;case"PrefabBindingCreated":case"PrefabBindingRebased":case"PrefabBindingSourceBaselineUpdated":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;case"PrefabBindingRetargeted":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.previousAssetId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;case"PrefabOverrideChanged":{const nt=tt.prefab.bindings[et.bindingId];nt?this.readModelStore.prefabBindings.get(et.bindingId)?this.updatePrefabBindingOverrideCount(et.bindingId,nt,et.bucket):this.setPrefabBindingReadModel(et.bindingId,nt):this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break}case"PrefabBindingRemoved":this.refreshPrefabBindingFromState(et.bindingId,tt),this.refreshAssetBindingIdsFromState(et.assetId,tt);break;default:return et}}refreshEntityFromState(_e,tt){const et=tt.entities[_e];if(!et){this.readModelStore.deleteEntity(_e);return}this.readModelStore.setEntity(_e,this.createEntityReadModel(_e,et))}refreshSceneFromState(_e){this.readModelStore.setScene({rootEntityIds:[..._e.scene.rootEntityIds]})}refreshPrefabBindingFromState(_e,tt){const et=tt.prefab.bindings[_e];et?this.setPrefabBindingReadModel(_e,et):(this.prefabOverrideBucketCounts.delete(_e),this.readModelStore.deletePrefabBinding(_e))}refreshAssetBindingIdsFromState(_e,tt){const et=tt.prefab.byAssetId[_e];this.readModelStore.setAssetBindingIds(_e,et?[...et]:[])}replayAssetContent(_e,tt,et,nt){if(this.contentApplier)try{const it=this.contentApplier(_e,tt,et);if(it&&typeof it.then=="function"){const at=Promise.resolve(it).catch(ot=>{this.warnDev(`[UIProjection] contentApplier failed for asset: ${_e}`,{error:ot,details:nt})}).finally(()=>{this.pendingContentReplayByAssetId.get(_e)===at&&this.pendingContentReplayByAssetId.delete(_e)});this.pendingContentReplayByAssetId.set(_e,at)}else this.pendingContentReplayByAssetId.delete(_e)}catch(it){this.warnDev(`[UIProjection] contentApplier threw for asset: ${_e}`,{error:it,details:nt})}}isSerializableEqual(_e,tt){return JSON.stringify(_e)===JSON.stringify(tt)}syncAssetPropsFromSnapshots(_e,tt,et){var it,at,ot;const nt=(it=this.assetStore)==null?void 0:it.assets[_e];if(nt){for(const st of Object.keys(tt??{}))(!et||!(st in et))&&((at=nt.resetPropertyToDefaultFromDomain)==null||at.call(nt,st));for(const[st,ct]of Object.entries(et??{}))(!tt||!this.isSerializableEqual(tt[st],ct))&&((ot=nt.applyPropertyFromDomain)==null||ot.call(nt,st,ct))}}syncAssetStoreFromSnapshots(_e,tt,et){var it,at,ot,st;const nt=(it=this.assetStore)==null?void 0:it.assets[_e];nt&&((!tt||tt.name!==et.name)&&((at=nt.applyNameFromDomain)==null||at.call(nt,et.name)),(!tt||tt.parentFolderId!==et.parentFolderId)&&((ot=nt.applyParentFolderFromDomain)==null||ot.call(nt,et.parentFolderId)),(!tt||!this.isSerializableEqual(tt.meta??{},et.meta??{}))&&((st=nt.applyMetaFromDomain)==null||st.call(nt,{...et.meta??{}})),this.syncAssetPropsFromSnapshots(_e,tt==null?void 0:tt.props,et.props)),(!tt||!this.isSerializableEqual(tt.content,et.content))&&et.content&&this.replayAssetContent(_e,et.type,et.content,{event:"AssetUpdated"})}applyAssetCreatedEvent(_e){var tt,et;this.readModelStore.setAsset(_e.assetId,this.createAssetReadModel(_e.assetId,_e.asset)),this.updateFolderChildrenOnAdd(_e.assetId,_e.asset.parentFolderId),this.assetStore&&(this.assetStore.assets[_e.assetId]?this.syncAssetStoreFromSnapshots(_e.assetId,void 0,_e.asset):(et=(tt=this.assetStore).createEditorAssetFromState)==null||et.call(tt,_e.assetId,_e.asset))}applyAssetUpdatedEvent(_e){this.readModelStore.setAsset(_e.assetId,this.createAssetReadModel(_e.assetId,_e.asset)),_e.previousAsset.parentFolderId!==_e.asset.parentFolderId&&this.updateFolderChildrenOnMove(_e.assetId,_e.previousAsset.parentFolderId,_e.asset.parentFolderId),this.syncAssetStoreFromSnapshots(_e.assetId,_e.previousAsset,_e.asset)}applyAssetDeletedEvent(_e){var tt,et,nt;this.updateFolderChildrenOnRemove(_e.assetId,_e.snapshot.parentFolderId),this.readModelStore.deleteAsset(_e.assetId),(tt=this.assetStore)!=null&&tt.assets[_e.assetId]&&((nt=(et=this.assetStore).deleteEditorAsset)==null||nt.call(et,_e.assetId))}updateFolderChildrenOnAdd(_e,tt){if(tt){const et=this.readModelStore.folderChildren.get(tt)??[];et.includes(_e)||(et.push(_e),this.readModelStore.setFolderChildren(tt,et))}else this.readModelStore.rootAssetIds.includes(_e)||this.readModelStore.rootAssetIds.push(_e)}updateFolderChildrenOnRemove(_e,tt){if(tt){const et=this.readModelStore.folderChildren.get(tt)??[],nt=et.indexOf(_e);nt!==-1&&(et.splice(nt,1),this.readModelStore.setFolderChildren(tt,et))}else{const et=this.readModelStore.rootAssetIds.indexOf(_e);et!==-1&&this.readModelStore.rootAssetIds.splice(et,1)}}updateFolderChildrenOnMove(_e,tt,et){this.updateFolderChildrenOnRemove(_e,tt),this.updateFolderChildrenOnAdd(_e,et)}applySceneSettingValueToStore(_e,tt){var et,nt;(nt=(et=this._sceneStore)==null?void 0:et.applySettingFromDomain)==null||nt.call(et,_e,tt)}measureOverrideBucketCounts(_e){return{entityProps:Object.keys(_e.entityProps).length,componentProps:Object.keys(_e.componentProps).length,removedEntities:Object.keys(_e.removedEntities).length,removedComponents:Object.keys(_e.removedComponents).length,addedEntities:Object.keys(_e.addedEntities).length,addedComponents:Object.keys(_e.addedComponents).length}}sumOverrideBucketCounts(_e){return _e.entityProps+_e.componentProps+_e.removedEntities+_e.removedComponents+_e.addedEntities+_e.addedComponents}setPrefabBindingReadModel(_e,tt){const et=this.measureOverrideBucketCounts(tt.overrides),nt={};for(const[it,at]of Object.entries(tt.sourceEntitySnapshots??{}))at.instanceAssetKind&&(nt[it]=at.instanceAssetKind);this.prefabOverrideBucketCounts.set(_e,et),this.readModelStore.setPrefabBinding(_e,{id:_e,assetId:tt.assetId,assetKind:tt.assetKind,instanceRootEntityId:tt.instanceRootEntityId,sourceRevision:tt.sourceRevision,overrideCount:this.sumOverrideBucketCounts(et),addedEntityIds:Object.keys(tt.overrides.addedEntities),sourceEntityAssetKinds:nt})}updatePrefabBindingOverrideCount(_e,tt,et){const nt=this.readModelStore.prefabBindings.get(_e);if(!nt)return;const it=this.prefabOverrideBucketCounts.get(_e)??this.measureOverrideBucketCounts(tt.overrides),at=et?{...it,[et]:Object.keys(tt.overrides[et]).length}:this.measureOverrideBucketCounts(tt.overrides);this.prefabOverrideBucketCounts.set(_e,at),this.readModelStore.setPrefabBinding(_e,{...nt,overrideCount:this.sumOverrideBucketCounts(at),addedEntityIds:et===null||et==="addedEntities"?Object.keys(tt.overrides.addedEntities):nt.addedEntityIds})}createEntityReadModel(_e,tt){var nt;const et=new Map;for(const[it,at]of Object.entries(tt.components))et.set(it,{id:it,type:at.type,enabled:((nt=at.props)==null?void 0:nt.enabled)??!0,props:{...at.props}});return{id:_e,name:tt.name,isActive:tt.isActive,layer:tt.layer??0,isLocked:tt.isLocked??!1,parentId:tt.parentId,children:[...tt.children],isStripped:tt.isStripped===!0,transform:{position:{...tt.transform.position},rotation:{...tt.transform.rotation},scale:{...tt.transform.scale}},components:et,instance:tt.instance??null,instanceRef:this.resolveEntityInstanceRef(tt)}}resolveEntityInstanceRef(_e){return resolveEntityInstanceRef(_e)}createAssetReadModel(_e,tt){return{id:_e,name:tt.name,type:tt.type,parentFolderId:tt.parentFolderId,url:tt.url,meta:tt.meta?{...tt.meta}:void 0,props:tt.props&&Object.keys(tt.props).length>0?{...tt.props}:void 0,content:tt.content?{...tt.content}:void 0}}}function isNonPojoObject(rt){return!rt||typeof rt!="object"?!1:"constructor"in rt&&rt.constructor!==Object}function isUICanvasRenderCameraReady(rt){if(!rt||typeof rt!="object")return!0;const _e=rt.entity;return _e?!!_e._updateFlagManager:!0}function createComponentFactory(rt){const _e=new WeakMap,tt=[],et=new Map;let nt=new WeakMap;function it(ft){if(!ft||typeof ft!="object"||!("refId"in ft)||typeof ft.refId!="string")return null;const pt=ft;return pt.key?`${pt.refId}-${pt.key}`:pt.refId}function at(ft,pt){const mt=nt.get(ft),vt=mt==null?void 0:mt.get(pt);if(!vt)return;const _t=it(vt.value);if(_t){const yt=et.get(_t);yt==null||yt.delete(vt),(yt==null?void 0:yt.size)===0&&et.delete(_t)}mt==null||mt.delete(pt),(mt==null?void 0:mt.size)===0&&nt.delete(ft)}function ot(ft,pt,mt,vt){at(ft,mt);const _t=it(vt);if(!_t)return;const yt={component:ft,type:pt,key:mt,value:vt};let bt=nt.get(ft);bt||(bt=new Map,nt.set(ft,bt)),bt.set(mt,yt);let Et=et.get(_t);Et||(Et=new Set,et.set(_t,Et)),Et.add(yt)}function st(ft,pt){for(let mt=tt.length-1;mt>=0;mt--){const vt=tt[mt];vt.component===ft&&(pt===void 0||vt.key===pt)&&tt.splice(mt,1)}}function ct(ft,pt,mt,vt){var At,xt;const _t=getComponentSemantics(pt),yt=(At=_t==null?void 0:_t.proxyMap)==null?void 0:At[mt],bt=yt&&typeof ft[yt]=="function";if(!!yt&&((xt=_t==null?void 0:_t.methodKeys)==null?void 0:xt.has(mt))&&!yt.startsWith("set")||!(mt in ft)&&!bt||mt in ft&&isNonPojoObject(ft[mt]))return"applied";let St=vt;if(rt){const Ct=it(St);if(Ct){const Pt=rt(Ct);if(Pt===null)return"await-asset";isTraceEnabled()&&console.log(`[ComponentFactory] resolved ref ${Ct} → ${(Pt==null?void 0:Pt.name)??Pt}`),St=Pt}}if(pt==="UICanvas"&&mt==="renderCamera"&&!isUICanvasRenderCameraReady(St))return"needs-defer";try{return bt?(isTraceEnabled()&&console.log(`[ComponentFactory] ${pt}.${yt}(${St})`),ft[yt](St)):(isTraceEnabled()&&console.log(`[ComponentFactory] ${pt}.${mt} = ${St}`),ft[mt]=St),"applied"}catch(Ct){return console.warn(`[ComponentFactory] Failed to set prop "${mt}" on ${pt}:`,Ct),"needs-defer"}}function dt(ft){const pt=ft.__editorExternalComponentClaimRevision,mt=typeof pt=="number"?pt:0,vt=_e.get(ft);if(vt&&vt.revision===mt)return vt.components;const _t={revision:mt,components:new Set};return _e.set(ft,_t),_t.components}function ut(ft,pt){var bt;const mt=dt(ft),vt=[],_t=ft;if(_t.getComponents){_t.getComponents(pt,vt);for(const Et of vt)if(!mt.has(Et))return mt.add(Et),Et}const yt=((bt=_t.getComponent)==null?void 0:bt.call(_t,pt))??null;return yt&&!mt.has(yt)?(mt.add(yt),yt):null}const ht=(ft,pt,mt)=>{const vt=EditorComponent.getEngineComponent(pt);if(!vt)return console.warn(`[ComponentFactory] Unknown component type: ${pt}`),null;const _t=!!ft.__editorExternalEntity;let yt=null;if(_t){const Et=ut(ft,vt);Et&&(yt=Et)}yt||(yt=ft.addComponent(vt),_t&&dt(ft).add(yt)),isTraceEnabled()&&console.log(`[ComponentFactory] create ${pt} on entity ${ft.name}`);const bt=yt;for(const Et of Object.keys(mt)){const St=mt[Et];it(St)?ot(bt,pt,Et,St):at(bt,Et),ct(bt,pt,Et,St)==="needs-defer"&&tt.push({component:bt,type:pt,key:Et,value:St})}return yt};return ht.getProxyMap=ft=>{var pt;return(pt=getComponentSemantics(ft))==null?void 0:pt.proxyMap},ht.flushDeferred=()=>{if(tt.length===0)return;const ft=[];for(let pt=0,mt=tt.length;pt<mt;pt++){const vt=tt[pt];if(vt.type==="UICanvas"&&vt.key==="renderCamera"&&!isUICanvasRenderCameraReady(vt.value)){ft.push(vt);continue}ct(vt.component,vt.type,vt.key,vt.value)!=="applied"&&ft.push(vt)}tt.length=0,tt.push(...ft)},ht.trackAssetReference=(ft,pt,mt,vt)=>{if(it(vt)){ot(ft,pt,mt,vt);return}at(ft,mt)},ht.forgetComponentAssetReferences=ft=>{const pt=nt.get(ft);if(pt)for(const mt of Array.from(pt.keys()))at(ft,mt);st(ft)},ht.rebindAssetReferences=ft=>{const pt=et.get(ft);if(pt!=null&&pt.size)for(const mt of Array.from(pt))ct(mt.component,mt.type,mt.key,mt.value)==="applied"&&st(mt.component,mt.key)},ht.clearAssetReferenceTracking=()=>{tt.length=0,et.clear(),nt=new WeakMap},ht}function rebindEntityModels(rt,_e){for(const[tt,et]of rt.iterateEntityModels()){const nt=_e.getEntity(tt);if(!(!nt||et.engineObject===nt)){et.rebindEngineObject(nt);for(const it of et.components){const at=_e.getComponent(it.id);at&&it.engineObject!==at&&it.rebindEngineObject(at)}}}}class ReadModelStore{constructor(){Rt(this,"_logger",new TraceLogger("ReadModelStore"));Rt(this,"entities",new Map);Rt(this,"assets",new Map);Rt(this,"scene",{rootEntityIds:[]});Rt(this,"folderChildren",new Map);Rt(this,"prefabBindings",new Map);Rt(this,"instanceRootBindingIds",new Map);Rt(this,"assetBindingIds",new Map);Rt(this,"rootAssetIds",[]);Rt(this,"_globalListeners",new Set);Rt(this,"_entityListeners",new Map);Rt(this,"_batching",!1);Rt(this,"_batchedEntityIds",new Set)}subscribe(_e){return this._globalListeners.add(_e),()=>this._globalListeners.delete(_e)}subscribeEntity(_e,tt){let et=this._entityListeners.get(_e);return et||(et=new Set,this._entityListeners.set(_e,et)),et.add(tt),()=>{et.delete(tt),et.size===0&&this._entityListeners.delete(_e)}}_notifyGlobal(){if(!this._batching)for(const _e of this._globalListeners)_e()}_notifyEntity(_e){if(this._batching)return;const tt=this._entityListeners.get(_e);if(tt)for(const et of tt)et()}getEntity(_e){return this.entities.get(_e)}getEntityName(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.name)??""}getEntityChildren(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.children)??[]}getEntityParent(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.parentId)??null}getRootEntities(){return this.scene.rootEntityIds.map(_e=>this.entities.get(_e)).filter(_e=>_e!==void 0)}isEntityLocked(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.isLocked)??!1}isEntityActive(_e){var tt;return((tt=this.entities.get(_e))==null?void 0:tt.isActive)??!0}getAsset(_e){return this.assets.get(_e)}getAssetName(_e){var tt;return((tt=this.assets.get(_e))==null?void 0:tt.name)??""}getAssetType(_e){var tt;return((tt=this.assets.get(_e))==null?void 0:tt.type)??""}getFolderChildren(_e){return _e===null?this.rootAssetIds:this.folderChildren.get(_e)??[]}getRootAssets(){return this.rootAssetIds.map(_e=>this.assets.get(_e)).filter(_e=>_e!==void 0)}getComponent(_e,tt){var et;return(et=this.entities.get(_e))==null?void 0:et.components.get(tt)}getComponentsByEntity(_e){const tt=this.entities.get(_e);return tt?Array.from(tt.components.values()):[]}getComponentByType(_e,tt){const et=this.entities.get(_e);if(et){for(const nt of et.components.values())if(nt.type===tt)return nt}}getBindingByEntity(_e){const tt=this.entities.get(_e);if(tt!=null&&tt.instance)return this.prefabBindings.get(tt.instance.bindingId)}getInstanceRootBindingByEntity(_e){const et=(this.instanceRootBindingIds.get(_e)??[]).map(nt=>this.prefabBindings.get(nt)).filter(nt=>!!nt);return et.find(nt=>nt.assetKind==="glTF")??et[0]}getBindingsByAsset(_e){return(this.assetBindingIds.get(_e)??[]).map(et=>this.prefabBindings.get(et)).filter(et=>et!==void 0)}setEntity(_e,tt){if(this._logger.info("setEntity",{id:_e,name:tt.name}),this.entities.set(_e,tt),this._batching){this._batchedEntityIds.add(_e);return}this._notifyEntity(_e),this._notifyGlobal()}deleteEntity(_e){this.entities.delete(_e),this._notifyEntity(_e),this._notifyGlobal()}setAsset(_e,tt){this.assets.set(_e,tt),this._notifyGlobal()}deleteAsset(_e){this.assets.delete(_e),this._notifyGlobal()}setScene(_e){this._logger.info("setScene",{rootEntityIds:_e.rootEntityIds}),this.scene=_e,this._notifyGlobal()}setFolderChildren(_e,tt){this.folderChildren.set(_e,tt),this._notifyGlobal()}setRootAssetIds(_e){this.rootAssetIds=_e,this._notifyGlobal()}setPrefabBinding(_e,tt){const et=this.prefabBindings.get(_e);et&&this.removeInstanceRootBindingIndex(_e,et.instanceRootEntityId),this.prefabBindings.set(_e,tt),this.addInstanceRootBindingIndex(_e,tt.instanceRootEntityId),this._notifyGlobal()}deletePrefabBinding(_e){const tt=this.prefabBindings.get(_e);tt&&this.removeInstanceRootBindingIndex(_e,tt.instanceRootEntityId),this.prefabBindings.delete(_e),this._notifyGlobal()}setAssetBindingIds(_e,tt){tt.length===0?this.assetBindingIds.delete(_e):this.assetBindingIds.set(_e,tt),this._notifyGlobal()}beginBatch(){this._batching=!0,this._batchedEntityIds.clear()}endBatch(){this._batching=!1;for(const _e of this._batchedEntityIds)this._notifyEntity(_e);this._batchedEntityIds.clear(),this._notifyGlobal()}clear(){if(this._batching)for(const tt of this.entities.keys())this._batchedEntityIds.add(tt);const _e=this._batching?[]:Array.from(this.entities.keys());if(this.entities.clear(),this.assets.clear(),this.folderChildren.clear(),this.prefabBindings.clear(),this.instanceRootBindingIds.clear(),this.assetBindingIds.clear(),this.rootAssetIds=[],this.scene={rootEntityIds:[]},!this._batching){for(const tt of _e)this._notifyEntity(tt);this._notifyGlobal()}}addInstanceRootBindingIndex(_e,tt){const et=this.instanceRootBindingIds.get(tt)??[];et.includes(_e)||et.push(_e),this.instanceRootBindingIds.set(tt,et)}removeInstanceRootBindingIndex(_e,tt){const et=this.instanceRootBindingIds.get(tt);if(!et)return;const nt=et.filter(it=>it!==_e);nt.length===0?this.instanceRootBindingIds.delete(tt):this.instanceRootBindingIds.set(tt,nt)}}function parseUploadMeta(rt){if(!(typeof rt!="string"||rt.length===0))try{const _e=JSON.parse(rt);if(_e&&typeof _e=="object"&&!Array.isArray(_e))return _e}catch{}}class UploadService{constructor(_e){this.root=_e}async upload(_e){const{file:tt,name:et,projectId:nt,assetId:it,assetType:at,meta:ot,parentFolderId:st,isFBX:ct=!1,onProgress:dt}=_e,ut=await this.root.storage.assets.create({blob:tt,name:et,projectId:nt,uuid:it,type:at,meta:ot,parentId:st,options:{useCache:!ct,onProgress:dt}});return{serverId:ut.id,url:ut.url,meta:parseUploadMeta(ut.meta)}}async uploadAndUpdateState(_e,tt){try{const et=await this.upload(tt);return this.root.assetFacade.markAssetReady(_e,et.serverId,et.url),et}catch(et){throw this.root.assetFacade.markAssetError(_e,et instanceof Error?et.message:String(et)),et}}}function buildCreateAssetRequest(rt){const{assetId:_e,projectId:tt,state:et}=rt;return{blob:null,name:et.name,projectId:tt,uuid:_e,type:et.type==="Folder"?EProjectAssetType.Directory:EProjectAssetType.File,meta:JSON.stringify(et.meta),parentId:et.parentFolderId??void 0,url:et.url}}const to=class to{constructor(_e,tt,et,nt){Rt(this,"_sessionToken",0);Rt(this,"unsubscribe",null);Rt(this,"revisions",new Map);Rt(this,"assetChains",new Map);Rt(this,"pendingDeletes",[]);Rt(this,"workSet",new Set);Rt(this,"trackedPersistenceTasks",new WeakSet);Rt(this,"_lastError",null);Rt(this,"idleResolvers",[]);Rt(this,"statusListeners",new Set);this.domainStore=_e,this.projectIdOrGetter=tt,this.api=et,this.onError=nt}start(){this.unsubscribe||(this._sessionToken++,this.unsubscribe=this.domainStore.subscribe(_e=>this.handleTransaction(_e)))}stop(){var _e;this._sessionToken++,(_e=this.unsubscribe)==null||_e.call(this),this.unsubscribe=null,this.assetChains.clear()}get pendingCount(){return this.workSet.size}get lastError(){return this._lastError}clearLastError(){this._lastError&&(this._lastError=null,this.notifyStatusChange())}waitForIdle(){return this.pendingCount===0?Promise.resolve():new Promise(_e=>{this.idleResolvers.push(_e)})}onStatusChange(_e){return this.statusListeners.add(_e),()=>{this.statusListeners.delete(_e)}}trackPersistenceTask(_e,tt){_e&&(this.trackedPersistenceTasks.has(_e)||(this.trackedPersistenceTasks.add(_e),this.runTask((async()=>{try{await _e}catch(et){this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,"Asset persistence task failed",{...tt,originalError:et}))}})())))}get projectId(){return typeof this.projectIdOrGetter=="function"?this.projectIdOrGetter():this.projectIdOrGetter}handleTransaction(_e){if(_e.commandName==="system"||_e.commandName==="remote"||_e.commandName==="asset.init"||_e.commandName==="reset")return;const tt=this._sessionToken,et=this.projectId,nt=_e.commandName??"",it=nt.startsWith("undo:")||nt==="redo:asset.create"||nt==="asset.copy",at=new Map;for(const ot of _e.operations){const st=this.parsePropertyPath(ot.path);if(st&&ot.op==="replace"&&"value"in ot){const ut=at.get(st.assetId)??{hasParentId:!1};st.property==="name"?ut.name=ot.value:(ut.hasParentId=!0,ut.parentId=ot.value),at.set(st.assetId,ut);continue}const ct=this.extractRootAssetId(ot.path);if(!ct)continue;const dt=(this.revisions.get(ct)??0)+1;if(this.revisions.set(ct,dt),ot.op==="remove"){const ut=ot.oldValue;ut!=null&&ut.serverId&&this.scheduleAssetTask(ct,()=>this.executeDelete([ut.serverId],et),tt)}else if(ot.op==="add"&&it&&"value"in ot){const ut=ot.value;ut.url&&this.scheduleAssetTask(ct,()=>this.handleCreate(ct,ut,dt,et,tt),tt)}}for(const[ot,st]of at)this.scheduleAssetTask(ot,async()=>{var ut;let ct=(ut=this.domainStore.state.assets[ot])==null?void 0:ut.serverId;if(ct||(ct=await this.waitForServerId(ot,3e4,tt)),!ct)return;const dt={};st.name!==void 0&&(dt.name=st.name),st.hasParentId&&(dt.parentId=st.parentId),await this.executeUpdate(ct,dt)},tt)}async executeDelete(_e,tt){const{error:et}=await this.retryOnce(()=>this.api.assets.delete(_e,tt));et&&(this.pendingDeletes.push(..._e),console.warn("[AssetEffectsRunner] delete failed:",et.retryError),this.reportError(new EffectsError(EffectsErrorCode.DELETE_FAILED,"Asset delete side effects failed",{serverIds:_e,originalError:et.originalError,retryError:et.retryError})))}async executeUpdate(_e,tt){const{error:et}=await this.retryOnce(()=>this.api.assets.update(_e,tt));et&&(console.warn("[AssetEffectsRunner] update failed:",et.retryError),this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,`Asset update side effects failed: ${_e}`,{serverId:_e,data:tt,originalError:et.originalError,retryError:et.retryError})))}async retryOnce(_e){try{return await _e(),{}}catch(tt){await new Promise(et=>setTimeout(et,to.RETRY_DELAY_MS));try{return await _e(),{}}catch(et){return{error:{originalError:tt,retryError:et}}}}}getPendingDeletes(){return[...this.pendingDeletes]}async retryPendingDeletes(){const _e=this.pendingDeletes.splice(0);_e.length!==0&&await this.runTask(this.executeDelete(_e,this.projectId))}async handleCreate(_e,tt,et,nt,it){try{const at=await this.api.assets.create(buildCreateAssetRequest({assetId:_e,projectId:nt,state:tt}));if(this._sessionToken!==it){this.runTask(this.executeDelete([at.id],nt));return}const ot=this.domainStore.state.assets[_e];if(this.revisions.get(_e)!==et||!ot){this.runTask(this.executeDelete([at.id],nt));return}const st=Object.prototype.hasOwnProperty.call(ot,"serverId")?"replace":"add";try{this.domainStore.applySystem([{op:st,path:`/assets/${_e}/serverId`,value:at.id}])}catch(ct){throw this.runTask(this.executeDelete([at.id],nt)),ct}}catch(at){console.warn("[AssetEffectsRunner] recreate failed:",at),this.reportError(new EffectsError(EffectsErrorCode.CREATE_FAILED,`Asset create side effects failed: ${_e}`,{assetId:_e,originalError:at}))}}runTask(_e){const tt=this.beginWork();return _e.finally(()=>{this.endWork(tt)})}scheduleAssetTask(_e,tt,et){const nt=this.beginWork(),it=async()=>{this._sessionToken===et&&await tt()},at=this.assetChains.get(_e),ot=(at?at.catch(()=>{}).then(it):Promise.resolve(it())).catch(st=>{this.reportError(new EffectsError(EffectsErrorCode.UPDATE_FAILED,`Asset side effects scheduler failed: ${_e}`,{assetId:_e,originalError:st}))}).finally(()=>{this.endWork(nt),this.assetChains.get(_e)===ot&&this.assetChains.delete(_e)});this.assetChains.set(_e,ot)}beginWork(){const _e=Symbol("asset-effects-work");return this.workSet.size===0&&(this._lastError=null),this.workSet.add(_e),this.notifyStatusChange(),_e}endWork(_e){this.workSet.delete(_e)&&this.notifyStatusChange()}notifyStatusChange(){const _e=this.pendingCount;for(const tt of this.statusListeners)tt(_e,_e===0?this._lastError:null);if(_e===0){const tt=this.idleResolvers.splice(0);for(const et of tt)et()}}reportError(_e){var tt;this._lastError=_e,(tt=this.onError)==null||tt.call(this,_e)}parsePropertyPath(_e){const tt=_e.match(/^\/assets\/([^/]+)\/(name|parentFolderId)$/);return tt?{assetId:tt[1],property:tt[2]}:null}extractRootAssetId(_e){if(!_e.startsWith("/assets/"))return null;const tt=_e.slice(8);return!tt||tt.includes("/")?null:tt}waitForServerId(_e,tt,et){const nt=this.domainStore.state.assets[_e];return nt?nt.serverId?Promise.resolve(nt.serverId):this._sessionToken!==et?Promise.resolve(null):new Promise(it=>{let at=!1;const ot=dt=>{at||(at=!0,clearTimeout(st),ct(),it(dt))},st=setTimeout(()=>ot(null),tt),ct=this.domainStore.subscribe(()=>{if(this._sessionToken!==et)return ot(null);const dt=this.domainStore.state.assets[_e];if(!dt)return ot(null);dt.serverId&&ot(dt.serverId)})}):Promise.resolve(null)}};Rt(to,"RETRY_DELAY_MS",500);let AssetEffectsRunner=to;const SKIP_COMMANDS=new Set(["system","remote","asset.init","reset"]);class ScenePersistenceRunner{constructor(_e,tt){Rt(this,"_unsubscribe",null);this.domainStore=_e,this.config=tt}start(){this._unsubscribe||(this._unsubscribe=this.domainStore.subscribe(_e=>this.handleTransaction(_e)))}stop(){var _e;(_e=this._unsubscribe)==null||_e.call(this),this._unsubscribe=null}handleTransaction(_e){if(this.domainStore.isHistoryPaused)return;const tt=_e.commandName??"";SKIP_COMMANDS.has(tt)||!_e.operations.some(nt=>nt.path.startsWith("/entities/")||nt.path.startsWith("/scene/"))||this.config.persistSceneDebounced(tt||"unknown")}}class InspectorSelectionService{constructor(_e){this.root=_e}getSelectedEntityId(){var tt;const _e=((tt=this.root.sceneUIStore)==null?void 0:tt.lastSelectedId)??null;return!_e||_e===DEFAULT_SCENE?null:_e}getSelectedEntityModel(){const _e=this.getSelectedEntityId();return _e?this.root.sceneStore.getEntityModel(_e)??null:null}getSelectedEntityReadModel(){const _e=this.getSelectedEntityId();return _e?this.root.readModelStore.getEntity(_e)??null:null}getSelectedComponents(){var _e;return((_e=this.getSelectedEntityModel())==null?void 0:_e.components)??[]}}function disposeReloadState(rt,_e){var tt,et,nt,it,at,ot,st;(tt=rt.assetEffectsRunner)==null||tt.stop(),(et=rt.scenePersistenceRunner)==null||et.stop(),(nt=rt.selectionStore)==null||nt.dispose(),(it=rt.domainStateReactive)==null||it.dispose(),(at=rt.uiProjection)==null||at.dispose(),(ot=rt.runtimeBinderRegistry)==null||ot.dispose(),(st=rt.runtimeAssetStore)==null||st.dispose(),_e==null||_e()}function createRuntimeAssetResolver(rt){return _e=>{const tt=rt.get(_e);return(tt==null?void 0:tt.status)==="ready"?tt.engineObject??null:null}}function bindAssetRuntimeReadyToProjection(rt,_e,tt){return rt.subscribe((et,nt)=>{var it,at,ot;(nt==null?void 0:nt.status)==="ready"&&((it=_e())==null||it.rebindAssetReferences(et),(ot=(at=tt==null?void 0:tt())==null?void 0:at.rebindAssetReferences)==null||ot.call(at,et,!1))})}const Mr=class Mr{constructor(){Rt(this,"projectStore");Rt(this,"configDataStore");Rt(this,"layoutStore");Rt(this,"assetStore");Rt(this,"animationClipStore");Rt(this,"animatorControllerStore");Rt(this,"snapshot");Rt(this,"inspectorStore",inspectorStore);Rt(this,"selectionStore");Rt(this,"sceneUIStore");Rt(this,"assetUIStore");Rt(this,"assetService");Rt(this,"assetRegistry");Rt(this,"domainStore");Rt(this,"commandBus");Rt(this,"engineProjection",null);Rt(this,"_lastProjectionRebuildTime",0);Rt(this,"_projectionRebuildTimer",null);Rt(this,"_disposeAssetRuntimeReadySubscription",null);Rt(this,"domainStateReactive");Rt(this,"entityModelProjection");Rt(this,"runtimeProjection");Rt(this,"readModelStore");Rt(this,"uiProjection");Rt(this,"entityFacade");Rt(this,"assetFacade");Rt(this,"componentFacade");Rt(this,"sceneFacade");Rt(this,"inspectorFacade");Rt(this,"prefabFacade");Rt(this,"uploadService");Rt(this,"_logger",new TraceLogger("Root"));Rt(this,"assetEffectsRunner");Rt(this,"scenePersistenceRunner");Rt(this,"inspectorSelectionService");Rt(this,"runtimeBinderRegistry");Rt(this,"runtimeAssetStore");Rt(this,"storage");Rt(this,"esbuildInstancePromise",Mr.getEsbuildInstancePromise());Rt(this,"reload",()=>{disposeReloadState(this,()=>{var _e;(_e=this._disposeAssetRuntimeReadySubscription)==null||_e.call(this),this._disposeAssetRuntimeReadySubscription=null,this._projectionRebuildTimer&&(clearTimeout(this._projectionRebuildTimer),this._projectionRebuildTimer=null)}),this.configDataStore=new ConfigDataCenter,this.projectStore=new Project(this),this.layoutStore=new LayoutSystem(this),this.snapshot=snapshotStore,this.assetUIStore=new AssetUIStore,this.assetService=new AssetService(this),this.assetRegistry=new AssetRegistry,this.assetStore=new AssetManager(this),this.animationClipStore=new AnimationClipStore(this),this.animatorControllerStore=new AnimatorControllerStore(this),this.selectionStore=new SelectionStore(this),this.sceneUIStore=new SceneUIStore(this),this.domainStore=new DomainStore,this.domainStore.pauseHistory(),this.commandBus=new CommandBus(this.domainStore),this.domainStateReactive=new DomainStateReactive(this.domainStore),this.readModelStore=new ReadModelStore,this.runtimeAssetStore=new RuntimeAssetStore,this.runtimeBinderRegistry=new RuntimeBinderRegistry,this.uiProjection=new UIProjection(this.domainStore,this.readModelStore),this.uiProjection.setAssetStore(this.assetStore),this.runtimeProjection=new RuntimeProjection(()=>this.sceneStore,()=>this.engineProjection,this.runtimeBinderRegistry,()=>this.domainStore.canRedo),this.entityModelProjection=new EntityModelProjection(()=>this.sceneStore,()=>this.engineProjection),this.domainStore.subscribe(_e=>{if(this.engineProjection){if(_e.commandName==="reset"){this.runtimeProjection.reset();try{this.engineProjection.rebuildFromState(this.domainStore.state),this._rebindAllEntityModels()}catch(nt){console.error("EngineProjection rebuild failed:",nt),this._requestEngineProjectionRebuild(nt)}return}try{this.engineProjection.apply(_e.events,_e.commandName)}catch(nt){console.error("EngineProjection apply failed:",nt),this._requestEngineProjectionRebuild(nt)}}const tt=this.runtimeProjection.apply(_e.events,_e.commandName);this.entityModelProjection.apply(_e.events,tt),isUndoRedoCommand(_e.commandName)&&this._syncUploadingAssetIds(_e.operations),this._resumeCreateByAddAfterRedo(_e.operations,_e.commandName)}),this.entityFacade=new EntityFacade(this),this.assetFacade=new AssetFacade(this),this.componentFacade=new ComponentFacade(this),this.sceneFacade=new SceneFacade(this.domainStore,this.commandBus),this.inspectorFacade=new InspectorFacade(this),this.prefabFacade=new PrefabFacade(this),isTraceEnabled()&&(instrumentCommandBus(this.commandBus),instrumentDomainStore(this.domainStore),wrapFacadeWithTrace(this.entityFacade,"EntityFacade"),wrapFacadeWithTrace(this.componentFacade,"ComponentFacade"),wrapFacadeWithTrace(this.assetFacade,"AssetFacade"),wrapFacadeWithTrace(this.inspectorFacade,"InspectorFacade")),this.uploadService=new UploadService(this),this.assetEffectsRunner=new AssetEffectsRunner(this.domainStore,()=>this.projectStore.id,{assets:{delete:(..._e)=>this.storage.assets.delete(..._e),create:_e=>this.storage.assets.create(_e),update:(_e,tt)=>this.storage.assets.update(_e,tt).then(()=>{})}}),this.scenePersistenceRunner=new ScenePersistenceRunner(this.domainStore,{persistSceneDebounced:_e=>this.projectStore.persistSceneDebounced(_e)}),this.inspectorSelectionService=new InspectorSelectionService(this)});this.reload()}static getEsbuildInstancePromise(){return Mr.esbuildInstancePromiseSingleton||(Mr.esbuildInstancePromiseSingleton=browserExports.initialize({worker:!0,wasmURL:"https://gw.alipayobjects.com/os/lib/esbuild-wasm/0.25.8/esbuild.wasm"})),Mr.esbuildInstancePromiseSingleton}createLogger(_e){return new TraceLogger(_e)}get sceneStore(){return this.projectStore.currentScene}get viewportStore(){return this.projectStore.currentViewport}get currentSceneId(){var _e;return((_e=this.projectStore.currentScene)==null?void 0:_e.refId)??null}async switchActiveScene(_e){await this.projectStore.setActiveEditorScene(_e)}undo(){isTraceEnabled()&&beginTrace();try{return this.domainStore.undo()!==null}finally{isTraceEnabled()&&endTrace()}}redo(){isTraceEnabled()&&beginTrace();try{return this.domainStore.redo()!==null}finally{isTraceEnabled()&&endTrace()}}get canUndo(){return this.domainStore.canUndo}get canRedo(){return this.domainStore.canRedo}runInUndoGroup(_e,tt){this.domainStore.beginUndoGroup();const et=()=>{this.domainStore.endUndoGroup(_e)};try{const nt=tt();return nt&&typeof nt.then=="function"?nt.finally(et):(et(),nt)}catch(nt){throw et(),nt}}resumeHistoryCapture(){this.domainStore.resumeHistory.bind(this.domainStore)()}setStorage(_e){if(!(_e!=null&&_e.project)||!(_e!=null&&_e.assets)||!(_e!=null&&_e.schema))throw new Error("setStorage: storage must implement project, assets, and schema");this.storage=_e}initEngineProjection(_e){var et;(et=this._disposeAssetRuntimeReadySubscription)==null||et.call(this),this._disposeAssetRuntimeReadySubscription=null,this.engineProjection=new EngineProjection(_e,void 0,()=>this.domainStore.canRedo);const tt=createRuntimeAssetResolver(this.runtimeAssetStore);this.engineProjection.setAssetResolver(tt),this.engineProjection.setComponentFactory(createComponentFactory(tt)),this._disposeAssetRuntimeReadySubscription=bindAssetRuntimeReadyToProjection(this.runtimeAssetStore,()=>this.engineProjection,()=>this.sceneStore),this.sceneStore&&this.uiProjection.setSceneStore(this.sceneStore)}_requestEngineProjectionRebuild(_e){if(!this.engineProjection)return;const nt=Date.now()-this._lastProjectionRebuildTime;if(nt>=Mr.PROJECTION_REBUILD_THROTTLE_MS){this._runEngineProjectionRebuild(_e);return}if(this._projectionRebuildTimer)return;const it=Mr.PROJECTION_REBUILD_THROTTLE_MS-nt;this._projectionRebuildTimer=setTimeout(()=>{this._projectionRebuildTimer=null,this._runEngineProjectionRebuild(_e)},it)}_resumeCreateByAddAfterRedo(_e,tt){const et=collectCreateByAddResumeCandidates({commandName:tt,operations:_e,assets:this.domainStore.state.assets});for(const nt of et)this.assetStore.resumeCreateAssetByAddFromState(nt).catch(it=>{console.warn("[Root] resumeCreateAssetByAddFromState failed:",{assetId:nt,error:it})})}_runEngineProjectionRebuild(_e){const tt=this.engineProjection;if(tt){this._lastProjectionRebuildTime=Date.now();try{tt.rebuildFromState(this.domainStore.state),this._rebindAllEntityModels()}catch(et){console.error("EngineProjection rebuild failed:",et,"reason:",_e);try{tt.reset()}catch(nt){console.error("EngineProjection reset failed:",nt)}}}}_rebindAllEntityModels(){const _e=this.sceneStore;!_e||!this.engineProjection||rebindEntityModels(_e,this.engineProjection)}_syncUploadingAssetIds(_e){const tt=this.assetUIStore;if(!tt)return;const et=/^\/assets\/([^/]+)$/;for(const it of _e){const at=et.exec(it.path);if(!at)continue;const ot=at[1];it.op==="add"&&it.value&&typeof it.value=="object"&&it.value.status==="uploading"?tt.markAssetUploading(ot):it.op==="remove"&&tt.clearAssetUploading(ot)}const nt=/^\/assets\/([^/]+)\/status$/;for(const it of _e){const at=nt.exec(it.path);if(!at)continue;const ot=at[1];it.op!=="remove"&&"value"in it&&it.value==="uploading"?tt.markAssetUploading(ot):tt.clearAssetUploading(ot)}}};Rt(Mr,"esbuildInstancePromiseSingleton",null),Rt(Mr,"PROJECTION_REBUILD_THROTTLE_MS",3e3);let Root=Mr;async function initProjectReadRuntime({root:rt,storage:_e,projectId:tt,canvas:et,projectInfo:nt,onStage:it,viewport:at}){var ut;rt.setStorage(_e);const ot=nt??await(async()=>(it==null||it("query-project"),_e.project.query(tt)))(),st=rt.projectStore,ct=[...ot.assets??[]];it==null||it("init-project"),await st.init(ot),it==null||it("init-engine"),await st.initEngine(et),it==null||it("init-assets"),await st.initAssets(ct),it==null||it("init-scene"),await st.initScene(),it==null||it("run-engine"),st.runEngine(at);const dt=(ut=rt.sceneStore)!=null&&ut.iterateEntityModels?Array.from(rt.sceneStore.iterateEntityModels()).flatMap(([,ht])=>ht.components):[];return it==null||it("replay-bindings"),await Promise.all(dt.map(ht=>{var ft;return((ft=ht.replaySerializedBindings)==null?void 0:ft.call(ht))??Promise.resolve()})),it==null||it("resume-history"),rt.resumeHistoryCapture(),{root:rt,projectInfo:ot,projectStore:st,viewportStore:st.currentViewport}}function collectAssetPickerMatches(rt,_e){if(!rt)return[];const tt=[],et=getPropertyConfigs(rt);for(const nt in et){const it=et[nt];if(!it||it.type!==ComponentType.AssetPicker)continue;const at=rt[nt];at&&typeof at=="object"&&"refId"in at&&at.refId===_e&&tt.push({target:rt,key:nt})}return tt}function refreshAssetReferenceMatch(rt){var dt,ut,ht,ft,pt,mt,vt;const{target:_e,key:tt}=rt,et=(dt=getPropertyConfigs(_e))==null?void 0:dt[tt],nt=((ut=_e==null?void 0:_e[storedPropertyProxySymbol])==null?void 0:ut[tt])??((ht=getPropertyProxyConfigs(_e))==null?void 0:ht[tt]),it=nt==null?void 0:nt.engineKey;if(!!(et!=null&&et.bindPath||et!=null&&et.onChange)||!it){(ft=_e.triggerPropertyChange)==null||ft.call(_e,tt,!1);return}const ot=_e==null?void 0:_e.engineObject;if(!ot||typeof ot[it]!="function")return;const st=_e[tt],ct=st!=null&&st.refId?((vt=(mt=(pt=_e==null?void 0:_e.root)==null?void 0:pt.assetStore)==null?void 0:mt.assets)==null?void 0:vt[st.refId])??null:null;ot[it]((ct==null?void 0:ct.engineObject)??null)}async function reloadSceneStateFromAsset(rt){const _e=createEmptyDomainState();_e.version=rt.preserveVersion,_e.assets=rt.preserveAssets,rt.domainStore.reset(_e),await rt.sceneStore.init(rt.sceneAsset),rt.sceneFacade.initSettingsSystem(collectSceneSettings(rt.sceneStore))}const TEXT_ASSET_TYPES=new Set(["Scene","Prefab","script","Shader","ShaderChunk","StateMachineScript"]);function parseAssetMeta(rt,_e){if(!rt)return{};try{const tt=JSON.parse(rt);if(!tt||typeof tt!="object"||Array.isArray(tt))throw new Error("asset meta is not an object");return tt}catch(tt){return console.warn(`[applyProjectReadRefresh] invalid asset meta for ${_e}, fallback to empty meta`,tt),{}}}function toDomainAssetState(rt){const _e=parseAssetMeta(rt.meta,rt.uuid);return{id:rt.uuid,name:rt.name,type:_e.type??"Unknown",serverId:rt.id??null,parentFolderId:rt.parentId||null,url:rt.url||void 0,meta:_e,status:"ready"}}function isSerializableEqual(rt,_e){return JSON.stringify(rt)===JSON.stringify(_e)}async function fetchAssetPayload(rt,_e){const tt=await fetch(rt);if(!tt.ok)throw new Error(`asset fetch failed: ${tt.status}`);const et=await tt.blob(),nt=TEXT_ASSET_TYPES.has(_e)?await et.text():void 0;return{blob:et,text:nt}}function refreshSceneAssetPickerReferences(rt,_e){var it,at;const tt=rt.sceneStore;if(!tt)return;const et=ot=>{for(const st of collectAssetPickerMatches(ot,_e))refreshAssetReferenceMatch(st)};et(tt);const nt=typeof tt.iterateEntityModels=="function"?Array.from(tt.iterateEntityModels(),([,ot])=>ot):[];for(const ot of nt)for(const st of ot.components??[])et(st);for(const ot of((at=(it=tt.strippedEntities)==null?void 0:it.values)==null?void 0:at.call(it))??[])for(const st of ot.components??[])et(st)}function syncDomainAssetState(rt,_e){const tt=_e.id,et=rt.domainStore.state.assets[tt];if(et&&isSerializableEqual(et,_e))return;const nt=encodeJsonPointerSegment(tt),it=et?{op:"replace",path:`/assets/${nt}`,value:_e}:{op:"add",path:`/assets/${nt}`,value:_e};rt.domainStore.applyRemote([it])}function normalizeAssetBatchChanges(rt){const _e=new Map;for(const tt of rt){const et=_e.get(tt.assetId);if(!et){_e.set(tt.assetId,{assetId:tt.assetId,reason:tt.reason});continue}et.reason!=="main"&&tt.reason==="main"&&_e.set(tt.assetId,{assetId:tt.assetId,reason:"main"})}return Array.from(_e.values())}function isRuntimeOnlyAssetState(rt){var _e;return(rt==null?void 0:rt.serverId)==null&&((_e=rt==null?void 0:rt.meta)==null?void 0:_e.locked)===!0}function removeDomainAssetState(rt,_e){var et,nt;const tt=encodeJsonPointerSegment(_e);rt.domainStore.applyRemote([{op:"remove",path:`/assets/${tt}`}]),(nt=(et=rt.assetStore).deleteEditorAsset)==null||nt.call(et,_e)}function resolveRefreshSceneId(rt,_e){var nt;const tt=(nt=rt.content)==null?void 0:nt.scene;if(tt&&rt.assets.some(it=>it.uuid===tt))return tt;const et=rt.assets.find(it=>parseAssetMeta(it.meta,it.uuid).type==="Scene");return et?et.uuid:_e&&rt.assets.some(it=>it.uuid===_e)?_e:null}function assertRefreshSceneAvailable(rt,_e){if(!(rt||!_e))throw new Error(`[applyProjectReadFullRefresh] active scene ${_e} was removed and no replacement Scene asset is available`)}function syncProjectContent(rt,_e){!rt.projectStore||!_e.content||(rt.projectStore.content={...rt.projectStore.content??{},..._e.content,platform:_e.platform})}async function fetchAndLoadMainFile(rt,_e){var it;const tt=_e.url;if(!tt||typeof rt.reloadMainFileFromRemote!="function")return;const{blob:et,text:nt}=await fetchAssetPayload(tt,_e.type);return(it=rt.setUrl)==null||it.call(rt,tt),await rt.reloadMainFileFromRemote({blob:et,url:tt}),_e.type==="ShaderChunk"&&typeof nt=="string"&&typeof rt.updateCode=="function"&&rt.updateCode(nt),nt}async function reloadRuntimeAsset(rt,_e,tt,et){var nt;if(!rt){const it=tt.assetStore.initAsset(et);if(!it)return;let at;try{at=await fetchAndLoadMainFile(it,_e)}catch(ot){console.warn(`[applyProjectReadRefresh] initial main file load failed for ${et.uuid}`,ot)}try{await((nt=it.collectDependencies)==null?void 0:nt.call(it))}catch(ot){console.warn(`[applyProjectReadRefresh] collectDependencies failed for ${et.uuid}`,ot)}return at}return fetchAndLoadMainFile(rt,_e)}async function refreshCurrentScene(rt,_e){!rt.sceneStore||!_e||await reloadSceneStateFromAsset({sceneStore:rt.sceneStore,sceneFacade:rt.sceneFacade,domainStore:rt.domainStore,sceneAsset:_e,preserveAssets:rt.domainStore.state.assets,preserveVersion:rt.domainStore.state.version})}async function applyProjectReadFullRefresh(rt){var ct;const{root:_e,storage:tt,projectId:et}=rt,nt=rt.projectInfo??await tt.project.query(et),it=_e.domainStore.state.assets??{},at=((ct=_e.sceneStore)==null?void 0:ct.refId)??null,ot=resolveRefreshSceneId(nt,at),st=new Set(nt.assets.map(dt=>dt.uuid));assertRefreshSceneAvailable(ot,at),await EditorAsset.runWithGlobalAutoSaveSuspended(async()=>{await _e.domainStore.runAsRemote(async()=>{var ut,ht,ft,pt,mt;syncProjectContent(_e,nt),ot&&((ut=_e.projectStore)!=null&&ut.content)&&(_e.projectStore.content.scene=ot);for(const[vt,_t]of Object.entries(it))st.has(vt)||isRuntimeOnlyAssetState(_t)||removeDomainAssetState(_e,vt);let dt=ot?((ht=_e.assetStore.assets)==null?void 0:ht[ot])??null:null;for(const vt of nt.assets){const _t=toDomainAssetState(vt),yt=it[vt.uuid],bt=(ft=_e.assetStore.assets)==null?void 0:ft[vt.uuid],Et=vt.uuid===ot;if(Et&&(dt=bt??dt),!(!Et&&yt&&isSerializableEqual(yt,_t))){syncDomainAssetState(_e,_t);try{await reloadRuntimeAsset(bt,_t,_e,vt),Et&&(dt=((pt=_e.assetStore.assets)==null?void 0:pt[vt.uuid])??bt??dt)}catch(St){const At=Et?`[applyProjectReadFullRefresh] reload active scene asset failed for ${vt.uuid}, aborting full refresh`:`[applyProjectReadFullRefresh] reload runtime asset failed for ${vt.uuid}, skipping`;if(console.warn(At,St),Et)throw St}Et||refreshSceneAssetPickerReferences(_e,vt.uuid)}}if(dt||ot){const vt=dt??((mt=_e.assetStore.assets)==null?void 0:mt[ot]);await refreshCurrentScene(_e,vt)}})})}async function applyProjectReadAssetBatchRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,changes:nt}){const it=et??await _e.project.query(tt),at=normalizeAssetBatchChanges(nt);await EditorAsset.runWithGlobalAutoSaveSuspended(async()=>{await rt.domainStore.runAsRemote(async()=>{var st;const ot=new Map(it.assets.map(ct=>[ct.uuid,ct]));for(const ct of at){const dt=ot.get(ct.assetId);if(!dt){console.warn(`[applyProjectReadAssetBatchRefresh] asset missing from latest project detail, skipping ${ct.assetId}`);continue}const ut=toDomainAssetState(dt),ht=(st=rt.assetStore.assets)==null?void 0:st[ct.assetId];syncDomainAssetState(rt,ut),ct.reason==="main"&&(await reloadRuntimeAsset(ht,ut,rt,dt),refreshSceneAssetPickerReferences(rt,ct.assetId))}})})}async function applyProjectReadRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,change:nt}){if(nt.type==="scene-changed"){await applyProjectReadFullRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et});return}await applyProjectReadAssetBatchRefresh({root:rt,storage:_e,projectId:tt,projectInfo:et,changes:[{assetId:nt.assetId,reason:nt.reason}]})}function mountEngineCanvas(rt,_e){var et;const tt=_e.canvas;if(!tt)throw new Error("projectStore.canvas is missing");return tt.style.width="100%",tt.style.height="100%",tt.oncontextmenu=nt=>{nt.preventDefault()},tt.parentElement!==rt&&rt.appendChild(tt),(et=_e.engine)==null||et.dispatch("onReady"),tt}function unique(rt){return Array.from(new Set(rt))}function createRuntimeBootstrapPlan({projectInfo:rt,sceneData:_e}){const tt=Array.from(collectAssetTypes(rt.assets)).sort(),et=Array.from(collectComponentTypes(_e)).sort(),nt=tt.filter(at=>!ASSET_MODULE_KEYS_BY_TYPE[at]),it=et.filter(at=>!COMPONENT_MODULE_KEYS_BY_TYPE[at]);return!_e||nt.length>0||it.length>0?{mode:"full",assetTypes:tt,componentTypes:et,unknownAssetTypes:nt,unknownComponentTypes:it,assetModuleKeys:[...FULL_ASSET_MODULE_KEYS],componentModuleKeys:[...FULL_COMPONENT_MODULE_KEYS],shouldInitGlTFIO:!0}:{mode:"selective",assetTypes:tt,componentTypes:et,unknownAssetTypes:nt,unknownComponentTypes:it,assetModuleKeys:unique([...tt.map(at=>ASSET_MODULE_KEYS_BY_TYPE[at]).filter(Boolean),"ambient-light"]).sort(),componentModuleKeys:unique(et.map(at=>COMPONENT_MODULE_KEYS_BY_TYPE[at]).filter(Boolean)).sort(),shouldInitGlTFIO:tt.includes("glTF")}}async function loadRuntimeBootstrapContext({storage:rt,projectId:_e,fetchImpl:tt=fetch}){const et=await rt.project.query(_e),nt=await loadCurrentSceneData(et,tt);return{projectInfo:et,currentSceneData:nt,plan:createRuntimeBootstrapPlan({projectInfo:et,sceneData:nt})}}async function loadCurrentSceneData(rt,_e){var nt;const tt=(nt=rt.content)==null?void 0:nt.scene,et=resolveCurrentSceneAsset(rt.assets,tt);if(!(et!=null&&et.url))return null;try{const it=await _e(et.url);if(!it.ok)return null;const at=await it.json();return at&&typeof at=="object"?at:null}catch{return null}}function resolveCurrentSceneAsset(rt,_e){if(_e){const tt=rt.find(et=>et.uuid===_e);if(tt)return tt}return rt.find(tt=>parseAssetType(tt.meta)==="Scene")}function collectAssetTypes(rt){const _e=new Set;for(const tt of rt){const et=parseAssetType(tt.meta);et&&!NON_RUNTIME_ASSET_TYPES.has(et)&&_e.add(et)}return _e}function parseAssetType(rt){try{const _e=JSON.parse(rt);return typeof _e.type=="string"&&_e.type.length>0?_e.type:null}catch{return null}}function collectComponentTypes(rt){var nt;const _e=new Set,tt=rt==null?void 0:rt.components;if(Array.isArray(tt))for(const it of tt){if(!it||typeof it!="object")continue;const at=readString(it.type)??readString(it.class);at&&_e.add(at)}const et=rt==null?void 0:rt.entities;if(!Array.isArray(et))return _e;for(const it of et){if(!it||typeof it!="object")continue;const at=readString((nt=it.transform)==null?void 0:nt.class);at&&_e.add(at);const ot=it.components;if(Array.isArray(ot))for(const st of ot){const ct=readString(st==null?void 0:st.class);ct&&_e.add(ct)}}return _e}function readString(rt){return typeof rt=="string"&&rt.length>0?rt:null}class PreviewRuntime{constructor(){Rt(this,"root",null);Rt(this,"projectStore",null);Rt(this,"viewportStore",null);Rt(this,"container",null);Rt(this,"storage",null);Rt(this,"projectId",null);Rt(this,"taskQueue",Promise.resolve());Rt(this,"resizeObserver",null)}get engine(){var _e;return((_e=this.projectStore)==null?void 0:_e.engine)??null}async init(_e,tt,et,nt={}){this.container=_e,this.storage=tt,this.projectId=et,await this.enqueueBootstrap(_e,tt,et,!1,nt.onStage,nt.projectInfo)}async reload(_e=this.storage,tt=this.projectId){if(!_e)throw new Error("storage is required");if(!tt)throw new Error("projectId is required");if(this.storage=_e,this.projectId=tt,this.root){await this.enqueueTask(async()=>{await this.runRefreshWithBootstrap(async et=>{await applyProjectReadFullRefresh({root:this.root,storage:_e,projectId:tt,projectInfo:et==null?void 0:et.projectInfo})})});return}if(!this.container)throw new Error("container is required");await this.enqueueBootstrap(this.container,_e,tt,!0)}async applyChange(_e){if(_e.type==="project-changed"){await this.reload();return}await this.enqueueTask(async()=>{const tt=this.root,et=this.storage,nt=this.projectId;if(!tt)throw new Error("runtime root is required");if(!et)throw new Error("storage is required");if(!nt)throw new Error("projectId is required");await this.runRefreshWithBootstrap(async it=>{await applyProjectReadRefresh({root:tt,storage:et,projectId:nt,projectInfo:it==null?void 0:it.projectInfo,change:{type:_e.type,assetId:_e.assetId,reason:_e.reason}})})})}async applyAssetBatchChange({changes:_e}){await this.enqueueTask(async()=>{const tt=this.root,et=this.storage,nt=this.projectId;if(!tt)throw new Error("runtime root is required");if(!et)throw new Error("storage is required");if(!nt)throw new Error("projectId is required");await this.runRefreshWithBootstrap(async it=>{await applyProjectReadAssetBatchRefresh({root:tt,storage:et,projectId:nt,projectInfo:it==null?void 0:it.projectInfo,changes:_e})})})}async runRefreshWithBootstrap(_e){var et,nt;const tt=await this.ensureBootstrapForCurrentProject();await _e(tt),(nt=(et=this.viewportStore)==null?void 0:et.reapplySceneCameraIfUntouched)==null||nt.call(et)}async ensureBootstrapForCurrentProject(){const _e=this.storage,tt=this.projectId;if(!_e||!tt)return null;try{const et=await loadRuntimeBootstrapContext({storage:_e,projectId:tt});return await bootstrapEditorRuntime({plan:et.plan}),et}catch(et){throw console.warn("[PreviewRuntime] ensureBootstrapForCurrentProject failed:",et),et}}async setEntityTransform(_e,tt,et={}){await this.enqueueTask(async()=>{const{root:nt,projectStore:it}=this.requireRuntimeHandles();nt.entityFacade.setTransform(_e,tt),await this.persistSceneIfRequested(it,et.persist)})}async saveScene(){await this.enqueueTask(async()=>{const{projectStore:_e}=this.requireRuntimeHandles();await this.persistScene(_e)})}async undo(_e={}){return this.enqueueTask(async()=>{const{root:tt,projectStore:et}=this.requireRuntimeHandles(),nt=tt.undo();return nt&&await this.persistSceneIfRequested(et,_e.persist),nt})}async redo(_e={}){return this.enqueueTask(async()=>{const{root:tt,projectStore:et}=this.requireRuntimeHandles(),nt=tt.redo();return nt&&await this.persistSceneIfRequested(et,_e.persist),nt})}dispose(){this.disposeRuntime(),this.container=null,this.storage=null,this.projectId=null}enqueueBootstrap(_e,tt,et,nt=!1,it,at){return this.enqueueTask(async()=>{nt&&this.disposeRuntime(),await this.bootstrap(_e,tt,et,it,at)})}enqueueTask(_e){const tt=this.taskQueue.then(_e,_e);return this.taskQueue=tt.then(()=>{},()=>{}),tt}async bootstrap(_e,tt,et,nt,it){const at=new Root,ot=document.createElement("canvas"),st=await initProjectReadRuntime({root:at,storage:tt,projectId:et,canvas:ot,projectInfo:it,onStage:nt,viewport:{mode:"editor",useSceneCameraAsFallback:!0}});this.root=st.root,this.projectStore=st.projectStore,this.viewportStore=st.viewportStore,mountEngineCanvas(_e,this.projectStore),this.attachResizeSync(_e)}disposeRuntime(){var tt,et,nt,it;(tt=this.resizeObserver)==null||tt.disconnect(),this.resizeObserver=null;const _e=(et=this.projectStore)==null?void 0:et.canvas;_e!=null&&_e.parentElement&&_e.parentElement.removeChild(_e),(it=(nt=this.projectStore)==null?void 0:nt.reset)==null||it.call(nt),this.root=null,this.projectStore=null,this.viewportStore=null}attachResizeSync(_e){var et,nt,it;if((et=this.resizeObserver)==null||et.disconnect(),this.resizeObserver=null,(it=(nt=this.viewportStore)==null?void 0:nt.handleContainerResize)==null||it.call(nt),typeof ResizeObserver>"u")return;const tt=new ResizeObserver(()=>{var at,ot;(ot=(at=this.viewportStore)==null?void 0:at.handleContainerResize)==null||ot.call(at)});tt.observe(_e),this.resizeObserver=tt}requireRuntimeHandles(){const _e=this.root,tt=this.projectStore;if(!_e)throw new Error("runtime root is required");if(!tt)throw new Error("projectStore is required");return{root:_e,projectStore:tt}}async persistSceneIfRequested(_e,tt=!1){tt&&await this.persistScene(_e)}async persistScene(_e){var et;const tt=(et=_e.updateSceneAsset)==null?void 0:et.bind(_e);if(!tt)throw new Error("projectStore.updateSceneAsset is required");await tt()}}class HttpStorage{constructor(_e){Rt(this,"project");Rt(this,"assets");Rt(this,"schema");this.project={query:tt=>_e.project.query(tt),modifyProjectName:(tt,et)=>_e.project.modifyProjectName(tt,et).then(()=>{}),updateThumbnail:(tt,et)=>_e.project.updateThumbnail(tt,et),updateMetaInfo:(tt,et,nt)=>_e.project.updateMetaInfo(tt,et,nt).then(()=>{}),updateSetting:(tt,et)=>_e.project.updateSetting(tt,et).then(()=>{})},this.assets={create:async tt=>{const{id:et,url:nt,meta:it}=await _e.assets.create(tt);return{id:et,url:nt,meta:typeof it=="string"?it:void 0}},update:(tt,et)=>_e.assets.update(tt,et),delete:(tt,et)=>_e.assets.delete(tt,et),duplicate:async tt=>(await _e.assets.duplicateTo(tt)).data},this.schema={update:(tt,et)=>_e.schema.update(tt,et)}}}function createStorage(rt,_e=fetch){const tt={project:{query:async et=>{const nt=await _e(`${rt}/api/project/${et}`);if(!nt.ok)throw new Error(`project query failed: ${nt.status}`);return nt.json()},modifyProjectName:async()=>({}),updateThumbnail:async()=>({thumbnail:""}),updateMetaInfo:async()=>({}),updateSetting:async()=>({})},assets:{create:async()=>({id:"",url:""}),update:async(et,nt)=>{const it=await serializeAssetUpdate(nt),at=await _e(`${rt}/api/assets/${encodeURIComponent(et)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(it)});if(!at.ok)throw new Error(`asset update failed: ${at.status}`);return at.json()},delete:async()=>{},duplicateTo:async()=>({data:[]})},schema:{update:async()=>{}}};return new HttpStorage(tt)}async function serializeAssetUpdate(rt){return{file:rt.file?await serializeBlob(rt.file):void 0,meta:rt.meta,name:rt.name,parentId:rt.parentId,url:rt.url}}async function serializeBlob(rt){const _e=await rt.arrayBuffer();return{base64:encodeBase64(_e),type:rt.type}}function encodeBase64(rt){if(typeof Buffer<"u")return Buffer.from(rt).toString("base64");let _e="";const tt=new Uint8Array(rt);for(let et=0;et<tt.length;et++)_e+=String.fromCharCode(tt[et]);return btoa(_e)}async function loadRuntimeProjectId(rt,_e=fetch){const tt=normalizeBaseUrl(rt),et=await _e(`${tt}/healthz`);if(!et.ok)throw new Error(`project id query failed: ${et.status}`);const nt=await et.json();return typeof nt.projectId=="string"&&nt.projectId.length>0?nt.projectId:"local"}async function loadRuntimeProjectContext(rt,_e={}){var ot,st;const tt=normalizeBaseUrl(rt),et=_e.fetchImpl??fetch;(ot=_e.onStage)==null||ot.call(_e,"resolve-project-id");const nt=await loadRuntimeProjectId(tt,et),it=createStorage(tt,et);(st=_e.onStage)==null||st.call(_e,"query-project");const at=await loadRuntimeBootstrapContext({storage:it,projectId:nt,fetchImpl:et});return{storage:it,projectId:nt,...at}}function normalizeBaseUrl(rt){return rt.replace(/\/$/,"")}async function main(){const rt=document.getElementById("app"),_e=document.getElementById("status");if(!rt)throw new Error("preview container not found");const tt=(ct,dt="busy")=>{_e&&(_e.textContent=ct,_e.setAttribute("data-state",dt))},et=createStartupStatusReporter({setStatus:tt});let nt=!1;const it=(ct,dt="busy")=>{if(ct==="hot reload disconnected, retrying..."){nt=!0,tt(ct,dt);return}if(ct==="hot reload connected"){if(!nt)return;nt=!1}tt(ct,dt)},at="",ot=new PreviewRuntime;let st=null;try{const{storage:ct,projectId:dt,projectInfo:ut,plan:ht}=await loadRuntimeProjectContext(at,{onStage:et.reportStage});et.reportStage("boot-runtime"),await bootstrapEditorRuntime({onStage:et.reportStage,plan:ht}),await ot.init(rt,ct,dt,{onStage:et.reportStage,projectInfo:ut}),window.__runtime=ot,Object.defineProperty(window,"__engine",{configurable:!0,enumerable:!0,get:()=>ot.engine}),et.finish(),st=attachSceneHotReload({runtime:ot,onStatus:it});const ft=()=>{st==null||st(),ot.dispose()};window.addEventListener("beforeunload",ft)}catch(ct){console.error(ct),tt(ct instanceof Error?ct.message:String(ct))}}main();export{Sprite$1 as $,AntiAliasing as A,BoundingBox as B,ComponentType as C,DepthTextureMode as D,EditorComponent as E,Vector2 as F,resourceLoader as G,Loader as H,Renderer$1 as I,ignoreClone as J,Entity as K,LayerSetting as L,MSAASamples as M,SpriteRenderer as N,TextRenderer as O,PhysicsMaterialCombineMode as P,Font as Q,RenderFace as R,Script as S,TextureWrapMode$1 as T,Logger as U,Vector4 as V,Engine as W,AssetPromise as X,Utils$3 as Y,AssetType as Z,EngineObject as _,Layer as a,TextureFormat as a$,SubPrimitive as a0,BlendFactor as a1,BlendOperation as a2,VertexElement as a3,VertexElementFormat as a4,Buffer$3 as a5,BufferBindFlag as a6,BufferUsage as a7,IndexBufferBinding as a8,IndexFormat as a9,SpriteMaskLayer as aA,SpriteMaskInteraction as aB,action as aC,hdrColorSerializer as aD,ValueTypeEnum as aE,SpriteDrawMode as aF,resolveSceneChangeUpdate as aG,styled as aH,Flex as aI,observer as aJ,useTranslation as aK,ActionButton as aL,reactExports as aM,Collapsible as aN,InspectorForm as aO,Button$2 as aP,AnimatorController as aQ,AnimatorControllerLayer as aR,AnimatorLayerBlendingMode as aS,meta as aT,override as aU,AnimatorStateTransition as aV,parseSourceV2SceneFileJson as aW,stringifySourceV2SceneFile as aX,reportSavingWhileDestroy as aY,buildSourceSceneFile as aZ,Texture2D as a_,assignmentClone as aa,deepClone as ab,ReferResource as ac,TextureFilterMode as ad,Shader as ae,CullMode as af,RenderQueueType as ag,Material as ah,Vector3 as ai,Primitive as aj,VertexBufferBinding as ak,XRManager as al,decoder as am,Ray as an,Plane as ao,decode as ap,CameraType$1 as aq,Matrix as ar,Signal as as,Rect$1 as at,Quaternion as au,jsxRuntimeExports as av,FormItem as aw,extractFormItemProps as ax,StyledText as ay,angleSerializer as az,CameraClearFlags as b,Root as b$,AUDIO_EXT_LIST as b0,ShaderProperty as b1,ShaderPropertyType as b2,Color$1 as b3,createCollection$1 as b4,createContextScope$4 as b5,createCollapsibleScope as b6,React$1 as b7,useControllableState as b8,useComposedRefs$6 as b9,FormItemAssetPicker$1 as bA,createReactComponent$1 as bB,IconPlus$1 as bC,PrimitiveMesh as bD,ParticleRenderer as bE,reaction as bF,extendObservable as bG,BlendMode as bH,cloneDeep$1 as bI,isObservableProp as bJ,virtualPropertyManually as bK,InterpolationType as bL,addPropertyProxyConfig as bM,ModelMesh as bN,BlendShape as bO,MeshTopology as bP,BlinnPhongMaterial as bQ,ensureUploadMainFile as bR,AssetPreviewer as bS,Select as bT,SelectItem as bU,v4 as bV,collectDependenciesFromMeta as bW,n as bX,extname$1 as bY,basename$1 as bZ,assetService as b_,useDirection as ba,composeEventHandlers$6 as bb,Primitive$8 as bc,useId as bd,Root$d as be,Trigger$5 as bf,Content$5 as bg,keyframes$2 as bh,IconChevronRight as bi,Spin as bj,FormItemSelect as bk,normalizeToDomainValueRecord as bl,FormItemVector3 as bm,EntityPicker$1 as bn,Transform as bo,AnimatorCullingMode as bp,BaseScript as bq,Animator as br,viewport as bs,ViewportPlugin as bt,MathUtil as bu,VertexAttribute as bv,ContentRestorer as bw,BufferMesh as bx,RenderTarget as by,Separator as bz,Downsampling as c,isSubProperty as c$,assetIconMap as c0,showEditorUiToastError as c1,computed as c2,getBoundingBox as c3,FormItemButton as c4,toJS as c5,normalizeToDomainValue as c6,api as c7,ParticleCurve as c8,CurveKey as c9,StaticCollider as cA,CharacterController as cB,SpringJoint as cC,FixedJoint as cD,HingeJoint as cE,AudioSource as cF,PostProcess as cG,AnimationFloatCurve as cH,AnimationFloatArrayCurve as cI,AnimationVector2Curve as cJ,AnimationVector3Curve as cK,AnimationVector4Curve as cL,AnimationQuaternionCurve as cM,AnimationColorCurve as cN,AnimationRefCurve as cO,AnimationRectCurve as cP,AnimationBoolCurve as cQ,AnimationStringCurve as cR,AnimationArrayCurve as cS,PropertyType as cT,getPropertyProxyConfigs as cU,TangentMode as cV,TangentType as cW,openAnimatorStateReport as cX,AnimationClip as cY,getPropertyUniquePath as cZ,getPropertyConfigs as c_,denormalizeColor as ca,ColorPicker as cb,normalizeColor as cc,ParticleGradient as cd,GradientColorKey as ce,GradientAlphaKey as cf,TrailTextureMode as cg,TextVerticalAlignment as ch,TextHorizontalAlignment as ci,FontStyle as cj,OverflowMode as ck,FormItemInput as cl,FormItemInputNumber as cm,DirectLight as cn,Camera as co,SkinnedMeshRenderer as cp,PointLight as cq,SpotLight as cr,SpriteMask$1 as cs,UITransform as ct,UICanvas as cu,UIGroup as cv,Button$1 as cw,Image$3 as cx,Text as cy,DynamicCollider as cz,decomposeLayersByBitwise as d,assertSourceV2PrefabFileStructure as d$,storedPropertyProxySymbol as d0,Keyframe$1 as d1,useEscapeKeydown as d2,useCallbackRef$1 as d3,dispatchDiscreteCustomEvent$1 as d4,useLayoutEffect2 as d5,$1CM7W$reactdom as d6,composeRefs$7 as d7,createPopperScope$1 as d8,Anchor$2 as d9,toBuffer as dA,toBufferKTX2 as dB,SphericalHarmonics3 as dC,AmbientLight as dD,DiffuseMode as dE,FileHeader as dF,createStore as dG,get as dH,set as dI,__vitePreload as dJ,md5 as dK,logger$2 as dL,ReturnableObjectPool as dM,ClearableObjectPool as dN,ShaderLanguage as dO,CompareFunction as dP,StencilOperation as dQ,ColorWriteMask as dR,RenderStateElementKey as dS,shaders as dT,browserExports as dU,Group$2 as dV,resolve$2 as dW,ShaderFactory as dX,openCodeEditor as dY,openScriptReport as dZ,mergeSourceValueRecords as d_,Presence$2 as da,Content$3 as db,Arrow$2 as dc,Root2$6 as dd,Checkbox as de,PostProcessEffectParameter as df,PostProcessEffectVector4Parameter as dg,FormItemVector4 as dh,PostProcessEffectVector3Parameter as di,PostProcessEffectVector2Parameter as dj,FormItemVector2 as dk,PostProcessEffectTextureParameter as dl,PostProcessEffectColorParameter as dm,FormItemColor as dn,PostProcessEffectEnumParameter as dp,PostProcessEffectBoolParameter as dq,FormItemToggle as dr,PostProcessEffectFloatParameter as ds,TonemappingEffect as dt,BloomEffect as du,TextureCubeFace as dv,BakerResolution as dw,DecodeMode as dx,IBLBaker as dy,isValidFileHeader as dz,t$7 as e,CameraModifyFlags as e$,isPlainRecord as e0,FormItemGroup as e1,ParticleStopMode as e2,isSourceInstanceBoundary as e3,resolveSourceInstanceRootOverrideTarget as e4,readSourceEntityResolvedState as e5,isTraceEnabled as e6,beginTrace as e7,endTrace as e8,EntityManager as e9,getTextureInformation as eA,resolveLocalWorkspaceRelativePath as eB,Galacean as eC,ColliderShapeUpAxis$1 as eD,SphereColliderShape as eE,PlaneColliderShape as eF,CapsuleColliderShape as eG,BoxColliderShape as eH,FormItemToggleGroup as eI,DynamicColliderConstraints as eJ,CollisionDetectionMode as eK,ControllerNonWalkableMode as eL,FormItemEntityPicker as eM,EditorDependentMode as eN,JointLimits as eO,JointMotor as eP,ScaleTransition as eQ,ColorTransition as eR,SpriteTransition as eS,HorizontalAlignmentMode as eT,VerticalAlignmentMode as eU,css$1 as eV,InputNumber as eW,EntityModifyFlags as eX,debounce$2 as eY,CanvasRenderMode as eZ,ResolutionAdaptationMode as e_,parseSourceV2PrefabFileJson as ea,stringifySourceV2PrefabFile as eb,normalizePrefabRootInstanceOverrides as ec,SerializeContext as ed,createSourceRefCodec as ee,convertAssetRefsToDomainRefs as ef,assertCanonicalSourceRef as eg,readComponentSourceProps as eh,readComponentSourcePropsWithEditorValues as ei,diffSourceValueRecord as ej,combineLayersByBitwise as ek,buildSourceIdIndex as el,encodeJsonPointerSegment as em,sourceValuesEqual as en,getSerializeConfigs as eo,buildInitialComponentProps as ep,showAlert as eq,PrefabResource as er,TraceLogger as es,GLTFResource as et,MessageCenter as eu,reactDomExports as ev,FormItemSlider as ew,LineDrawer as ex,TextureCube as ey,replaceExtname as ez,propertyProxy as f,PopoverCloseTrigger as f$,createReactComponent$3 as f0,clamp$2 as f1,mergeRefs as f2,ActionButtonGroup as f3,Popover as f4,getDefaultExportFromCjs as f5,Input as f6,autorun as f7,buildGlTFDomainInstanceBindingSync as f8,Component as f9,Title as fA,Description$1 as fB,IconX as fC,Root$4 as fD,Portal$3 as fE,lightTheme as fF,darkTheme as fG,Badge as fH,Breadcrumbs as fI,BreadcrumbItem as fJ,CascadeSlider as fK,useColorSpaceConversion as fL,createDisplayColorSpaceToggle as fM,toNormalizeHexStr as fN,isEqual$1 as fO,blendParticleStops as fP,generateLinearGradient as fQ,generateHDR as fR,generatePreviewColor as fS,srgbColorToLinear as fT,linearColorToSRGB as fU,GradientSlider as fV,ParticleSlider as fW,HDRSlider as fX,EyeDropperIcon as fY,IconRightBottomCorner as fZ,IconPendingFile$1 as f_,ParticleShapeArcMode as fa,ConeEmitType as fb,MeshShape as fc,SphereShape as fd,HemisphereShape as fe,ConeShape as ff,CircleShape as fg,BoxShape as fh,ParticleCurveMode as fi,FormItemTable as fj,ParticleCompositeCurve as fk,Burst as fl,ParticleGradientMode as fm,ParticleRenderMode as fn,ParticleSimulationSpace as fo,ParticleScaleMode as fp,Ie as fq,useDrop as fr,Overlay$2 as fs,overlayFadeIn as ft,Content$1 as fu,contentShow as fv,contentFadeIn as fw,contentFadeOut as fx,DialogClose as fy,Trigger$2 as fz,getMultipleLayerOptions as g,createRovingFocusGroupScope as g$,SegmentControl as g0,SegmentControlItem as g1,Slider as g2,StyledTextarea as g3,ToggleGroup$1 as g4,ToggleGroupItem as g5,StyledBold as g6,StyledLink as g7,StyledTitle$1 as g8,TreeItemRoot as g9,Slot as gA,useSize as gB,useFloating as gC,autoUpdate as gD,offset$2 as gE,shift as gF,limitShift as gG,flip as gH,size as gI,arrow as gJ,hide as gK,hideOthers as gL,useFocusGuards as gM,FocusScope as gN,DismissableLayer$1 as gO,RemoveScroll as gP,Portal$6 as gQ,createSidecarMedium as gR,__rest$r as gS,useMergeRefs as gT,__assign as gU,fullWidthClassName as gV,zeroRightClassName as gW,styleSingleton as gX,__spreadArray as gY,RemoveScrollBar as gZ,exportSidecar as g_,TreeItemContent as ga,TreeItemIcon as gb,TreeItemPreview as gc,TreeGroup$1 as gd,AlertDialog as ge,AssetItem as gf,HoverCard as gg,resetStyle as gh,globalCss as gi,theme as gj,getCssText as gk,createTheme as gl,recipes as gm,keyframes$1 as gn,DragContext as go,DragDropContextProvider as gp,useDrag as gq,domainWhiteList as gr,Env as gs,EQueryKeys as gt,EventBus as gu,reloadSceneStateFromAsset as gv,Scene as gw,storedMainSymbol as gx,FormItemRect as gy,SpriteAtlas as gz,layerProxy as h,Root$7 as h0,Item$1 as h1,clamp$3 as h2,radioGroupStyle as h3,labelStyle as h4,basicItemStyle as h5,contentStyle as h6,contextMenuContentStyle as h7,subMenuItemStyle as h8,separatorStyle as h9,checkboxItemStyle as ha,radioItemStyle as hb,indicatorStyle as hc,dropdownMenuContentStyle as hd,IconCheck as he,ShadowType as i,EditorAsset as j,PhysicsMaterial as k,layerSerializer as l,main$1 as m,asset as n,AssetsImportType as o,propertyField as p,DragLayer as q,runInAction as r,serialize as s,transformEnumToOptions as t,makeObservable as u,virtualProperty as v,openMarkdownEditor as w,observable as x,MeshRenderer as y,PBRMaterial as z};
|