@needle-tools/engine 5.1.13 → 5.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/gltf-progressive-4EjGCbsd.umd.cjs +10 -0
  3. package/dist/{gltf-progressive-DaeP5KBr.js → gltf-progressive-BidVoP6g.js} +205 -198
  4. package/dist/gltf-progressive-JsCmImqa.min.js +10 -0
  5. package/dist/{materialx-BBv-42Th.min.js → materialx-D3ZU4CP6.min.js} +1 -1
  6. package/dist/{materialx-0m1xlF5m.js → materialx-FhjQQgNu.js} +1 -1
  7. package/dist/{materialx-8OpPwNc7.umd.cjs → materialx-RxB3AN7d.umd.cjs} +2 -2
  8. package/dist/{needle-engine.bundle-B_ZctaDt.umd.cjs → needle-engine.bundle-BivRq9Io.umd.cjs} +146 -146
  9. package/dist/{needle-engine.bundle-DTvJ1zCJ.js → needle-engine.bundle-ByEd2JMt.js} +6457 -6427
  10. package/dist/{needle-engine.bundle-DR967VjU.min.js → needle-engine.bundle-DiobwRVT.min.js} +146 -146
  11. package/dist/needle-engine.d.ts +14 -12
  12. package/dist/needle-engine.js +246 -246
  13. package/dist/needle-engine.min.js +1 -1
  14. package/dist/needle-engine.umd.cjs +1 -1
  15. package/dist/{vendor-DiDMDryv.js → vendor-BVzQovzJ.js} +5161 -5161
  16. package/dist/{vendor-DE_m5MvL.umd.cjs → vendor-C5YVRzxf.umd.cjs} +5 -5
  17. package/dist/{vendor-B7IfFLrR.min.js → vendor-rvNvQ-IU.min.js} +5 -5
  18. package/lib/engine/api.d.ts +1 -1
  19. package/lib/engine/api.js +1 -1
  20. package/lib/engine/api.js.map +1 -1
  21. package/lib/engine/engine_context.js +3 -0
  22. package/lib/engine/engine_context.js.map +1 -1
  23. package/lib/engine/engine_gameobject.js +1 -1
  24. package/lib/engine/engine_gameobject.js.map +1 -1
  25. package/lib/engine/engine_gltf_builtin_components.js +1 -1
  26. package/lib/engine/engine_gltf_builtin_components.js.map +1 -1
  27. package/lib/engine/engine_init.js +2 -2
  28. package/lib/engine/engine_instantiate_resolve.js.map +1 -1
  29. package/lib/engine/engine_license.d.ts +7 -7
  30. package/lib/engine/engine_license.js +75 -75
  31. package/lib/engine/engine_license.js.map +1 -1
  32. package/lib/engine/engine_loaders.gltf.d.ts +3 -1
  33. package/lib/engine/engine_loaders.gltf.js +6 -1
  34. package/lib/engine/engine_loaders.gltf.js.map +1 -1
  35. package/lib/engine/engine_materialpropertyblock.js +18 -0
  36. package/lib/engine/engine_materialpropertyblock.js.map +1 -1
  37. package/lib/engine/engine_networking.d.ts +1 -1
  38. package/lib/engine/engine_networking.js +1 -1
  39. package/lib/engine/engine_networking.js.map +1 -1
  40. package/lib/engine/engine_networking_blob.js +3 -3
  41. package/lib/engine/engine_networking_blob.js.map +1 -1
  42. package/lib/engine/engine_physics.d.ts +2 -0
  43. package/lib/engine/engine_physics.js +23 -1
  44. package/lib/engine/engine_physics.js.map +1 -1
  45. package/lib/engine/engine_utils_qrcode.js +2 -2
  46. package/lib/engine/engine_utils_qrcode.js.map +1 -1
  47. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
  48. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
  49. package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
  50. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  51. package/lib/engine/webcomponents/needle-engine.js +2 -2
  52. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  53. package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
  54. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  55. package/lib/engine/xr/NeedleXRSession.js +11 -10
  56. package/lib/engine/xr/NeedleXRSession.js.map +1 -1
  57. package/lib/engine/xr/TempXRContext.js +2 -2
  58. package/lib/engine/xr/TempXRContext.js.map +1 -1
  59. package/lib/engine-components/AnimationBuilder.d.ts +1 -1
  60. package/lib/engine-components/AnimationBuilder.js.map +1 -1
  61. package/lib/engine-components/AnimatorController.builder.d.ts +2 -2
  62. package/lib/engine-components/AnimatorController.builder.js +2 -2
  63. package/lib/engine-components/AnimatorController.builder.js.map +1 -1
  64. package/lib/engine-components/Component.d.ts +1 -1
  65. package/lib/engine-components/Component.js +1 -1
  66. package/lib/engine-components/Component.js.map +1 -1
  67. package/lib/engine-components/DragControls.d.ts +2 -2
  68. package/lib/engine-components/DragControls.js +2 -2
  69. package/lib/engine-components/DragControls.js.map +1 -1
  70. package/lib/engine-components/DragControlsConstraints.js.map +1 -1
  71. package/lib/engine-components/Light.js +1 -1
  72. package/lib/engine-components/Light.js.map +1 -1
  73. package/lib/engine-components/api.d.ts +2 -2
  74. package/lib/engine-components/api.js +1 -1
  75. package/lib/engine-components/api.js.map +1 -1
  76. package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
  77. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  78. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js.map +1 -1
  79. package/lib/engine-components/postprocessing/index.d.ts +1 -1
  80. package/lib/engine-components/postprocessing/index.js +1 -1
  81. package/lib/engine-components/postprocessing/index.js.map +1 -1
  82. package/lib/engine-components/timeline/TimelineBuilder.d.ts +4 -4
  83. package/lib/engine-components/timeline/TimelineBuilder.js +2 -2
  84. package/lib/engine-components/timeline/TimelineBuilder.js.map +1 -1
  85. package/lib/engine-components/timeline/TimelineTracks.js +24 -15
  86. package/lib/engine-components/timeline/TimelineTracks.js.map +1 -1
  87. package/lib/engine-components/webxr/WebXRImageTracking.utils.js.map +1 -1
  88. package/package.json +2 -2
  89. package/plugins/common/license.js +4 -4
  90. package/plugins/vite/license.js +4 -4
  91. package/src/engine/api.ts +1 -1
  92. package/src/engine/engine_context.ts +3 -0
  93. package/src/engine/engine_gameobject.ts +2 -2
  94. package/src/engine/engine_gltf_builtin_components.ts +1 -1
  95. package/src/engine/engine_init.ts +2 -2
  96. package/src/engine/engine_instantiate_resolve.ts +1 -1
  97. package/src/engine/engine_license.ts +72 -72
  98. package/src/engine/engine_loaders.gltf.ts +8 -2
  99. package/src/engine/engine_materialpropertyblock.ts +21 -0
  100. package/src/engine/engine_networking.ts +2 -2
  101. package/src/engine/engine_networking_blob.ts +3 -3
  102. package/src/engine/engine_physics.ts +22 -1
  103. package/src/engine/engine_utils_qrcode.ts +2 -2
  104. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
  105. package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
  106. package/src/engine/webcomponents/needle-engine.loading.ts +6 -6
  107. package/src/engine/webcomponents/needle-engine.ts +2 -2
  108. package/src/engine/xr/NeedleXRSession.ts +11 -10
  109. package/src/engine/xr/TempXRContext.ts +2 -2
  110. package/src/engine-components/AnimationBuilder.ts +1 -1
  111. package/src/engine-components/AnimatorController.builder.ts +4 -4
  112. package/src/engine-components/Component.ts +1 -1
  113. package/src/engine-components/DragControls.ts +2 -3
  114. package/src/engine-components/DragControlsConstraints.ts +1 -2
  115. package/src/engine-components/Light.ts +1 -1
  116. package/src/engine-components/api.ts +2 -2
  117. package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
  118. package/src/engine-components/export/usdz/extensions/behavior/BehaviourComponents.ts +1 -1
  119. package/src/engine-components/postprocessing/index.ts +1 -1
  120. package/src/engine-components/timeline/TimelineBuilder.ts +5 -5
  121. package/src/engine-components/timeline/TimelineTracks.ts +25 -17
  122. package/src/engine-components/webxr/WebXRImageTracking.utils.ts +0 -1
  123. package/dist/gltf-progressive-BnLTsXZw.umd.cjs +0 -10
  124. package/dist/gltf-progressive-D6RT9IkB.min.js +0 -10
@@ -111,19 +111,20 @@ async function handleSessionGranted() {
111
111
  // wasn't granted it), XR can't run here — skip the probe so we don't log a
112
112
  // Permissions-Policy violation on load.
113
113
  if (!isXrSpatialTrackingAllowed()) return;
114
- // In app clips we default to AR
114
+ // An App Clip has already granted AR. Register its sessiongranted listener
115
+ // synchronously: awaiting a support probe here can miss the native event.
115
116
  if (DeviceUtilities.isNeedleAppClip()) {
116
117
  defaultMode = "immersive-ar";
117
118
  }
118
- // Check if VR is even supported, otherwise try AR
119
- else if (!(await navigator.xr?.isSessionSupported("immersive-vr"))) {
120
- defaultMode = "immersive-ar";
121
- }
122
- // Check if AR is supported, otherwise we can't do anything
123
- if (!(await navigator.xr?.isSessionSupported("immersive-ar")) && defaultMode === "immersive-ar") {
124
- // console.warn("[NeedleXRSession:granted] Neither VR nor AR supported, aborting session start.");
125
- // showBalloonMessage("NeidleXRSession: Neither VR nor AR supported, aborting session start.");
126
- return;
119
+ else {
120
+ // Check if VR is even supported, otherwise try AR.
121
+ if (!(await navigator.xr?.isSessionSupported("immersive-vr"))) {
122
+ defaultMode = "immersive-ar";
123
+ }
124
+ // Check if AR is supported, otherwise we can't do anything.
125
+ if (defaultMode === "immersive-ar" && !(await navigator.xr?.isSessionSupported("immersive-ar"))) {
126
+ return;
127
+ }
127
128
  }
128
129
  } catch (e) {
129
130
  console.debug("[NeedleXRSession:granted] Error while checking XR support:", e);
@@ -3,7 +3,7 @@ import { ArrayCamera, AxesHelper, Camera, Color, DirectionalLight, Fog, GridHelp
3
3
  import { needleLogoOnlySVG } from "../assets/index.js";
4
4
  import { isDevEnvironment } from "../debug/index.js";
5
5
  import { ObjectUtils, PrimitiveType } from "../engine_create_objects.js";
6
- import { __PemN } from "../engine_license.js";
6
+ import { _RUUSWrG } from "../engine_license.js";
7
7
  import { Mathf } from "../engine_math.js";
8
8
  import { delay, DeviceUtilities } from "../engine_utils.js";
9
9
 
@@ -215,7 +215,7 @@ export class TemporaryXRContext {
215
215
  this._scene.background = new Color(0x000000);
216
216
 
217
217
  let logoSrc = needleLogoOnlySVG;
218
- if (__PemN()) {
218
+ if (_RUUSWrG()) {
219
219
  const htmlComponent = document.querySelector("needle-engine");
220
220
  if (htmlComponent) {
221
221
  const licenseLogo = htmlComponent.getAttribute("logo-src");
@@ -1,8 +1,8 @@
1
+ import type { Camera, InterpolationModes, Light, Material, PerspectiveCamera } from "three";
1
2
  import { AnimationClip, BooleanKeyframeTrack, Color, ColorKeyframeTrack, Euler,
2
3
  InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack,
3
4
  NumberKeyframeTrack, Object3D, Quaternion, QuaternionKeyframeTrack,
4
5
  Vector3, VectorKeyframeTrack } from "three";
5
- import type { Camera, InterpolationModes, Light, Material, PerspectiveCamera } from "three";
6
6
 
7
7
  import { isDevEnvironment } from "../engine/debug/index.js";
8
8
 
@@ -1,11 +1,11 @@
1
- import { AnimationClip, Object3D } from "three";
2
1
  import type { Light, Material, PerspectiveCamera } from "three";
2
+ import { AnimationClip, Object3D } from "three";
3
3
 
4
- import { AnimatorConditionMode, AnimatorControllerParameterType } from "../engine/extensions/NEEDLE_animator_controller_model.js";
5
- import type { AnimatorControllerModel, Condition, Parameter, State, Transition } from "../engine/extensions/NEEDLE_animator_controller_model.js";
6
4
  import { InstantiateIdProvider } from "../engine/engine_networking_instantiate.js";
5
+ import type { AnimatorControllerModel, Condition, Parameter, State, Transition } from "../engine/extensions/NEEDLE_animator_controller_model.js";
6
+ import { AnimatorConditionMode, AnimatorControllerParameterType } from "../engine/extensions/NEEDLE_animator_controller_model.js";
7
+ import { type AnimationKeyframe, type ColorValue,type EulerValue, type QuatValue, resolveClipSource, track as trackFn, type TrackDescriptor, type TrackOptions, type Tween, type Vec3Value } from "./AnimationBuilder.js";
7
8
  import { AnimatorController } from "./AnimatorController.js";
8
- import { resolveClipSource, track as trackFn, type TrackDescriptor, type TrackOptions, type AnimationKeyframe, type Tween, type Vec3Value, type QuatValue, type EulerValue, type ColorValue } from "./AnimationBuilder.js";
9
9
 
10
10
  /** Keyframe array or tween shorthand */
11
11
  type KF<V> = AnimationKeyframe<V>[] | Tween<V>;
@@ -4,6 +4,7 @@ import { isDevEnvironment } from "../engine/debug/index.js";
4
4
  import { type AssetReference } from "../engine/engine_addressables.js";
5
5
  import { addComponent, destroyComponentInstance, findObjectOfType, findObjectsOfType, getComponent, getComponentInChildren, getComponentInParent, getComponents, getComponentsInChildren, getComponentsInParent, getOrAddComponent, removeComponent } from "../engine/engine_components.js";
6
6
  import { activeInHierarchyFieldName } from "../engine/engine_constants.js";
7
+ import { DisposableStore, type DisposeFn,type IDisposable } from "../engine/engine_disposable.js";
7
8
  import { destroy, findByGuid, foreachComponent, type IInstantiateOptions, instantiate, isActiveInHierarchy, isActiveSelf, isDestroyed, isUsingInstancing, markAsInstancedRendered, setActive } from "../engine/engine_gameobject.js";
8
9
  import { isHotReloadEnabled, registerHotReloadType, unregisterHotReloadType } from "../engine/engine_hot_reload.js";
9
10
  import * as main from "../engine/engine_mainloop_utils.js";
@@ -13,7 +14,6 @@ import * as threeutils from "../engine/engine_three_utils.js";
13
14
  import { $componentName, type Collision, type ComponentInit, type Constructor, type ConstructorConcrete, type ICollider, type IComponent, type IGameObject, type SourceIdentifier } from "../engine/engine_types.js";
14
15
  import { TypeStore } from "../engine/engine_typestore.js";
15
16
  import type { INeedleXRSessionEventReceiver, NeedleXRControllerEventArgs, NeedleXREventArgs } from "../engine/engine_xr.js";
16
- import { DisposableStore, type IDisposable, type DisposeFn } from "../engine/engine_disposable.js";
17
17
  import { type IPointerEventHandler, PointerEventData } from "./ui/PointerEvents.js";
18
18
 
19
19
 
@@ -1,9 +1,7 @@
1
1
  import { AxesHelper, Box3, Euler, Matrix4, Object3D, Plane, Quaternion, Ray, Vector3 } from "three";
2
2
 
3
3
  export type { IDragConstraint, IDragConstraintContext } from "./DragControlsConstraints.js";
4
- export { AxisRotationConstraint, GridSnapConstraint, GrabPointPlaneConstraint, KeepRotationConstraint, KeepScaleConstraint, ScaleLimitConstraint, RotationAxis, FixedRotationAxesConstraint, PlaneHeightLockConstraint, SnapToSurfaceConstraint, applyFollowObjectConstraints } from "./DragControlsConstraints.js";
5
- import { IDragConstraint, IDragConstraintContext, AxisRotationConstraint, GridSnapConstraint, GrabPointPlaneConstraint, KeepRotationConstraint, ScaleLimitConstraint, FixedRotationAxesConstraint, PlaneHeightLockConstraint, SnapToSurfaceConstraint, applyFollowObjectConstraints } from "./DragControlsConstraints.js";
6
-
4
+ export { applyFollowObjectConstraints,AxisRotationConstraint, FixedRotationAxesConstraint, GrabPointPlaneConstraint, GridSnapConstraint, KeepRotationConstraint, KeepScaleConstraint, PlaneHeightLockConstraint, RotationAxis, ScaleLimitConstraint, SnapToSurfaceConstraint } from "./DragControlsConstraints.js";
7
5
  import { Gizmos } from "../engine/engine_gizmos.js";
8
6
  import { InstancingUtil } from "../engine/engine_instancing.js";
9
7
  import { Mathf } from "../engine/engine_math.js";
@@ -14,6 +12,7 @@ import { type IGameObject } from "../engine/engine_types.js";
14
12
  import { getParam } from "../engine/engine_utils.js";
15
13
  import { NeedleXRSession } from "../engine/engine_xr.js";
16
14
  import { Behaviour, GameObject } from "./Component.js";
15
+ import { applyFollowObjectConstraints,AxisRotationConstraint, FixedRotationAxesConstraint, GrabPointPlaneConstraint, GridSnapConstraint, IDragConstraint, IDragConstraintContext, KeepRotationConstraint, PlaneHeightLockConstraint, ScaleLimitConstraint, SnapToSurfaceConstraint } from "./DragControlsConstraints.js";
17
16
  import { EventList } from "./EventList.js";
18
17
  import { UsageMarker } from "./Interactable.js";
19
18
  import { Rigidbody } from "./RigidBody.js";
@@ -1,9 +1,8 @@
1
1
  import { Box3, Euler, Object3D, Plane, Quaternion, Ray, Vector3 } from "three";
2
2
 
3
3
  import type { Context } from "../engine/engine_setup.js";
4
-
5
- import { GameObject } from "./Component.js";
6
4
  import type { IGameObject } from "../engine/engine_types.js";
5
+ import { GameObject } from "./Component.js";
7
6
 
8
7
  // #region Interfaces
9
8
  /**
@@ -1,12 +1,12 @@
1
1
  import { CameraHelper, Color, DirectionalLight, DirectionalLightHelper, Light as ThreeLight, OrthographicCamera, PointLight, SpotLight, Vector3 } from "three";
2
2
 
3
+ import { isDevEnvironment } from "../engine/debug/index.js";
3
4
  import { serializable } from "../engine/engine_serialization_decorator.js";
4
5
  import { setWorldPositionXYZ } from "../engine/engine_three_utils.js";
5
6
  import type { ILight } from "../engine/engine_types.js";
6
7
  import { getParam } from "../engine/engine_utils.js";
7
8
  import type { NeedleXREventArgs } from "../engine/xr/api.js";
8
9
  import { Behaviour, GameObject } from "./Component.js";
9
- import { isDevEnvironment } from "../engine/debug/index.js";
10
10
 
11
11
  // https://threejs.org/examples/webgl_shadowmap_csm.html
12
12
 
@@ -34,7 +34,7 @@
34
34
  * @module Built-in Components
35
35
  */
36
36
 
37
- export { AnimationBuilder, type AnimationKeyframe, type Tween, type AnimationInterpolation } from "./AnimationBuilder.js";
37
+ export { AnimationBuilder, type AnimationInterpolation,type AnimationKeyframe, type Tween } from "./AnimationBuilder.js";
38
38
  export { AnimatorControllerBuilder, type ConditionMode, type StateOptions, type TransitionOptions } from "./AnimatorController.builder.js";
39
39
  export * from "./codegen/components.js";
40
40
  export { Collider } from "./Collider.js"; // export abstract type
@@ -44,11 +44,11 @@ export { Behaviour, Component, GameObject } from "./Component.js";
44
44
  export { AudioRolloffMode } from "./AudioSource.js";
45
45
  export { ClearFlags } from "./Camera.js"
46
46
  export { DragMode } from "./DragControls.js";
47
- export { ShadowCastingMode, ReflectionProbeUsage } from "./Renderer.js";
48
47
  export type { DropListenerNetworkEventArguments, DropListenerOnDropArguments } from "./DropListener.js";
49
48
  export * from "./export/index.js"
50
49
  export * from "./particlesystem/api.js"
51
50
  export * from "./postprocessing/index.js"
51
+ export { ReflectionProbeUsage,ShadowCastingMode } from "./Renderer.js";
52
52
  export { type ISceneEventListener } from "./SceneSwitcher.js";
53
53
  export * from "./splines/index.js";
54
54
  export * from "./timeline/index.js"
@@ -3,7 +3,7 @@ import { Euler, Material, Matrix4, Mesh, Object3D, Quaternion, Vector3 } from "t
3
3
 
4
4
  import { isDevEnvironment, showBalloonMessage, showBalloonWarning } from "../../../engine/debug/index.js";
5
5
  import { findObjectOfType } from "../../../engine/engine_components.js";
6
- import { __csRKN } from "../../../engine/engine_license.js";
6
+ import { __iOMsPxgl } from "../../../engine/engine_license.js";
7
7
  import { serializable } from "../../../engine/engine_serialization.js";
8
8
  import { getFormattedDate, Progress } from "../../../engine/engine_time_utils.js";
9
9
  import { DeviceUtilities, getParam } from "../../../engine/engine_utils.js";
@@ -277,7 +277,7 @@ export class USDZExporter extends Behaviour {
277
277
  let name = this.exportFileName ?? this.objectToExport?.name ?? this.name;
278
278
  name += "-" + getFormattedDate(); // seems iOS caches the file in some cases, this ensures we always have a fresh file
279
279
 
280
- if (!__csRKN()) {
280
+ if (!__iOMsPxgl()) {
281
281
  if (name !== "") name += "-";
282
282
  name += "MadeWithNeedle";
283
283
  }
@@ -682,7 +682,7 @@ export class USDZExporter extends Behaviour {
682
682
  if (debug)
683
683
  showBalloonMessage("Quicklook url: " + callToActionURL);
684
684
  if (callToActionURL) {
685
- if (!__csRKN()) {
685
+ if (!__iOMsPxgl()) {
686
686
  console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing", callToActionURL)
687
687
  }
688
688
  else {
@@ -697,7 +697,7 @@ export class USDZExporter extends Behaviour {
697
697
  private buildQuicklookOverlay(): CustomBranding {
698
698
  const obj: CustomBranding = {};
699
699
  if (this.customBranding) Object.assign(obj, this.customBranding);
700
- if (!__csRKN()) {
700
+ if (!__iOMsPxgl()) {
701
701
  console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing");
702
702
  obj.callToAction = "Close";
703
703
  obj.checkoutTitle = "🌵 Made with Needle";
@@ -3,6 +3,7 @@ import { AnimationClip, Material, Matrix4, Mesh, Object3D, Quaternion, Vector3 }
3
3
  import { isDevEnvironment, showBalloonWarning } from "../../../../../engine/debug/index.js";
4
4
  import { serializable } from "../../../../../engine/engine_serialization_decorator.js";
5
5
  import { getWorldPosition, getWorldQuaternion, getWorldScale, setWorldPosition, setWorldQuaternion, setWorldScale } from "../../../../../engine/engine_three_utils.js";
6
+ import type { ComponentInit } from "../../../../../engine/engine_types.js";
6
7
  import { getParam } from "../../../../../engine/engine_utils.js";
7
8
  import { compareAssociation } from "../../../../../engine/extensions/extension_utils.js";
8
9
  import type { State } from "../../../../../engine/extensions/NEEDLE_animator_controller_model.js";
@@ -11,7 +12,6 @@ import { Animation } from "../../../../Animation.js";
11
12
  import { Animator } from "../../../../Animator.js";
12
13
  import { AudioSource } from "../../../../AudioSource.js";
13
14
  import { Behaviour, GameObject } from "../../../../Component.js";
14
- import type { ComponentInit } from "../../../../../engine/engine_types.js";
15
15
  import { Rigidbody } from "../../../../RigidBody.js";
16
16
  import type { IPointerClickHandler, PointerEventData } from "../../../../ui/PointerEvents.js";
17
17
  import { makeNameSafeForUSD, USDDocument, USDObject, USDZExporterContext } from "../../ThreeUSDZExporter.js";
@@ -4,8 +4,8 @@ export { PostProcessingEffectOrder } from "./utils.js";
4
4
  /* Effect option enums. The effect components themselves are exported from
5
5
  codegen/components.ts, but these were unreachable: `DepthOfField.mode`
6
6
  could not be set to a named value from outside the package. */
7
- export { DepthOfFieldMode } from "./Effects/DepthOfField.js";
8
7
  export { QualityLevel } from "./Effects/Antialiasing.js";
8
+ export { DepthOfFieldMode } from "./Effects/DepthOfField.js";
9
9
  export { ScreenSpaceAmbientOcclusionN8QualityMode } from "./Effects/ScreenspaceAmbientOcclusionN8.js";
10
10
  export { NEToneMappingMode } from "./Effects/Tonemapping.utils.js";
11
11
  export { PostProcessingManager } from "./Volume.js"
@@ -1,19 +1,19 @@
1
- import { AnimationClip, Object3D } from "three";
2
1
  import type { Light, Material, PerspectiveCamera } from "three";
2
+ import { AnimationClip, Object3D } from "three";
3
3
 
4
+ import { InstantiateIdProvider } from "../../engine/engine_networking_instantiate.js";
5
+ import { type AnimationKeyframe, type ColorValue,type EulerValue, isTrackDescriptor, type QuatValue, resolveToClip, track as trackFn, type TrackDescriptor, type TrackOptions, type Tween, type Vec3Value } from "../AnimationBuilder.js";
4
6
  import type { Animator } from "../Animator.js";
5
7
  import type { AudioSource } from "../AudioSource.js";
6
8
  import { GameObject } from "../Component.js";
7
- import { InstantiateIdProvider } from "../../engine/engine_networking_instantiate.js";
8
9
  import { EventList } from "../EventList.js";
9
- import { isTrackDescriptor, resolveToClip, track as trackFn, type TrackDescriptor, type TrackOptions, type AnimationKeyframe, type Tween, type Vec3Value, type QuatValue, type EulerValue, type ColorValue } from "../AnimationBuilder.js";
10
10
 
11
11
  /** Keyframe array or tween shorthand */
12
12
  type KF<V> = AnimationKeyframe<V>[] | Tween<V>;
13
- import { SignalAsset, SignalReceiver, SignalReceiverEvent } from "./SignalAsset.js";
14
13
  import type { PlayableDirector } from "./PlayableDirector.js";
14
+ import { SignalAsset, SignalReceiver, SignalReceiverEvent } from "./SignalAsset.js";
15
+ import type { AnimationClipModel, AudioClipModel, ClipModel, ControlClipModel, MarkerModel, SignalMarkerModel, TimelineAssetModel, TrackModel, TrackOffset } from "./TimelineModels.js";
15
16
  import { ClipExtrapolation, TrackType } from "./TimelineModels.js";
16
- import type { TimelineAssetModel, TrackModel, ClipModel, AnimationClipModel, AudioClipModel, ControlClipModel, MarkerModel, SignalMarkerModel, TrackOffset } from "./TimelineModels.js";
17
17
  import { MarkerType } from "./TimelineModels.js";
18
18
 
19
19
  /**
@@ -1,6 +1,7 @@
1
1
  import { AnimationAction, AnimationClip, AnimationMixer, Audio, AudioListener, AudioLoader, Euler, Object3D, Quaternion, QuaternionKeyframeTrack, Vector3, VectorKeyframeTrack } from "three";
2
2
 
3
3
  import { isDevEnvironment } from "../../engine/debug/index.js";
4
+ import { AnimationUtils } from "../../engine/engine_animation.js";
4
5
  import { Context } from "../../engine/engine_setup.js";
5
6
  import type { Constructor } from "../../engine/engine_types.js";
6
7
  import { getParam, resolveUrl } from "../../engine/engine_utils.js";
@@ -9,9 +10,8 @@ import { AudioSource } from "../AudioSource.js";
9
10
  import { GameObject } from "../Component.js";
10
11
  import type { PlayableDirector } from "./PlayableDirector.js";
11
12
  import { SignalReceiver } from "./SignalAsset.js";
12
- import * as Models from "./TimelineModels.js";
13
13
  import type { TimelineBuilder } from "./TimelineBuilder.js";
14
- import { AnimationUtils } from "../../engine/engine_animation.js";
14
+ import * as Models from "./TimelineModels.js";
15
15
 
16
16
  const debug = getParam("debugtimeline");
17
17
 
@@ -722,6 +722,20 @@ export class TimelineAudioTrack extends TimelineTrackHandler {
722
722
  audio.playbackRate = this.director.context.time.timeScale * this.director.speed;
723
723
  audio.loop = asset.loop;
724
724
  if (time >= model.start && time <= model.end && time < this.director.duration) {
725
+ let vol = asset.volume as number;
726
+ if (this.track.volume !== undefined)
727
+ vol *= this.track.volume;
728
+ if (isMuted) vol = 0;
729
+ if (model.easeInDuration > 0) {
730
+ const easeIn = Math.min((time - model.start) / model.easeInDuration, 1);
731
+ vol *= easeIn;
732
+ }
733
+ if (model.easeOutDuration > 0) {
734
+ const easeOut = Math.min((model.end - time) / model.easeOutDuration, 1);
735
+ vol *= easeOut;
736
+ }
737
+ vol *= this.director.weight;
738
+
725
739
  if (!audio.isPlaying || !this.director.isPlaying) {
726
740
  // if the timeline is paused we trigger the audio clip once when the model is entered
727
741
  // we dont playback the audio clip if we scroll back in time
@@ -733,6 +747,11 @@ export class TimelineAudioTrack extends TimelineTrackHandler {
733
747
  audio.offset = model.clipIn + (time - model.start) * model.timeScale;
734
748
  else audio.offset = 0;
735
749
  if (debug) console.log("Timeline Audio (" + this.track.name + ") play with offset " + audio.offset + " - " + model.asset.clip);
750
+ // Audio.setVolume() fades over 10 ms. Set the initial gain immediately
751
+ // before starting the source so short muted clips cannot be heard.
752
+ const gain = audio.gain.gain;
753
+ gain.cancelScheduledValues(audio.context.currentTime);
754
+ gain.setValueAtTime(vol, audio.context.currentTime);
736
755
  audio.play(playTimeOffset);
737
756
  model._didTriggerPlay = true;
738
757
  }
@@ -750,24 +769,13 @@ export class TimelineAudioTrack extends TimelineTrackHandler {
750
769
  if (diff > 0.3) {
751
770
  audio.offset = targetOffset;
752
771
  audio.stop();
772
+ const gain = audio.gain.gain;
773
+ gain.cancelScheduledValues(audio.context.currentTime);
774
+ gain.setValueAtTime(vol, audio.context.currentTime);
753
775
  audio.play(playTimeOffset);
754
776
  }
755
777
  }
756
- let vol = asset.volume as number;
757
-
758
- if (this.track.volume !== undefined)
759
- vol *= this.track.volume;
760
-
761
- if (isMuted) vol = 0;
762
- if (model.easeInDuration > 0) {
763
- const easeIn = Math.min((time - model.start) / model.easeInDuration, 1);
764
- vol *= easeIn;
765
- }
766
- if (model.easeOutDuration > 0) {
767
- const easeOut = Math.min((model.end - time) / model.easeOutDuration, 1);
768
- vol *= easeOut;
769
- }
770
- audio.setVolume(vol * this.director.weight);
778
+ audio.setVolume(vol);
771
779
  }
772
780
  else {
773
781
  model._didTriggerPlay = false;
@@ -1,6 +1,5 @@
1
1
  import { isDevEnvironment } from "../../engine/debug/index.js";
2
2
  import { getParam } from "../../engine/engine_utils.js";
3
-
4
3
  import type { WebXRImageTrackingModel } from "./WebXRImageTracking.js";
5
4
 
6
5
  // Kept in a dedicated module (with only lightweight imports) so the marker-loading logic can be unit
@@ -1,10 +0,0 @@
1
- "use strict";const f=require("./three-core.umd.cjs"),Z=require("./three-examples.umd.cjs");var fe=typeof document<"u"?document.currentScript:null;const Ne="";globalThis.GLTF_PROGRESSIVE_VERSION=Ne;console.debug("[gltf-progressive] version -");let $="https://www.gstatic.com/draco/versioned/decoders/1.5.7/",K="https://cdn.needle.tools/static/three/0.179.1/basis2/";const Xe=$,je=K,Ie=new URL($+"draco_decoder.js");Ie.searchParams.append("range","true");fetch(Ie,{method:"GET",headers:{Range:"bytes=0-1"}}).catch(o=>{console.debug(`Failed to fetch remote Draco decoder from ${$} (offline: ${typeof navigator<"u"?navigator.onLine:"unknown"})`),$===Xe&&Ge("./include/draco/"),K===je&&$e("./include/ktx2/")}).finally(()=>{Be()});const Ke=()=>({dracoDecoderPath:$,ktx2TranscoderPath:K});function Ge(o){$=o,P&&P[xe]!=$?(console.debug("Updating Draco decoder path to "+o),P[xe]=$,P.setDecoderPath($),P.preload()):console.debug("Setting Draco decoder path to "+o)}function $e(o){K=o,B&&B.transcoderPath!=K?(console.debug("Updating KTX2 transcoder path to "+o),B.setTranscoderPath(K),B.init()):console.debug("Setting KTX2 transcoder path to "+o)}function ce(o){return Be(),o?B.detectSupport(o):o!==null&&console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures might fail"),{dracoLoader:P,ktx2Loader:B,meshoptDecoder:ue}}function Me(o){o.dracoLoader||o.setDRACOLoader(P),o.ktx2Loader||o.setKTX2Loader(B),o.meshoptDecoder||o.setMeshoptDecoder(ue)}const xe=Symbol("dracoDecoderPath");let P,ue,B;function Be(){P||(P=new Z.DRACOLoader,P[xe]=$,P.setDecoderPath($),P.setDecoderConfig({type:"js"}),P.preload()),B||(B=new Z.KTX2Loader,B.setTranscoderPath(K),B.init()),ue||(ue=Z.MeshoptDecoder)}const Le=new WeakMap;function _e(o,t){let e=Le.get(o);e?e=Object.assign(e,t):e=t,Le.set(o,e)}const He=Z.GLTFLoader.prototype.load;function Ye(...o){const t=Le.get(this);let e=o[0];const s=Qe(e);if(s?.hostname.endsWith("needle.tools")){const n=t?.progressive!==void 0?t.progressive:!0,i=t?.usecase?t.usecase:"default";n?this.requestHeader.Accept=`*/*;progressive=allowed;usecase=${i}`:this.requestHeader.Accept=`*/*;usecase=${i}`,e=s.toString()}return o[0]=e,He?.call(this,...o)}Z.GLTFLoader.prototype.load=Ye;function Qe(o){try{if(o instanceof URL)return o;const t=globalThis.location?.href;return t?new URL(o,t):new URL(o)}catch{return null}}function be(o){return o!=null&&o.data!=null}function we(o){const t=o.source?.data;return t!=null&&typeof t=="object"?t:null}function Je(o){const t=o.image;return t!=null&&typeof t=="object"?t:null}function De(o){const t=Je(o),e=we(o);return{width:t?.width||e?.width||0,height:t?.height||e?.height||0}}V("debugprogressive");function V(o){const t=globalThis.location?.href;if(!t)return!1;const s=new URL(t).searchParams.get(o);return s==null||s==="0"||s==="false"?!1:s===""?!0:s}function Ze(o,t){if(t===void 0||o===void 0||t.startsWith("./")||t.startsWith("http")||t.startsWith("data:")||t.startsWith("blob:"))return t;const e=o.lastIndexOf("/");if(e>=0){const s=o.substring(0,e+1);for(;s.endsWith("/")&&t.startsWith("/");)t=t.substring(1);return s+t}return t}function Te(){if(te!==void 0)return te;const o=globalThis.navigator?.userAgent||"";return te=/iPhone|iPad|iPod|Android|IEMobile/i.test(o),V("debugprogressive")&&console.log("[glTF Progressive]: isMobileDevice",te),te}let te;function qe(){const o=globalThis.location?.href;if(!o)return!1;const t=new URL(o),e=t.hostname==="localhost"||/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t.hostname);return t.hostname==="127.0.0.1"||e}class et{constructor(t,e={}){this.maxConcurrent=t,this.debug=e.debug??!1,typeof globalThis.requestAnimationFrame=="function"?globalThis.requestAnimationFrame(this.tick):setTimeout(this.tick,0)}_running=new Map;_queue=[];debug=!1;tick=()=>{this.internalUpdate(),setTimeout(this.tick,10)};slot(t){return this.debug&&console.debug(`[PromiseQueue]: Requesting slot for key ${t}, running: ${this._running.size}, waiting: ${this._queue.length}`),new Promise(e=>{this._queue.push({key:t,resolve:e})})}add(t,e){this._running.has(t)||(this._running.set(t,e),e.finally(()=>{this._running.delete(t),this.debug&&console.debug(`[PromiseQueue]: Promise finished now running: ${this._running.size}, waiting: ${this._queue.length}. (finished ${t})`)}),this.debug&&console.debug(`[PromiseQueue]: Added new promise, now running: ${this._running.size}, waiting: ${this._queue.length}. (added ${t})`))}internalUpdate(){const t=this.maxConcurrent-this._running.size;for(let e=0;e<t&&this._queue.length>0;e++){this.debug&&console.debug(`[PromiseQueue]: Running ${this._running.size} promises, waiting for ${this._queue.length} more.`);const{key:s,resolve:r}=this._queue.shift();r({use:n=>this.add(s,n)})}}}function tt(o){const t=o.image,e=t?.width??0,s=t?.height??0,r=t?.depth??1,n=Math.floor(Math.log2(Math.max(e,s,r)))+1,i=st(o);return e*s*r*i*(1-Math.pow(.25,n))/(1-.25)}function st(o){let t=4;const e=o.format;e===f.RedFormat||e===f.RedIntegerFormat?t=1:e===f.RGFormat||e===f.RGIntegerFormat?t=2:e===f.RGBFormat||e===1029?t=3:(e===f.RGBAFormat||e===f.RGBAIntegerFormat)&&(t=4);let s=1;const r=o.type;return r===1009||r===1010?s=1:r===1011||r===1012?s=2:r===1013||r===1014||r===1015?s=4:r===1016&&(s=2),t*s}const rt=typeof window>"u"&&typeof document>"u",ve=Symbol("needle:raycast-mesh");function ee(o){return o?.[ve]instanceof f.BufferGeometry?o[ve]:null}function nt(o,t){if((o.type==="Mesh"||o.type==="SkinnedMesh")&&!ee(o)){const s=it(t);s.userData={isRaycastMesh:!0},o[ve]=s}}function ot(o=!0){if(o){if(se)return;const t=se=f.Mesh.prototype.raycast;f.Mesh.prototype.raycast=function(e,s){const r=this,n=ee(r);let i;n&&r.isMesh&&(i=r.geometry,r.geometry=n),t.call(this,e,s),i&&(r.geometry=i)}}else{if(!se)return;f.Mesh.prototype.raycast=se,se=null}}let se=null;function it(o){const t=new f.BufferGeometry;for(const e in o.attributes)t.setAttribute(e,o.getAttribute(e));return t.setIndex(o.getIndex()),t}const F=new Array,p=V("debugprogressive");let oe,X=-1;if(p&&typeof window<"u"){let o=function(){X+=1,X>=t&&(X=-1),console.log(`Toggle LOD level [${X}]`)};const t=6;window.addEventListener("keyup",e=>{e.key==="p"&&o(),e.key==="w"&&(oe=!oe,console.log(`Toggle wireframe [${oe}]`));const s=parseInt(e.key);!isNaN(s)&&s>=0&&(X=s,console.log(`Set LOD level to [${X}]`))})}function Fe(o){if(p&&oe!==void 0)if(Array.isArray(o))for(const t of o)Fe(t);else o&&"wireframe"in o&&(o.wireframe=oe===!0)}const re=new Array;let at=0;const lt=Te()?2:10;function ut(o){if(re.length<lt){const s=re.length;p&&console.warn(`[Worker] Creating new worker #${s}`);const r=Oe.createWorker(o||{});return re.push(r),r}const t=at++%re.length;return re[t]}class Oe{constructor(t,e){this.worker=t,this._debug=e.debug??!1,t.onmessage=s=>{const r=s.data;switch(this._debug&&console.log("[Worker] EVENT",r),r.type){case"loaded-gltf":for(const n of this._running)if(n.url===r.result.url){ct(r.result),n.resolve(r.result);const i=n.url;i.startsWith("blob:")&&URL.revokeObjectURL(i)}}},t.onerror=s=>{console.error("[Worker] Error in gltf-progressive worker:",s)},t.postMessage({type:"init"})}static async createWorker(t){const e=new Worker(new URL("/gltf-progressive.worker-BqODMeeW.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:fe&&fe.tagName.toUpperCase()==="SCRIPT"&&fe.src||new URL("gltf-progressive-BnLTsXZw.umd.cjs",document.baseURI).href),{type:"module"});return new Oe(e,t)}_running=[];_webglRenderer=null;async load(t,e){const s=Ke();let r=e?.renderer;r||(this._webglRenderer??=(async()=>{const{WebGLRenderer:u}=await Promise.resolve().then(()=>require("./three-core.umd.cjs")).then(h=>h.THREE);return new u})(),r=await this._webglRenderer);const l=ce(r).ktx2Loader.workerConfig;if(t instanceof URL)t=t.toString();else if(t.startsWith("file:"))t=URL.createObjectURL(new Blob([t]));else if(!t.startsWith("blob:")&&!t.startsWith("http:")&&!t.startsWith("https:")){const u=globalThis.location?.href;u&&(t=new URL(t,u).toString())}const a={type:"load",url:t,dracoDecoderPath:s.dracoDecoderPath,ktx2TranscoderPath:s.ktx2TranscoderPath,ktx2LoaderConfig:l};return this._debug&&console.debug("[Worker] Sending load request",a),this.worker.postMessage(a),new Promise(u=>{this._running.push({url:t.toString(),resolve:u})})}_debug=!1}function ct(o){for(const t of o.geometries){const e=t.geometry,s=new f.BufferGeometry;if(s.name=e.name||"",e.index){const r=e.index;s.setIndex(de(r))}for(const r in e.attributes){const n=e.attributes[r],i=de(n);s.setAttribute(r,i)}if(e.morphAttributes)for(const r in e.morphAttributes){const i=e.morphAttributes[r].map(l=>de(l));s.morphAttributes[r]=i}if(s.morphTargetsRelative=e.morphTargetsRelative??!1,s.boundingBox=new f.Box3,s.boundingBox.min=new f.Vector3(e.boundingBox?.min.x,e.boundingBox?.min.y,e.boundingBox?.min.z),s.boundingBox.max=new f.Vector3(e.boundingBox?.max.x,e.boundingBox?.max.y,e.boundingBox?.max.z),s.boundingSphere=new f.Sphere(new f.Vector3(e.boundingSphere?.center.x,e.boundingSphere?.center.y,e.boundingSphere?.center.z),e.boundingSphere?.radius),e.groups)for(const r of e.groups)s.addGroup(r.start,r.count,r.materialIndex);e.userData&&(s.userData=e.userData),t.geometry=s}for(const t of o.textures){const e=t.texture;let s=null;if(e.isCompressedTexture){const r=e.mipmaps,{width:n,height:i}=De(e);s=new f.CompressedTexture(r,n,i,e.format,e.type,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.anisotropy,e.colorSpace)}else s=new f.Texture(e.image,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),s.mipmaps=e.mipmaps,s.channel=e.channel,s.source.data=e.source.data,s.flipY=e.flipY,s.premultiplyAlpha=e.premultiplyAlpha,s.unpackAlignment=e.unpackAlignment,s.matrix=new f.Matrix3(...e.matrix.elements);if(!s){console.error("[Worker] Failed to create new texture from received data. Texture is not a CompressedTexture or Texture.");continue}t.texture=s}return o}function de(o){let t=o;if("isInterleavedBufferAttribute"in o&&o.isInterleavedBufferAttribute){const e=o.data,s=e.array,r=new f.InterleavedBuffer(s,e.stride);t=new f.InterleavedBufferAttribute(r,o.itemSize,s.byteOffset,o.normalized),t.offset=o.offset}else"isBufferAttribute"in o&&o.isBufferAttribute&&(t=new f.BufferAttribute(o.array,o.itemSize,o.normalized),t.usage=o.usage,t.gpuType=o.gpuType,t.updateRanges=o.updateRanges);return t}const ft=V("gltf-progressive-worker");V("gltf-progressive-reduce-mipmaps");const ne=V("gltf-progressive-gc"),he=Symbol("needle-progressive-texture"),W="NEEDLE_progressive";class m{get name(){return W}static getMeshLODExtension(t){const e=this.getAssignedLODInformation(t);return e?.key?this.lodInfos.get(e.key):null}static getPrimitiveIndex(t){const e=this.getAssignedLODInformation(t)?.index;return e??-1}static getMaterialMinMaxLODsCount(t,e){const s=this,r="LODS:minmax",n=t[r];if(n!=null)return n;if(e||(e={min_count:1/0,max_count:0,lods:[]}),Array.isArray(t)){for(const l of t)this.getMaterialMinMaxLODsCount(l,e);return t[r]=e,e}if(p==="verbose"&&console.log("getMaterialMinMaxLODsCount",t),t.type==="ShaderMaterial"||t.type==="RawShaderMaterial"){const l=t;for(const a of Object.keys(l.uniforms)){const u=l.uniforms[a].value;u?.isTexture===!0&&i(u,e)}}else if(t.isMaterial)for(const l of Object.keys(t)){const a=t[l];a?.isTexture===!0&&i(a,e)}else p&&console.warn(`[getMaterialMinMaxLODsCount] Unsupported material type: ${t.type}`);return t[r]=e,e;function i(l,a){const u=s.getAssignedLODInformation(l);if(u){const h=s.lodInfos.get(u.key);if(h&&h.lods){a.min_count=Math.min(a.min_count,h.lods.length),a.max_count=Math.max(a.max_count,h.lods.length);for(let c=0;c<h.lods.length;c++){const d=h.lods[c];d.width&&(a.lods[c]=a.lods[c]||{min_height:1/0,max_height:0},a.lods[c].min_height=Math.min(a.lods[c].min_height,d.height),a.lods[c].max_height=Math.max(a.lods[c].max_height,d.height))}}}}}static hasLODLevelAvailable(t,e){if(Array.isArray(t)){for(const n of t)if(this.hasLODLevelAvailable(n,e))return!0;return!1}if(t.isMaterial===!0){for(const n of Object.keys(t)){const i=t[n];if(i&&i.isTexture&&this.hasLODLevelAvailable(i,e))return!0}return!1}else if(t.isGroup===!0){for(const n of t.children)if(n.isMesh===!0&&this.hasLODLevelAvailable(n,e))return!0}let s,r;if(t.isMesh?s=t.geometry:(t.isBufferGeometry||t.isTexture)&&(s=t),s&&s?.userData?.LODS){const n=s.userData.LODS;if(r=this.lodInfos.get(n.key),e===void 0)return r!=null;if(r)return Array.isArray(r.lods)?e<r.lods.length:e===0}return!1}static assignMeshLOD(t,e,s){if(!t)return Promise.resolve(null);if(t instanceof f.Mesh||t.isMesh===!0){const r=t.geometry,n=this.getAssignedLODInformation(r);if(!n)return Promise.resolve(null);for(const l of F)l.onBeforeGetLODMesh?.(t,e);t["LOD:requested level"]=e;const i=()=>t["LOD:requested level"]===e||this.shouldApplyStaleMeshLOD(t,e);return m.getOrLoadLOD(r,e,{isCurrent:i}).then(l=>{if(Array.isArray(l)){const u=n.index||0;l=l[u]}const a=t["LOD:requested level"]===e;return(a||this.shouldApplyStaleMeshLOD(t,e))&&(a&&delete t["LOD:requested level"],l&&r!=l&&(l?.isBufferGeometry?typeof s?.apply=="function"?s.apply(l,e,t):s?.apply!==!1&&(t.geometry=l):p&&console.error("Invalid LOD geometry",l))),l}).catch(l=>(console.error("Error loading mesh LOD",t,l),null))}else p&&console.error("Invalid call to assignMeshLOD: Request mesh LOD but the object is not a mesh",t);return Promise.resolve(null)}static assignTextureLOD(t,e=0,s){if(!t)return Promise.resolve(null);const r=s?.force===!0;if(t.isMesh===!0){const n=t;if(Array.isArray(n.material)){const i=new Array;for(const l of n.material){const a=this.assignTextureLOD(l,e,s);i.push(a)}return Promise.all(i).then(l=>{const a=new Array;for(const u of l)Array.isArray(u)&&a.push(...u);return a})}else return this.assignTextureLOD(n.material,e,s)}if(t.isMaterial===!0){const n=t,i=[],l=new Array;if(this.trackCurrentMaterialTextureSlots(n),n.uniforms&&(n.isRawShaderMaterial||n.isShaderMaterial===!0)){const a=n;for(const u of Object.keys(a.uniforms)){const h=a.uniforms[u].value;if(h?.isTexture===!0){const c=this.assignTextureLODForSlot(h,e,n,u,r).then(d=>(d&&a.uniforms[u].value!=d&&(a.uniforms[u].value=d,a.uniformsNeedUpdate=!0),d));i.push(c),l.push(u)}}}else for(const a of Object.keys(n)){const u=n[a];if(u?.isTexture===!0){const h=this.assignTextureLODForSlot(u,e,n,a,r);i.push(h),l.push(a)}}return Promise.all(i).then(a=>{const u=new Array;for(let h=0;h<a.length;h++){const c=a[h],d=l[h];c&&c.isTexture===!0?u.push({material:n,slot:d,texture:c,level:e}):u.push({material:n,slot:d,texture:null,level:e})}return u})}if(t instanceof f.Texture||t.isTexture===!0){const n=t;return this.assignTextureLODForSlot(n,e,null,null,r)}return Promise.resolve(null)}static set maxConcurrentLoadingTasks(t){m.queue.maxConcurrent=t}static get maxConcurrentLoadingTasks(){return m.queue.maxConcurrent}static assignTextureLODForSlot(t,e,s,r,n){if(t?.isTexture!==!0)return Promise.resolve(null);if(r==="glyphMap")return Promise.resolve(t);const i=this.getAssignedLODInformation(t);if(i&&(i.level===e||!n&&i.level<e))return Promise.resolve(t);if(s&&r){const c=this.getPendingTextureSlotRequest(s,r);if(c&&c.level===e&&c.force===n)return c.promise}const l=s&&r?this.nextTextureSlotRequestId(s,r,e,n):0,a=()=>!s||!r||this.getLatestTextureSlotRequest(s,r)?.id===l,u=()=>a()||this.shouldApplyStaleTextureSlotLOD(s,r,e,n),h=m.getOrLoadLOD(t,e,{isCurrent:u}).then(c=>{if(!a()&&!this.shouldApplyStaleTextureSlotLOD(s,r,e,n))return null;if(Array.isArray(c))return console.warn("Progressive: Got an array of textures for a texture slot, this should not happen..."),null;if(c?.isTexture===!0){if(c!=t&&s&&r){const d=this.getMaterialTextureSlot(s,r)??t;if(d&&!n){const g=this.getAssignedLODInformation(d);if(g&&g?.level<e)return p==="verbose"&&console.warn("Assigned texture level is already higher: ",g.level,e,s,d,c),null}this.assignTrackedTextureSlot(s,r,c)}return c}else p=="verbose"&&console.warn("No LOD found for",t,e);return null}).catch(c=>(console.error("Error loading LOD",t,c),null));return s&&r&&this.setPendingTextureSlotRequest(s,r,e,n,l,h),h}static trackedTextureSlots=new WeakMap;static pendingTextureSlotRequests=new WeakMap;static latestTextureSlotRequests=new WeakMap;static textureSlotRequestId=0;static trackCurrentMaterialTextureSlots(t){if(t.uniforms&&(t.isRawShaderMaterial||t.isShaderMaterial===!0)){const e=t;for(const s of Object.keys(e.uniforms)){const r=e.uniforms[s].value;r?.isTexture===!0&&this.ensureTrackedTextureSlot(t,s,r)}return}for(const e of Object.keys(t)){const s=t[e];s?.isTexture===!0&&this.ensureTrackedTextureSlot(t,e,s)}}static getPendingTextureSlotRequest(t,e){return this.pendingTextureSlotRequests.get(t)?.get(e)}static nextTextureSlotRequestId(t,e,s,r){let n=this.latestTextureSlotRequests.get(t);n||(n=new Map,this.latestTextureSlotRequests.set(t,n));const i=++this.textureSlotRequestId;return n.set(e,{id:i,level:s,force:r}),i}static getLatestTextureSlotRequest(t,e){return this.latestTextureSlotRequests.get(t)?.get(e)}static shouldApplyStaleTextureSlotLOD(t,e,s,r){if(!t||!e)return!1;const n=this.getLatestTextureSlotRequest(t,e),i=this.getMaterialTextureSlot(t,e),l=this.getAssignedLODInformation(i)?.level??1/0;return s>=l?!1:r?n?s>=n.level:!1:!0}static shouldApplyStaleMeshLOD(t,e){const s=t["LOD:requested level"];if(typeof s!="number")return!1;const r=this.getAssignedLODInformation(t.geometry)?.level??1/0;return e<r&&e>=s}static setPendingTextureSlotRequest(t,e,s,r,n,i){let l=this.pendingTextureSlotRequests.get(t);l||(l=new Map,this.pendingTextureSlotRequests.set(t,l));const a={level:s,force:r,id:n,promise:i};l.set(e,a),i.finally(()=>{l.get(e)?.id===n&&l.delete(e)})}static getMaterialTextureSlot(t,e){const r=t.uniforms?.[e];if(r?.value?.isTexture===!0)return r.value;const n=t[e];return n?.isTexture===!0?n:null}static setMaterialTextureSlot(t,e,s){const n=t.uniforms?.[e];if(n?.value?.isTexture===!0){n.value=s,t.uniformsNeedUpdate=!0;return}t[e]=s}static assignTrackedTextureSlot(t,e,s){let r=this.trackedTextureSlots.get(t);r||(r=new Map,this.trackedTextureSlots.set(t,r));const n=this.getMaterialTextureSlot(t,e);let i=r.get(e);!i&&n?i=this.ensureTrackedTextureSlot(t,e,n):i&&n&&i!==n&&(this.releaseTrackedTextureSlot(t,e,i),i=this.ensureTrackedTextureSlot(t,e,n)),!(i===s&&n===s)&&(i&&i!==s&&this.releaseTrackedTextureSlot(t,e,i),i!==s&&(this.trackTextureUsage(s),r.set(e,s)),n!==s&&this.setMaterialTextureSlot(t,e,s))}static ensureTrackedTextureSlot(t,e,s){let r=this.trackedTextureSlots.get(t);r||(r=new Map,this.trackedTextureSlots.set(t,r));const n=r.get(e);return n===s?n:(n&&this.releaseTrackedTextureSlot(t,e,n),this.trackTextureUsage(s),r.set(e,s),s)}static releaseTrackedTextureSlot(t,e,s){const r=this.trackedTextureSlots.get(t);if(r?.get(e)===s&&r.delete(e),this.untrackTextureUsage(s)&&(p||ne)){const i=this.getAssignedLODInformation(s);console.log(`[gltf-progressive] Disposed old texture LOD ${i?.level??"?"} for ${t.name||t.type}.${e}`,s.uuid)}}parser;url;constructor(t){const e=t.options.path;p&&console.log("Progressive extension registered for",e),this.parser=t,this.url=e}_isLoadingMesh;loadMesh=t=>{if(this._isLoadingMesh)return null;const e=this.parser.json.meshes[t]?.extensions?.[W];return e?(this._isLoadingMesh=!0,this.parser.getDependency("mesh",t).then(s=>(this._isLoadingMesh=!1,s&&m.registerMesh(this.url,e.guid,s,e.lods?.length,0,e),s))):null};afterRoot(t){return p&&console.log("AFTER",this.url,t),this.parser.json.textures?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[W];if(r){if(!r.lods){p&&console.warn("Texture has no LODs",r);return}let n=!1;for(const i of this.parser.associations.keys())i.isTexture===!0&&this.parser.associations.get(i)?.textures===s&&(n=!0,m.registerTexture(this.url,i,r.lods?.length,s,r));n||this.parser.getDependency("texture",s).then(i=>{i&&m.registerTexture(this.url,i,r.lods?.length,s,r)})}}}),this.parser.json.meshes?.forEach((e,s)=>{if(e?.extensions){const r=e?.extensions[W];if(r&&r.lods){for(const n of this.parser.associations.keys())if(n.isMesh){const i=this.parser.associations.get(n);i?.meshes===s&&m.registerMesh(this.url,r.guid,n,r.lods.length,i.primitives,r)}}}}),null}static registerTexture=(t,e,s,r,n)=>{if(!e){p&&console.error("!! gltf-progressive: Called register texture without texture");return}if(p){const{width:l,height:a}=De(e);console.log(`> gltf-progressive: register texture[${r}] "${e.name||e.uuid}", Current: ${l}x${a}, Max: ${n.lods[0]?.width}x${n.lods[0]?.height}, uuid: ${e.uuid}`,n,e)}e.source&&(e.source[he]=n);const i=n.guid;m.assignLODInformation(t,e,i,s,r),m.lodInfos.set(i,n),m.lowresCache.set(i,new WeakRef(e))};static registerMesh=(t,e,s,r,n,i)=>{const l=s.geometry;if(!l){p&&console.warn("gltf-progressive: Register mesh without geometry");return}l.userData||(l.userData={}),p&&console.log("> Progressive: register mesh "+s.name,{index:n,uuid:s.uuid},i,s),m.assignLODInformation(t,l,e,r,n),m.lodInfos.set(e,i);let u=m.lowresCache.get(e)?.deref();u?u.push(s.geometry):u=[s.geometry],m.lowresCache.set(e,new WeakRef(u)),r>0&&!ee(s)&&nt(s,l);for(const h of F)h.onRegisteredNewMesh?.(s,i)};static dispose(t){if(t){this.lodInfos.delete(t);const e=this.lowresCache.get(t);if(e){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}this.lowresCache.delete(t)}for(const[s,r]of this.cache)s.includes(t)&&(this._disposeCacheEntry(r),this.cache.delete(s))}else{this.cacheGeneration++,this.lodInfos.clear();for(const[,e]of this.lowresCache){const s=e.deref();if(s){if(s.isTexture){const r=s;this.textureRefCounts.delete(r.uuid),r.dispose()}else if(Array.isArray(s))for(const r of s)r.dispose()}}this.lowresCache.clear();for(const[,e]of this.cache)this._disposeCacheEntry(e);this.cache.clear(),this.textureRefCounts.clear(),this.trackedTextureSlots=new WeakMap,this.pendingTextureSlotRequests=new WeakMap,this.latestTextureSlotRequests=new WeakMap,this.textureSlotRequestId=0}}static _disposeCacheEntry(t){if(t instanceof WeakRef){const e=t.deref();e&&(e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose())}else this.disposedRequests.add(t),t.then(e=>{if(e)if(Array.isArray(e))for(const s of e)s.dispose();else e.isTexture&&this.textureRefCounts.delete(e.uuid),e.dispose()}).catch(()=>{})}static lodInfos=new Map;static cache=new Map;static lowresCache=new Map;static textureRefCounts=new Map;static _resourceRegistry=new FinalizationRegistry(t=>{const e=m.cache.get(t);(p||ne)&&console.debug(`[gltf-progressive] Memory: Resource GC'd
2
- ${t}`),e instanceof WeakRef&&(e.deref()||(m.cache.delete(t),(p||ne)&&console.log("[gltf-progressive] ↪ Cache entry deleted (GC)")))});static trackTextureUsage(t){const e=t.uuid,s=this.textureRefCounts.get(e)||0;this.textureRefCounts.set(e,s+1),p==="verbose"&&console.log(`[gltf-progressive] Track texture ${e}, refCount: ${s} → ${s+1}`)}static untrackTextureUsage(t){const e=t.uuid,s=this.textureRefCounts.get(e);if(!s)return(p==="verbose"||ne)&&n("[gltf-progressive] Memory: Untrack untracked texture (dispose immediately)",0),t.dispose(),!0;const r=s-1;if(r<=0)return this.textureRefCounts.delete(e),(p||ne)&&n("[gltf-progressive] Memory: Dispose texture",r),t.dispose(),!0;return this.textureRefCounts.set(e,r),p==="verbose"&&n("[gltf-progressive] Memory: Untrack texture",r),!1;function n(i,l){let{width:a,height:u}=De(t);const h=a&&u?`${a}x${u}`:"N/A";let c="N/A";a&&u&&(c=`~${(tt(t)/(1024*1024)).toFixed(2)} MB`),console.log(`${i} — ${t.name} ${h} (${c}), refCount: ${s} → ${l}
3
- ${e}`)}}static workers=[];static cacheGeneration=0;static disposedRequests=new WeakSet;static _workersIndex=0;static async getOrLoadLOD(t,e,s){const r=this.cacheGeneration,n=p=="verbose",i=this.getAssignedLODInformation(t);if(!i)return p&&console.warn(`[gltf-progressive] No LOD information found: ${t.name}, uuid: ${t.uuid}, type: ${t.type}`,t),null;const l=i?.key;let a;if(t.isTexture===!0){const h=t;h.source&&h.source[he]&&(a=h.source[he])}if(a||(a=m.lodInfos.get(l)),!a)p&&console.warn(`Can not load LOD ${e}: no LOD info found for "${l}" ${t.name}`,t.type,m.lodInfos);else{if(e>0){let d=!1;const g=Array.isArray(a.lods);if(g&&e>=a.lods.length?d=!0:g||(d=!0),d){const M=this.lowresCache.get(l);if(M){const w=M.deref();if(w)return w;this.lowresCache.delete(l),p&&console.log(`[gltf-progressive] Lowres cache entry was GC'd: ${l}`)}return null}}const h=Array.isArray(a.lods)?a.lods[e]?.path:a.lods;if(!h)return p&&!a["missing:uri"]&&(a["missing:uri"]=!0,console.warn("Missing uri for progressive asset for LOD "+e,a)),null;const c=Ze(i.url,h);if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!a.guid)return console.warn("missing pointer for glb/gltf texture",a),null;const d=c+"_"+a.guid,g=await this.tryResolveLODCacheEntry(this.cache.get(d),d,c,t,e,n);if(r!==this.cacheGeneration)return null;if(g.found)return g.value;if(s?.isCurrent?.()===!1)return n&&console.log(`Skipping stale LOD ${e} request before queue: ${c}`),null;const M=await this.queue.slot(c);if(r!==this.cacheGeneration)return null;if(s?.isCurrent?.()===!1)return n&&console.log(`Skipping stale LOD ${e} request after queue: ${c}`),null;const w=await this.tryResolveLODCacheEntry(this.cache.get(d),d,c,t,e,n);if(r!==this.cacheGeneration)return null;if(w.found)return w.value;const L=this.cache.get(d);if(L!==void 0){const x=await this.tryResolveLODCacheEntry(L,d,c,t,e,n);if(r!==this.cacheGeneration)return null;if(x.found)return x.value}if(!M.use)return p&&console.log(`LOD ${e} was aborted: ${c}`),null;const D=a,_=new Promise(async(x,S)=>{if(ft){const y=await(await ut({})).load(c);if(y.textures.length>0)for(const v of y.textures){let R=v.texture;return m.assignLODInformation(i.url,R,l,e,void 0),t instanceof f.Texture&&(R=this.copySettings(t,R)),R&&(R.guid=D.guid),x(R)}if(y.geometries.length>0){const v=new Array;for(const R of y.geometries){const N=R.geometry;m.assignLODInformation(i.url,N,l,e,R.primitiveIndex),v.push(N)}return x(v)}return x(null)}const I=new Z.GLTFLoader;Me(I),p&&(await new Promise(O=>setTimeout(O,1e3)),n&&console.warn("Start loading (delayed) "+c,D.guid));let k=c;if(D&&Array.isArray(D.lods)){const O=D.lods[e];O.hash&&(k+="?v="+O.hash)}const T=await I.loadAsync(k).catch(O=>(console.error(`Error loading LOD ${e} from ${c}
4
- `,O),x(null)));if(!T)return x(null);const U=T.parser;n&&console.log("Loading finished "+c,D.guid);let A=0;if(T.parser.json.textures){let O=!1;for(const y of T.parser.json.textures){if(y?.extensions){const v=y?.extensions[W];if(v?.guid&&v.guid===D.guid){O=!0;break}}A++}if(O){let y=await U.getDependency("texture",A);return y&&m.assignLODInformation(i.url,y,l,e,void 0),n&&console.log('change "'+t.name+'" → "'+y.name+'"',c,A,y,d),t instanceof f.Texture&&(y=this.copySettings(t,y)),y&&(y.guid=D.guid),x(y)}else p&&console.warn("Could not find texture with guid",D.guid,T.parser.json)}if(A=0,T.parser.json.meshes){let O=!1;for(const y of T.parser.json.meshes){if(y?.extensions){const v=y?.extensions[W];if(v?.guid&&v.guid===D.guid){O=!0;break}}A++}if(O){const y=await U.getDependency("mesh",A);if(n&&console.log(`Loaded Mesh "${y.name}"`,c,A,y,d),y.isMesh===!0){const v=y.geometry;return m.assignLODInformation(i.url,v,l,e,0),x(v)}else{const v=new Array;for(let R=0;R<y.children.length;R++){const N=y.children[R];if(N.isMesh===!0){const H=N.geometry;m.assignLODInformation(i.url,H,l,e,R),v.push(H)}}return x(v)}}else p&&console.warn("Could not find mesh with guid",D.guid,T.parser.json)}return x(null)});this.cache.set(d,_),M.use(_);const b=await _;return r!==this.cacheGeneration||this.cache.get(d)!==_?null:(b!=null?b instanceof f.Texture?(this.cache.set(d,new WeakRef(b)),m._resourceRegistry.register(b,d)):Array.isArray(b)?this.cache.set(d,Promise.resolve(b)):this.cache.set(d,Promise.resolve(b)):this.cache.set(d,Promise.resolve(null)),b)}else if(t instanceof f.Texture){if(s?.isCurrent?.()===!1)return n&&console.log(`Skipping stale texture LOD ${e} request: ${c}`),null;n&&console.log("Load texture from uri: "+c);const g=await new f.TextureLoader().loadAsync(c);return r!==this.cacheGeneration||s?.isCurrent?.()===!1?(g?.dispose(),null):(g?(g.guid=a.guid,g.flipY=!1,g.needsUpdate=!0,g.colorSpace=t.colorSpace,n&&console.log(a,g)):p&&console.warn("failed loading",c),g)}}return null}static async tryResolveLODCacheEntry(t,e,s,r,n,i){if(t===void 0)return{found:!1};if(i&&console.log(`LOD ${n} was already loading/loaded: ${e}`),t instanceof WeakRef){const u=t.deref();if(u){let h=u,c=!1;if(h instanceof f.Texture&&r instanceof f.Texture?be(h.image)||we(h)?h=this.copySettings(r,h):c=!0:h instanceof f.BufferGeometry&&r instanceof f.BufferGeometry&&(h.attributes.position?.array||(c=!0)),!c)return{found:!0,value:h}}return this.cache.delete(e),p&&console.log(`[gltf-progressive] Re-loading GC'd/disposed resource: ${e}`),{found:!1}}let l=await t.catch(u=>(console.error(`Error loading LOD ${n} from ${s}
5
- `,u),null));if(this.disposedRequests.has(t))return{found:!0,value:null};let a=!1;return l==null||(l instanceof f.Texture&&r instanceof f.Texture?be(l.image)||we(l)?l=this.copySettings(r,l):(a=!0,this.cache.delete(e)):l instanceof f.BufferGeometry&&r instanceof f.BufferGeometry&&(l.attributes.position?.array||(a=!0,this.cache.delete(e)))),a?{found:!1}:{found:!0,value:l}}static _queue;static get queue(){return this._queue??=new et(Te()?20:50,{debug:p!=!1})}static assignLODInformation(t,e,s,r,n){if(!e)return;e.userData||(e.userData={});const i=new dt(t,s,r,n);e.userData.LODS=i,"source"in e&&typeof e.source=="object"&&(e.source.LODS=i)}static getAssignedLODInformation(t){return t?t.userData?.LODS?t.userData.LODS:"source"in t&&t.source?.LODS?t.source.LODS:null:null}static copySettings(t,e){return e?(p==="verbose"&&console.debug(`Copy texture settings
6
- `,t.uuid,`
7
- `,e.uuid),e=e.clone(),e.offset=t.offset,e.repeat=t.repeat,e.colorSpace=t.colorSpace,e.magFilter=t.magFilter,e.minFilter=t.minFilter,e.wrapS=t.wrapS,e.wrapT=t.wrapT,e.flipY=t.flipY,e.anisotropy=t.anisotropy,e.mipmaps||(e.generateMipmaps=t.generateMipmaps),e):t}}class dt{url;key;level;index;constructor(t,e,s,r){this.url=t,this.key=e,this.level=s,r!=null&&(this.index=r)}}class ae{static addPromise=(t,e,s,r)=>{r.forEach(n=>{n.add(t,e,s)})};ready;get awaitedCount(){return this._addedCount}get resolvedCount(){return this._resolvedCount}get currentlyAwaiting(){return this._awaiting.length}_resolve;_signal;_frame_start;_frames_to_capture;_resolved=!1;_addedCount=0;_resolvedCount=0;_awaiting=[];_maxPromisesPerObject=1;constructor(t,e){const r=Math.max(e.frames??2,2);this._frame_start=e.waitForFirstCapture?void 0:t,this._frames_to_capture=r,this.ready=new Promise(n=>{this._resolve=n}),this.ready.finally(()=>{this._resolved=!0,this._awaiting.length=0}),this._signal=e.signal,this._signal?.addEventListener("abort",()=>{this.resolveNow()}),this._maxPromisesPerObject=Math.max(1,e.maxPromisesPerObject??1)}_currentFrame=0;update(t){this._currentFrame=t,this._frame_start===void 0&&this._addedCount>0&&(this._frame_start=t),(this._signal?.aborted||this._awaiting.length===0&&this._frame_start!==void 0&&t>this._frame_start+this._frames_to_capture)&&this.resolveNow()}_seen=new WeakMap;add(t,e,s){if(this._resolved){p&&console.warn("PromiseGroup: Trying to add a promise to a resolved group, ignoring.");return}if(!(this._frame_start!==void 0&&this._currentFrame>this._frame_start+this._frames_to_capture)){if(this._maxPromisesPerObject>=1)if(this._seen.has(e)){const r=this._seen.get(e);if(r>=this._maxPromisesPerObject){p&&console.warn("PromiseGroup: Already awaiting object ignoring new promise for it.");return}this._seen.set(e,r+1)}else this._seen.set(e,1);this._awaiting.push(s),this._addedCount++,s.finally(()=>{this._resolvedCount++,this._awaiting.splice(this._awaiting.indexOf(s),1)})}}resolveNow(){this._resolved||this._resolve?.({awaited_count:this._addedCount,resolved_count:this._resolvedCount,cancelled:this._signal?.aborted??!1})}}const G=V("debugprogressive"),ht=G==="colors",gt=V("noprogressive"),ge=Symbol("Needle:LODSManager"),pe=Symbol("Needle:LODState"),z=Symbol("Needle:CurrentLOD"),Se=f.THREE,C={mesh_lod:-1,texture_lod:-1},pt=new f.Color,Re=[3526751,11065402,15978811,15897394,15749691,11032304,4827122,3332036,16739229,7306743,14053330,3516499,12035359,14703919,3963096,42662,14100029,8344319,4633680,16229681,3120096,12076434,9083434,2060171,15751837,10182117,48121,62932,16704576,15817653,5083278,5592405];function mt(){const o=Se.Timer||Se.Clock;return new o}const me=new f.Box3,E=new f.Box3,Ce=new f.Box3,yt=new f.Vector3,xt=new f.Vector3,Lt=new f.Matrix4,q=new f.Vector3,Y=new f.Vector3,Q=new f.Vector3,J=new f.Vector3;function wt(o,t){const e=o.min,s=o.max,r=(e.x+s.x)*.5,n=(e.y+s.y)*.5;return q.set(r,n,e.z).applyMatrix4(t).z<0}function We(o){const{geometry:t,matrixWorld:e,camera:s,projectionScreenMatrix:r,desiredDensity:n,canvasHeight:i=0,currentLevel:l=-1,xrEnabled:a=!1,debugDrawLine:u,warnMissingPrimitiveDensities:h=!1}=o,c=m.getMeshLODExtension(t)?.lods,d=m.getPrimitiveIndex(t),g=o.target??{level:l,primitiveIndex:d,screenCoverage:0,screenspaceVolume:new f.Vector3,centrality:1};g.level=l,g.primitiveIndex=d,g.screenCoverage=0,g.screenspaceVolume.set(0,0,0),g.centrality=1;let M=o.boundingBox??t.boundingBox;if(M||(t.computeBoundingBox(),M=t.boundingBox),!M)return g;if(me.copy(M).applyMatrix4(e),s.isPerspectiveCamera&&wt(me,r))return g.level=0,g.screenCoverage=1/0,g.screenspaceVolume.set(1/0,1/0,1/0),g;if(E.copy(me).applyMatrix4(r),a&&s.isPerspectiveCamera&&s.fov>70){const x=E.min,S=E.max;let I=x.x,k=x.y,T=S.x,U=S.y;const A=2,O=1.5,y=(x.x+S.x)*.5,v=(x.y+S.y)*.5;I=(I-y)*A+y,k=(k-v)*A+v,T=(T-y)*A+y,U=(U-v)*A+v;const R=I<0&&T>0?0:Math.min(Math.abs(x.x),Math.abs(S.x)),N=k<0&&U>0?0:Math.min(Math.abs(x.y),Math.abs(S.y)),H=Math.max(R,N);g.centrality=(O-H)*(O-H)*(O-H)}const w=E.getSize(yt);w.multiplyScalar(.5),globalThis.screen?.availHeight>0&&i>0&&w.multiplyScalar(i/globalThis.screen.availHeight),s.isPerspectiveCamera&&(w.x*=s.aspect),Ce.copy(M).applyMatrix4(e).applyMatrix4(s.matrixWorldInverse);const L=Ce.getSize(xt),D=Math.max(w.x,w.y),_=Math.max(L.x,L.y);D!==0&&_!==0&&(w.z=L.z/_*D);const b=Math.max(w.x,w.y,w.z)*g.centrality;if(g.screenCoverage=b,g.screenspaceVolume.copy(w),b<=0)return g;if(u){const x=Lt.copy(r);x.invert(),q.copy(E.min),Y.copy(E.max),Y.x=q.x,Q.copy(E.max),Q.y=q.y,J.copy(E.max);const S=(q.z+J.z)*.5;q.z=Y.z=Q.z=J.z=S,q.applyMatrix4(x),Y.applyMatrix4(x),Q.applyMatrix4(x),J.applyMatrix4(x),u(q,Y,255),u(q,Q,255),u(Y,J,255),u(Q,J,255)}if(c?.length)for(let x=0;x<c.length;x++){const S=c[x],I=S.densities?.[d]||S.density||1e-5;if(d>0&&h&&qe()&&!S.densities&&!globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]&&(globalThis["NEEDLE:MISSING_LOD_PRIMITIVE_DENSITIES"]=!0,console.warn("[Needle Progressive] Detected usage of mesh without primitive densities. This might cause incorrect LOD level selection: Consider re-optimizing your model by updating your Needle Integration, Needle glTF Pipeline or running optimization again on Needle Cloud.")),I/b<n){g.level=x;break}}return g}let ie=class j{static debugDrawLine;static getObjectLODState(t){return t[pe]}static addPlugin(t){F.push(t)}static removePlugin(t){const e=F.indexOf(t);e>=0&&F.splice(e,1)}static getPlugins(){return F}static get(t,e){if(t[ge])return console.debug("[gltf-progressive] LODsManager already exists for this renderer"),t[ge];const s=new j(t,{engine:"unknown",...e});return t[ge]=s,s}renderer;context;projectionScreenMatrix=new f.Matrix4;get plugins(){return F}overrideLodLevel=void 0;targetTriangleDensity=2e5;skinnedMeshAutoUpdateBoundsInterval=30;updateInterval="auto";#e=1;pause=!1;manual=!1;_newPromiseGroups=[];_promiseGroupIds=0;awaitLoading(t){const e=this._promiseGroupIds++,s=new ae(this.#r,{...t});this._newPromiseGroups.push(s);const r=performance.now();return s.ready.finally(()=>{const n=this._newPromiseGroups.indexOf(s);n>=0&&(this._newPromiseGroups.splice(n,1),qe()&&performance.measure("LODsManager:awaitLoading",{start:r,detail:{id:e,name:t?.name,awaited:s.awaitedCount,resolved:s.resolvedCount}}))}),s.ready}trackLoadingPromise(t,e,s){return ae.addPromise(t,e,s,this._newPromiseGroups),s}_postprocessPromiseGroups(){if(this._newPromiseGroups.length!==0)for(let t=this._newPromiseGroups.length-1;t>=0;t--)this._newPromiseGroups[t].update(this.#r)}_lodchangedlisteners=[];addEventListener(t,e){return t==="changed"?(this._lodchangedlisteners.push(e),()=>{this.removeEventListener(t,e)}):()=>{}}removeEventListener(t,e){let s=!1;if(t==="changed"){const r=this._lodchangedlisteners.indexOf(e);r>=0&&(this._lodchangedlisteners.splice(r,1),s=!0)}return s}constructor(t,e){this.renderer=t,this.context={...e}}#t;#r=0;#n=0;#i=0;#s=0;#o=mt();_fpsBuffer=[60,60,60,60,60];enable(){if(this.#t)return;console.debug("[gltf-progressive] Enabling LODsManager for renderer");let t=0;this.#t=this.renderer.render;const e=this;ce(this.renderer),this.renderer.render=function(s,r){const n=e.renderer.getRenderTarget();(n==null||"isXRRenderTarget"in n&&n.isXRRenderTarget)&&(t=0,e.#r+=1,e.#o.update?.(),e.#n=Math.max(e.#o.getDelta(),1/1e3),e.#i+=e.#n,e._fpsBuffer.shift(),e._fpsBuffer.push(1/e.#n),e.#s=e._fpsBuffer.reduce((l,a)=>l+a)/e._fpsBuffer.length,G&&e.#r%200===0&&console.log("FPS",Math.round(e.#s),"Interval:",e.#e));const i=t++;e.#t.call(this,s,r),e.onAfterRender(s,r,i)}}disable(){this.#t&&(console.debug("[gltf-progressive] Disabling LODsManager for renderer"),this.renderer.render=this.#t,this.#t=void 0)}update(t,e){this.internalUpdate(t,e)}onAfterRender(t,e,s){if(this.pause)return;const r=this.getRenderList(t,e,s);if(!r)return;const n=r.opaque;let i=!0;if(n.length===1){const l=n[0].material;(l.name==="EffectMaterial"||l.name==="CopyShader")&&(i=!1)}if((e.parent&&e.parent.type==="CubeCamera"||s>=1&&e.type==="OrthographicCamera")&&(i=!1),i){if(gt||(this.updateInterval==="auto"?this.#s<40&&this.#e<10?(this.#e+=1,G&&console.warn("↓ Reducing LOD updates",this.#e,this.#s.toFixed(0))):this.#s>=60&&this.#e>1&&(this.#e-=1,G&&console.warn("↑ Increasing LOD updates",this.#e,this.#s.toFixed(0))):this.#e=this.updateInterval,this.#e>0&&this.#r%this.#e!=0))return;this.internalUpdate(t,e),this._postprocessPromiseGroups()}}internalUpdate(t,e){const s=this.getRenderList(t,e,0);if(!s)return;const r=s.opaque;this.projectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const n=this.targetTriangleDensity;for(const a of r){if(a.material&&(a.geometry?.type==="BoxGeometry"||a.geometry?.type==="BufferGeometry")&&(a.material.name==="SphericalGaussianBlur"||a.material.name=="BackgroundCubeMaterial"||a.material.name==="CubemapFromEquirect"||a.material.name==="EquirectangularToCubeUV")){G&&(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]||(a.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]=!0,console.warn("Ignoring skybox or BLIT object",a,a.material.name,a.material.type)));continue}switch(a.material.type){case"LineBasicMaterial":case"LineDashedMaterial":case"PointsMaterial":case"ShadowMaterial":case"MeshDistanceMaterial":case"MeshDepthMaterial":continue}const u=a.object;(u instanceof f.Mesh||u.isMesh)&&this.updateLODs(t,e,u,n)}const i=s.transparent;for(const a of i){const u=a.object;(u instanceof f.Mesh||u.isMesh)&&this.updateLODs(t,e,u,n)}const l=s.transmissive;for(const a of l){const u=a.object;(u instanceof f.Mesh||u.isMesh)&&this.updateLODs(t,e,u,n)}}getRenderList(t,e,s){const r=this.renderer;let n=null;if(r.isWebGPURenderer===!0){const i=r._renderLists;if(!i)return null;n=i.get(t,e)}else if(r.isWebGLRenderer===!0){const i=r.renderLists;if(!i)return null;n=i.get(t,s)}return n?{opaque:n.opaque||[],transparent:n.transparent||[],transmissive:n.transmissive||n.transparentDoublePass||[],transparentDoublePass:n.transparentDoublePass||[]}:null}updateLODs(t,e,s,r){s.userData||(s.userData={});let n=s[pe];if(n||(n=new Dt,s[pe]=n),n.frames++<2)return;for(const l of F)l.onBeforeUpdateLOD?.(this.renderer,t,e,s);const i=this.overrideLodLevel!==void 0?this.overrideLodLevel:X;i>=0?(C.mesh_lod=i,C.texture_lod=i):(this.calculateLodLevel(e,s,n,r,C),C.mesh_lod=Math.round(C.mesh_lod),C.texture_lod=Math.round(C.texture_lod)),C.mesh_lod>=0&&this.loadProgressiveMeshes(s,C.mesh_lod),s.material&&C.texture_lod>=0&&this.loadProgressiveTextures(s.material,C.texture_lod,i),p&&s.material&&!s.isGizmo&&Fe(s.material),ht&&s.material&&!s.isGizmo&&!s.isBatchedMesh&&Ue(s.material,C.mesh_lod);for(const l of F)l.onAfterUpdatedLOD?.(this.renderer,t,e,s,C);n.lastLodLevel_Mesh=C.mesh_lod,n.lastLodLevel_Texture=C.texture_lod}loadProgressiveTextures(t,e,s){if(!t)return;if(Array.isArray(t)){for(const i of t)this.loadProgressiveTextures(i,e,s);return}let r=!1;(t[z]===void 0||e<t[z])&&(r=!0);const n=s!==void 0&&s>=0;if(n&&(r=t[z]!=s,e=s),r){t[z]=e;const i=n?{force:!0}:void 0,l=m.assignTextureLOD(t,e,i).then(a=>{this._lodchangedlisteners.forEach(u=>u({type:"texture",level:e,object:t}))});ae.addPromise("texture",t,l,this._newPromiseGroups)}}loadProgressiveMeshes(t,e){if(!t)return Promise.resolve(null);let s=t[z]!==e;const r=t["DEBUG:LOD"];if(r!=null&&(s=t[z]!=r,e=r),s){t[z]=e;const n=t.geometry,i=m.assignMeshLOD(t,e).then(l=>(l&&t[z]==e&&n!=t.geometry&&this._lodchangedlisteners.forEach(a=>a({type:"mesh",level:e,object:t})),l));return ae.addPromise("mesh",t,i,this._newPromiseGroups),i}return Promise.resolve(null)}_sphere=new f.Sphere;_tempWorldPosition=new f.Vector3;static skinnedMeshBoundsFrameOffsetCounter=0;static $skinnedMeshBoundsOffset=Symbol("gltf-progressive-skinnedMeshBoundsOffset");calculateLodLevel(t,e,s,r,n){if(!e){n.mesh_lod=-1,n.texture_lod=-1;return}if(!t){n.mesh_lod=-1,n.texture_lod=-1;return}let l=10+1,a=!1;if(G&&e["DEBUG:LOD"]!=null)return e["DEBUG:LOD"];const u=m.getMeshLODExtension(e.geometry)?.lods,h=m.getPrimitiveIndex(e.geometry),c=u&&u.length>0,d=m.getMaterialMinMaxLODsCount(e.material),g=d.min_count!==1/0&&d.min_count>=0&&d.max_count>=0;if(!c&&!g){n.mesh_lod=0,n.texture_lod=0;return}c||(a=!0,l=0);const M=this.renderer.domElement.clientHeight||this.renderer.domElement.height;let w=e.geometry.boundingBox;if(e.type==="SkinnedMesh"){const L=e;if(!L.boundingBox)L.computeBoundingBox();else if(this.skinnedMeshAutoUpdateBoundsInterval>0){if(!L[j.$skinnedMeshBoundsOffset]){const _=j.skinnedMeshBoundsFrameOffsetCounter++;L[j.$skinnedMeshBoundsOffset]=_}const D=L[j.$skinnedMeshBoundsOffset];if((s.frames+D)%this.skinnedMeshAutoUpdateBoundsInterval===0){const _=ee(L),b=L.geometry;_&&(L.geometry=_),L.computeBoundingBox(),L.geometry=b}}w=L.boundingBox}if(w){if(e.geometry.attributes.color&&e.geometry.attributes.color.count<100&&e.geometry.boundingSphere){this._sphere.copy(e.geometry.boundingSphere),this._sphere.applyMatrix4(e.matrixWorld);const _=t.getWorldPosition(this._tempWorldPosition);if(this._sphere.containsPoint(_)){n.mesh_lod=0,n.texture_lod=0;return}}const L=We({geometry:e.geometry,matrixWorld:e.matrixWorld,camera:t,projectionScreenMatrix:this.projectionScreenMatrix,desiredDensity:r,canvasHeight:M,currentLevel:s.lastLodLevel_Mesh,boundingBox:w,xrEnabled:this.renderer.xr.enabled,debugDrawLine:G?j.debugDrawLine:void 0,warnMissingPrimitiveDensities:!0});if(s.lastCentrality=L.centrality,s.lastScreenCoverage=L.screenCoverage,s.lastScreenspaceVolume.copy(L.screenspaceVolume),L.screenCoverage===1/0){n.mesh_lod=0,n.texture_lod=0;return}L.level>=0&&L.level<l&&(l=L.level,a=!0)}if(a?n.mesh_lod=l:n.mesh_lod=s.lastLodLevel_Mesh,G&&n.mesh_lod!=s.lastLodLevel_Mesh){const D=u?.[n.mesh_lod];D&&console.log(`Mesh LOD changed: ${s.lastLodLevel_Mesh} → ${n.mesh_lod} (density: ${D.densities?.[h].toFixed(0)}) | ${e.name}`)}if(g){const L="saveData"in globalThis.navigator&&globalThis.navigator.saveData===!0;if(s.lastLodLevel_Texture<0){if(n.texture_lod=d.max_count-1,G){const D=d.lods[d.max_count-1];G&&console.log(`First Texture LOD ${n.texture_lod} (${D.max_height}px) - ${e.name}`)}}else{const D=s.lastScreenspaceVolume.x+s.lastScreenspaceVolume.y+s.lastScreenspaceVolume.z;let _=s.lastScreenCoverage*4;this.context?.engine==="model-viewer"&&(_*=1.5);const b=this.renderer.getPixelRatio?.()||globalThis.devicePixelRatio||1,S=M/b*_;let I=!1;for(let k=d.lods.length-1;k>=0;k--){const T=d.lods[k];if(!(L&&T.max_height>=2048)&&!(Te()&&T.max_height>4096)&&(T.max_height>S||!I&&k===0)){if(I=!0,n.texture_lod=k,G&&n.texture_lod<s.lastLodLevel_Texture){const U=T.max_height;console.log(`Texture LOD changed: ${s.lastLodLevel_Texture} → ${n.texture_lod} = ${U}px
8
- Screensize: ${S.toFixed(0)}px, Coverage: ${(100*s.lastScreenCoverage).toFixed(2)}%, Volume ${D.toFixed(1)}
9
- ${e.name}`)}break}}}}else n.texture_lod=0}};class Dt{frames=0;lastLodLevel_Mesh=-1;lastLodLevel_Texture=-1;lastScreenCoverage=0;lastScreenspaceVolume=new f.Vector3;lastCentrality=0}function Ue(o,t){if(!(t<0)){if(Array.isArray(o)){for(const e of o)Ue(e,t);return}"color"in o&&o.color instanceof f.Color&&(o.color.copy(ze(t,pt)),o.needsUpdate=!0)}}function ze(o,t){const e=Math.max(0,Math.min(Re.length-1,Math.floor(o)));return t.setHex(Re[e])}const Pe=Symbol("NEEDLE_mesh_lod"),le=Symbol("NEEDLE_texture_lod");let ye=null;function Ee(){const o=vt();o&&(o.mapURLs(function(t){return ke(),t}),ke(),ye?.disconnect(),ye=new MutationObserver(t=>{t.forEach(e=>{e.addedNodes.forEach(s=>{s instanceof HTMLElement&&s.tagName.toLowerCase()==="model-viewer"&&Ve(s)})})}),ye.observe(document,{childList:!0,subtree:!0}))}function vt(){if(typeof customElements>"u")return null;const o=customElements.get("model-viewer");return o||(customElements.whenDefined("model-viewer").then(()=>{console.debug("[gltf-progressive] model-viewer defined"),Ee()}),null)}function ke(){if(typeof document>"u")return;document.querySelectorAll("model-viewer").forEach(t=>{Ve(t)})}const Ae=new WeakSet;let Mt=0;function Ve(o){if(!o||Ae.has(o))return null;Ae.add(o),console.debug("[gltf-progressive] found new model-viewer..."+ ++Mt+`
10
- `,o.getAttribute("src"));let t=null,e=null,s=null;for(let r=o;r!=null;r=Object.getPrototypeOf(r)){const n=Object.getOwnPropertySymbols(r),i=n.find(u=>u.toString()=="Symbol(renderer)"),l=n.find(u=>u.toString()=="Symbol(scene)"),a=n.find(u=>u.toString()=="Symbol(needsRender)");!t&&i!=null&&(t=o[i].threeRenderer),!e&&l!=null&&(e=o[l]),!s&&a!=null&&(s=o[a])}if(t&&e){let r=function(){if(s){let i=0;const l=setInterval(()=>{if(i++>5){clearInterval(l);return}s?.call(o)},300)}};console.debug("[gltf-progressive] setup model-viewer");const n=ie.get(t,{engine:"model-viewer"});return ie.addPlugin(new _t),n.enable(),n.addEventListener("changed",()=>{s?.call(o)}),o.addEventListener("model-visibility",i=>{i.detail.visible&&s?.call(o)}),o.addEventListener("load",()=>{r()}),()=>{n.disable()}}return null}class _t{_didWarnAboutMissingUrl=!1;onBeforeUpdateLOD(t,e,s,r){this.tryParseMeshLOD(e,r),this.tryParseTextureLOD(e,r)}getUrl(t){if(!t)return null;let e=t.getAttribute("src");return e||(e=t.src),e||(this._didWarnAboutMissingUrl||console.warn("No url found in modelviewer",t),this._didWarnAboutMissingUrl=!0),e}tryGetCurrentGLTF(t){return t._currentGLTF}tryGetCurrentModelViewer(t){return t.element}tryParseTextureLOD(t,e){if(e[le]==!0)return;e[le]=!0;const s=this.tryGetCurrentGLTF(t),r=this.tryGetCurrentModelViewer(t),n=this.getUrl(r);if(n&&s&&e.material){let i=function(a){if(a[le]==!0)return;a[le]=!0,a.userData&&(a.userData.LOD=-1);const u=Object.keys(a);for(let h=0;h<u.length;h++){const c=u[h],d=a[c];if(d?.isTexture===!0){const g=d.userData?.associations?.textures;if(g==null)continue;const M=s.parser.json.textures[g];if(!M){console.warn("Texture data not found for texture index "+g);continue}if(M?.extensions?.[W]){const w=M.extensions[W];w&&n&&m.registerTexture(n,d,w.lods.length,g,w)}}}};const l=e.material;if(Array.isArray(l))for(const a of l)i(a);else i(l)}}tryParseMeshLOD(t,e){if(e[Pe]==!0)return;e[Pe]=!0;const s=this.tryGetCurrentModelViewer(t),r=this.getUrl(s);if(!r)return;const n=e.userData?.gltfExtensions?.[W];if(n&&r){const i=e.uuid;m.registerMesh(r,i,e,0,n.lods.length,n)}}}function Tt(...o){let t,e,s,r;switch(o.length){case 2:[s,e]=o,r={};break;case 3:[s,e,r]=o;break;case 4:[t,e,s,r]=o;break;default:throw new Error("Invalid arguments")}ce(e),Me(s),_e(s,{progressive:!0,...r?.hints}),s.register(i=>new m(i));const n=ie.get(e);return r?.enableLODsManager!==!1&&n.enable(),n}Ee();if(!rt){const o={gltfProgressive:{useNeedleProgressive:Tt,LODsManager:ie,configureLoader:_e,getRaycastMesh:ee,useRaycastMeshes:ot}};if(!globalThis.Needle)globalThis.Needle=o;else for(const t in o)globalThis.Needle[t]=o[t]}exports.LODsManager=ie;exports.NEEDLE_progressive=m;exports.addDracoAndKTX2Loaders=Me;exports.calculateMeshLODLevel=We;exports.configureLoader=_e;exports.createLoaders=ce;exports.getLODColor=ze;exports.getRaycastMesh=ee;exports.setDracoDecoderLocation=Ge;exports.setKTX2TranscoderLocation=$e;