@hology/core 0.0.157 → 0.0.159

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 (180) hide show
  1. package/dist/gameplay/services/physics/physics-system.d.ts +10 -1
  2. package/dist/gameplay/services/physics/physics-system.js +1 -1
  3. package/dist/rendering.js +1 -1
  4. package/dist/scene/asset-resource-loader.d.ts +13 -0
  5. package/dist/scene/asset-resource-loader.js +1 -1
  6. package/dist/scene/materializer.d.ts +7 -0
  7. package/dist/scene/materializer.js +1 -1
  8. package/dist/utils/three/traverse.d.ts +8 -0
  9. package/dist/utils/three/traverse.js +1 -1
  10. package/package.json +2 -2
  11. package/tsconfig.tsbuildinfo +1 -1
  12. package/dist/config/project-config.d.ts.map +0 -1
  13. package/dist/controllers/base-game-controller.d.ts.map +0 -1
  14. package/dist/csm.d.ts.map +0 -1
  15. package/dist/effects/particles/examples.d.ts.map +0 -1
  16. package/dist/effects/particles/particle-system-config.d.ts.map +0 -1
  17. package/dist/effects/vfx/behaviours.d.ts.map +0 -1
  18. package/dist/effects/vfx/index.d.ts.map +0 -1
  19. package/dist/effects/vfx/initializsers.d.ts.map +0 -1
  20. package/dist/effects/vfx/rates.d.ts.map +0 -1
  21. package/dist/effects/vfx/stretched-sprite.d.ts.map +0 -1
  22. package/dist/effects/vfx/trail-renderer.d.ts.map +0 -1
  23. package/dist/effects/vfx/vfx-actor.d.ts.map +0 -1
  24. package/dist/effects/vfx/vfx-asset.d.ts.map +0 -1
  25. package/dist/effects/vfx/vfx-collision-behaviour.d.ts.map +0 -1
  26. package/dist/effects/vfx/vfx-defs.d.ts.map +0 -1
  27. package/dist/effects/vfx/vfx-materializer.d.ts.map +0 -1
  28. package/dist/effects/vfx/vfx-old-materializer.d.ts.map +0 -1
  29. package/dist/effects/vfx/vfx-param.d.ts.map +0 -1
  30. package/dist/effects/vfx/vfx-renderers.d.ts.map +0 -1
  31. package/dist/effects/vfx/vfx-service.d.ts.map +0 -1
  32. package/dist/effects/vfx/zones.d.ts.map +0 -1
  33. package/dist/game-component/component-decorators.d.ts.map +0 -1
  34. package/dist/game-component/game-component.d.ts.map +0 -1
  35. package/dist/gameplay/actors/actor.d.ts.map +0 -1
  36. package/dist/gameplay/actors/builtin/camera-actor.d.ts.map +0 -1
  37. package/dist/gameplay/actors/builtin/components/character/character-animation.d.ts.map +0 -1
  38. package/dist/gameplay/actors/builtin/components/character/character-movement.d.ts.map +0 -1
  39. package/dist/gameplay/actors/builtin/components/character/modes.d.ts.map +0 -1
  40. package/dist/gameplay/actors/builtin/components/editor-sprite-component.d.ts.map +0 -1
  41. package/dist/gameplay/actors/builtin/components/mesh-component.d.ts.map +0 -1
  42. package/dist/gameplay/actors/builtin/components/scene-component.d.ts.map +0 -1
  43. package/dist/gameplay/actors/builtin/components/volume-editor-component.d.ts.map +0 -1
  44. package/dist/gameplay/actors/builtin/index.d.ts.map +0 -1
  45. package/dist/gameplay/actors/builtin/navmesh-actor.d.ts.map +0 -1
  46. package/dist/gameplay/actors/builtin/positional-audio-actor.d.ts.map +0 -1
  47. package/dist/gameplay/actors/builtin/post-process-volume-actor.d.ts.map +0 -1
  48. package/dist/gameplay/actors/builtin/spawn-point.d.ts.map +0 -1
  49. package/dist/gameplay/actors/builtin/trigger-volume.d.ts.map +0 -1
  50. package/dist/gameplay/actors/camera/camera-component.d.ts.map +0 -1
  51. package/dist/gameplay/actors/camera/third-person-camera-component.d.ts.map +0 -1
  52. package/dist/gameplay/actors/component.d.ts.map +0 -1
  53. package/dist/gameplay/actors/factory.d.ts.map +0 -1
  54. package/dist/gameplay/actors/index.d.ts.map +0 -1
  55. package/dist/gameplay/actors/internal/component-init.d.ts.map +0 -1
  56. package/dist/gameplay/actors/internal/container-map.d.ts.map +0 -1
  57. package/dist/gameplay/ai/behavior-tree/bt.d.ts.map +0 -1
  58. package/dist/gameplay/ai/behavior-tree/move.d.ts.map +0 -1
  59. package/dist/gameplay/ai/build-tile.d.ts.map +0 -1
  60. package/dist/gameplay/ai/dynamic-tiled-navmesh.d.ts.map +0 -1
  61. package/dist/gameplay/ai/dynamic-tiled-navmesh.worker.d.ts.map +0 -1
  62. package/dist/gameplay/ai/index.d.ts.map +0 -1
  63. package/dist/gameplay/ai/navigation.d.ts.map +0 -1
  64. package/dist/gameplay/animation/anim-sm.d.ts.map +0 -1
  65. package/dist/gameplay/animation/root-motion.d.ts.map +0 -1
  66. package/dist/gameplay/env.d.ts.map +0 -1
  67. package/dist/gameplay/index.d.ts.map +0 -1
  68. package/dist/gameplay/initiate.d.ts.map +0 -1
  69. package/dist/gameplay/inject.d.ts.map +0 -1
  70. package/dist/gameplay/input/index.d.ts.map +0 -1
  71. package/dist/gameplay/input/input-service.d.ts.map +0 -1
  72. package/dist/gameplay/input/input.d.ts.map +0 -1
  73. package/dist/gameplay/input/keybind.d.ts.map +0 -1
  74. package/dist/gameplay/polyfill.d.ts.map +0 -1
  75. package/dist/gameplay/services/asset-loader.d.ts.map +0 -1
  76. package/dist/gameplay/services/physics/abstract-physics-system.d.ts.map +0 -1
  77. package/dist/gameplay/services/physics/collision-contact.d.ts.map +0 -1
  78. package/dist/gameplay/services/physics/physics-system.d.ts.map +0 -1
  79. package/dist/gameplay/services/pointer-events.d.ts.map +0 -1
  80. package/dist/gameplay/services/render.d.ts.map +0 -1
  81. package/dist/gameplay/services/shader-provider.d.ts.map +0 -1
  82. package/dist/gameplay/services/world.d.ts.map +0 -1
  83. package/dist/index.d.ts.map +0 -1
  84. package/dist/rendering/bloom/LuminosityHighPassShader.d.ts.map +0 -1
  85. package/dist/rendering/bloom/UnrealBloomPass.d.ts.map +0 -1
  86. package/dist/rendering/bloom/types.d.ts.map +0 -1
  87. package/dist/rendering/color-pass.d.ts.map +0 -1
  88. package/dist/rendering/fog/fog-volume-actor.d.ts.map +0 -1
  89. package/dist/rendering/fog/fog-volume-object.d.ts.map +0 -1
  90. package/dist/rendering/fog/volumetric-fog-pass.d.ts.map +0 -1
  91. package/dist/rendering/outline-effect.d.ts.map +0 -1
  92. package/dist/rendering/shader-override.d.ts.map +0 -1
  93. package/dist/rendering/ssr/SSRPass.d.ts.map +0 -1
  94. package/dist/rendering/ssr/SSRShader.d.ts.map +0 -1
  95. package/dist/rendering/tone-mapping.d.ts.map +0 -1
  96. package/dist/rendering.d.ts.map +0 -1
  97. package/dist/scene/asset-resource-loader.d.ts.map +0 -1
  98. package/dist/scene/assets-provider.d.ts.map +0 -1
  99. package/dist/scene/batched-mesh-2.d.ts.map +0 -1
  100. package/dist/scene/bootstrap.d.ts.map +0 -1
  101. package/dist/scene/collision/collision-shape-import.d.ts.map +0 -1
  102. package/dist/scene/collision/collision-shape.d.ts.map +0 -1
  103. package/dist/scene/landscape/landscape-manager.d.ts.map +0 -1
  104. package/dist/scene/landscape/landscape.d.ts.map +0 -1
  105. package/dist/scene/landscape/utils.d.ts.map +0 -1
  106. package/dist/scene/materializer.d.ts.map +0 -1
  107. package/dist/scene/materials/grass-foliage.d.ts.map +0 -1
  108. package/dist/scene/materials/grass.d.ts.map +0 -1
  109. package/dist/scene/materials/utils/material-painting.d.ts.map +0 -1
  110. package/dist/scene/materials/utils/noise.glsl.d.ts.map +0 -1
  111. package/dist/scene/materials/water.d.ts.map +0 -1
  112. package/dist/scene/model.d.ts.map +0 -1
  113. package/dist/scene/objects/prefab.d.ts.map +0 -1
  114. package/dist/scene/objects/ramp-geometry.d.ts.map +0 -1
  115. package/dist/scene/objects/shapes.d.ts.map +0 -1
  116. package/dist/scene/objects/stairs-geometry.d.ts.map +0 -1
  117. package/dist/scene/runtime-asset-service.d.ts.map +0 -1
  118. package/dist/scene/runtime-backend-service.d.ts.map +0 -1
  119. package/dist/scene/runtime-bundled-backend-service.d.ts.map +0 -1
  120. package/dist/scene/scene-data-service.d.ts.map +0 -1
  121. package/dist/scene/sky.d.ts.map +0 -1
  122. package/dist/scene/storage/storage.d.ts.map +0 -1
  123. package/dist/shader/builtin/decal-standard-shader.d.ts.map +0 -1
  124. package/dist/shader/builtin/decal-unlit-shader.d.ts.map +0 -1
  125. package/dist/shader/builtin/index.d.ts.map +0 -1
  126. package/dist/shader/builtin/lambert-shader.d.ts.map +0 -1
  127. package/dist/shader/builtin/landscape-composite-shader.d.ts.map +0 -1
  128. package/dist/shader/builtin/landscape-shader.d.ts.map +0 -1
  129. package/dist/shader/builtin/layered-shader.d.ts.map +0 -1
  130. package/dist/shader/builtin/standard-shader.d.ts.map +0 -1
  131. package/dist/shader/builtin/toon-shader.d.ts.map +0 -1
  132. package/dist/shader/builtin/unlit-shader.d.ts.map +0 -1
  133. package/dist/shader/color-layer.d.ts.map +0 -1
  134. package/dist/shader/decal-shader.d.ts.map +0 -1
  135. package/dist/shader/index.d.ts.map +0 -1
  136. package/dist/shader/parameter.d.ts.map +0 -1
  137. package/dist/shader/shader.d.ts.map +0 -1
  138. package/dist/shader/sprite-shader.d.ts.map +0 -1
  139. package/dist/shader/trail-shader.d.ts.map +0 -1
  140. package/dist/shader-nodes/bulge.d.ts.map +0 -1
  141. package/dist/shader-nodes/curve-sample.d.ts.map +0 -1
  142. package/dist/shader-nodes/decal.d.ts.map +0 -1
  143. package/dist/shader-nodes/depth.d.ts.map +0 -1
  144. package/dist/shader-nodes/effects.d.ts.map +0 -1
  145. package/dist/shader-nodes/glsl-node.d.ts.map +0 -1
  146. package/dist/shader-nodes/index.d.ts.map +0 -1
  147. package/dist/shader-nodes/landscape.d.ts.map +0 -1
  148. package/dist/shader-nodes/layers.d.ts.map +0 -1
  149. package/dist/shader-nodes/math.d.ts.map +0 -1
  150. package/dist/shader-nodes/particle.d.ts.map +0 -1
  151. package/dist/shader-nodes/pom.d.ts.map +0 -1
  152. package/dist/shader-nodes/scene-sample.d.ts.map +0 -1
  153. package/dist/shader-nodes/shapes.d.ts.map +0 -1
  154. package/dist/shader-nodes/texture-sequence.d.ts.map +0 -1
  155. package/dist/shader-nodes/time.d.ts.map +0 -1
  156. package/dist/shader-nodes/voronoi.d.ts.map +0 -1
  157. package/dist/test/injection.test.d.ts.map +0 -1
  158. package/dist/utils/async.d.ts.map +0 -1
  159. package/dist/utils/buffer.d.ts.map +0 -1
  160. package/dist/utils/collections.d.ts.map +0 -1
  161. package/dist/utils/curve.d.ts.map +0 -1
  162. package/dist/utils/files.d.ts.map +0 -1
  163. package/dist/utils/materials.d.ts.map +0 -1
  164. package/dist/utils/math.d.ts.map +0 -1
  165. package/dist/utils/mesh.d.ts.map +0 -1
  166. package/dist/utils/polyfill.d.ts.map +0 -1
  167. package/dist/utils/three/cleanup.d.ts.map +0 -1
  168. package/dist/utils/three/depth-pass.d.ts.map +0 -1
  169. package/dist/utils/three/gpu-stats-panel.d.ts.map +0 -1
  170. package/dist/utils/three/line-sphere.d.ts.map +0 -1
  171. package/dist/utils/three/outline-pass.d.ts.map +0 -1
  172. package/dist/utils/three/positional-audio-helper.d.ts.map +0 -1
  173. package/dist/utils/three/stats.d.ts.map +0 -1
  174. package/dist/utils/three/transform-controls.d.ts.map +0 -1
  175. package/dist/utils/three/traverse.d.ts.map +0 -1
  176. package/dist/utils/three/unscaled-sprite.d.ts.map +0 -1
  177. package/dist/utils/type.d.ts.map +0 -1
  178. package/dist/utils/uuid.d.ts.map +0 -1
  179. package/dist/utils/voxel-bitset.d.ts.map +0 -1
  180. package/dist/worker/index.d.ts.map +0 -1
@@ -3,7 +3,7 @@ import { Observable, Subject } from "rxjs";
3
3
  import * as THREE from "three";
4
4
  import { ColorRepresentation, Object3D, Quaternion, Vector3 } from "three";
5
5
  import { CollisionShape } from '../../../index.js';
6
- import { AbstractType } from '../../../utils/type.js';
6
+ import { AbstractType, Type } from '../../../utils/type.js';
7
7
  import { BaseActor } from '../../actors/actor.js';
8
8
  import { ViewController } from '../render.js';
9
9
  import { AbstractPhysicsSystem, ActorPhysicsOptions } from './abstract-physics-system.js';
@@ -108,6 +108,15 @@ export declare class PhysicsSystem extends AbstractPhysicsSystem {
108
108
  * @returns
109
109
  */
110
110
  hasSphereIntersection(sphere: THREE.Sphere): boolean;
111
+ /**
112
+ * Finds all actors whose collision shapes intersect with a given sphere.
113
+ * Note that this is relatively expensive so don't call it every frame.
114
+ * @param position
115
+ * @param radius
116
+ * @param actorType Limit the search to a specific actor class.
117
+ * @returns List of actors
118
+ */
119
+ findActorsInRadius<T = BaseActor>(position: Vector3, radius: number, actorType?: Type<T>): T[];
111
120
  private debugMesh;
112
121
  private createDebugMesh;
113
122
  /**
@@ -1,4 +1,4 @@
1
- import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as l,takeUntil as c}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as y,BufferGeometry as u,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as B,Scene as x,Vector3 as b}from"three";import{Service as v}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as A,CapsuleCollisionShape as S,CollisionShapeSource as R,ConeCollisionShape as D,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as T,PhysicalShapeMesh as M,PlaneCollisionShape as E,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as k}from"../render.js";import{World as F}from"../world.js";import*as I from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as W}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as j,Component as L}from"../../../gameplay/actors/component.js";import{inject as O}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.normal=new b}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new b,K=new b,q=new w,U=new w,H=(new w,[]);let Q=class extends N{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t){super(),this.viewController=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new B,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new i.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,s){const o=t+1e6*e+1e12*s;let n=this.shapeCacheBox.get(o);return null==n&&(n=new i.Cuboid(t,e,s),this.shapeCacheBox.set(o,n)),n}hasBoxIntersection(t){const e=t.getCenter(G),i=t.getSize(K),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,q,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,q,e)}createDebugMesh(){return new g(new u,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new y(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await rt(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;null!=e&&e.parent instanceof x&&(ct(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&dt(e.quaternion,t.rotation()),e.updateMatrix(),e.updateWorldMatrix(!1,!1))}),this.afterStep.next(t)})}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})})}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(st,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;at(mt.origin,t),at(mt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(mt,r,!1,void 0,s?.collisionFilter,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=mt.pointAt(a.timeOfImpact);i._internal=a,ct(i.hitNormal,a.normal),ct(i.hitPoint,e),i.distance=yt.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){let e;H.length>0?(e=H.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),H.push(e)},s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return J.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())ht(t,t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof M&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof C&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&(t.children[0].instanceMatrix||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof _?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes?.[o];if(null==e){console.warn("Missing collision shapes for batched instance");continue}let n=s.get(e);null==n&&(n=this.instancedShapeReset(e),s.set(e,n));const r=new f;r.matrix.identity(),t.getMatrixAt(o,i),r.applyMatrix4(i);this.createStaticBody(r,n)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>t.source===R.rendered?t.withOffset(wt):t)}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,pt);const a=e.computedMovement();return ct(ut,a),ut}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const s=(()=>{switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return i.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return i.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyDesc.kinematicVelocityBased();default:return i.RigidBodyDesc.dynamic()}})();e.position&&s.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&s.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&s.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&s.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&s.setGravityScale(e.gravityScale),"number"==typeof e.mass&&s.setAdditionalMass(e.mass),void 0!==e.userData&&(s.userData=e.userData);const o=this.world.createRigidBody(s);return new PhysicsBody(o,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,pt);const r=e.computedMovement();return ct(ut,r),ut}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setNextKinematicTranslation(ot(i)),t.setNextKinematicRotation(nt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setAngvel(tt,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setLinvel(tt,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(ot(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ct(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&dt(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some(t=>t.m===n.name&&0!==t.w[0])){const t=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const l=t.index;for(let t=0;t<l.count;t+=3){const e=r.getX(l.getX(t)),i=r.getX(l.getY(t)),s=r.getX(l.getZ(t));(e>.5||i>.5||s>.5)&&(l.setX(t,0),l.setY(t,0),l.setZ(t,0))}const c=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(c,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,s={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);return ht(r,t=>{null!=s.isTrigger&&(t.setSensor(s.isTrigger),t.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&t.setFriction(s.friction),null!=s.density&&t.setDensity(s.density),null!=s.mass&&t.setMass(s.mass),null!=s.restitution&&t.setRestitution(s.restitution)}),Z(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t),new PhysicsBody(r,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addTorque(tt,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyTorqueImpulse(tt,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addForce(tt,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyImpulse(tt,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s?.addForce(tt,!0):(at(et,i),s?.addForceAtPoint(tt,et,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s.applyImpulse(tt,!0):(at(et,i),s.applyImpulseAtPoint(tt,et,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach(o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=it;ct(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);tt.x=a.x,tt.y=a.y,tt.z=a.z,o.applyImpulse(tt,!0)})}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse(t=>{e.add(t.uuid)});for(const[t,i]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof _){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(({started:t})=>t===i),a(({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i})),r(({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s)),a(({a2:t})=>t))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>!t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe(t=>{e.add(t),i.next(e.size>0)}),this.onEndContact(t).subscribe(t=>{e.delete(t),i.next(e.size>0)}),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e&&Z(e,t.object)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n=void 0){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n,null,void 0,void 0);if(null!=c){ct(o.hitPoint,c.witness1),o.normal.set(c.normal1.x,c.normal1.y,c.normal1.z),o.distance=c.time_of_impact,o.hasHit=!0;const t=c.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const y=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=y){y.collider;const t=r;return ct(s.hitPoint,y.witness1),Bt(t.rotation(),y.normal1,s.normal,U),s.distance=y.time_of_impact,s.actor=this.bodyActors.get(y.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){this.world?.bodies.forEach(t=>this.world.removeRigidBody(t)),this.world?.free(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),H.length=0}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Z(n,t),n.userData=t.uuid,n}addShape(t=void 0,e,i){const s=i?.getWorldScale(gt)??$,o=this.createShape(e,s);this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);at(o.translation,n);const r=(new w).setFromEuler(e.rotation);e instanceof z&&e.mesh instanceof d.Mesh&&r.multiply(e.mesh.getWorldQuaternion(Y)),lt(o.rotation,r);return this.world.createCollider(o,t)}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof A)return i.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof S){return i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof V){const s=null!=t.geometry.getIndex()?t.geometry:I.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=W(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof P){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof T?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof D?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};Q=t([v(),e("design:paramtypes",[k])],Q);export{Q as PhysicsSystem};const X=new b,Y=new d.Quaternion;function Z(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setTranslation(ot(i),!1),t.setRotation(nt(s),!1)}const J=new b,$=new b(1,1,1),tt=new i.Vector3(0,0,0),et=new i.Vector3(0,0,0),it=new b,st=new d.Vector2;function ot(t){return at(tt,t),tt}function nt(t){return lt(U,t),U}const rt=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function at(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ct(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function dt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ht(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const yt=new b,ut=new b,pt=t=>!t.isSensor(),gt=new b;const mt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let ft=class extends j{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),this.world=O(F)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};ft=t([L()],ft);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}const wt=new b;function Bt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
1
+ import{__decorate as t,__metadata as e}from"tslib";import*as i from"@dimforge/rapier3d-compat";import{QueryFilterFlags as s}from"@dimforge/rapier3d-compat";import{BehaviorSubject as o,distinctUntilChanged as n,filter as r,map as a,Subject as l,takeUntil as c}from"rxjs";import*as d from"three";import{ArrowHelper as h,BufferAttribute as y,BufferGeometry as u,Group as p,LineSegments as g,Matrix4 as m,Object3D as f,Quaternion as w,Raycaster as B,Scene as x,Vector3 as b}from"three";import{Service as v}from"typedi";import{AssetMeshInstance as C}from"../../../scene/asset-resource-loader.js";import{BoxCollisionShape as A,CapsuleCollisionShape as S,CollisionShapeSource as R,ConeCollisionShape as D,ConvexPolyhedronCollisionShape as z,CylinderCollisionShape as T,PhysicalShapeMesh as M,PlaneCollisionShape as E,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as I}from"../render.js";import{World as k}from"../world.js";import*as F from"three/examples/jsm/utils/BufferGeometryUtils.js";import{calculateEffectiveScale as W}from"../../../utils/three/traverse.js";import{AbstractPhysicsSystem as N}from"./abstract-physics-system.js";import{ActorComponent as j,Component as L}from"../../../gameplay/actors/component.js";import{inject as O}from"../../../gameplay/inject.js";export{Component,ActorComponent,attach,Attach}from"../../actors/component.js";export class RayTestResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.hitNormal=new b}}export class ShapeCastResult{constructor(){this.hasHit=!1,this.hitPoint=new b,this.normal=new b}reset(){this.actor=void 0,this.hasHit=!1,this.distance=0,this.hitPoint.set(0,0,0),this.normal.set(0,0,0)}}ShapeCastResult.shared=new ShapeCastResult;export var PhysicsBodyType;!function(t){t[t.dynamic=1]="dynamic",t[t.static=2]="static",t[t.kinematic=4]="kinematic",t[t.kinematicVelocityBased=8]="kinematicVelocityBased"}(PhysicsBodyType||(PhysicsBodyType={}));const G=new b,K=new b,q=new w,U=new w,H=(new w,[]);let Q=class extends N{set showDebug(t){this.shouldRenderDebug=t,this.debugMesh&&(this.debugMesh.visible=t)}get showDebug(){return this.shouldRenderDebug}constructor(t){super(),this.viewController=t,this.staticMeshes=new Map,this.staticBodies=new Map,this.actorBodies=new Map,this.bodyActors=new Map,this.colliders=new Map,this.collisionEvents=new l,this.beforeStep=new l,this.afterStep=new l,this.shouldRenderDebug=!1,this.shapeCacheBox=new Map,this.shapeCacheBall=new Map,this._raycaster=new B,this._reusableResult=new RayTestResult,this._raytestDiff=new b,this._raytestDirection=new b,this.controlledActors=new Set,this.ready=this.setup()}getBallShape(t){let e=this.shapeCacheBall.get(t);return null==e&&(e=new i.Ball(t),this.shapeCacheBall.set(t,e)),e}getBoxShape(t,e,s){const o=t+1e6*e+1e12*s;let n=this.shapeCacheBox.get(o);return null==n&&(n=new i.Cuboid(t,e,s),this.shapeCacheBox.set(o,n)),n}hasBoxIntersection(t){const e=t.getCenter(G),i=t.getSize(K),s=this.getBoxShape(i.x/2,i.y/2,i.z/2);return null!=this.world.intersectionWithShape(e,q,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,q,e)}findActorsInRadius(t,e,i){const s=this.getBallShape(e),o=[];for(const[e,n]of this.bodyActors)if(n instanceof i||null==i)for(let i=0,r=e.numColliders();i<r;i++){e.collider(i).intersectsShape(s,t,q)&&o.push(n)}return o}createDebugMesh(){return new g(new u,new d.LineBasicMaterial({color:255}))}async start(){return await this.ready,this.handleTick(),this.handleCollisionEvents(),this.ready}handleCollisionEvents(){this.collisionSub=this.collisionEvents.subscribe(t=>{const e=this.colliders.get(t.handle1);if(null==e)return;const i=this.world.getCollider(t.handle2);if(null==i||null==i.parent())return;const s=this.bodyActors.get(i.parent());null!=s&&(t.started?e.onBeginOverlapActor.next({actor:s}):e.onEndOverlapActor.next({actor:s}))})}renderDebug(){if(null==this.scene)return;null==this.debugMesh&&(this.debugMesh=this.createDebugMesh(),this.debugMesh.visible=this.shouldRenderDebug,this.debugMesh.raycast=function(){},this.scene?.add(this.debugMesh));const t=this.world.debugRender();this.debugMesh.geometry.setAttribute("position",new y(t.vertices,3))}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await rt(),this.eventQueue=new i.EventQueue(!0),this.setupWorld()}handleTick(){this.fixedupdateSub=this.viewController.onUpdate().subscribe(t=>{t=Math.min(.1,t),this.beforeStep.next(t),this.updatePhysics(t),this.showDebug&&this.renderDebug(),this.world.bodies.forEach(t=>{if(t.isFixed())return;const e=this.staticMeshes.get(t)??this.bodyActors.get(t)?.object;null!=e&&e.parent instanceof x&&(ct(e.position,t.translation()),(t.isDynamic()||t.isKinematic()&&!this.controlledActors.has(this.bodyActors.get(t)?.id))&&dt(e.quaternion,t.rotation()),e.updateMatrix(),e.updateWorldMatrix(!1,!1))}),this.afterStep.next(t)})}_updateWorld(){this.world.timestep=0,this.world.step()}updatePhysics(t){this.world.timestep=t,this.world.step(this.eventQueue),this.eventQueue.drainCollisionEvents((t,e,i)=>{this.collisionEvents.next({handle1:t,handle2:e,started:i}),this.collisionEvents.next({handle1:e,handle2:t,started:i})})}rayTestFromCamera(t,e,i){this._raycaster.setFromCamera(st,this.viewController.getCamera());const s=this._raycaster.ray.origin,o=this._raycaster.ray.direction.multiplyScalar(t).add(s);return this.rayTest(s,o,e,i)}rayTest(t,e,i,s){null==i&&(i=this._reusableResult);const o=this._raytestDiff,n=this._raytestDirection;if(o.subVectors(e,t),n.copy(o).normalize(),0===n.length())return console.warn("Ray test called with to and from being equal"),i;at(mt.origin,t),at(mt.dir,n);const r=o.length(),a=this.world.castRayAndGetNormal(mt,r,!1,void 0,s?.collisionFilter,void 0,null!=s?.excludeActor?this.actorBodies.get(s.excludeActor.id):void 0,s?.excludeTriggers?t=>!t.isSensor():void 0);if(i.hasHit=null!=a,i.hasHit){const e=mt.pointAt(a.timeOfImpact);i._internal=a,ct(i.hitNormal,a.normal),ct(i.hitPoint,e),i.distance=yt.subVectors(i.hitPoint,t).length();const s=this.world.bodies.getAll().find(t=>function(t,e){for(let i=0,s=t.numColliders();i<s;i++){const s=t.collider(i);if(e(s))return s}}(t,t=>t===a.collider));i.actor=null!=s?this.bodyActors.get(s):null}if(this.showDebug){let e;H.length>0?(e=H.pop(),e.setDirection(n),e.position.copy(t),e.setLength(r,.2,.1),e.setColor(s?.debugColor??255)):e=new h(n,t,r,s?.debugColor??255),this.scene?.add(e),setTimeout(()=>{this.scene?.remove(e),H.push(e)},s?.debugLifetime??200)}return i}setGravity(t,e,i){this.world.gravity.x=t,this.world.gravity.y=e,this.world.gravity.z=i}getGravity(){return J.set(this.world.gravity.x,this.world.gravity.y,this.world.gravity.z)}addFromScene(t){this.addRecursively(t);for(const t of this.staticBodies.values())ht(t,t=>t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS))}addRecursively(t){if(this.removeSceneObject(t),!function(t){if(null!=t.userData?.src){const e=t.userData?.src;return"actor"===e.type}return!1}(t))if(t instanceof M&&null!=t.collisionShape){const e=this.createStaticBody(t,[t.collisionShape],t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else if(t instanceof C&&!1!==t.userData?.src?.collisionDetection)if(t.children[0]&&(t.children[0].instanceMatrix||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else{const e=this.createStaticBody(t,t.collisionShapes,t.physics);this.staticMeshes.set(e,t),this.staticBodies.set(t,e)}else t instanceof _?this.addLandscapeGroup(t):(t instanceof p||t instanceof x)&&t.children.forEach(t=>this.addRecursively(t))}createForInstancedMesh(t,e){const i=new m;if(t instanceof d.BatchedMesh){const e=t._instanceInfo??t._drawInfo,s=new Map;for(let o=0;o<e.length;o++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[o])continue;const e=t.userData.collisionShapes?.[o];if(null==e)continue;let n=s.get(e);null==n&&(n=this.instancedShapeReset(e),s.set(e,n));const r=new f;r.matrix.identity(),t.getMatrixAt(o,i),r.applyMatrix4(i);this.createStaticBody(r,n)}}else{const s=this.instancedShapeReset(e);for(let e=0;e<t.count;e++){if(null!=t.userData.hasCollision&&!t.userData.hasCollision[e])continue;const o=new f;o.matrix.identity(),i.fromArray(t.instanceMatrix.array,16*e),o.applyMatrix4(i);this.createStaticBody(o,s)}}}instancedShapeReset(t){return t.filter(t=>null!=t).map(t=>t.source===R.rendered?t.withOffset(wt):t)}getCharacterController(t){return this.world?.createCharacterController(t)}getActorComputedMovement(t,e,i,o=null){const n=this.actorBodies.get(t.id);this.controlledActors.add(t.id);const r=n.collider(0);e.computeColliderMovement(r,i,s.EXCLUDE_SENSORS,o,pt);const a=e.computedMovement();return ct(ut,a),ut}createCollider(t,e){const i=this.addShape(e?.body,t),s=new PhysicsCollider(i,this.world);return this.colliders.set(i.handle,s),s.disposed.subscribe(()=>{this.colliders.delete(i.handle)}),s}createBody(t=PhysicsBodyType.dynamic,e={}){const s=(()=>{switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyDesc.dynamic();case PhysicsBodyType.static:return i.RigidBodyDesc.fixed();case PhysicsBodyType.kinematic:return i.RigidBodyDesc.kinematicPositionBased();case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyDesc.kinematicVelocityBased();default:return i.RigidBodyDesc.dynamic()}})();e.position&&s.setTranslation(e.position.x,e.position.y,e.position.z),e.rotation&&s.setRotation({x:e.rotation.x,y:e.rotation.y,z:e.rotation.z,w:e.rotation.w}),"boolean"==typeof e.canSleep&&s.setCanSleep(e.canSleep),"boolean"==typeof e.ccdEnabled&&s.setCcdEnabled(e.ccdEnabled),"number"==typeof e.gravityScale&&s.setGravityScale(e.gravityScale),"number"==typeof e.mass&&s.setAdditionalMass(e.mass),void 0!==e.userData&&(s.userData=e.userData);const o=this.world.createRigidBody(s);return new PhysicsBody(o,this.world)}getCharacterComputedMovement(t,e,i,o=null){const n=t.collider;e.computeColliderMovement(n,i,s.EXCLUDE_SENSORS,o,pt);const r=e.computedMovement();return ct(ut,r),ut}setNextKinematicTranslation(t,e){const i=this.actorBodies.get(t.id),s=i.translation();s.x+=e.x,s.y+=e.y,s.z+=e.z,i?.setNextKinematicTranslation(s)}setNextKinematicPosition(t,e){this.actorBodies.get(t.id).setNextKinematicTranslation(e)}setNextKinematicRotation(t,e){this.actorBodies.get(t.id).setNextKinematicRotation(e)}setNextKinematicTransform(t){!function(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setNextKinematicTranslation(ot(i)),t.setNextKinematicRotation(nt(s))}(this.actorBodies.get(t.id),t.object)}setAngularVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setAngvel(tt,!0)}setLinearVelocity(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.setLinvel(tt,!0)}getLinearVelocity(t,e=new b){const i=this.actorBodies.get(t.id).linvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}getAngularVelocity(t,e=new b){const i=this.actorBodies.get(t.id).angvel();return e.x=i.x,e.y=i.y,e.z=i.z,e}setLinearDamping(t,e){const i=this.actorBodies.get(t.id);i?.setLinearDamping(e)}getLienarDamping(t){const e=this.actorBodies.get(t.id);return e?.linearDamping()??0}setAngularDamping(t,e){const i=this.actorBodies.get(t.id);i?.setAngularDamping(e)}getAngularDamping(t){const e=this.actorBodies.get(t.id);e?.angularDamping()}setPosition(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(ot(e),!1)}getPosition(t,e=new b){const i=this.actorBodies.get(t.id);i&&ct(e,i.translation())}setRotation(t,e){const i=this.actorBodies.get(t.id);i?.setTranslation(nt(e),!1)}getRotation(t,e=new w){const i=this.actorBodies.get(t.id);i&&dt(e,i.rotation())}lockTranslations(t,e){const i=this.actorBodies.get(t.id);i?.lockTranslations(e,!1)}lockRotations(t,e){const i=this.actorBodies.get(t.id);i?.lockRotations(e,!1)}setEnabledTranslations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledTranslations(e,i,s,!1)}setEnabledRotations(t,e,i,s){const o=this.actorBodies.get(t.id);o?.setEnabledRotations(e,i,s,!1)}addLandscapeGroup(t){const e=t.userData.src,s=e.landscape.heightMaps;for(const n of t.sections){this.staticBodies.has(n)&&this.world.removeRigidBody(this.staticBodies.get(n));var o=n.getWorldPosition(new b);if(e.landscape.holes&&e.landscape.holes.some(t=>t.m===n.name&&0!==t.w[0])){const t=n.geometry.clone(),s=n.scale,r=n.geometry.getAttribute("hole"),a=new Float32Array(t.getAttribute("position").array);for(let t=0;t<a.length;t+=3)a[t]*=s.x,a[t+1]*=s.y,a[t+2]*=s.z;const l=t.index;for(let t=0;t<l.count;t+=3){const e=r.getX(l.getX(t)),i=r.getX(l.getY(t)),s=r.getX(l.getZ(t));(e>.5||i>.5||s>.5)&&(l.setX(t,0),l.setY(t,0),l.setZ(t,0))}const c=i.ColliderDesc.trimesh(a,new Uint32Array(t.getIndex().array));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(c,t),this.staticBodies.set(n,t)}continue}const t=e.landscape.options.density+1,r=e.landscape.options.sectionSize,a=new Array(t);for(let e=0;e<t;e++)a[e]=new Array(t).fill(0);const l=s.find(t=>t.x===n.x&&t.y==n.y);if(null!=l)for(const e of l.points){if(null==a[e.i%t])continue;const i=t-1-Math.floor(e.i/t);i in a[e.i%t]?a[e.i%t][i]=e.y/r:console.warn("wrong index",{points:a,point:e,i:e.i%t,k:i,heightMap:l})}const c=e.landscape.options.density,d=a.flatMap(t=>t.reverse()),h=i.ColliderDesc.heightfield(c,c,new Float32Array(d),new i.Vector3(r,r,r));if(!1!==e.collisionDetection){const t=this.world.createRigidBody(i.RigidBodyDesc.fixed()),e=new i.Vector3(0,0,0);at(e,o),t.setTranslation(e,!1),this.world.createCollider(h,t),this.staticBodies.set(n,t)}}}setEnabled(t,e){const i=this.actorBodies.get(t.id);i?.setEnabled(e)}addActor(t,e,s={}){if(0==e.length)return void console.error("No collision shapes were defined when adding actor to the physics system.");this.removeActor(t);const o=t.object;let n;switch(s.type??PhysicsBodyType.static){case PhysicsBodyType.dynamic:n=i.RigidBodyDesc.dynamic(),n.mass=s.mass??1;break;case PhysicsBodyType.kinematic:n=i.RigidBodyDesc.kinematicPositionBased();break;case PhysicsBodyType.kinematicVelocityBased:n=i.RigidBodyDesc.kinematicVelocityBased();break;default:n=s.isTrigger?i.RigidBodyDesc.kinematicVelocityBased():i.RigidBodyDesc.fixed()}const r=this.world.createRigidBody(n);r.enableCcd(1==s.continousCollisionDetection);for(const t of e)this.addShape(r,t,o);return ht(r,t=>{null!=s.isTrigger&&(t.setSensor(s.isTrigger),t.setActiveCollisionTypes(i.ActiveCollisionTypes.ALL),t.setActiveEvents(i.ActiveEvents.COLLISION_EVENTS)),null!=s.friction&&t.setFriction(s.friction),null!=s.density&&t.setDensity(s.density),null!=s.mass&&t.setMass(s.mass),null!=s.restitution&&t.setRestitution(s.restitution)}),Z(r,o),!0===s.ignoreForNavMesh&&(r.userData={ignoreForNavMesh:!0}),this.actorBodies.set(t.id,r),this.bodyActors.set(r,t),new PhysicsBody(r,this.world)}applyTorque(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addTorque(tt,!0)}applyTorqueImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyTorqueImpulse(tt,!0)}resetForces(t){const e=this.actorBodies.get(t.id);e?.resetForces(!1)}resetTorques(t){const e=this.actorBodies.get(t.id);e?.resetTorques(!1)}applyForce(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.addForce(tt,!0)}applyImpulse(t,e){const i=this.actorBodies.get(t.id);tt.x=e.x,tt.y=e.y,tt.z=e.z,i?.applyImpulse(tt,!0)}applyLocalForce(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s?.addForce(tt,!0):(at(et,i),s?.addForceAtPoint(tt,et,!0))}applyLocalImpulse(t,e,i){const s=this.actorBodies.get(t.id);at(tt,e),null==i?s.applyImpulse(tt,!0):(at(et,i),s.applyImpulseAtPoint(tt,et,!0))}applyRadiusImpulse(t,e,s){this.world.bodies.forEach(o=>{if(o.collider(0)?.isSensor())return;if(o.bodyType()!==i.RigidBodyType.Dynamic)return;const n=it;ct(n,o.translation());const r=n.clone().sub(t);if(r.length()>e)return;const a=r.clone().normalize().multiplyScalar(s);tt.x=a.x,tt.y=a.y,tt.z=a.z,o.applyImpulse(tt,!0)})}removeActor(t){if(null==t)return;this.controlledActors.delete(t.id);const e=this.actorBodies.get(t.id);null!=e&&(this.bodyActors.delete(e),this.world.removeRigidBody(e)),this.actorBodies.delete(t.id)}removeRemoved(t){if(null==t)return;const e=new Set;t.traverse(t=>{e.add(t.uuid)});for(const[t,i]of this.staticBodies.entries())!e.has(t.uuid)&&this.world.getRigidBody(i.handle)&&(this.staticBodies.delete(t),this.world.removeRigidBody(i))}removeSceneObject(t){if(t instanceof _){for(const e of t.sections)this.removeSceneObject(e);return}let e=this.staticBodies.get(t);null!=e&&this.world.getRigidBody(e.handle)&&this.world.removeRigidBody(e),this.staticBodies.delete(t)}activateActorEvents(t){this.actorBodies.get(t.id)}_onCollisionWithActorEvent(t,e,i){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(({started:t})=>t===i),a(({handle1:t,handle2:e,started:i})=>({a1:this.bodyActors.get(this.world.getCollider(t)?.parent()),a2:this.bodyActors.get(this.world.getCollider(e)?.parent()),started:i})),r(({a1:i,a2:s})=>null!=i&&null!=s&&i.id===t.id&&e(i,s)),a(({a2:t})=>t))}onBeginContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onEndContact(t){return this.activateActorEvents(t),this.collisionEvents.pipe(c(t.disposed),r(t=>!t.started),r(({handle1:e})=>{const i=this.bodyActors.get(this.world.getCollider(e)?.parent());return null!=i&&i.id===t.id}),a(t=>t.handle2))}onHasContactChanged(t){const e=new Set,i=new o(!1);return this.onBeginContact(t).subscribe(t=>{e.add(t),i.next(e.size>0)}),this.onEndContact(t).subscribe(t=>{e.delete(t),i.next(e.size>0)}),i.pipe(n())}onBeginOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!0)}onEndOverlapWithActorType(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>i instanceof e,!1)}onBeginOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!0)}onEndOverlapWithActor(t,e){return this._onCollisionWithActorEvent(t,(t,i)=>e.id===i.id,!1)}onCollisionWithActor(t,e){return this.onBeginOverlapWithActor(t,e)}onCollisionWithActorType(t,e){return this.onBeginOverlapWithActorType(t,e)}updateActorTransform(t){const e=this.actorBodies.get(t.id);null!=e&&Z(e,t.object)}setupWorld(){const t=new i.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n=void 0){o.reset();const r=this.getBallShape(e);this.shapeCacheBall.get;const a={x:t.x,y:t.y,z:t.z},l={x:i.x,y:i.y,z:i.z},c=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n,null,void 0,void 0);if(null!=c){ct(o.hitPoint,c.witness1),o.normal.set(c.normal1.x,c.normal1.y,c.normal1.z),o.distance=c.time_of_impact,o.hasHit=!0;const t=c.collider.parent();if(t){const e=this.bodyActors.get(t);e&&(o.actor=e)}}return o}castActorShape(t,e,i,s=ShapeCastResult.shared,o=void 0){s.reset();const n=this.actorBodies.get(t.id);if(n&&n.numColliders()>0){for(let t=0;t<n.numColliders();t++){const r=n.collider(t);let a=r.shape,l=r.translation(),c=r.rotation(),d=e,h=i;const y=this.world.castShape(l,c,d,a,.01,h,!0,null,o,null,n,void 0);if(null!=y){y.collider;const t=r;return ct(s.hitPoint,y.witness1),Bt(t.rotation(),y.normal1,s.normal,U),s.distance=y.time_of_impact,s.actor=this.bodyActors.get(y.collider.parent()),s.hasHit=!0,s}}return s}return console.warn("Actor is not added to the physics system"),s}stop(){this.world?.bodies.forEach(t=>this.world.removeRigidBody(t)),this.world?.free(),this.fixedupdateSub?.unsubscribe(),this.collisionSub?.unsubscribe(),H.length=0}createStaticBody(t,e,s){const o=s?.type===PhysicsBodyType.dynamic?i.RigidBodyDesc.dynamic():i.RigidBodyDesc.fixed(),n=this.world.createRigidBody(o);for(const i of e){if(null==i){console.warn("Collision shape is missing for object",t);continue}const o=this.addShape(n,i,t);null!=s?.friction&&o.setFriction(s.friction),null!=s?.density&&o.setDensity(s.density),null!=s?.mass&&o.setMass(s.mass/e.length),null!=s?.restitution&&o.setRestitution(s.restitution)}return Z(n,t),n.userData=t.uuid,n}addShape(t=void 0,e,i){const s=i?.getWorldScale(gt)??$,o=this.createShape(e,s);this.applyShapeSettings(o,e);const n=e.offset.clone().multiply(s);at(o.translation,n);const r=(new w).setFromEuler(e.rotation);e instanceof z&&e.mesh instanceof d.Mesh&&r.multiply(e.mesh.getWorldQuaternion(Y)),lt(o.rotation,r);return this.world.createCollider(o,t)}applyShapeSettings(t,e){null!=e.collisionGroup&&t.setCollisionGroups(e.collisionGroup),t.friction=e.friction??.1,null!=e.restitution&&(t.restitution=e.restitution),null!=e.density&&(t.density=e.density,t.massPropsMode=i.MassPropsMode.Density),null!=e.mass&&(t.mass=e.mass,t.massPropsMode=i.MassPropsMode.Mass)}createShape(t,e){if(t instanceof A)return i.ColliderDesc.cuboid(t.dimensions.x*e.x/2,t.dimensions.y*e.y/2,t.dimensions.z*e.z/2);if(t instanceof S){return i.ColliderDesc.capsule(t.length/2*e.y,t.radius*Math.max(e.z,e.x))}if(t instanceof V){const s=null!=t.geometry.getIndex()?t.geometry:F.mergeVertices(t.geometry),o=extractFloat32Array(s.getAttribute("position"));for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;return i.ColliderDesc.trimesh(o,new Uint32Array(s.getIndex().array))}if(t instanceof z){let s;t.mesh instanceof d.Mesh?s=t.mesh.geometry:t.mesh instanceof d.BufferGeometry?s=t.mesh:console.log("Unknownd shape",{shapeInfo:t});const o=extractFloat32Array(s.getAttribute("position"));if(t.mesh instanceof d.Mesh){const e=W(t.mesh);for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z}for(let t=0;t<o.length;t+=3)o[t]*=e.x,o[t+1]*=e.y,o[t+2]*=e.z;const n=o;n.length;return i.ColliderDesc.convexHull(n)}if(t instanceof P){const s=2*e.x-e.y-e.z;return Math.abs(s)>.01?this.createShape(new z(new d.SphereGeometry(t.radius).scale(e.x,e.y,e.z)),new b(1,1,1)):i.ColliderDesc.ball(t.radius*Math.max(e.x,e.y,e.z))}return t instanceof T?i.ColliderDesc.cylinder(t.height/2*e.y,t.radiusTop*Math.max(e.z,e.x)):t instanceof D?i.ColliderDesc.cone(t.height*e.y,t.radiusBottom/2*Math.max(e.z,e.x)):t instanceof E?i.ColliderDesc.cuboid(t.width/2*e.x,t.height/2*e.y,.001):(console.error("Unsupported shape",t),i.ColliderDesc.cuboid(1,1,1))}createCharacterCollision(){return new i.CharacterCollision}};Q=t([v(),e("design:paramtypes",[I])],Q);export{Q as PhysicsSystem};const X=new b,Y=new d.Quaternion;function Z(t,e){const i=e.getWorldPosition(X),s=e.getWorldQuaternion(Y);t.setTranslation(ot(i),!1),t.setRotation(nt(s),!1)}const J=new b,$=new b(1,1,1),tt=new i.Vector3(0,0,0),et=new i.Vector3(0,0,0),it=new b,st=new d.Vector2;function ot(t){return at(tt,t),tt}function nt(t){return lt(U,t),U}const rt=async()=>{let t=await import("@dimforge/rapier3d-compat");return await t.init(),t};function at(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function lt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ct(t,e){t.x=e.x,t.y=e.y,t.z=e.z}function dt(t,e){t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w}function ht(t,e){for(let i=0,s=t.numColliders();i<s;i++){e(t.collider(i))}}const yt=new b,ut=new b,pt=t=>!t.isSensor(),gt=new b;const mt=new i.Ray(new i.Vector3(0,0,0),new i.Vector3(0,1,0));let ft=class extends j{constructor(){super(...arguments),this._active=!0,this.physics=O(Q),this.world=O(k)}set active(t){this._active=t,t?(this.world.scene.remove(this.actor.object),this.physics.setEnabled(this.actor,t)):(this.world.scene.add(this.actor.object),this.physics.setEnabled(this.actor,t))}get active(){return this._active}};ft=t([L()],ft);export function extractFloat32Array(t){const e=t.itemSize,i=t.count,s=new Float32Array(i*e);for(let o=0;o<i;o++)for(let i=0;i<e;i++)s[o*e+i]=t.getComponent(o,i);return s}const wt=new b;function Bt(t,e,i,s){return s.set(t.x,t.y,t.z,t.w),i.set(e.x,e.y,e.z),i.applyQuaternion(s),i}export class PhysicsCollider{constructor(t,e){this.collider=t,this.world=e,this.disposed=new l,this.onBeginOverlapActor=new l,this.onEndOverlapActor=new l}dispose(){this.world.removeCollider(this.collider,!1),this.disposed.next(!0),this.disposed.complete(),this.onBeginOverlapActor.complete(),this.onEndOverlapActor.complete()}set mass(t){this.collider.setMass(t)}get mass(){return this.collider.mass()}set friction(t){this.collider.setFriction(t)}get friction(){return this.collider.friction()}set restitution(t){this.collider.setRestitution(t)}get restitution(){return this.collider.restitution()}set density(t){this.collider.setDensity(t)}get density(){return this.collider.density()}set isTrigger(t){this.collider.setSensor(t)}get isTrigger(){return this.collider.isSensor()}set collisionGroups(t){this.collider.setCollisionGroups(t)}get collisionGroups(){return this.collider.collisionGroups()}set enabled(t){this.collider.setEnabled(t)}get enabled(){return this.collider.isEnabled()}}export class PhysicsBody{constructor(t,e){this.body=t,this.world=e}dispose(){this.world.removeRigidBody(this.body)}setEnabled(t){this.body.setEnabled(t)}isEnabled(){return this.body.isEnabled()}getPosition(t){const e=this.body.translation();return t.set(e.x,e.y,e.z),t}setPosition(t){this.body.setTranslation({x:t.x,y:t.y,z:t.z},!0)}getRotation(t){const e=this.body.rotation();return t.set(e.x,e.y,e.z,e.w),t}setRotation(t){this.body.setRotation({x:t.x,y:t.y,z:t.z,w:t.w},!0)}getLinearVelocity(t){const e=this.body.linvel();return t.set(e.x,e.y,e.z),t}setLinearVelocity(t){this.body.setLinvel({x:t.x,y:t.y,z:t.z},!0)}getAngularVelocity(t){const e=this.body.angvel();return t.set(e.x,e.y,e.z),t}setAngularVelocity(t){this.body.setAngvel({x:t.x,y:t.y,z:t.z},!0)}applyImpulse(t,e=!0){this.body.applyImpulse({x:t.x,y:t.y,z:t.z},e)}applyTorqueImpulse(t,e=!0){this.body.applyTorqueImpulse({x:t.x,y:t.y,z:t.z},e)}setNextKinematicPosition(t){this.body.setNextKinematicTranslation(t)}setNextKinematicRotation(t){this.body.setNextKinematicRotation(t)}setType(t){this.body.setBodyType(function(t){switch(t){case PhysicsBodyType.dynamic:return i.RigidBodyType.Dynamic;case PhysicsBodyType.static:return i.RigidBodyType.Fixed;case PhysicsBodyType.kinematic:return i.RigidBodyType.KinematicPositionBased;case PhysicsBodyType.kinematicVelocityBased:return i.RigidBodyType.KinematicVelocityBased}}(t),t!==PhysicsBodyType.static)}setGravityScale(t){this.body.setGravityScale(t,!1)}getGravityScale(){return this.body.gravityScale()}isDynamic(){return this.body.isDynamic()}isKinematic(){return this.body.isKinematic()}isStatic(){return this.body.isFixed()}sleep(){this.body.sleep()}wakeUp(){this.body.wakeUp()}}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
package/dist/rendering.js CHANGED
@@ -1,4 +1,4 @@
1
- var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as c,WebGLRenderTarget as d}from"three";import{CopyShader as u,EffectComposer as m,FXAAShader as p,GammaCorrectionShader as f,LUTPass as g,RenderPass as v,ShaderPass as P,VRButton as M}from"three-stdlib";import{CSMShader as T,CSMUtil as b}from"./csm.js";import{bool as x,colorToNormal as y,float as w,NodeShaderMaterial as R,normalize as S,rgb as C,textureSampler2d as F,varyingAttributes as E,varyingTransformed as I,vec4 as A,BooleanExpression as B,select as W,ifDefApply as U}from"three-shader-graph";import{Reflector as D}from"three-stdlib";import{BokehPass as j,OutputPass as H}from"three/examples/jsm/Addons.js";import{CSM as L}from"three/examples/jsm/csm/CSM.js";import O from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as V}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as G}from"typedi";import{depthUniformName as k,farUniformName as N,nearUniformName as z,resolutionUniformName as _,sceneNormalUniformName as q,supportsDepthTextureExtension as X}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as Y}from"./shader-nodes/time.js";import{sceneMapUniformName as Q}from"./shader-nodes/scene-sample.js";import{DepthPass as K}from"./utils/three/depth-pass.js";import{GPUStatsPanel as J}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as Z}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as $,traverseVisibleStop as ee}from"./utils/three/traverse.js";import{clamp as te}from"./utils/math.js";import{ColorPass as se}from"./rendering/color-pass.js";import{SSRPass as ie}from"./rendering/ssr/SSRPass.js";import{SSRShader as re}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as ne}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as ae}from"./rendering/outline-effect.js";import{UnrealBloomPass as oe}from"./rendering/bloom/UnrealBloomPass.js";b.patchSetupMaterial();const le=document.createElement("div");le.style.position="absolute",le.style.left="50%",le.style.top="50%",le.style.color="black",le.style.zIndex="999";(new i.Layers).set(9);const he=new i.MeshBasicMaterial({color:"black"}),ce=new i.MeshDepthMaterial;ce.depthPacking=i.RGBADepthPacking,ce.blending=i.NoBlending,ce.side=i.DoubleSide;const de=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let ue=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof l&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.dofPass.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[0]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container))}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this.resolutionScale=1,this.maxPixelRatio=de?1:window.devicePixelRatio,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new O,this._showStats=!0,this.gbufferMaterialCache=new Map,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),window.renderer=this.renderer=new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(M.createButton(this.renderer));const n=new ae(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.gRenderTarget=new d(t.clientWidth,t.clientHeight,{count:2,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat}),this.gRenderTarget.depthTexture=new i.DepthTexture(t.clientWidth,t.clientHeight),this.gRenderTarget.depthTexture.type=i.UnsignedShortType,this.gRenderTarget.depthTexture.minFilter=i.NearestFilter,this.gRenderTarget.depthTexture.magFilter=i.NearestFilter,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1,this.composer=new m(this.renderer);var a=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,a,.5,800);o.layers.enable(19),this.setCamera(o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,b.renderingView=this,this.isDepthTextureExtensionSupported=X(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=new v(this.scene,this.camera);this.composer.addPass(h);const c=new oe(l,1.5,.4,.85);c.threshold=1,c.strength=.9,c.radius=.5,this.bloomPass=c;const T=new V(this.scene,this.camera,t.clientWidth,t.clientWidth,{});T.normalRenderTarget?.dispose(),T.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[0]),T.output=V.OUTPUT.Default,T.enabled=!1,this.aoPass=T,re.fragmentShader=re.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const x=new ie({renderer:this.renderer,scene:this.scene,camera:this.camera,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[0],depthTexture:this.gRenderTarget.depthTexture});x.output=ie.OUTPUT.Default,x.blur=!0,x.fresnel=!1,x.distanceAttenuation=!0,x.maxDistance=50,x.selective=!0,x.bouncing=!1,x.opacity=.4,x.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=x,this.composer.addPass(x),!1!==this.options.ao?.enabled&&this.composer.addPass(T),this.composer.addPass(c),c.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.options.bloom,this.volumetricFogPass=new ne(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new j(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const y=new se;this.composer.addPass(y),this.colorPass=y,y.vignetteEnabled=!1,this.outlinePass=new Z(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const w=new P(p);w.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(w),this.fxaaPass=w,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new P(f).clear=!1,this.fixStatsStyle(),this.lutPass=new g({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const R=new P(u,"prevtexture");R.enabled=!0,R.needsSwap=!1,R.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],R.renderToScreen=!0;const S=new H;this.composer.addPass(S)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){this.camera=e,this.composer.passes.forEach(t=>{t instanceof v?t.camera=e:t instanceof Z?t.renderCamera=e:(t instanceof K||t instanceof V)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),null==this.csm?(this.csm=new L({maxFar:100,lightFar:250,lightMargin:20,cascades:de?2:4,shadowMapSize:2048*(de?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=T.lights_fragment_begin):(this.csm.camera=this.camera,this.camera),this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const r=new i.WebGLRenderTarget(t.clientWidth*s,t.clientHeight*s);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(128,128),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:i.HalfFloatType});return s.texture.minFilter=i.NearestFilter,s.texture.magFilter=i.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,s.depthTexture=new i.DepthTexture(128,128),s.depthTexture.type=i.UnsignedInt248Type,s.depthTexture.minFilter=i.NearestFilter,s.depthTexture.magFilter=i.NearestFilter,s}static createSceneColorRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio()*.5,t.clientHeight*e.getPixelRatio()*.5,{format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,stencilBuffer:!1});return s.texture.minFilter=i.LinearFilter,s.texture.magFilter=i.LinearFilter,s.texture.generateMipmaps=!1,s}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),b.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof R&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1*Math.PI},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity*Math.PI,e.envMap=this.scene.environment)}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}createGBufferMaterial(e){let t=this.gbufferMaterialCache.get(e);if(null==t){let r=I.normal;e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?null!=e.normalMap&&(r=y(F(e.normalMap).sample(E.uv),e.normalScale.x??1)):e instanceof R&&null!=e.outputNormal&&(r=e.outputNormal),!0!==e.userData.disableAO&&(r=U("DOUBLE_SIDED",r,e=>W(new B("gl_FrontFacing"),e,e.multiplyScalar(-1))));let n=e.userData?.reflective?w(0):w(1);e instanceof i.MeshStandardMaterial?n=null!=e.roughnessMap?F(e.roughnessMap).sample(E.uv).r.multiply(e.roughness??1):w(e.roughness??1):e instanceof R&&null!=e.outputRoughness&&(n=e.outputRoughness);const a=!0===e.userData.hasBloom;let o=C(0);a&&(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(o=null!=e.emissiveMap?F(e.emissiveMap).sample(E.uv).rgb.multiply(C(e.emissive??0)):C(e.emissive??0),o=o.multiplyScalar(e.emissiveIntensity)):e instanceof R&&(o=e.outputEmissive??e.outputColor.rgb.multiplyScalar(e.outputColor.a)));let l=w(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(null!=e.alphaMap&&(l=F(e.alphaMap).sample(E.uv).r),null!=e.map&&(l=l.multiply(F(e.map).sample(E.uv).a))):e instanceof R&&null!=e.opacity&&(l=e.outputOpacity.multiply(e.opacity??1));const h=e instanceof c&&null!=e.uniforms[k],d=e.transparent&&e.alphaTest<=0,u=e.alphaTest>0?l.lt(e.alphaTest):d?l.lt(.8):x(!1);let m;m=(s=r,S(s).multiplyScalar(.5).addScalar(.5)).rgba(n);let p=e instanceof R?e.outputPosition:void 0;t=new R({position:p,outputs:[m,o.rgba(e.alphaTest)],outputEncoding:!1,fog:!1,transparent:!1,lights:!1,discard:u}),t.toneMapped=!1,t.side=e.side,d&&a&&(t.transparent=!0,t.blending=i.AdditiveBlending),t.depthWrite=!0,t.depthTest=!0,t.visible=e.visible&&e.depthTest&&!h&&t.visible,e instanceof c&&Object.assign(t.uniforms,e.uniforms),this.gbufferMaterialCache.set(e,t)}var s;if(e instanceof c)for(const s in e.uniforms)null!=t.uniforms[s]&&(t.uniforms[s].value=e.uniforms[s].value);return t}loop(e,t=!1){const s=this.stats,r=s.addPanel(new O.Panel("Calls","#83f","#002")),n=s.addPanel(new O.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new J(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),n.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;const m=[],p=[],f=[];let g=0;const v=new a,P=new a;let M=0;let T=this.paused;const b=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>b(t),500),void(T=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let n=(t*=.001)-g;if(g=t,T&&(n=.016,T=!1),v.copy(this.camera.matrixWorld),n>1){let t=n;for(;t>.05;)e(me),t-=me;e(t)}else e(n);this.onLoopCallbacks.forEach(e=>e(n)),this.camera?.updateMatrixWorld(),P.copy(this.camera.matrixWorld),t-M>.08&&!P.equals(v)&&(this.renderer.shadowMap.needsUpdate=!0,M=t),this.resizeRender(),this.csm.update();let a=!1;m.length=0,p.length=0,f.length=0;const h=fe;ve.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(ve),this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(a=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[k])&&isObjectInFrustum(e,h)?this.initDepthUniform(e.material):e instanceof D&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[Q]&&isObjectInFrustum(e,h)&&(e.visible=!1,f.push(e),e.material.uniforms[Q].value=this.sceneColorRenderTarget.texture),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[Y])e.material.uniforms[Y].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[Y]&&(s.uniforms[Y].value=t)}),this.bloomPass.enabled=a;const d=new Map,x=new Map;ee(this.scene,e=>{if(e instanceof i.Sprite||e.isPoints||e.isLine||e.isTransformControls||e.isTransformControlsGizmo)return x.set(e,e.visible),e.visible=!1,!1;if(e instanceof o)if(d.set(e,e.material),Array.isArray(e.material)){e.material=e.material.slice();for(let s=0;s<e.material.length;s++)e.material[s]=this.createGBufferMaterial(e.material[s]),e.material[s]instanceof c&&null!=e.material[s].uniforms[Y]&&(e.material[s].uniforms[Y].value=t)}else e.material=this.createGBufferMaterial(e.material),e.material instanceof c&&null!=e.material.uniforms[Y]&&(e.material.uniforms[Y].value=t)});const y=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}if(this.renderer.setRenderTarget(null),d.forEach((e,t)=>{t.material=e}),x.forEach((e,t)=>{t.visible=e}),this.renderer.shadowMap.autoUpdate=y,f.length>0){if(this.renderer.setRenderTarget(this.sceneColorRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(!0,!0,!1);try{this.renderer.render(this.scene,this.camera)}catch(e){}}catch(e){console.warn("Error rendering scene color:",e)}this.renderer.setRenderTarget(null)}m.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(n),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(b)},1e3/this.fpsCap):requestAnimationFrame(b))};!0===this.options.enableXR?this.renderer.setAnimationLoop(b):requestAnimationFrame(b)}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,n=!1,a=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Pe);let c=[];for(const e of this.postProcessVolumes){if(!pe(e.object))continue;let l=e.blendWeight??1;const d=e.distanceToPoint(h);d>e.blendRadius||(e.blendRadius>0&&(l*=te(1-d/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(c.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),n=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,a=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),a=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=n,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=n||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=a,a&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,fe)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=$(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===he.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=he:(e.visible=!1,this.bloomHidden.push(e))}else"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof c&&(e.uniforms[k].value=this.gRenderTarget.depthTexture,this.camera instanceof l&&(null!=e.uniforms[z]&&(e.uniforms[z].value=this.camera.near),null!=e.uniforms[N]&&(e.uniforms[N].value=this.camera.far)))}initNormalUniform(e){e instanceof c&&null!=e.uniforms[q]&&(e.uniforms[q].value=this.gRenderTarget.textures[0])}initResolutionUniform(e){e instanceof c&&null!=e.uniforms[_]&&e.uniforms[_].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio())}};ue=e=t([G(),s("design:paramtypes",[HTMLElement,Object])],ue);export{ue as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const me=.05;function pe(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}V.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const fe=new i.Frustum,ge=new i.Box3,ve=new i.Matrix4;export function isObjectInFrustum(e,t){const s=ge.setFromObject(e);return t.intersectsBox(s)}const Pe=new i.Vector3;/*
1
+ var e;import{__decorate as t,__metadata as s}from"tslib";import*as i from"three";import{Color as r,Material as n,Matrix4 as a,Mesh as o,PerspectiveCamera as l,ShaderChunk as h,ShaderMaterial as c,WebGLRenderTarget as d,Euler as u}from"three";import{CopyShader as m,EffectComposer as p,FXAAShader as f,GammaCorrectionShader as g,LUTPass as v,RenderPass as T,ShaderPass as M,VRButton as P}from"three-stdlib";import{CSMShader as b,CSMUtil as x}from"./csm.js";import{bool as y,colorToNormal as w,float as R,NodeShaderMaterial as S,normalize as C,rgb as F,textureSampler2d as E,varyingAttributes as A,varyingTransformed as I,vec4 as B,BooleanExpression as W,select as U,ifDefApply as D}from"three-shader-graph";import{Reflector as j}from"three-stdlib";import{BokehPass as H,OutputPass as L}from"three/examples/jsm/Addons.js";import{CSM as O}from"three/examples/jsm/csm/CSM.js";import V from"three/examples/jsm/libs/stats.module.js";import{GTAOPass as G}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as k}from"typedi";import{depthUniformName as N,farUniformName as z,nearUniformName as _,resolutionUniformName as q,sceneNormalUniformName as X,supportsDepthTextureExtension as Y}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as Q}from"./shader-nodes/time.js";import{sceneMapUniformName as K}from"./shader-nodes/scene-sample.js";import{DepthPass as J}from"./utils/three/depth-pass.js";import{GPUStatsPanel as Z}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as $}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ee,traverseVisibleStop as te}from"./utils/three/traverse.js";import{clamp as se}from"./utils/math.js";import{ColorPass as ie}from"./rendering/color-pass.js";import{SSRPass as re}from"./rendering/ssr/SSRPass.js";import{SSRShader as ne}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as ae}from"./rendering/fog/volumetric-fog-pass.js";import{OutlineEffect as oe}from"./rendering/outline-effect.js";import{UnrealBloomPass as le}from"./rendering/bloom/UnrealBloomPass.js";x.patchSetupMaterial();const he=document.createElement("div");he.style.position="absolute",he.style.left="50%",he.style.top="50%",he.style.color="black",he.style.zIndex="999";(new i.Layers).set(9);const ce=new i.MeshBasicMaterial({color:"black"}),de=new i.MeshDepthMaterial;de.depthPacking=i.RGBADepthPacking,de.blending=i.NoBlending,de.side=i.DoubleSide;const ue=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let me=e=class{setPaused(e){this.paused=e}resizeRender(){this.previousClientWith===this.container.clientWidth&&this.previousClientHeight===this.container.clientHeight||0!==this.container.clientWidth&&0!==this.container.clientHeight&&(this.previousClientWith=this.container.clientWidth,this.previousClientHeight=this.container.clientHeight,this.camera instanceof l&&(this.camera.aspect=this.container.clientWidth/this.container.clientHeight,this.camera.updateProjectionMatrix()),this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(this.container.clientWidth,this.container.clientHeight),this.composer.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.dofPass.setSize(this.container.clientWidth*this.resolutionScale,this.container.clientHeight*this.resolutionScale),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[0]),this.sceneColorRenderTarget.dispose(),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container))}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}constructor(t,s={}){this.container=t,this.options=s,this.windowVisible=!0,this.running=!0,this.paused=!1,this.fpsCap=null,this.postProcessVolumes=[],this.postProcessSettings={},this.resolutionScale=1,this.maxPixelRatio=ue?1:window.devicePixelRatio,this.onResize=()=>{if(this.resizeRender(),!this.paused)try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.onLoopCallbacks=[],this.stats=new V,this._showStats=!0,this.gbufferMaterialCache=new Map,this.pmremGeneratorResults=new WeakMap,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),window.renderer=this.renderer=new i.WebGLRenderer({antialias:!1,powerPreference:"high-performance"});new i.MeshStandardMaterial({color:"#ccc"});this.scene=new i.Scene,this.scene.matrixWorldAutoUpdate=!0,this.renderer.setPixelRatio(Math.min(this.maxPixelRatio,window.devicePixelRatio)*this.resolutionScale),this.renderer.setSize(t.clientWidth,t.clientHeight),this.renderer.xr.enabled=this.options.enableXR??!1,!0===this.options.enableXR&&document.body.appendChild(P.createButton(this.renderer));const n=new oe(this.renderer,{defaultThickness:.005,defaultColor:[0,0,0],defaultAlpha:1,defaultKeepAlive:!0});this.outlineEffect=n,this.gRenderTarget=new d(t.clientWidth,t.clientHeight,{count:2,minFilter:i.NearestFilter,magFilter:i.NearestFilter,type:i.HalfFloatType,format:i.RGBAFormat}),this.gRenderTarget.depthTexture=new i.DepthTexture(t.clientWidth,t.clientHeight),this.gRenderTarget.depthTexture.type=i.UnsignedShortType,this.gRenderTarget.depthTexture.minFilter=i.NearestFilter,this.gRenderTarget.depthTexture.magFilter=i.NearestFilter,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1,this.composer=new p(this.renderer);var a=(t.clientWidth||1)/(t.clientHeight||1);const o=new i.PerspectiveCamera(45,a,.5,800);o.layers.enable(19),this.setCamera(o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=i.PCFSoftShadowMap,this.renderer.shadowMap.autoUpdate=s.shadows?.autoUpdate??!1,this.renderer.outputColorSpace=i.SRGBColorSpace,this.renderer.toneMapping=i.NoToneMapping,this.renderer.toneMappingExposure=1,this.renderer.gammaFactor=1.4,x.renderingView=this,this.isDepthTextureExtensionSupported=Y(this.renderer),t.replaceChildren(this.renderer.domElement),this.setupEventListeners(),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container),this.sceneColorRenderTarget=e.createSceneColorRenderTarget(this.renderer,this.container);const l=new i.Vector2(t.clientWidth,t.clientHeight),h=new T(this.scene,this.camera);this.composer.addPass(h);const c=new le(l,1.5,.4,.85);c.threshold=1,c.strength=.9,c.radius=.5,this.bloomPass=c;const u=new G(this.scene,this.camera,t.clientWidth,t.clientWidth,{});u.normalRenderTarget?.dispose(),u.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[0]),u.output=G.OUTPUT.Default,u.enabled=!1,this.aoPass=u,ne.fragmentShader=ne.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const b=new re({renderer:this.renderer,scene:this.scene,camera:this.camera,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[0],depthTexture:this.gRenderTarget.depthTexture});b.output=re.OUTPUT.Default,b.blur=!0,b.fresnel=!1,b.distanceAttenuation=!0,b.maxDistance=50,b.selective=!0,b.bouncing=!1,b.opacity=.4,b.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=b,this.composer.addPass(b),!1!==this.options.ao?.enabled&&this.composer.addPass(u),this.composer.addPass(c),c.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.options.bloom,this.volumetricFogPass=new ae(l),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new H(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const y=new ie;this.composer.addPass(y),this.colorPass=y,y.vignetteEnabled=!1,this.outlinePass=new $(new i.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const w=new M(f);w.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(w),this.fxaaPass=w,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new M(g).clear=!1,this.fixStatsStyle(),this.lutPass=new v({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const R=new M(m,"prevtexture");R.enabled=!0,R.needsSwap=!1,R.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],R.renderToScreen=!0;const S=new L;this.composer.addPass(S)}fixStatsStyle(){const e=this.stats.dom;e.style.position="absolute";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++)t.item(e).style.display="inline-block"}setEnableOutlines(e){this.outlinePass.enabled=e,this.fxaaPass.enabled=e}setCamera(e){this.camera=e,this.composer.passes.forEach(t=>{t instanceof T?t.camera=e:t instanceof $?t.renderCamera=e:(t instanceof J||t instanceof G)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),null==this.csm?(this.csm=new O({maxFar:100,lightFar:250,lightMargin:20,cascades:ue?2:4,shadowMapSize:2048*(ue?.5:1),lightDirection:new i.Vector3(.5,-1,-.6).normalize(),lightIntensity:.5*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"}),this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,h.lights_fragment_begin=b.lights_fragment_begin):(this.csm.camera=this.camera,this.camera),this.csm.updateFrustums()}setSelectedObjects(e){if(null==this.outlinePass)return;const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.outlinePass.selectedObjects=Array.from(t.values())}static createDepthRenderTarget(e,t,s){const r=new i.WebGLRenderTarget(t.clientWidth*s,t.clientHeight*s);return r.texture.minFilter=i.NearestFilter,r.texture.magFilter=i.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new i.DepthTexture(128,128),r.depthTexture.type=i.UnsignedShortType,r.depthTexture.minFilter=i.NearestFilter,r.depthTexture.magFilter=i.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio(),t.clientHeight*e.getPixelRatio(),{type:i.HalfFloatType});return s.texture.minFilter=i.NearestFilter,s.texture.magFilter=i.NearestFilter,s.texture.generateMipmaps=!1,s.stencilBuffer=!1,s.depthTexture=new i.DepthTexture(128,128),s.depthTexture.type=i.UnsignedInt248Type,s.depthTexture.minFilter=i.NearestFilter,s.depthTexture.magFilter=i.NearestFilter,s}static createSceneColorRenderTarget(e,t){const s=new i.WebGLRenderTarget(t.clientWidth*e.getPixelRatio()*.5,t.clientHeight*e.getPixelRatio()*.5,{format:i.RGBAFormat,colorSpace:i.SRGBColorSpace,stencilBuffer:!1});return s.texture.minFilter=i.LinearFilter,s.texture.magFilter=i.LinearFilter,s.texture.generateMipmaps=!1,s}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(){this.running=!1,window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),this.onLoopCallbacks=[],this.renderer.dispose(),this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.csm.dispose(),this.container.replaceChildren(),this.volumetricFogPass.dispose(),x.clearSceneCache(this.scene)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.find(e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){this._showStats=e,this._showStats&&!this.container.contains(this.stats.dom)?this.container.appendChild(this.stats.dom):!this._showStats&&this.container.contains(this.stats.dom)&&this.container.removeChild(this.stats.dom)}get showStats(){return this._showStats}applyEnvMap(e){null!=this.scene.environment&&e instanceof S&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:xe(this.scene.environmentRotation,this.scene.environment,new i.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment)}setupCsm(e){if(e instanceof i.Mesh||e instanceof i.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}createGBufferMaterial(e){let t=this.gbufferMaterialCache.get(e);if(null==t){let r=I.normal;e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?null!=e.normalMap&&(r=w(E(e.normalMap).sample(A.uv),e.normalScale.x??1)):e instanceof S&&null!=e.outputNormal&&(r=e.outputNormal),!0!==e.userData.disableAO&&(r=D("DOUBLE_SIDED",r,e=>U(new W("gl_FrontFacing"),e,e.multiplyScalar(-1))));let n=e.userData?.reflective?R(0):R(1);e instanceof i.MeshStandardMaterial?n=null!=e.roughnessMap?E(e.roughnessMap).sample(A.uv).r.multiply(e.roughness??1):R(e.roughness??1):e instanceof S&&null!=e.outputRoughness&&(n=e.outputRoughness);const a=!0===e.userData.hasBloom;let o=F(0);a&&(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(o=null!=e.emissiveMap?E(e.emissiveMap).sample(A.uv).rgb.multiply(F(e.emissive??0)):F(e.emissive??0),o=o.multiplyScalar(e.emissiveIntensity)):e instanceof S&&(o=e.outputEmissive??e.outputColor.rgb.multiplyScalar(e.outputColor.a)));let l=R(1);e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial||e instanceof i.MeshToonMaterial||e instanceof i.MeshPhongMaterial?(null!=e.alphaMap&&(l=E(e.alphaMap).sample(A.uv).r),null!=e.map&&(l=l.multiply(E(e.map).sample(A.uv).a))):e instanceof S&&null!=e.opacity&&(l=e.outputOpacity.multiply(e.opacity??1));const h=e instanceof c&&null!=e.uniforms[N],d=e.transparent&&e.alphaTest<=0,u=e.alphaTest>0?l.lt(e.alphaTest):d?l.lt(.8):y(!1);let m;m=(s=r,C(s).multiplyScalar(.5).addScalar(.5)).rgba(n);let p=e instanceof S?e.outputPosition:void 0;t=new S({position:p,outputs:[m,o.rgba(e.alphaTest)],outputEncoding:!1,fog:!1,transparent:!1,lights:!1,discard:u}),t.toneMapped=!1,t.side=e.side,d&&a&&(t.transparent=!0,t.blending=i.AdditiveBlending),t.depthWrite=!0,t.depthTest=!0,t.visible=e.visible&&e.depthTest&&!h&&t.visible,e instanceof c&&Object.assign(t.uniforms,e.uniforms),this.gbufferMaterialCache.set(e,t)}var s;if(e instanceof c)for(const s in e.uniforms)null!=t.uniforms[s]&&(t.uniforms[s].value=e.uniforms[s].value);return t}loop(e,t=!1){const s=this.stats,r=s.addPanel(new V.Panel("Calls","#83f","#002")),n=s.addPanel(new V.Panel("Triangles","#c32","#002"));let l;navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(l=new Z(this.renderer.getContext()),s.addPanel(l)),this.showStats=t;let h=10,d=1e3;const u=()=>{const e=this.renderer.info.render.calls;e>h&&(h=e,setTimeout(()=>h=10,5e3)),r.update(e,h);const t=this.renderer.info.render.triangles;t>d&&(d=t,setTimeout(()=>d=1e3,5e3)),n.update(t,d)};performance.now();i.Ray.prototype.intersectTriangle;const m=[],p=[],f=[];let g=0;const v=new a,T=new a;let M=0;let P=this.paused;const b=t=>{const r=this.renderer.getContext();if(this.paused&&this.running&&r.drawingBufferHeight>1)return setTimeout(()=>b(t),500),void(P=!0);this.renderer.clear(),this.applyPostProcessSettings(),this.renderer.autoClear=!1,this.renderer.clear(),this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight),this.camera,s.begin(),this.showStats&&l?.startQuery(),this.ssrPass.gpuPanel=l;let n=(t*=.001)-g;if(g=t,P&&(n=.016,P=!1),v.copy(this.camera.matrixWorld),n>1){let t=n;for(;t>.05;)e(pe),t-=pe;e(t)}else e(n);this.onLoopCallbacks.forEach(e=>e(n)),this.camera?.updateMatrixWorld(),T.copy(this.camera.matrixWorld),t-M>.08&&!T.equals(v)&&(this.renderer.shadowMap.needsUpdate=!0,M=t),this.resizeRender(),this.csm.update();let a=!1;m.length=0,p.length=0,f.length=0;const h=ge;Te.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),h.setFromProjectionMatrix(Te),this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),(e instanceof o||e instanceof i.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),null!=this.scene.environment&&function(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(a=!0)),(e instanceof o||e instanceof i.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[N])&&isObjectInFrustum(e,h)?this.initDepthUniform(e.material):e instanceof j&&(e.visible=!1,p.push(e)),(e instanceof o||e instanceof i.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[K]&&isObjectInFrustum(e,h)&&(e.visible=!1,f.push(e),e.material.uniforms[K].value=this.sceneColorRenderTarget.texture),e instanceof o&&e.material?.uniforms&&null!=e.material?.uniforms[Q])e.material.uniforms[Q].value=t;else if(e instanceof o&&Array.isArray(e.material))for(const s of e.material)s.uniforms&&null!=s.uniforms[Q]&&(s.uniforms[Q].value=t)}),this.bloomPass.enabled=a;const d=new Map,x=new Map;te(this.scene,e=>{if(e instanceof i.Sprite||e.isPoints||e.isLine||e.isTransformControls||e.isTransformControlsGizmo)return x.set(e,e.visible),e.visible=!1,!1;if(e instanceof o)if(d.set(e,e.material),Array.isArray(e.material)){e.material=e.material.slice();for(let s=0;s<e.material.length;s++)e.material[s]=this.createGBufferMaterial(e.material[s]),e.material[s]instanceof c&&null!=e.material[s].uniforms[Q]&&(e.material[s].uniforms[Q].value=t)}else e.material=this.createGBufferMaterial(e.material),e.material instanceof c&&null!=e.material.uniforms[Q]&&(e.material.uniforms[Q].value=t)});const y=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}if(this.renderer.setRenderTarget(null),d.forEach((e,t)=>{t.material=e}),x.forEach((e,t)=>{t.visible=e}),this.renderer.shadowMap.autoUpdate=y,f.length>0){if(this.renderer.setRenderTarget(this.sceneColorRenderTarget),!this.paused&&null!=this.camera)try{this.renderer.clear(!0,!0,!1);try{this.renderer.render(this.scene,this.camera)}catch(e){}}catch(e){console.warn("Error rendering scene color:",e)}this.renderer.setRenderTarget(null)}m.forEach(e=>e.visible=!0),p.forEach(e=>e.visible=!0),f.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=t),this.volumetricFogPass&&this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene);try{!this.paused&&this.running&&(this.render(n),this.showStats&&l?.endQuery(),this.showStats&&u(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}s.end(),this.csm?.update(),this.running&&!0!==this.options.enableXR&&(this.fpsCap?setTimeout(()=>{requestAnimationFrame(b)},1e3/this.fpsCap):requestAnimationFrame(b))};!0===this.options.enableXR?this.renderer.setAnimationLoop(b):requestAnimationFrame(b)}getEnvTexture(e){null==this.pmremGenerator&&(this.pmremGenerator=new i.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader());let t=this.pmremGeneratorResults.get(e);return null==t&&(t=this.pmremGenerator.fromEquirectangular(e).texture,this.pmremGeneratorResults.set(e,t)),t.colorSpace=i.SRGBColorSpace,t}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.lutPass.enabled=!1,void(this.colorPass.enabled=!1);var e;(e=this.postProcessSettings).tonemapMapping=void 0,e.tonemapExposure=1,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=new i.Color("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.lut=void 0,e.lutIntensity=0;const t=this.postProcessSettings;let s,r=!1,n=!1,a=!1,o=!1;if(null==this.camera)return;const h=this.camera.getWorldPosition(Me);let c=[];for(const e of this.postProcessVolumes){if(!fe(e.object))continue;let l=e.blendWeight??1;const d=e.distanceToPoint(h);d>e.blendRadius||(e.blendRadius>0&&(l*=se(1-d/e.blendRadius,0,1)),l>1&&(l=1),l>0&&(c.push(e),void 0!==e.settings.tonemapMapping&&(t.tonemapMapping=e.settings.tonemapMapping),void 0!==e.settings.tonemapExposure&&(t.tonemapExposure=i.MathUtils.lerp(t.tonemapExposure,e.settings.tonemapExposure,l)),void 0!==e.settings.envTexture&&(t.envTexture=e.settings.envTexture),void 0!==e.settings.envIntensity&&(t.envIntensity=i.MathUtils.lerp(t.envIntensity,e.settings.envIntensity,l)),void 0!==e.settings.vignetteIntensity&&(t.vignetteIntensity=i.MathUtils.lerp(t.vignetteIntensity,e.settings.vignetteIntensity,l),n=!0),void 0!==e.settings.colorTint&&void 0!==e.settings.colorTintIntensity&&e.settings.colorTintIntensity>0&&(t.colorTint=t.colorTint.lerp(e.settings.colorTint,l),o=!0),void 0!==e.settings.colorTintIntensity&&(t.colorTintIntensity=i.MathUtils.lerp(t.colorTintIntensity,e.settings.colorTintIntensity,l)),void 0!==e.settings.depthFocus&&(r=!0,t.depthFocus=void 0!==t.depthFocus?i.MathUtils.lerp(t.depthFocus,e.settings.depthFocus,l):e.settings.depthFocus),void 0!==e.settings.depthAperture&&(r=!0,t.depthAperture=void 0!==t.depthAperture?i.MathUtils.lerp(t.depthAperture,e.settings.depthAperture,l):e.settings.depthAperture),void 0!==e.settings.depthMaxBlur&&(r=!0,t.depthMaxBlur=void 0!==t.depthMaxBlur?i.MathUtils.lerp(t.depthMaxBlur,e.settings.depthMaxBlur,l):e.settings.depthMaxBlur),void 0!==e.settings.temperature&&(t.temperature=i.MathUtils.lerp(t.temperature,e.settings.temperature,l)),void 0!==e.settings.temperatureTint&&(t.temperatureTint=i.MathUtils.lerp(t.temperatureTint,e.settings.temperatureTint,l)),void 0!==e.settings.lut&&(s=e.settings.lut,a=!0),void 0!==e.settings.lutIntensity&&(t.lutIntensity=i.MathUtils.lerp(t.lutIntensity,e.settings.lutIntensity,l),a=!0)))}this.renderer.toneMapping=t.tonemapMapping??i.NoToneMapping,this.renderer.toneMappingExposure=t.tonemapExposure,null!=t.envTexture&&(this.scene.environment=this.getEnvTexture(t.envTexture)),this.scene.environmentIntensity=t.envIntensity,this.colorPass.vignetteIntensity=t.vignetteIntensity,this.colorPass.vignetteEnabled=n,this.colorPass.colorTint=t.colorTint,this.colorPass.colorTintIntensity=t.colorTintIntensity,this.colorPass.enabled=n||o,r&&this.camera instanceof l?(this.dofPass.enabled=!0,void 0!==t.depthFocus&&(this.dofPass.uniforms.focus.value=t.depthFocus),void 0!==t.depthAperture&&(this.dofPass.uniforms.aperture.value=t.depthAperture),void 0!==t.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=t.depthMaxBlur)):this.dofPass.enabled=!1,this.colorPass.temperature=t.temperature,this.colorPass.temperatureTint=t.temperatureTint,this.lutPass.enabled=a,a&&(null!=s&&(s.flipY=!0,s.generateMipmaps=!1),this.lutPass.lut=s,this.lutPass.intensity=t.lutIntensity)}renderOverlay(){const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.container.clientWidth/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof o&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,ge)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.options.bloom,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ee(this.scene,e=>e instanceof o&&!0===e.material?.userData?.hasBloom)}darkenNonBloomed(e){if((e instanceof o||e instanceof i.Sprite||e instanceof i.Line)&&e.visible&&(null==e.material.userData||!0!==e.material.userData.hasBloom)){if(e.material?.id===ce.id)return;this.bloomStoredMaterials[e.uuid]=e.material,!0!==e.material.transparent?e.material=ce:(e.visible=!1,this.bloomHidden.push(e))}else"TransformControlsPlane"!==e.type&&"TransformControlsGizmo"!==e.type||(e.visible=!1,this.bloomHidden.push(e))}restoreMaterial(e){this.bloomStoredMaterials[e.uuid]&&(e.material=this.bloomStoredMaterials[e.uuid],delete this.bloomStoredMaterials[e.uuid],e.visible=!0)}initDepthUniform(e){e instanceof c&&(e.uniforms[N].value=this.gRenderTarget.depthTexture,this.camera instanceof l&&(null!=e.uniforms[_]&&(e.uniforms[_].value=this.camera.near),null!=e.uniforms[z]&&(e.uniforms[z].value=this.camera.far)))}initNormalUniform(e){e instanceof c&&null!=e.uniforms[X]&&(e.uniforms[X].value=this.gRenderTarget.textures[0])}initResolutionUniform(e){e instanceof c&&null!=e.uniforms[q]&&e.uniforms[q].value.set(this.container.clientWidth*this.renderer.getPixelRatio(),this.container.clientHeight*this.renderer.getPixelRatio())}};me=e=t([k(),s("design:paramtypes",[HTMLElement,Object])],me);export{me as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const pe=.05;function fe(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}G.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};const ge=new i.Frustum,ve=new i.Box3,Te=new i.Matrix4;export function isObjectInFrustum(e,t){const s=ve.setFromObject(e);return t.intersectsBox(s)}const Me=new i.Vector3;const Pe=new a,be=new u;function xe(e,t,s=new i.Matrix3){return be.copy(e),be.x*=-1,be.y*=-1,be.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(be.y*=-1,be.z*=-1),s.setFromMatrix4(Pe.makeRotationFromEuler(be))}/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -51,7 +51,20 @@ export declare class AssetResourceLoader {
51
51
  private computeCollisionShapes;
52
52
  private loadMesh;
53
53
  private optimizedMeshes;
54
+ /**
55
+ * This function will attempt to merge geometries and draw groups so that we only have
56
+ * one material per mesh and that we don't have redundant groups.
57
+ * This is required for batching to work.
58
+ * @param object
59
+ * @returns
60
+ */
54
61
  private optimizeDrawGroups;
62
+ /**
63
+ * Extracts specific geometry groups from a BufferGeometry and creates a new geometry
64
+ * containing only those groups. This is used to split meshes with material arrays
65
+ * into separate meshes per material.
66
+ */
67
+ private extractGeometryGroups;
55
68
  private loadByAsset;
56
69
  /**
57
70
  * Dispose all resource loaded.
@@ -1,4 +1,4 @@
1
- import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as i,Mesh as r,Object3D as a,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as l,DRACOLoader as c,LUTCubeLoader as d}from"three-stdlib";import{FBXLoader as u}from"three-stdlib";import{cloneMesh as m}from"../utils/mesh.js";import{pathJoin as p}from"../utils/files.js";import{Subject as f,firstValueFrom as g}from"rxjs";import{importCollisionShapes as w,isCollisionMesh as y}from"./collision/collision-shape-import.js";import*as x from"three";import{iterateMaterials as L}from"../utils/materials.js";import{BufferGeometryUtils as M,EXRLoader as b,KTX2Loader as A,TGALoader as v,UltraHDRLoader as R}from"three/examples/jsm/Addons.js";import{disposeScene as S}from"../utils/three/cleanup.js";const C=new c;C.setDecoderConfig({type:"js"}),C.setDecoderPath("/assets/draco/");const T=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new i,this.glbLoader=new o(this.loadingManager).setDRACOLoader(C),this.fbxLoader=new u(this.loadingManager),this.objLoader=new l(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new v(this.loadingManager),this.exrLoader=new b(this.loadingManager),this.cubeLoader=new d(this.loadingManager),this.hdrLoader=new R(this.loadingManager),this.ktx2Loader=new A(this.loadingManager),this._textureLoader=new x.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new f,this.ready=g(this.makeReady),this._texturePromises=new Map,this.asyncMeshResults=new Map,this.asyncAudioResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0;null!=getElectronArg("windowId")||import.meta.url.includes(".vite")?this.ktx2Loader.setTranscoderPath("/assets/basis/"):this.ktx2Loader.setTranscoderPath(new URL("../assets/basis/",import.meta.url).href),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=p(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=getElectronArg("windowId");return null!=t||import.meta.url.includes(".vite")?p(this.basePath,e)+(null!=t?`?windowId=${t}`:""):new URL(p("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if(this._texturePromises.has(e.id))return this._texturePromises.get(e.id);const t=this._getTexture(e).finally(()=>{this._texturePromises.delete(e.id)});return this._texturePromises.set(e.id,t),t}async _getTexture(e){if(null==e||null==e.fileKey)return null;if(await this.ready,this.textureCache.has(e.id)){const t=this.textureCache.get(e.id);t.dispose(),null!=e.texture&&(t.flipY!==e.texture?.flipY?(t.needsUpdate=!0,t.flipY=e.texture?.flipY??!0):t.wrapS!==j(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=j(e.texture?.wrapS)):t.wrapT!==j(e.texture?.wrapT)&&(t.wrapT=j(e.texture?.wrapT),t.needsUpdate=!0))}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=j(e.texture?.wrapS),t.wrapT=j(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0),this.textureCache.set(e.id,t),this._retrievedTextures.push(t),t))}catch(t){return console.warn("Failed to load texture "+e.name,t),null}return this.textureCache.get(e.id)}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:e?.toLowerCase().endsWith(".cube")?this.cubeLoader:this.textureLoader}clearCache(e){"mesh"===e.type&&Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)})}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!T.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const i=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(i))try{this.asyncMeshResults.has(i)||this.asyncMeshResults.set(i,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(i))),this.cache.set(i,await this.asyncMeshResults.get(i))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const a=this.cache.get(i).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=m(a),h=this.cache.get(i).animations;o.traverse(e=>{e instanceof r&&e.material instanceof Array&&(e.material=e.material.slice())});const l=new AssetMeshInstance;l.add(o),l.collisionShapes=n,l.animations=h;const c=e.receiveShadow??!0,d=e.castShadow??!1;return o.traverse(e=>{e.castShadow=d,e.receiveShadow=c}),{scene:l,animations:h}}async getAudio(e){await this.ready;const t=e.fileKey;if(this.asyncAudioResults.has(t))return await this.asyncAudioResults.get(t);const s=this.audioLoader.loadAsync(this.getUri(e.fileKey)).finally(()=>{setTimeout(()=>{this.asyncAudioResults.delete(t)},1e3)});return this.asyncAudioResults.set(t,s),s}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,w(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(e=>(e.scene.traverse(e=>{e instanceof r&&e.material,y(e)?e.visible=!1:e instanceof r&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(e.scene),e.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{k.test(e.name)&&(s=!0)}),!s)return t;const i=new x.LOD,r=[t];for(;r.length>0;){const e=r.shift(),t=e.name.match(k);if(null!=t){const s=parseInt(t[1]);0===s?i.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else r.push(...e.children)}return i}(0,e.scene),e))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,i=0,a=0;if(e.traverse(e=>{if(e instanceof r&&e.geometry instanceof t&&!y(e)){i++;const t=Object.keys(e.geometry.attributes).length;t!==a&&0!==a&&(s=!1),a=t}else(e instanceof x.SkinnedMesh||e instanceof x.Bone)&&(s=!1)}),i>1&&s){const s=[],i=[],a=[];e.updateWorldMatrix(!0,!0),e.traverse(e=>{e instanceof r&&e.geometry instanceof t&&!y(e)&&!Array.isArray(e.material)&&(e.updateWorldMatrix(!0,!0),s.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),i.push(e.material),a.push(e))});for(const e of a)e.removeFromParent();const n=M.mergeGeometries(s,!0),o=[];let h=0;e:for(const e of i){for(const t of o)if(t.m.id===e.id){t.indices.push(h),h++;continue e}o.push({m:e,indices:[h]}),h++}let l=0;for(const e of o){for(const t of e.indices)n.groups[t].materialIndex=l;l++}e.add(new r(n,o.map(e=>e.m)))}e.traverse(e=>{if(e instanceof r&&e.geometry instanceof t){const t=e.geometry;Array.isArray(e.material)&&t.groups.length>1&&t.groups.length>e.material.length&&M.mergeGroups(t)}})}async loadByAsset(e){this.fbxLoader;const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then(e=>({scene:e.scene,animations:e.animations}));case"fbx":return this.fbxLoader.loadAsync(t).then(e=>({scene:e,animations:e.animations}));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then(e=>(_(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>S(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}function _(e){if(e instanceof r)for(const t of L(e.material))t instanceof x.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(_)}export class AssetMeshInstance extends a{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function j(e){switch(e){case"clamp":return x.ClampToEdgeWrapping;case"repeat":return x.RepeatWrapping;case"mirror":return x.MirroredRepeatWrapping}return x.RepeatWrapping}new x.Matrix4;const k=/_LOD(\d+)$/;/*
1
+ import{AudioLoader as e,BufferGeometry as t,Group as s,LoadingManager as r,Mesh as i,Object3D as a,TextureLoader as n}from"three";import{GLTFLoader as o,MTLLoader as h,OBJLoader as l,DRACOLoader as c,LUTCubeLoader as u}from"three-stdlib";import{FBXLoader as d}from"three-stdlib";import{cloneMesh as m}from"../utils/mesh.js";import{pathJoin as f}from"../utils/files.js";import{Subject as p,firstValueFrom as g}from"rxjs";import{importCollisionShapes as w,isCollisionMesh as y}from"./collision/collision-shape-import.js";import*as x from"three";import{iterateMaterials as M}from"../utils/materials.js";import{BufferGeometryUtils as L,EXRLoader as b,KTX2Loader as A,TGALoader as v,UltraHDRLoader as S}from"three/examples/jsm/Addons.js";import{disposeScene as R}from"../utils/three/cleanup.js";const C=new c;C.setDecoderConfig({type:"js"}),C.setDecoderPath("/assets/draco/");const T=["glb","gltf","fbx","obj"];export class AssetResourceLoader{onError(e){console.error(e)}constructor(){this.cache=new Map,this.textureCache=new Map,this.loadingManager=new r,this.glbLoader=new o(this.loadingManager).setDRACOLoader(C),this.fbxLoader=new d(this.loadingManager),this.objLoader=new l(this.loadingManager),this.textureLoader=new n(this.loadingManager),this.tgaLoader=new v(this.loadingManager),this.exrLoader=new b(this.loadingManager),this.cubeLoader=new u(this.loadingManager),this.hdrLoader=new S(this.loadingManager),this.ktx2Loader=new A(this.loadingManager),this._textureLoader=new x.ImageBitmapLoader(this.loadingManager),this.audioLoader=new e(this.loadingManager),this.initialisedKtx2=!1,this._retrievedMeshes=[],this._retrievedTextures=[],this.makeReady=new p,this.ready=g(this.makeReady),this._texturePromises=new Map,this.asyncMeshResults=new Map,this.asyncAudioResults=new Map,this.collisionShapeCache=new Map,this.optimizedMeshes=new Set}initKtx2(e){this.initialisedKtx2=!0;null!=getElectronArg("windowId")||import.meta.url.includes(".vite")?this.ktx2Loader.setTranscoderPath("/assets/basis/"):this.ktx2Loader.setTranscoderPath(new URL("../assets/basis/",import.meta.url).href),this.ktx2Loader.detectSupport(e)}setDataDir(e){this.basePath=f(e,"asset-resources"),this.makeReady.next(!0)}getUri(e){const t=getElectronArg("windowId");return null!=t||import.meta.url.includes(".vite")?f(this.basePath,e)+(null!=t?`?windowId=${t}`:""):new URL(f("..",this.basePath,e),import.meta.url).href}async getTexture(e){if(!e||!e.fileKey)return null;if(this._texturePromises.has(e.id))return this._texturePromises.get(e.id);const t=this._getTexture(e).finally(()=>{this._texturePromises.delete(e.id)});return this._texturePromises.set(e.id,t),t}async _getTexture(e){if(null==e||null==e.fileKey)return null;if(await this.ready,this.textureCache.has(e.id)){const t=this.textureCache.get(e.id);t.dispose(),null!=e.texture&&(t.flipY!==e.texture?.flipY?(t.needsUpdate=!0,t.flipY=e.texture?.flipY??!0):t.wrapS!==j(e.texture?.wrapS)?(t.needsUpdate=!0,t.wrapS=j(e.texture?.wrapS)):t.wrapT!==j(e.texture?.wrapT)&&(t.wrapT=j(e.texture?.wrapT),t.needsUpdate=!0))}else try{await this._getTextureLoader(e.fileKey).loadAsync(this.getUri(e.fileKey)).then(t=>(t.texture3D?t=t.texture3D:(t.wrapS=j(e.texture?.wrapS),t.wrapT=j(e.texture?.wrapT),t.flipY=e.texture?.flipY??!0),this.textureCache.set(e.id,t),this._retrievedTextures.push(t),t))}catch(t){return console.warn("Failed to load texture "+e.name,t),null}return this.textureCache.get(e.id)}_getTextureLoader(e){return e?.toLowerCase().endsWith(".tga")?this.tgaLoader:e?.toLowerCase().endsWith(".ktx2")?this.ktx2Loader:e?.toLowerCase().endsWith(".exr")?this.exrLoader:e?.toLowerCase().endsWith(".cube")?this.cubeLoader:this.textureLoader}clearCache(e){"mesh"===e.type&&Array.from(this.cache.keys()).forEach(t=>{t.startsWith(e.fileKey)&&this.cache.delete(t)})}async getMesh(e,t){if(await this.ready,null==e)return console.error("No asset was provided"),{scene:new s,animations:[]};if(!T.includes(e.fileFormat?.toLowerCase()))return console.error("Unsupported mesh file format "+e.fileFormat,e),{scene:new s,animations:[]};const r=e.fileKey+(!0===t?.mergeGeomtries?"1":"0");if(!this.cache.has(r))try{this.asyncMeshResults.has(r)||this.asyncMeshResults.set(r,this.loadMesh(e).finally(()=>this.asyncMeshResults.delete(r))),this.cache.set(r,await this.asyncMeshResults.get(r))}catch(e){return this.onError(e),{scene:new s,animations:[]}}const a=this.cache.get(r).scene,n=this.computeCollisionShapes(e,a);!0===t?.mergeGeomtries&&this.optimizeDrawGroups(a);const o=m(a),h=this.cache.get(r).animations;o.traverse(e=>{e instanceof i&&e.material instanceof Array&&(e.material=e.material.slice())});const l=new AssetMeshInstance;l.add(o),l.collisionShapes=n,l.animations=h;const c=e.receiveShadow??!0,u=e.castShadow??!1;return o.traverse(e=>{e.castShadow=u,e.receiveShadow=c}),{scene:l,animations:h}}async getAudio(e){await this.ready;const t=e.fileKey;if(this.asyncAudioResults.has(t))return await this.asyncAudioResults.get(t);const s=this.audioLoader.loadAsync(this.getUri(e.fileKey)).finally(()=>{setTimeout(()=>{this.asyncAudioResults.delete(t)},1e3)});return this.asyncAudioResults.set(t,s),s}computeCollisionShapes(e,t){const s=e.id+e.mesh?.collisions?.shapeType;return this.collisionShapeCache.has(s)||this.collisionShapeCache.set(s,w(t,e)),this.collisionShapeCache.get(s)}async loadMesh(e){return await this.ready,await this.loadByAsset(e).then(e=>(e.scene.traverse(e=>{e instanceof i&&e.material,y(e)?e.visible=!1:e instanceof i&&e.geometry instanceof t&&(e.geometry.hasAttribute("normal")||e.geometry.computeVertexNormals())}),this._retrievedMeshes.push(e.scene),e.scene=function(e,t){let s=!1;if(t.traverseVisible(e=>{P.test(e.name)&&(s=!0)}),!s)return t;const r=new x.LOD,i=[t];for(;i.length>0;){const e=i.shift(),t=e.name.match(P);if(null!=t){const s=parseInt(t[1]);0===s?r.addLevel(e,0):console.warn(`Skipping LOD level ${s} for now as LOD is not fully supported`)}else i.push(...e.children)}return r}(0,e.scene),e))}optimizeDrawGroups(e){if(this.optimizedMeshes.has(e.uuid))return;this.optimizedMeshes.add(e.uuid);let s=!0,r=0,a=0;if(e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){r++;const t=Object.keys(e.geometry.attributes).length;t!==a&&0!==a&&(s=!1),a=t}else(e instanceof x.SkinnedMesh||e instanceof x.Bone)&&(s=!1)}),r>1&&s){const s=new Map;e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){if(Array.isArray(e.material))return;e.updateWorldMatrix(!0,!0);const t=e.material?.uuid||"default";s.has(t)||s.set(t,{material:e.material,geometries:[],objects:[]});const r=s.get(t);r.geometries.push(e.geometry.clone().applyMatrix4(e.matrixWorld)),r.objects.push(e)}});for(const e of s.values())for(const t of e.objects)t.removeFromParent();for(const t of s.values()){let s;s=1===t.geometries.length?t.geometries[0]:L.mergeGeometries(t.geometries,!0),s.groups.length>1&&L.mergeGroups(s),e.add(new i(s,t.material))}}const n=[];e.traverse(e=>{e instanceof i&&e.geometry instanceof t&&Array.isArray(e.material)&&!y(e)&&n.push({mesh:e,geometry:e.geometry,materialArray:e.material,parent:e.parent})});for(const{mesh:t,geometry:s,materialArray:r,parent:a}of n){t.removeFromParent();for(let t=0;t<r.length;t++){const n=r[t],o=s.groups.filter(e=>e.materialIndex===t);if(0===o.length)continue;const h=this.extractGeometryGroups(s,o);h.groups.length>1&&L.mergeGroups(h);const l=new i(h,n);a?a.add(l):e.add(l)}s.dispose()}e.traverse(e=>{if(e instanceof i&&e.geometry instanceof t&&!y(e)){const t=e.geometry;!Array.isArray(e.material)&&t.groups.length>1&&L.mergeGroups(t)}})}extractGeometryGroups(e,s){const r=e.index;if(!r){const r=new t;let i=0;for(const e of s)i+=e.count;if(0===i)return r;for(const t in e.attributes){const a=e.attributes[t],n=a.itemSize,o=a.array,h=new(0,o.constructor)(i*n);let l=0;for(const e of s){const t=e.start*n,s=e.count*n;for(let e=0;e<s;e++)h[l+e]=o[t+e];l+=s}const c=new x.BufferAttribute(h,n,a.normalized);r.setAttribute(t,c)}return r.groups=[{start:0,count:i,materialIndex:0}],r}const i=[];for(const e of s)for(let t=0;t<e.count;t++){const s=r.getX(e.start+t);i.push(s)}if(0===i.length)return new t;const a=new Map,n=[];let o=0;for(const e of i)a.has(e)||(a.set(e,o),o++),n.push(a.get(e));if(0===n.length||0===a.size)return new t;const h=new t;for(const t in e.attributes){const s=e.attributes[t],r=s.itemSize,i=s.array,n=new(0,i.constructor)(a.size*r);for(const[e,t]of a)for(let s=0;s<r;s++)n[t*r+s]=i[e*r+s];const o=new x.BufferAttribute(n,r,s.normalized);h.setAttribute(t,o)}const l=new((n.length>0?Math.max(...n):0)>65535?Uint32Array:Uint16Array)(n.length);for(let e=0;e<n.length;e++)l[e]=n[e];return h.setIndex(new x.BufferAttribute(l,1)),h.groups=[{start:0,count:n.length,materialIndex:0}],h}async loadByAsset(e){this.fbxLoader;const t=this.getUri(e.fileKey);switch(e.fileFormat){case"glb":case"gltf":return this.glbLoader.loadAsync(t).then(e=>({scene:e.scene,animations:e.animations}));case"fbx":return this.fbxLoader.loadAsync(t).then(e=>({scene:e,animations:e.animations}));case"obj":if(null!=e.materialLib){const t=new h;t.materialOptions={normalizeRGB:!1};const s=await t.loadAsync(this.getUri(e.materialLib));this.objLoader.setMaterials(s)}return this.objLoader.loadAsync(t).then(e=>(_(e),e)).then(e=>({scene:e,animations:e.animations}))}}disposeAll(){this.cache.clear(),this._retrievedMeshes.forEach(e=>R(e)),this._retrievedTextures.forEach(e=>e.dispose()),this._retrievedMeshes.length=0,this._retrievedTextures.length=0}}function _(e){if(e instanceof i)for(const t of M(e.material))t instanceof x.MeshPhongMaterial&&!t.color.isLinear&&(t.color.isLinear=!0);e.children?.forEach(_)}export class AssetMeshInstance extends a{}export function getElectronArg(e){const t=`--${e}=`,s=window.process?.argv.find(e=>e.startsWith(t));return s?.substring(t.length)}function j(e){switch(e){case"clamp":return x.ClampToEdgeWrapping;case"repeat":return x.RepeatWrapping;case"mirror":return x.MirroredRepeatWrapping}return x.RepeatWrapping}new x.Matrix4;const P=/_LOD(\d+)$/;/*
2
2
  * Copyright (©) 2025 Hology Interactive AB. All rights reserved.
3
3
  * See the LICENSE.md file for details.
4
4
  */
@@ -283,6 +283,13 @@ export declare class SceneMaterializer {
283
283
  private prepareCollisionShapesForInstanced;
284
284
  private testCanBatch;
285
285
  private testCanBatchMaterial;
286
+ /**
287
+ *
288
+ * @param group
289
+ * @param batchedObjectMaterials A map with object id -> mesh uuid -> material so that we can get material respecting per object overrides
290
+ * @param batchingInfos
291
+ * @returns
292
+ */
286
293
  private createBatchedMesh;
287
294
  private createInstancedMesh;
288
295
  private configureBatchedInstancedMesh;