@hology/core 0.0.179 → 0.0.181
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/effects/vfx/behaviours.d.ts +9 -0
- package/dist/effects/vfx/behaviours.js +1 -1
- package/dist/effects/vfx/vfx-actor.d.ts +2 -0
- package/dist/effects/vfx/vfx-actor.js +1 -1
- package/dist/effects/vfx/vfx-defs.d.ts +11 -3
- package/dist/effects/vfx/vfx-defs.js +1 -1
- package/dist/effects/vfx/vfx-materializer.d.ts +3 -1
- package/dist/effects/vfx/vfx-materializer.js +1 -1
- package/dist/gameplay/actors/builtin/post-process-volume-actor.js +1 -1
- package/dist/gameplay/initiate.js +1 -1
- package/dist/gameplay/services/asset-loader.js +1 -1
- package/dist/gameplay/services/physics/physics-system.js +1 -1
- package/dist/gameplay/services/world.d.ts +2 -2
- package/dist/gameplay/services/world.js +1 -1
- package/dist/scene/asset-resource-loader.d.ts +11 -0
- package/dist/scene/asset-resource-loader.js +1 -1
- package/dist/scene/assets-provider.d.ts +3 -3
- package/dist/scene/assets-provider.js +1 -1
- package/dist/scene/materializer.d.ts +23 -4
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +98 -2
- package/dist/scene/model.js +1 -1
- package/dist/scene/objects/prefab.d.ts +6 -1
- package/dist/scene/objects/prefab.js +1 -1
- package/dist/scene/runtime-asset-service.d.ts +1 -1
- package/dist/scene/runtime-asset-service.js +1 -1
- package/dist/shader/parameter.d.ts +21 -3
- package/dist/shader/parameter.js +1 -1
- package/package.json +3 -3
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -80,4 +80,13 @@ export declare class MoveOverLife extends Behaviour {
|
|
|
80
80
|
initialize(particle: Particle): void;
|
|
81
81
|
mutate(target: Particle | Emitter, time: number, index: number): void;
|
|
82
82
|
}
|
|
83
|
+
export declare class AnimationBehavior extends Behaviour {
|
|
84
|
+
private clip;
|
|
85
|
+
private timeScale;
|
|
86
|
+
private mixer;
|
|
87
|
+
private action;
|
|
88
|
+
constructor(clip: THREE.AnimationClip, timeScale?: number, easing?: EasingFunction);
|
|
89
|
+
initialize(particle: Particle): void;
|
|
90
|
+
mutate(target: Particle | Emitter, time: number, index: number): void;
|
|
91
|
+
}
|
|
83
92
|
//# sourceMappingURL=behaviours.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vector3 as
|
|
1
|
+
import{Vector3 as i}from"three";import{Behaviour as t,Vector3D as e,ease as s,MathUtils as o}from"@hology/nebula";import*as n from"three";export class RotatePosition extends t{constructor(i,t){super(),this.axis=i,this.angle=t,this.axis3D=new e(this.axis.x,this.axis.y,this.axis.z)}mutate(i,t,e){this.energize(i,t),null!=i.old&&0!=i.old.position.lengthSq()&&(a.copy(i.old.position),a.sub(i.parent.position),a.applyAxisAngle(this.axis3D,this.angle*t),a.add(i.parent.position),a.sub(i.old.position).divideScalar(t),i.velocity.sub(a)),a.copy(i.position),a.sub(i.parent.position),a.applyAxisAngle(this.axis3D,this.angle*t),a.add(i.parent.position),a.sub(i.position).divideScalar(t),i.velocity.add(a)}}const a=new i;export var AxisDirection;!function(i){i[i.x=0]="x",i[i.y=1]="y",i[i.z=2]="z",i[i.mx=3]="mx",i[i.my=4]="my",i[i.mz=5]="mz"}(AxisDirection||(AxisDirection={}));export class OrientAlongVelocity extends t{constructor(i){super(),this.axisDirection=i}initialize(i){i.transform.orientAlongVelocity=!0}mutate(i,t,e){i.target,n.Object3D}}export class FollowParent extends t{constructor(i){super(),this.speed=i}initialize(i){}mutate(i,t,e){const s=i.parent.parentParticle??i.parent;if(0===this.speed)return i.position.copy(s.old.position),i.acceleration.copy(s.acceleration),void i.velocity.copy(s.velocity);const o=r.copy(s.position).sub(i.position),n=(o.length(),o.normalize());l.copy(n).multiplyScalar(this.speed),i.velocity.copy(l)}}export class Scale extends t{constructor(i,t,e){super(void 0,e),this.scaleA=i,this.scaleB=t}initialize(i){i.transform.scaleA=i.scale*this.scaleA,i.transform.scaleB=i.scale*this.scaleB,i.transform.oldRadius=i.radius}mutate(i,t,e){this.energize(i,t),i.scale=o.lerp(i.transform.scaleA,i.transform.scaleB,this.energy),i.scale<5e-4&&(i.scale=0),i.radius=i.transform.oldRadius*i.scale}}export class ScaleComponents extends t{constructor(i,t,e){super(void 0,e),this.scaleA=i,this.scaleB=t}initialize(t){let e=t.transform.initialScale;e?(e=e.clone(),t.transform.initialScale=e):(e=new i(1,1,1),t.transform.initialScale=e),t.transform.scaleComponentsA=e.clone().multiply(this.scaleA),t.transform.scaleComponentsB=e.clone().multiply(this.scaleB)}mutate(i,t,e){this.energize(i,t);const s=i.transform.scaleComponentsA,o=i.transform.scaleComponentsB;i.transform.initialScale.lerpVectors(o,s,this.energy)}}export class LinearDamping extends t{constructor(i){super(),this.factor=i}mutate(i,t,e){this.energize(i,t);const s=r.copy(i.velocity).multiplyScalar(-this.factor*t);i.velocity.add(s)}}const r=new e,l=new e;export var AxisPlane;!function(i){i[i.xy=0]="xy",i[i.xz=1]="xz",i[i.yz=2]="yz",i[i.xyz=3]="xyz"}(AxisPlane||(AxisPlane={}));export class Disperse extends t{constructor(i,t,e=s.easeLinear){super(void 0,e,void 0,!0),this.distance=i,this.plane=t}initialize(i){i.transform.initialPos=i.position.clone();const t=c.copy(i.transform.initialPos).sub(i.parent.position).normalize();switch(this.plane){case AxisPlane.xy:t.setComponent(2,0);break;case AxisPlane.xz:t.setComponent(1,0);break;case AxisPlane.yz:t.setComponent(0,0)}i.transform.displacement=t.clone().multiplyScalar(this.distance),i.transform.prevEnergy=1}mutate(i,t,e){this.energize(i,t);i.transform.initialPos;const s=i.transform.displacement,o=i.transform.prevEnergy-this.energy;i.transform.prevEnergy=this.energy;i.position.x+=s.x*o,i.position.y+=s.y*o,i.position.z+=s.z*o}}export class MoveOverLife extends t{constructor(i,t,e,o=s.easeLinear){super(void 0,o,void 0,!0),this.x=i,this.y=t,this.z=e}initialize(i){i.transform.initialPos=i.position.clone()}mutate(i,t,e){this.energize(i,t);const s=i.transform.initialPos,o=1-this.energy;i.position.x=s.x+this.x*o,i.position.y=s.y+this.y*o,i.position.z=s.z+this.z*o}}const c=new e;export class AnimationBehavior extends t{constructor(i,t=1,e=s.easeLinear){super(void 0,e,void 0,!0),this.clip=i,this.timeScale=t}initialize(i){this.mixer=null,this.action=null}mutate(i,t,e){if(this.energize(i,t),null==this.mixer){const t=i.target;t instanceof n.Object3D&&(this.mixer=new n.AnimationMixer(t.children[0]),this.action=this.mixer.clipAction(this.clip),this.action.timeScale=this.timeScale,this.action.play())}this.mixer&&this.mixer.update(t)}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t}from"tslib";import*as s from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as h}from"../../gameplay/services/render.js";import{World as m}from"../../gameplay/services/world.js";import{DelayRate as l}from"./rates.js";import{materializeVfx as d}from"./vfx-materializer.js";import{PhysicsSystem as
|
|
1
|
+
import{__decorate as t}from"tslib";import*as s from"three";import{Rate as e}from"@hology/nebula";import{Actor as i,BaseActor as r}from"../../gameplay/actors/actor.js";import{inject as o}from"../../gameplay/inject.js";import{AssetLoader as a}from"../../gameplay/services/asset-loader.js";import{ViewController as h}from"../../gameplay/services/render.js";import{World as m}from"../../gameplay/services/world.js";import{DelayRate as l}from"./rates.js";import{materializeVfx as d}from"./vfx-materializer.js";import{PhysicsSystem as n}from"../../gameplay/services/physics/physics-system.js";import{ShaderProvider as p}from"../../gameplay/services/shader-provider.js";import{AssetResourceLoader as c}from"../../scene/asset-resource-loader.js";import{AssetsProvider as y}from"../../scene/assets-provider.js";let u=class extends r{constructor(){super(...arguments),this.timescale=1,this.paused=!0,this.assetLoader=o(a),this.assetManagerService=o(c),this.assetService=o(y),this.world=o(m),this.view=o(h),this.physics=o(n),this.shaderProvider=o(p),this._worldPos=new s.Vector3,this._worldRot=new s.Quaternion,this._worldEul=new s.Euler,this.max=0}async fromAsset(t){if("vfx"!==t.type)throw"Asset must be a VFX asset but is "+t.type;null!=this.system&&(this.system.destroy(),this.system.emitters.forEach(t=>t.reset())),this.sourceAsset=t,this.disposeSystem&&this.disposeSystem(),this.world.scene.add(this.object);const{system:s,dispose:e,container:i}=await d(this.sourceAsset,this.object,{getAsset:t=>this.assetLoader.getAsset(t),getMaterial:t=>this.assetLoader.getMaterialByAssetId(t),getTexture:t=>this.assetLoader.getTextureByAssetId(t),getMesh:t=>this.assetLoader.getModelByAssetId(t).then(t=>t.scene)},this.view,this.physics,this.shaderProvider,this.assetService,this.assetManagerService);this.system=s,this.disposeSystem=e,this.particleSystemContainer=i,this.object.visible=!1,this.object.matrixAutoUpdate=!1,this.object.matrixWorldAutoUpdate=!1,this.particleSystemContainer.matrixAutoUpdate=!1,this.particleSystemContainer.matrixWorldAutoUpdate=!1}play(){null==this.particleSystemContainer.parent&&this.world.scene.add(this.particleSystemContainer),this.object.matrixAutoUpdate=!0,this.object.matrixWorldAutoUpdate=!0,this.particleSystemContainer.matrixAutoUpdate=!0,this.particleSystemContainer.matrixWorldAutoUpdate=!0,this.object.visible=!0,this.paused=!1;this.system.emitters.every(t=>t.dead)&&this.restart()}pause(){this.paused=!0}stop(){this.system.emitters.forEach(t=>{const s=t.rate;s instanceof e&&(s.nextTime=1/0)})}restart(){if(null!=this.system&&null!=this.system.emitters)for(const t of this.system.emitters){const s=t.rate;s instanceof l?s.restart():s.nextTime=0,t.removeAllParticles()}}onUpdate(t){this.paused||(this.object.getWorldPosition(this._worldPos),this.object.getWorldQuaternion(this._worldRot),this._worldEul.setFromQuaternion(this._worldRot),this.system?.emitters.forEach(t=>{"world"===t._space&&(t.setPosition(this._worldPos),t.setRotation(this._worldEul))}),this.system?.update(t*this.timescale))}getParticleCount(){return this.system?.getCount()??0}onEndPlay(){this.stop(),null!=this.disposeSystem&&this.disposeSystem()}};u=t([i()],u);export{u as VfxActor};/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Vector2, Vector3 } from "three";
|
|
1
|
+
import { AnimationClip, Vector2, Vector3 } from "three";
|
|
2
2
|
import { Behaviour, Initializer } from "@hology/nebula";
|
|
3
3
|
import { Curve2 } from "../../utils/curve.js";
|
|
4
4
|
type HexColor = `#${string}`;
|
|
5
|
-
export type ShapeParameterDef<T = boolean | number | string | Vector3 | Vector2 | HexColor | Curve2> = {
|
|
6
|
-
type: T extends number ? 'number' : T extends HexColor ? 'color' : T extends string ? 'string' | 'select' : T extends Vector2 ? 'vec2' : T extends Vector3 ? 'vec3' : T extends Curve2 ? 'curve' : T extends boolean ? 'boolean' : never;
|
|
5
|
+
export type ShapeParameterDef<T = boolean | number | string | Vector3 | Vector2 | HexColor | Curve2 | AnimationClip> = {
|
|
6
|
+
type: T extends number ? 'number' : T extends HexColor ? 'color' : T extends string ? 'string' | 'select' : T extends Vector2 ? 'vec2' : T extends Vector3 ? 'vec3' : T extends Curve2 ? 'curve' : T extends AnimationClip ? 'animationclip' : T extends boolean ? 'boolean' : never;
|
|
7
7
|
default: T;
|
|
8
8
|
};
|
|
9
9
|
type FloatParameterDef = ShapeParameterDef<number> & {
|
|
@@ -279,6 +279,13 @@ declare class WorldCollisionDef extends BaseBevDef<WorldCollisionDef> {
|
|
|
279
279
|
};
|
|
280
280
|
make(params?: ParamsType<this>): Behaviour;
|
|
281
281
|
}
|
|
282
|
+
declare class AnimationBehaviorDef extends BaseBevDef<AnimationBehaviorDef> {
|
|
283
|
+
parameters: {
|
|
284
|
+
clip: ShapeParameterDef<AnimationClip>;
|
|
285
|
+
timeScale: FloatParameterDef;
|
|
286
|
+
};
|
|
287
|
+
make(params?: ParamsType<this>): Behaviour;
|
|
288
|
+
}
|
|
282
289
|
declare const vfxInitializsers: {
|
|
283
290
|
lifetime: LifetimeDef;
|
|
284
291
|
randomLifetime: RandomLifetimeDef;
|
|
@@ -316,6 +323,7 @@ declare const vfxBehaviours: {
|
|
|
316
323
|
linearDamping: LinearDampingDef;
|
|
317
324
|
followParent: FollowParentDef;
|
|
318
325
|
worldCollision: WorldCollisionDef;
|
|
326
|
+
animation: AnimationBehaviorDef;
|
|
319
327
|
};
|
|
320
328
|
export type LibraryVfxInitalizerType = keyof typeof vfxInitializsers;
|
|
321
329
|
export declare const VfxInitializserLibrary: Record<LibraryVfxInitalizerType, InitializerDefinition>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{MathUtils as e,Vector2 as
|
|
1
|
+
import{MathUtils as e,Vector2 as t,Vector3 as r}from"three";import{Alpha as s,Attraction as n,BoxZone as a,CircleZone as o,Color as i,ease as c,Force as u,Gravity as m,Life as d,LineZone as p,Mass as l,Position as w,RadialVelocity as x,RandomDrift as f,Repulsion as h,Rotate as y,Vector3D as g}from"@hology/nebula";import{AnimationBehavior as k,AxisDirection as b,AxisPlane as v,Disperse as z,FollowParent as R,LinearDamping as T,MoveOverLife as L,OrientAlongVelocity as V,RotatePosition as j,Scale as D,ScaleComponents as C}from"./behaviours.js";import{AdditiveVelocity as B,InitialScale as S,InitialScaleComponents as I,RandomDirection as O,RandomRotation as A,randomRotationAxis as K,RandomScale as P,Rotation as Y}from"./initializsers.js";import{PointZone as M,SphereZone as X}from"./zones.js";import{WorldCollisionBehaviour as Z}from"./vfx-collision-behaviour.js";import{Curve2 as q}from"../../utils/curve.js";class E{build(e={}){const t=U(e,this.parameters);return this.make(t)}}class F{build(e={}){const t=U(e,this.parameters);return this.make(t)}}function G(e,t,r){return{type:"number",default:e,float:!0,min:t,max:r}}function H(e){return{type:"vec3",default:(new r).fromArray(e)}}function J(e){return{type:"color",default:e}}function N(e,t){return{type:"select",opts:e,default:t}}function Q(){return{type:"curve",default:q.linear()}}function U(e,t){const r={};for(let s in t)null==e[s]?r[s]=t[s].default:r[s]=e[s];return r}function W(e){return t=>e.getY(t)}const $={lifetime:new class extends F{constructor(){super(...arguments),this.parameters={duration:G(1,0,1e5)}}make(e={}){return new d(e.duration)}},randomLifetime:new class extends F{constructor(){super(...arguments),this.parameters={minDuration:G(1,0,1e5),maxDuration:G(2,0,1e5)}}make(e={}){return new d(e.minDuration,e.maxDuration)}},positionPoint:new class extends F{constructor(){super(...arguments),this.parameters={position:H([0,0,0])}}make(e={}){const{x:t,y:r,z:s}=e.position;return new w(new M(t,r,s))}},positionBox:new class extends F{constructor(){super(...arguments),this.parameters={position:H([0,0,0]),dimensions:H([0,0,0])}}make(e={}){const{x:t,y:r,z:s}=e.position,{x:n,y:o,z:i}=e.dimensions;return new w(new a(t,r,s,n,o,i))}},positionSphere:new class extends F{constructor(){super(...arguments),this.parameters={position:H([0,0,0]),radius:G(1)}}make(e={}){const{x:t,y:r,z:s}=e.position;return new w(new X(t,r,s,e.radius))}},positionLine:new class extends F{constructor(){super(...arguments),this.parameters={a:H([0,0,0]),b:H([0,0,1])}}make(e={}){const{x:t,y:r,z:s}=e.a,{x:n,y:a,z:o}=e.b;return new w(new p(t,r,s,n,a,o))}},positionCircle:new class extends F{constructor(){super(...arguments),this.parameters={position:H([0,0,0]),rotation:H([0,0,0]),radius:G(1,0,1e4)}}make(t={}){const{x:r,y:s,z:n}=t.position,{x:a,y:i,z:c}=t.rotation;return new w(new o(r,s,n,t.radius,0,e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},positionRing:new class extends F{constructor(){super(...arguments),this.parameters={position:H([0,0,0]),rotation:H([0,0,0]),radius:G(1,0,1e4),thickness:G(.2,0,1e4)}}make(t={}){const{x:r,y:s,z:n}=t.position,{x:a,y:i,z:c}=t.rotation;return new w(new o(r,s,n,t.radius,Math.max(t.thickness,1e-4),e.degToRad(a),e.degToRad(i),e.degToRad(c)))}},rotation:new class extends F{constructor(){super(...arguments),this.parameters={rotation:H([0,0,0])}}make(t={}){const{x:s,y:n,z:a}=t.rotation;return new Y(new r(e.degToRad(s),e.degToRad(n),e.degToRad(a)))}},randomRotation:new class extends F{constructor(){super(...arguments),this.parameters={axis:N(K,"XYZ")}}make(e={}){return new A(e.axis)}},scale:new class extends F{constructor(){super(...arguments),this.parameters={scale:G(1)}}make(e={}){return new S(e.scale)}},scaleComponents:new class extends F{constructor(){super(...arguments),this.parameters={scale:H([1,1,1])}}make(e={}){return new I(e.scale)}},randomScale:new class extends F{constructor(){super(...arguments),this.parameters={min:G(1),max:G(1)}}make(e={}){return new P(e.min,e.max)}},mass:new class extends F{constructor(){super(...arguments),this.parameters={min:G(1)}}make(e={}){return new l(e.min)}},velocity:new class extends F{constructor(){super(...arguments),this.parameters={velocity:H([0,0,0])}}make(e={}){const{x:t,y:s,z:n}=e.velocity;return new B(new r(t,s,n))}},randomVelocity:new class extends F{constructor(){super(...arguments),this.parameters={min:H([0,0,0]),max:H([0,0,0])}}make(e={}){return new B(e.min,e.max)}},radialVelocity:new class extends F{constructor(){super(...arguments),this.parameters={speed:G(1),direction:H([0,1,0]),spread:G(0)}}make(e={}){return new x(e.speed,new g(e.direction.x,e.direction.y,e.direction.z),e.spread)}},randomDirection:new class extends F{constructor(){super(...arguments),this.parameters={speed:G(1)}}make(e={}){return new O(e.speed)}}},_={force:new class extends E{constructor(){super(...arguments),this.parameters={force:H([0,0,0]),ease:Q()}}make(e={}){return new u(e.force.x,e.force.y,e.force.z,void 0,W(e.ease))}},gravity:new class extends E{constructor(){super(...arguments),this.parameters={gravity:G(8),easing:Q()}}make(e={}){return new m(e.gravity,void 0,W(e.easing))}},repulsion:new class extends E{constructor(){super(...arguments),this.parameters={target:H([0,0,0]),force:G(1),radius:G(1),easing:Q()}}make(e={}){const t=new g(e.target.x,e.target.y,e.target.z);return new h(t,e.force,e.radius,void 0,W(e.easing))}},attraction:new class extends E{constructor(){super(...arguments),this.parameters={target:H([0,0,0]),force:G(1),radius:G(1),easing:Q()}}make(e={}){const t=new g(e.target.x,e.target.y,e.target.z);return new n(t,e.force,e.radius,void 0,W(e.easing))}},scale:new class extends E{constructor(){super(...arguments),this.parameters={a:G(1),b:G(1),ease:Q()}}make(e={}){return new D(e.a,e.b,W(e.ease))}},scaleComponents:new class extends E{constructor(){super(...arguments),this.parameters={a:H([1,1,1]),b:H([1,1,1]),ease:Q()}}make(e={}){return new C(e.a,e.b,W(e.ease))}},randomDrift:new class extends E{constructor(){super(...arguments),this.parameters={drift:H([1,1,1]),delay:G(0),ease:Q()}}make(e={}){return new f(e.drift.x,e.drift.y,e.drift.z,e.delay,void 0,W(e.ease))}},rotate:new class extends E{constructor(){super(...arguments),this.parameters={rotation:H([0,0,0]),ease:Q()}}make(t={}){const{x:r,y:s,z:n}=t.rotation;return new y(e.degToRad(r),e.degToRad(s),e.degToRad(n),void 0,W(t.ease))}},rotateAdd:new class extends E{constructor(){super(...arguments),this.parameters={rotation:H([0,0,0])}}make(t={}){const{x:r,y:s,z:n}=t.rotation,a=new y(e.degToRad(r),e.degToRad(s),e.degToRad(n),void 0);return a.rotationType="add",a}},changeColor:new class extends E{constructor(){super(...arguments),this.parameters={a:J("#ffffff"),b:J("#ffffff"),ease:Q()}}make(e={}){return new i(e.a,e.b,void 0,W(e.ease))}},changeOpacity:new class extends E{constructor(){super(...arguments),this.parameters={a:G(1,0,1),b:G(0,0,1),ease:Q()}}make(e={}){return new s(e.a,e.b,void 0,W(e.ease))}},vortex:new class extends E{constructor(){super(...arguments),this.parameters={axis:H([0,1,0]),amount:G(1)}}make(e={}){return new j(e.axis,e.amount)}},moveTo:new class extends E{constructor(){super(...arguments),this.parameters={target:H([0,1,0]),ease:Q()}}make(e={}){return new L(e.target.x,e.target.y,e.target.z,W(e.ease))}},linearDamping:new class extends E{constructor(){super(...arguments),this.parameters={factor:G(.1,0,1e3)}}make(e={}){return new T(e.factor)}},followParent:new class extends E{constructor(){super(...arguments),this.parameters={speed:G(0)}}make(e={}){return new R(e.speed)}},worldCollision:new class extends E{constructor(){super(...arguments),this.parameters={friction:G(1,0,1),bounce:G(1,0,1),lifeLoss:G(0,0)}}make(e={}){return new Z(null,e.bounce,e.friction,e.lifeLoss)}},animation:new class extends E{constructor(){super(...arguments),this.parameters={clip:{type:"animationclip",default:null},timeScale:G(1)}}make(e={}){return new k(e.clip,e.timeScale,c.easeLinear)}}};export const VfxInitializserLibrary=$;export const VfxInitializserLibraryKeys=Object.keys(VfxInitializserLibrary);export const VfxBehaviourLibrary=_;export const VfxBehaviourLibraryKeys=Object.keys(VfxBehaviourLibrary);/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -5,13 +5,15 @@ import { PhysicsSystem } from '../../gameplay/services/physics/physics-system.js
|
|
|
5
5
|
import { ViewController } from '../../gameplay/services/render.js';
|
|
6
6
|
import { Asset, VfxAsset } from '../../scene/model.js';
|
|
7
7
|
import { ShaderProvider } from "../../gameplay/services/shader-provider.js";
|
|
8
|
+
import { AssetResourceLoader } from "../../scene/asset-resource-loader.js";
|
|
9
|
+
import { AssetsProvider } from "../../scene/assets-provider.js";
|
|
8
10
|
export type VfxAssetProvider = {
|
|
9
11
|
getAsset(assetId: string): Promise<Asset>;
|
|
10
12
|
getTexture(assetId: string): Promise<THREE.Texture>;
|
|
11
13
|
getMesh(assetId: string): Promise<THREE.Object3D>;
|
|
12
14
|
getMaterial(assetId: string): Promise<THREE.Material>;
|
|
13
15
|
};
|
|
14
|
-
export declare function materializeVfx(asset: VfxAsset, target: Object3D, assetProvider: VfxAssetProvider, view: ViewController, physics: PhysicsSystem, shaderProvider: ShaderProvider): Promise<{
|
|
16
|
+
export declare function materializeVfx(asset: VfxAsset, target: Object3D, assetProvider: VfxAssetProvider, view: ViewController, physics: PhysicsSystem, shaderProvider: ShaderProvider, assetsService: AssetsProvider, assetManagerService: AssetResourceLoader): Promise<{
|
|
15
17
|
container: THREE.Object3D<THREE.Object3DEventMap>;
|
|
16
18
|
system: System;
|
|
17
19
|
dispose: () => void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e,{Behaviour as t,Body as a,Emitter as s,Rate as n}from"@hology/nebula";import*as i from"three";import{Object3D as r}from"three";import{AttributeVec3Node as o,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as u,UniformFloatNode as p,UniformVec3Node as m,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as w,attributes as g,clamp as b,float as v,glslFunction as A,lambertMaterial as E,log as M,pow as x,rgb as I,rgba as T,smoothstep as P,standardMaterial as S,textureSampler2d as B,uniformFloat as C,uniforms as R,varying as k,varyingAttributes as j,varyingVec3 as D,varyingVec4 as z}from"three-shader-graph";import{prepareClassParameters as V,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as L}from"../../scene/model.js";import{ShapeLibrary as O}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as Q,linearEyeDepth as W}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as H,particleTimeUniformName as U,particleUniforms as q,particleVelcoityUniformName as G}from"../../shader-nodes/particle.js";import{sampleFlipbook as J}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as Y}from"./rates.js";import{StretchedSprite as X}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{getSpritePosition as ae,SpriteNodeShaderMaterial as se}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ne}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as ie}from"../../shader/builtin/decal-standard-shader.js";export async function materializeVfx(t,a,s,n,o,l){let c=a;for(;null!=c.parent;)c=c.parent;const u=new r;u.name="particle system local",a.add(u);const p=new r;p.name="particle system world";const m=new ee(p,u,i,n),h=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await re(e,s,h,o,l);return t.setParentRecursive(h),t.emit()}))).forEach(e=>h.addEmitter(e)),h.addRenderer(m).emit({onEnd:()=>{}}),{container:p,system:h,dispose:()=>{p.removeFromParent(),u.removeFromParent(),m.dispose()}}}async function re(e,t,s,u,v){const x=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new Y(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new n(0,1/0)}return t}(e);let I;switch(e.output.type){case"decal":I=new a(await async function(e,t){const a=!1!==e.unlit?new ne:new ie;a.color=new i.Color(e.color),a instanceof ne?a.intensity=e.intensity??1:a.emissiveIntensity=e.intensity??1;if(e.colorMap){const s=await t.getTexture(e.colorMap);a.colorMap=s}if(e.alphaMap){const s=await t.getTexture(e.alphaMap);a.alphaMap=s}const s=a.build();s.blending=Z[e.blendingMode]??i.NormalBlending,s.transparent=!0,s.side=i.BackSide,s.depthTest=!1,null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0);s.defines.IS_PARTICLE="";const n=new i.BoxGeometry(1,1,1),r=new i.Mesh(n,s);null!=e.renderOrder&&(r.renderOrder=e.renderOrder);return r}(e.output,t));break;case"sprite":I=new a(await async function(e,t,a){let s=null;s=null!=e.shader?await le(e,t,a):await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,s=B(a);let n=s.sample(j.uv);e.flipbook?.enabled&&(n=J(s,g.uv,e.flipbook.columns,e.flipbook.rows,q.time,e.flipbook.fps,e.flipbook.mode));const r=new p("rotation",0),o=new m("color").rgb,l=C("opacity",1),c=W.subtract(Q).divide(W);let u=l;switch(e.opacityChannel??"red"){case"none":break;case"red":u=u.multiply(n.r);break;case"alpha":u=u.multiply(n.a)}if("number"==typeof e.softness&&e.softness>0){const t=b(c,0,1e3);u=u.multiply(P(0,.2*e.softness,t))}const h=ae(r),d=T(o.multiply(n.rgb).multiplyScalar(e.intensity??1),u);var f=new se({color:d,emissive:d.rgb.multiplyScalar(u),transparent:!0,position:h,alphaTest:1e-4,uniforms:{color:{value:new i.Color(e.color)}}});f.alphaHash=!0,null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??i.NormalBlending,f}(e,t);s instanceof i.ShaderMaterial&&!0===e.lockY&&(s.defines.LOCK_Y_AXIS="");const n=new i.Mesh(new i.PlaneGeometry(1,1),s);return n.name="sprite",n}(e.output,t,v));break;case"stretchedSprite":I=new a(await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,s=B(a).sample(j.uv),n=z(new l("color")),r=n.rgb.multiply(s.rgb);let o=n.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(s.r);break;case"alpha":o=o.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=W.subtract(Q).divide(M(W)),a=b(t,0,1e3);o=o.multiply(P(0,.2*e.softness,a))}const c=A(d,{position:g.position,offset:y("offset"),modelViewMatrix:R.modelViewMatrix,velocity:w("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var u=new se({color:T(r.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new i.Color(e.color)}}});null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);u.blending=Z[e.blendingMode]??i.NormalBlending;const p=new X(new i.PlaneGeometry(1,1),u);return p.scaleFactor=e.scale,p}(e.output,t));break;case"shape":I=new a(await async function(e,t,a){if(null==e.shape)return console.log("Shape is null"),new r;const s=O[e.shape];if(null==s)return console.error(`No shape with type ${e.shape}`),new r;const n=F(e.params??{}),l=s.geometry(n);let u=null;u=null!=e.shader?await le(e,t,a):null!=e.material?ce(await t.getMaterial(e.material)):function(){const e=k(new h("instanceColor")).rgb,t=k(new o("particleData")).x;return new c({color:E({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}();null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);return new i.Mesh(l,u)}(e.output,t,v));break;case"mesh":I=new a(await async function(e,t,a){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new r;const s=await t.getMesh(e.assetId),n=await t.getAsset(e.assetId);if(null!=e.shader||null!=e.material){let n;n=null!=e.shader?await le(e,t,a):ce(await t.getMaterial(e.material)),null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0),null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0),s.traverse(e=>{e instanceof i.Mesh&&(e.material=n)})}else{const e=[];if(null!=n.materialAssignments)for(const a of n.materialAssignments)s.traverse(s=>{s instanceof i.Mesh&&s.material instanceof i.Material&&s.material.color instanceof i.Color&&(s.material.name!=a.name&&null!=a.name||"#"+s.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>s.material=e)))});await Promise.all(e)}const o=[];if(s.traverse(e=>{e instanceof i.Mesh&&o.push(e)}),1===o.length){const e=o[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return s}(e.output,t,v));break;case"trail":I=new a({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const S=new pe;S.parent=s,S.setRate(x),S._space=e.output.space;const D=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type],a=await F(e.params??{});return t.build(a)}));D.push(I,new N),S.addInitializers(D);const V=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=_[e.type]).map(async e=>{const t=_[e.type];for(const[a,s]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&s.type!==L.Curve&&(s.type=L.Curve);const a=await F(e.params??{});return t.build(a)}).sort((e,t)=>e instanceof te?1:0));V.push(new ue);for(const e of V)e instanceof te&&(e.physics=u);S.addBehaviours(V);for(const a of e.children){const e=await re(a,t,s,u,v),n=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=S.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&S.childEmitters.splice(e,1),n.release(t)},t}),i=S.eventDispatcher,r=new Map;S.bindEmitterEvent=!0,i.addEventListener("PARTICLE_DEAD",e=>{const t=r.get(e.id);if(null!=t){const e=S.childEmitters.findIndex(e=>e.id===t.id);null!=e&&(t.stopEmit(),S.childEmitters.splice(e,1))}});let o="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":o="PARTICLE_COLLISION";break;case"start":o="PARTICLE_CREATED"}i.addEventListener(o,e=>{const t=n.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),S.childEmitters.push(t),r.set(e.id,t),t.parentParticle=e,t.system=S.system,t.emit()})}return S}const oe=(new i.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function le(e,t,a){const s=a.get(e.shader);if(null==s)return console.error("No shader exists with name "+e.shader),new i.Material;const n=new s.type,r=await V(e.shaderParams,s.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(n,r),n.build()}function ce(e){const t=k(new h("instanceColor")).rgb;let a,s=k(new o("particleData")).x;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial){let n=t.multiply(I(e.color));null!=e.map&&(n=n.multiply(B(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(s=s.multiply(B(e.alphaMap).sample(j.uv).r)),e instanceof i.MeshStandardMaterial?a=new c({color:S({color:n,emissive:I(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(s),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}):e instanceof i.MeshLambertMaterial?a=new c({color:E({color:n}).rgb.rgba(s),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}):e instanceof i.MeshBasicMaterial&&(a=new c({color:n.rgb.rgba(s),emissive:n.rgb,transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class ue extends t{initialize(e){e.body instanceof i.Object3D&&e.body.traverse(e=>{if(e instanceof i.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[H]||null!=t.uniforms[U]||t.uniforms[G])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof r&&e.target.traverse(t=>{if(t instanceof i.Mesh){const a=t.material;a instanceof c&&(null!=a.uniforms[H]&&(a.uniforms[H].value=this.energy),null!=a.uniforms[U]&&(a.uniforms[U].value=e.age),null!=a.uniforms[G]&&(a.uniforms[G].value=e.velocity))}})}}class pe extends s{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new pe;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
|
1
|
+
import e,{Behaviour as t,Body as a,Emitter as s,Rate as n}from"@hology/nebula";import*as i from"three";import{Object3D as r}from"three";import{AttributeVec3Node as o,AttributeVec4Node as l,NodeShaderMaterial as c,RgbNode as u,UniformFloatNode as p,UniformVec3Node as m,Vec3ExpressionNode as h,Vec4Node as d,attributeFloat as f,attributeVec3 as y,attributeVec4 as w,attributes as g,clamp as b,float as v,glslFunction as A,lambertMaterial as E,log as M,pow as x,rgb as I,rgba as T,smoothstep as P,standardMaterial as S,textureSampler2d as B,uniformFloat as C,uniforms as R,varying as k,varyingAttributes as j,varyingVec3 as D,varyingVec4 as z}from"three-shader-graph";import{prepareClassParameters as V,prepareShapeParameters as F}from"../../scene/materializer.js";import{SerializedParamType as L}from"../../scene/model.js";import{ShapeLibrary as O}from"../../scene/objects/shapes.js";import{fragmentLinearEyeDepth as Q,linearEyeDepth as W}from"../../shader-nodes/depth.js";import{particleEnergyUniformName as H,particleTimeUniformName as U,particleUniforms as q,particleVelcoityUniformName as G}from"../../shader-nodes/particle.js";import{sampleFlipbook as J}from"../../shader-nodes/texture-sequence.js";import{DefaultInitializer as N}from"./initializsers.js";import{DelayRate as K,OnceRate as Y}from"./rates.js";import{StretchedSprite as X}from"./stretched-sprite.js";import{ThreeBlendingMode as Z}from"./vfx-asset.js";import{VfxBehaviourLibrary as _,VfxInitializserLibrary as $}from"./vfx-defs.js";import{MultiRenderer as ee}from"./vfx-renderers.js";import{WorldCollisionBehaviour as te}from"./vfx-collision-behaviour.js";import{getSpritePosition as ae,SpriteNodeShaderMaterial as se}from"../../shader/sprite-shader.js";import{DecalUnlitShader as ne}from"../../shader/builtin/decal-unlit-shader.js";import{DecalStandardShader as ie}from"../../shader/builtin/decal-standard-shader.js";export async function materializeVfx(t,a,s,n,o,l,c,u){let p=a;for(;null!=p.parent;)p=p.parent;const m=new r;m.name="particle system local",a.add(m);const h=new r;h.name="particle system world";const d=new ee(h,m,i,n),f=new e;return(await Promise.all(t.vfx.emitters.slice().sort((e,t)=>(t.output.renderOrder??0)-(e.output.renderOrder??0)).map(async e=>{const t=await re(e,s,c,u,f,o,l);return t.setParentRecursive(f),t.emit()}))).forEach(e=>f.addEmitter(e)),f.addRenderer(d).emit({onEnd:()=>{}}),{container:h,system:f,dispose:()=>{h.removeFromParent(),m.removeFromParent(),d.dispose()}}}async function re(e,t,s,u,v,x,I){const S=function(e){let t;switch(e.rate.type){case"continuous":t=new K(e.rate.delay??0,e.rate.count,e.rate.time,e.rate.duration);break;case"once":t=new Y(e.rate.delay??0,e.rate.count);break;default:console.warn(`Failed to configure rate for emitter: ${JSON.stringify(e)}`),t=new n(0,1/0)}return t}(e);let D;switch(e.output.type){case"decal":D=new a(await async function(e,t){const a=!1!==e.unlit?new ne:new ie;a.color=new i.Color(e.color),a instanceof ne?a.intensity=e.intensity??1:a.emissiveIntensity=e.intensity??1;if(e.colorMap){const s=await t.getTexture(e.colorMap);a.colorMap=s}if(e.alphaMap){const s=await t.getTexture(e.alphaMap);a.alphaMap=s}const s=a.build();s.blending=Z[e.blendingMode]??i.NormalBlending,s.transparent=!0,s.side=i.BackSide,s.depthTest=!1,null!=s&&!0===e.bloom&&(s.userData.hasBloom=!0);s.defines.IS_PARTICLE="";const n=new i.BoxGeometry(1,1,1),r=new i.Mesh(n,s);null!=e.renderOrder&&(r.renderOrder=e.renderOrder);return r}(e.output,t));break;case"sprite":D=new a(await async function(e,t,a){let s=null;s=null!=e.shader?await le(e,t,a):await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,s=B(a);let n=s.sample(j.uv);e.flipbook?.enabled&&(n=J(s,g.uv,e.flipbook.columns,e.flipbook.rows,q.time,e.flipbook.fps,e.flipbook.mode));const r=new p("rotation",0),o=new m("color").rgb,l=C("opacity",1),c=W.subtract(Q).divide(W);let u=l;switch(e.opacityChannel??"red"){case"none":break;case"red":u=u.multiply(n.r);break;case"alpha":u=u.multiply(n.a)}if("number"==typeof e.softness&&e.softness>0){const t=b(c,0,1e3);u=u.multiply(P(0,.2*e.softness,t))}const h=ae(r),d=T(o.multiply(n.rgb).multiplyScalar(e.intensity??1),u);var f=new se({color:d,emissive:d.rgb.multiplyScalar(u),transparent:!0,position:h,alphaTest:1e-4,uniforms:{color:{value:new i.Color(e.color)}}});f.alphaHash=!0,null!=f&&!0===e.bloom&&(f.userData.hasBloom=!0);return f.blending=Z[e.blendingMode]??i.NormalBlending,f}(e,t);s instanceof i.ShaderMaterial&&!0===e.lockY&&(s.defines.LOCK_Y_AXIS="");const n=new i.Mesh(new i.PlaneGeometry(1,1),s);return n.name="sprite",n}(e.output,t,I));break;case"stretchedSprite":D=new a(await async function(e,t){const a=null!=e.texture?await t.getTexture(e.texture):oe,s=B(a).sample(j.uv),n=z(new l("color")),r=n.rgb.multiply(s.rgb);let o=n.w;switch(e.opacityChannel??"red"){case"none":break;case"red":o=o.multiply(s.r);break;case"alpha":o=o.multiply(s.a)}if("number"==typeof e.softness&&e.softness>0){const t=W.subtract(Q).divide(M(W)),a=b(t,0,1e3);o=o.multiply(P(0,.2*e.softness,a))}const c=A(d,{position:g.position,offset:y("offset"),modelViewMatrix:R.modelViewMatrix,velocity:w("velocity"),size:y("size"),rotation:f("rotation")},"\n float lengthFactor = velocity.w;\n float avgSize = (size.x + size.y) * 0.5;\n\n vec4 mvPosition = modelViewMatrix * vec4( offset , 1.0 );\n vec3 viewVelocity = normalMatrix * velocity.xyz;\n float vlength = length(viewVelocity); \n mvPosition.xyz += position.y * normalize(cross(mvPosition.xyz, viewVelocity)) * avgSize; \n mvPosition.xyz -= (position.x + 0.5) * viewVelocity * (1.0 + lengthFactor / vlength) * avgSize;\n return projectionMatrix * mvPosition;\n ");var u=new se({color:T(r.multiplyScalar(e.intensity??1),o),alphaTest:.1,transparent:!0,position:c,uniforms:{color:{value:new i.Color(e.color)}}});null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);u.blending=Z[e.blendingMode]??i.NormalBlending;const p=new X(new i.PlaneGeometry(1,1),u);return p.scaleFactor=e.scale,p}(e.output,t));break;case"shape":D=new a(await async function(e,t,a){if(null==e.shape)return console.log("Shape is null"),new r;const s=O[e.shape];if(null==s)return console.error(`No shape with type ${e.shape}`),new r;const n=F(e.params??{}),l=s.geometry(n);let u=null;u=null!=e.shader?await le(e,t,a):null!=e.material?ce(await t.getMaterial(e.material)):function(){const e=k(new h("instanceColor")).rgb,t=k(new o("particleData")).x;return new c({color:E({color:e}).rgb.rgba(t),opacity:t,transparent:!0})}();null!=u&&!0===e.bloom&&(u.userData.hasBloom=!0);return new i.Mesh(l,u)}(e.output,t,I));break;case"mesh":D=new a(await async function(e,t,a){if(null==e.assetId)return console.warn("Can't use mesh as particle without asset id"),new r;const s=await t.getMesh(e.assetId),n=await t.getAsset(e.assetId);if(null!=e.shader||null!=e.material){let n;n=null!=e.shader?await le(e,t,a):ce(await t.getMaterial(e.material)),null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0),null!=n&&!0===e.bloom&&(n.userData.hasBloom=!0),s.traverse(e=>{e instanceof i.Mesh&&(e.material=n)})}else{const e=[];if(null!=n.materialAssignments)for(const a of n.materialAssignments)s.traverse(s=>{s instanceof i.Mesh&&s.material instanceof i.Material&&s.material.color instanceof i.Color&&(s.material.name!=a.name&&null!=a.name||"#"+s.material.color.getHexString()!==a.color||e.push(t.getMaterial(a.materialId).then(e=>s.material=e)))});await Promise.all(e)}const o=[];if(s.traverse(e=>{e instanceof i.Mesh&&o.push(e)}),1===o.length){const e=o[0];return e.updateWorldMatrix(!0,!0),e.updateMatrixWorld(),e.matrix.copy(e.matrixWorld),e.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.removeFromParent(),e}return s}(e.output,t,I));break;case"trail":D=new a({type:"trail",taper:e.output.taper,headGeometry:null,dragTexture:!1,texture:null!=e.output.texture?await t.getTexture(e.output.texture):null,opacityChannel:e.output.opacityChannel,color:e.output.color,colorEnd:e.output.colorEnd,intensity:e.output.intensity??1,intensityEnd:e.output.intensityEnd??1,length:e.output.length,opacityStart:e.output.opacityStart,opacityEnd:e.output.opacityEnd,bloom:e.output.bloom,scrollSpeed:e.output.scrollSpeed,width:e.output.width,billboard:e.output.billboard??!1});break;default:console.error("Failed to create particly system body: "+JSON.stringify(e))}const V=new pe;V.parent=v,V.setRate(S),V._space=e.output.space;const H=await Promise.all(e.initializers.filter(e=>!1!==e.enabled).filter(e=>null!=$[e.type]).map(async e=>{const t=$[e.type],a=await F(e.params??{});return t.build(a)}));H.push(D,new N),V.addInitializers(H);const U=await Promise.all(e.behaviours.filter(e=>!1!==e.enabled).filter(e=>null!=_[e.type]).map(async e=>{const t=_[e.type];for(const[a,s]of Object.entries(e.params))t.parameters&&null!=t.parameters[a]&&"curve"===t.parameters[a].type&&s.type!==L.Curve&&(s.type=L.Curve);const a=await F(e.params??{},s,u);return t.build(a)}).sort((e,t)=>e instanceof te?1:0));U.push(new ue);for(const e of U)e instanceof te&&(e.physics=x);V.addBehaviours(U);for(const a of e.children){const e=await re(a,t,s,u,v,x,I),n=new EmitterPool(()=>{const t=e.clone();return t.onExpired=()=>{const e=V.childEmitters.findIndex(e=>e.id===t.id);-1!=e&&V.childEmitters.splice(e,1),n.release(t)},t}),i=V.eventDispatcher,r=new Map;V.bindEmitterEvent=!0,i.addEventListener("PARTICLE_DEAD",e=>{const t=r.get(e.id);if(null!=t){const e=V.childEmitters.findIndex(e=>e.id===t.id);null!=e&&(t.stopEmit(),V.childEmitters.splice(e,1))}});let o="PARTICLE_CREATED";if("spawnEvent"in a)switch(a.spawnEvent){case"collision":o="PARTICLE_COLLISION";break;case"start":o="PARTICLE_CREATED"}i.addEventListener(o,e=>{const t=n.get();t.age=0,t.totalEmitTimes=-1,t.particles.length=0,t.currentEmitTime=0,t.cID=0,t.eventDispatcher.removeAllEventListeners(),V.childEmitters.push(t),r.set(e.id,t),t.parentParticle=e,t.system=V.system,t.emit()})}return V}const oe=(new i.TextureLoader).load("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJkSURBVHjaxJeJbusgEEW94S1L//83X18M2MSuLd2pbqc4wZGqRLrKBsyZhQHny7Jk73xVL8xpVhWrcmiB5lX+6GJ5YgQ2owbAm8oIwH1VgKZUmGcRqKGGPgtEQQAzGR8hQ59fAmhJHSAagigJ4E7GPWRXOYC6owAd1JM6wDQPADyMWUqZRMqmAojHp1Vn6EQQEgUNMJLnUjMyJsM49wygBkAPw9dVFwXRkncCIIW3GRgoTQUZn6HxCMAFEFd8TwEQ78X4rHbILoAUmeT+RFG4UhQ6MiIAE4W/UsYFjuVjAIa2nIY4q1R0GFtQWG3E84lqw2GO2QOoCKBVu0BAPgDSU0eUDjjQenNkV/AW/pWChhpMTelo1a64AOKM30vk18GzTHXCNtI/Knz3DFBgsUqBGIjTInXRY1yA9xkVoqW5tVq3pDR9A0hfF5BSARmVnh7RMDCaIdcNgbPBkgzn1Bu+SfIEFSpSBmkxyrMicb0fAEuCZrWnN89veA/4XcakrPcjBWzkTuLjlbfTQPOlBhz+HwkqqPXmPQDdrQItxE1moGof1S74j/8txk8EHhTQrAE8qlwfqS5yukm1x/rAJ9Jiaa6nyATqD78aUVBhFo8b1V4DdTXdCW+IxA1zB4JhiOhZMEWO1HqnvdoHZ4FAMIhV9REF8FiUm0jsYPEJx/Fm/N8OhH90HI9YRHesWbXXZwAShU8qThe7H8YAuJmw5yOd989uRINKRTJAhoF8jbqrHKfeCYdIISZfSq26bk/K+yO3YvfKrVgiwQBHnwt8ynPB25+M8hceTt/ybPhnryJ78+tLgAEAuCFyiQgQB30AAAAASUVORK5CYII=");async function le(e,t,a){const s=a.get(e.shader);if(null==s)return console.error("No shader exists with name "+e.shader),new i.Material;const n=new s.type,r=await V(e.shaderParams,s.type,t,{getTexture:e=>t.getTexture(e.id),getMaterial:e=>t.getMaterial(e.id),getMesh:e=>t.getMesh(e.id)},void 0,void 0,void 0,void 0);return Object.assign(n,r),n.build()}function ce(e){const t=k(new h("instanceColor")).rgb;let a,s=k(new o("particleData")).x;if(e instanceof i.MeshStandardMaterial||e instanceof i.MeshLambertMaterial||e instanceof i.MeshBasicMaterial){let n=t.multiply(I(e.color));null!=e.map&&(n=n.multiply(B(e.map).sample(j.uv).rgb)),null!=e.alphaMap&&(s=s.multiply(B(e.alphaMap).sample(j.uv).r)),e instanceof i.MeshStandardMaterial?a=new c({color:S({color:n,emissive:I(e.emissive),emissiveIntensity:v(e.emissiveIntensity),roughness:e.roughness,metalness:e.metalness}).rgb.rgba(s),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}):e instanceof i.MeshLambertMaterial?a=new c({color:E({color:n}).rgb.rgba(s),emissive:I(e.emissive).multiplyScalar(e.emissiveIntensity),transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}):e instanceof i.MeshBasicMaterial&&(a=new c({color:n.rgb.rgba(s),emissive:n.rgb,transparent:e.transparent,opacity:s,alphaTest:e.alphaTest}))}else e instanceof c&&(a=e.clone(),a.defines.IS_PARTICLE="");return null!=a&&(!0===e.userData?.hasBloom&&null!=a&&(a.userData.hasBloom=!0),a.side=e.side,a.transparent=e.transparent),a??e}class ue extends t{initialize(e){e.body instanceof i.Object3D&&e.body.traverse(e=>{if(e instanceof i.Mesh){const t=e.material;t instanceof c&&(null!=t.uniforms[H]||null!=t.uniforms[U]||t.uniforms[G])}})}mutate(e,t,a){this.energize(e,t),e.target instanceof r&&e.target.traverse(t=>{if(t instanceof i.Mesh){const a=t.material;a instanceof c&&(null!=a.uniforms[H]&&(a.uniforms[H].value=this.energy),null!=a.uniforms[U]&&(a.uniforms[U].value=e.age),null!=a.uniforms[G]&&(a.uniforms[G].value=e.velocity))}})}}class pe extends s{constructor(){super(...arguments),this.childEmitters=[],this.bindEmitterEvent=!1,this.onExpired=()=>{}}update(e){if(!this.isEmitting&&0===this.particles.length)return;this.age+=e,(this.dead||this.age>=this.life)&&this.destroy(),this.generate(e),this.integrate(e);let t=this.particles.length;for(;t--;){const e=this.particles[t];e.dead&&(this.system&&this.system.dispatch("PARTICLE_DEAD",e),this.bindEmitterEvent&&this.dispatch("PARTICLE_DEAD",e),this.system.pool.expire(e.reset()),this.particles.splice(t,1))}this.updateEmitterBehaviours(e),this.updateChildren(e),this.isEmitting||0!==this.particles.length||this.onExpired()}updateChildren(e){for(const t of this.childEmitters)null!=t.parentParticle?t.position.copy(t.parentParticle.position):t.setPosition(this.position),t.update(e)}clone(){const e=new pe;return e.setRate(this.rate.clone()),e.behaviours=this.behaviours,e.initializers=this.initializers,e._space=this._space,e.body=this.body,e.parent=this.parent,e.system=this.system,e}setParentRecursive(e){this.system=e,this.childEmitters.forEach(t=>t.setParentRecursive(e))}}export class EmitterPool{constructor(e){this.creator=e,this.instances=[]}get(){0==this.instances.length&&this.instances.push(this.creator());return this.instances.pop()}release(e){this.instances.push(e)}dispose(){this.instances.length=0}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as
|
|
1
|
+
import{__decorate as t,__metadata as e}from"tslib";import{Actor as o,attach as i,BaseActor as p,Component as r,inject as n,Parameter as s}from"../..";import{Texture as d}from"three";import{tonemapMappings as m}from"../../../rendering/tone-mapping";import{OBB as a}from"three/examples/jsm/math/OBB.js";import{Vector3 as y}from"three";import*as l from"three";import{RenderingView as u}from"../../../rendering.js";import{TriggerVolumeMesh as b}from"./components/volume-editor-component.js";import{ActorComponent as h}from"../../actors/component.js";let g=class extends h{};t([s({options:m,optional:!0}),e("design:type",Number)],g.prototype,"tonemapMapping",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"tonemapExposure",void 0),t([s({optional:!0}),e("design:type",d)],g.prototype,"envTexture",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"envIntensity",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"vignetteIntensity",void 0),t([s({optional:!0}),e("design:type",l.Color)],g.prototype,"colorTint",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"colorTintIntensity",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"depthFocus",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"depthAperture",void 0),t([s({optional:!0}),e("design:type",Number)],g.prototype,"depthMaxBlur",void 0),t([s({optional:!0,range:[1e3,4e4],precision:.1}),e("design:type",Number)],g.prototype,"temperature",void 0),t([s({optional:!0,range:[-1,1]}),e("design:type",Number)],g.prototype,"temperatureTint",void 0),t([s({label:"LUT",optional:!0}),e("design:type",d)],g.prototype,"lut",void 0),t([s({label:"LUT Intensity",range:[0,1],optional:!0}),e("design:type",Number)],g.prototype,"lutIntensity",void 0),g=t([r()],g);export{g as PostProcessSettings};let v=class extends p{constructor(){super(),this.settings=i(g),this.bounded=!1,this.priority=0,this.blendWeight=1,this.blendRadius=0,this.box=new a(void 0,new l.Vector3(.5,.5,.5)),this.view=n(u),this.editorView=i(b),this.disposed.subscribe(()=>{this.view.removePostProcessVolume(this)})}onInit(){this.view.addPostProcessVolume(this),this.editorView.visible=this.bounded}containsPoint(t){return!this.bounded||(this.resetBox(),this.box.containsPoint(t))}distanceToPoint(t){return this.bounded?(this.resetBox(),this.box.clampPoint(t,x),x.distanceTo(t)):0}resetBox(){const t=this.box;t.center.set(0,0,0),t.halfSize.set(.5,.5,.5),t.rotation.copy(c.rotation),t.applyMatrix4(this.object.matrixWorld)}};t([s(),e("design:type",Boolean)],v.prototype,"bounded",void 0),t([s({precision:0}),e("design:type",Number)],v.prototype,"priority",void 0),t([s({range:[0,1]}),e("design:type",Number)],v.prototype,"blendWeight",void 0),t([s(),e("design:type",Number)],v.prototype,"blendRadius",void 0),v=t([o(),e("design:paramtypes",[])],v);export{v as PostProcessVolume};const c=new a,x=new y;/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as
|
|
1
|
+
import e from"typedi";import{loadScene as t}from"../scene/bootstrap.js";import{ActorFactory as s}from"./actors/factory.js";import{World as n}from"./services/world.js";import{SceneMaterializer as r}from"../scene/materializer.js";import{ViewController as o}from"./services/render.js";import{RenderingView as i}from"../rendering.js";import{PhysicsSystem as a}from"./services/physics/physics-system.js";import{MeshComponent as c}from"./actors/builtin/components/mesh-component.js";import{builtInComponents as m}from"./actors/builtin/components/index.js";import{activeContainerInstance as d}from"./actors/internal/container-map.js";import{InputService as l}from"./input/index.js";import{RuntimeAssetsService as p}from"../scene/runtime-asset-service.js";import{AssetResourceLoader as h}from"../scene/asset-resource-loader.js";import{AssetLoader as f}from"./services/asset-loader.js";import{polyfillClient as u}from"./polyfill.js";import{Subject as g}from"rxjs";import{PointerEvents as w}from"./services/pointer-events.js";import{RuntimeBundledBackendService as j}from"../scene/runtime-bundled-backend-service.js";import{Scene as v}from"three";import{ShaderProvider as b}from"./services/shader-provider.js";import{SceneDataService as S}from"../scene/scene-data-service.js";import{AssetsProvider as y}from"../scene/assets-provider.js";export function initiateGame(l,g){if(u(),0!=g.element.childNodes.length)return console.error("Can not initialize the game with a non-empty html element"),null;e.has(o);const I=e.of("default"),x=new HologyRuntime(I),D=new s(I,{inEditor:!1});var R;e.set(s,D),R=g.element,Object.assign(R.style,{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"hidden"});const A=new i(g.element,{enableXR:!0===g.xr?.enabled,maxPixelRatio:g.rendering?.maxPixelRatio,resolutionScale:g.rendering?.resolutionScale,bloom:{enabled:!1!==g?.rendering?.bloom?.enabled},reflection:{enabled:!1!==g?.rendering?.reflection?.enabled},shadows:{cascadeUpdateIntervals:[22,135,250,500]}});A.renderer.shadowMap.enabled=g.rendering?.shadows?.enabled??!0,A.renderer.shadowMap.autoUpdate=g.rendering?.shadows?.autoUpdate??!0,A.renderer.debug.checkShaderErrors=!1,e.set(i,A);const G=new o(A);e.set(o,G);const M=new j,O=new p(M),P=new h;P.setDataDir(g.dataDir),P.initKtx2(A.renderer);const z=Object.entries(g.shaders).map(([e,t])=>({name:e,type:t})),E=Object.entries(g.actors).map(([e,t])=>({name:e,type:t})),H={...m,...g.components??{}},U=Object.entries(H).map(([e,t])=>({name:e,type:t})),W=new b(z);e.set(b,W);const k=new f(P,O,z);e.set(y,this.assetsService),e.set(h,this.assetManagerService),e.set(f,k);const F=new v,N=new r(F,new S,O,P,A,z,E,D,U);e.set(r,N);const T=e.get(n);return e.set(n,T),T.materializer=N,(async()=>{const s=e.get(a);if(await s.start(),x.isShutdown)return;if(await M.preloadData(),x.isShutdown)return;T.scene=F;const{scene:n,actors:r}=await t(A,g.sceneName,g.dataDir,g.shaders,g.actors,H,D,M,O,P,{detailTier:g.detailTier});T.scene=n,s.scene=T.scene;for(const e of F.children)T.scene.add(e);if(x.isShutdown)return void A.stop();e.import([c]);for(const e of r)T.addActor(e);s.addFromScene(n),console.log("Start compile shaders"),console.time("compile shaders"),await A.compileAsync(),console.timeEnd("compile shaders"),console.log("Finished compile shaders. Programs: ",A.renderer.info.programs?.length??0),A.loop(e=>{}),x.status=5,x.shutdownStarted.subscribe(()=>{P.disposeAll()}),d.value=I,I.remove(l),I.set({id:l,type:l});const o=I.get(l);d.value=null,x.gameInstance=o,I.get(w).start(),o instanceof GameInstance&&await o.onStart(),x._resolver(!0)})(),x}export class GameInstance{onStart(){}onShutdown(){}}export function createHologyScene(){}export class HologyRuntime{constructor(e){this.containerInstance=e,this.status=0,this.isShutdown=!1,this.shutdownStarted=new g,this.ready=new Promise(e=>{this._resolver=e})}getWorld(){return this.containerInstance.get(n)}getService(e){return this.containerInstance.get(e)}shutdown(){this.isShutdown=!0;const e=this.shutdownStarted;e.next(),e.complete(),this.gameInstance instanceof GameInstance&&this.gameInstance.onShutdown(),this.containerInstance.get(l).stop();const t=this.containerInstance.get(i);t?.stop();const s=this.containerInstance.get(o);s.setMuted(!0),s.dispose();for(const e of this.getWorld().actors)this.getWorld().removeActor(e);this.containerInstance.get(a).stop(),this.containerInstance.get(r).dispose(),this.containerInstance.get(w).stop(),this.containerInstance.reset()}}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as e,__metadata as t}from"tslib";import{AudioLoader as s,LoadingManager as a,TextureLoader as r}from"three";import{FBXLoader as i,GLTFLoader as o,MTLLoader as n,OBJLoader as h,TGALoader as d}from"three-stdlib";import{KTX2Loader as l}from"three/examples/jsm/Addons.js";import{Service as c}from"typedi";import{AssetResourceLoader as u}from"../../scene/asset-resource-loader.js";import{applyMaterial as g}from"../../scene/materializer";import{materialFromAsset as w}from"../../scene/materializer.js";import{Prefab as f}from"../../scene/objects/prefab.js";import{pathJoin as m}from"../../utils/files.js";let y=class{constructor(e,t,c){this.assetResourceLoader=e,this.assetService=t,this.shaders=c,this.baseUrl="",this.urlSuffix="",this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new i(this.loadingManager),this.objLoader=new h(this.loadingManager),this.mtlLoader=new n(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.ktx2Loader=new l(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new s(this.loadingManager)}resolvePath(e){return m(this.baseUrl,e)+this.urlSuffix}getAudioAtPath(e){const t=this.resolvePath(e);return this.audioLoader.loadAsync(t)}async getAudioByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset id ${e}`);return this.assetResourceLoader.getAudio(t)}async getAudioByAssetName(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset name ${e}`);return this.assetResourceLoader.getAudio(t)}async getModelAtPath(e){const t=this.resolvePath(e);switch(e.split(".").pop().toLowerCase()){case"glb":case"gltf":return(await this.glbLoader.loadAsync(t)).scene;case"fbx":return this.fbxLoader.loadAsync(t);case"obj":return this.objLoader.loadAsync(t);default:throw new Error(`File suffix is not supperted in file ${e}`)}}async getGltfAtPath(e){const t=this.resolvePath(e);return this.glbLoader.loadAsync(t)}async getModelByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No model could be found with asset name ${e}`);const s=await this.assetResourceLoader.getMesh(t);return this.applyMaterials(t,s.scene),s}async getModelByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No model could be found with asset id ${e}`);const s=await this.assetResourceLoader.getMesh(t);return this.applyMaterials(t,s.scene),s}async applyMaterials(e,t){for(const s of e.materialAssignments??[])await g(t,s,async e=>this.getMaterialByAssetId(e))}async getTextureByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No texture could be found with asset name ${e}`);return this.assetResourceLoader.getTexture(t)}async getTextureByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No texture could be found with asset id ${e}`);return this.assetResourceLoader.getTexture(t)}async getMaterialByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No material could be found with asset id ${e}`);return w(t,null,this.assetService,this.assetResourceLoader,this.shaders,!1)}async getAsset(e){return this.assetService.getAsset(e)}async getPrefabByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if("prefab"!==t.type)throw`Asset with name ${e} is not a prefab`;return new f(t)}async getPrefabById(e){const t=await this.getAsset(e);if("prefab"!==t.type)throw`Asset with name ${name} is not a prefab`;return new f(t)}};y=e([c(),t("design:paramtypes",[u,
|
|
1
|
+
import{__decorate as e,__metadata as t}from"tslib";import{AudioLoader as s,LoadingManager as a,TextureLoader as r}from"three";import{FBXLoader as i,GLTFLoader as o,MTLLoader as n,OBJLoader as h,TGALoader as d}from"three-stdlib";import{KTX2Loader as l}from"three/examples/jsm/Addons.js";import{Service as c}from"typedi";import{AssetResourceLoader as u}from"../../scene/asset-resource-loader.js";import{applyMaterial as g}from"../../scene/materializer";import{materialFromAsset as w}from"../../scene/materializer.js";import{Prefab as f}from"../../scene/objects/prefab.js";import{pathJoin as m}from"../../utils/files.js";let y=class{constructor(e,t,c){this.assetResourceLoader=e,this.assetService=t,this.shaders=c,this.baseUrl="",this.urlSuffix="",this.loadingManager=new a,this.glbLoader=new o(this.loadingManager),this.fbxLoader=new i(this.loadingManager),this.objLoader=new h(this.loadingManager),this.mtlLoader=new n(this.loadingManager),this.tgaLoader=new d(this.loadingManager),this.ktx2Loader=new l(this.loadingManager),this.textureLoader=new r(this.loadingManager),this.audioLoader=new s(this.loadingManager)}resolvePath(e){return m(this.baseUrl,e)+this.urlSuffix}getAudioAtPath(e){const t=this.resolvePath(e);return this.audioLoader.loadAsync(t)}async getAudioByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset id ${e}`);return this.assetResourceLoader.getAudio(t)}async getAudioByAssetName(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No audio could be found with asset name ${e}`);return this.assetResourceLoader.getAudio(t)}async getModelAtPath(e){const t=this.resolvePath(e);switch(e.split(".").pop().toLowerCase()){case"glb":case"gltf":return(await this.glbLoader.loadAsync(t)).scene;case"fbx":return this.fbxLoader.loadAsync(t);case"obj":return this.objLoader.loadAsync(t);default:throw new Error(`File suffix is not supperted in file ${e}`)}}async getGltfAtPath(e){const t=this.resolvePath(e);return this.glbLoader.loadAsync(t)}async getModelByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No model could be found with asset name ${e}`);const s=await this.assetResourceLoader.getMesh(t);return this.applyMaterials(t,s.scene),s}async getModelByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No model could be found with asset id ${e}`);const s=await this.assetResourceLoader.getMesh(t);return this.applyMaterials(t,s.scene),s}async applyMaterials(e,t){for(const s of e.materialAssignments??[])await g(t,s,async e=>this.getMaterialByAssetId(e))}async getTextureByAssetName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if(null==t)throw new Error(`No texture could be found with asset name ${e}`);return this.assetResourceLoader.getTexture(t)}async getTextureByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No texture could be found with asset id ${e}`);return this.assetResourceLoader.getTexture(t)}async getMaterialByAssetId(e){const t=await this.assetService.getAsset(e);if(null==t)throw new Error(`No material could be found with asset id ${e}`);return w(t,null,this.assetService,this.assetResourceLoader,this.shaders,!1)}async getAsset(e){return this.assetService.getAsset(e)}async getPrefabByName(e){const t=(await this.assetService.getAssets()).find(t=>t.name===e);if("prefab"!==t.type)throw`Asset with name ${e} is not a prefab`;return new f(t)}async getPrefabById(e){const t=await this.getAsset(e);if("prefab"!==t.type)throw`Asset with name ${name} is not a prefab`;return new f(t)}};y=e([c(),t("design:paramtypes",[u,Function,Array])],y);export{y as AssetLoader};/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -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 E,PlaneCollisionShape as M,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as F}from"../render.js";import{World as I}from"../world.js";import*as k 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,U=new w,q=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(){super(),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.viewController=O(F),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,U,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,U,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,U)&&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().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new y(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/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.matrixWorldNeedsUpdate=!0)}),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 E&&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){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e){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;let e=t.userData.collisionShapes?.[o];if(null==e&&t.parent instanceof C&&(e=t.parent.collisionShapes),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){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=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){ct(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.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,q),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();o.setSleeping(!0);const 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.sleep(),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:k.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 M?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",[])],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(q,t),q}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(I)}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 E,PlaneCollisionShape as M,SphereCollisionShape as P,TrimeshCollisionShape as V}from"../../../index.js";import{LandscapeGroup as _}from"../../../scene/landscape/landscape.js";import{ViewController as F}from"../render.js";import{World as I}from"../world.js";import*as k 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,U=new w,q=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(){super(),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.viewController=O(F),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,U,s)}hasSphereIntersection(t){const e=this.getBallShape(t.radius);return null!=this.world.intersectionWithShape(t.center,U,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,U)&&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().vertices,e=this.debugMesh.geometry,i=e.getAttribute("position");null==i||(i.array.length,t.length);{const i=new y(t,3);i.setUsage(d.DynamicDrawUsage),e.setAttribute("position",i)}e.setDrawRange(0,t.length/3)}async setup(){if(null!=this.rapier)throw new Error("Rapier is already estup");this.rapier=await rt(),this.eventQueue=new this.rapier.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.matrixWorldNeedsUpdate=!0)}),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 E&&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){const e=!1!==t.userData?.src?.collisionDetection;if(t.children[0]&&(t.children[0].instanceMatrix&&e||t.children[0].isBatchedMesh))this.createForInstancedMesh(t.children[0],t.collisionShapes);else if(e){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;let e=t.userData.collisionShapes?.[o];if(null==e&&t.parent instanceof C&&(e=t.parent.collisionShapes),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 this.rapier.World({x:0,y:-9.81,z:0});this.world=t}sphereCast(t,e,i,s,o=ShapeCastResult.shared,n){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=n?.excludeActor?this.actorBodies.get(n.excludeActor.id):null,d=this.world.castShape(a,{x:0,y:0,z:0,w:1},l,r,.01,s,!0,null,n?.collisionFilter??void 0,null,c,n?.excludeTriggers?t=>!t.isSensor():void 0);if(null!=d){ct(o.hitPoint,d.witness1),o.normal.set(d.normal1.x,d.normal1.y,d.normal1.z),o.distance=d.time_of_impact,o.hasHit=!0;const t=d.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,q),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();o.setSleeping(!0);const 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.sleep(),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:k.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 M?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",[])],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(q,t),q}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(I)}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
|
*/
|
|
@@ -3,7 +3,7 @@ import { BaseActor } from '../actors/actor.js';
|
|
|
3
3
|
import { Euler, Scene, Vector3 } from 'three';
|
|
4
4
|
import { Observable } from 'rxjs';
|
|
5
5
|
import { RenderingView } from "../../rendering.js";
|
|
6
|
-
import { Prefab } from "../../scene/objects/prefab.js";
|
|
6
|
+
import { Prefab, PrefabOf } from "../../scene/objects/prefab.js";
|
|
7
7
|
import { PrefabInstance } from '../../scene/objects/prefab';
|
|
8
8
|
declare class DirectionalLightController {
|
|
9
9
|
private view;
|
|
@@ -31,7 +31,7 @@ export declare class World {
|
|
|
31
31
|
readonly actorRemoved: Observable<BaseActor>;
|
|
32
32
|
scene: Scene;
|
|
33
33
|
readonly directionalLight: DirectionalLightController;
|
|
34
|
-
spawnActor<T extends BaseActor>(type: Constructable<T>, position?: Vector3, rotation?: Euler): Promise<T>;
|
|
34
|
+
spawnActor<T extends BaseActor>(type: Constructable<T> | PrefabOf<T>, position?: Vector3, rotation?: Euler): Promise<T>;
|
|
35
35
|
addActor(actor: BaseActor, position?: Vector3, rotation?: Euler): void;
|
|
36
36
|
removeActor(actor: BaseActor): void;
|
|
37
37
|
findActorByType<T extends BaseActor>(type: Constructable<T>, name?: string): T;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate as t}from"tslib";import{Service as
|
|
1
|
+
import{__decorate as t}from"tslib";import{Service as r}from"typedi";import{BaseActor as e}from"../actors/actor.js";import{ActorFactory as o}from"../actors/factory.js";import{Vector3 as i}from"three";import{ActorComponent as s}from"../../gameplay/actors/component.js";import{Subject as n}from"rxjs";import{RenderingView as c}from"../../rendering.js";import{randomUUID as a}from"../../utils/uuid";import{PrefabInstance as h}from"../../scene/objects/prefab";import{PhysicsSystem as m}from"./physics/physics-system.js";import{inject as p}from"../../gameplay/inject.js";const l=new i;class f{constructor(t){this.view=t}get direction(){return this.view.csm.lightDirection}set intensity(t){this.view.csm.lightIntensity=t,this.view.csm.lights.forEach(t=>t.intensity=this.view.csm.lightIntensity)}get intensity(){return this.view.csm.lightIntensity}get position(){return 0==this.view.csm.lights.length?l:this.view.csm.lights[0].position}}let d=class{constructor(){this.actorFactory=p(o),this.view=p(c),this.physics=p(m),this.actors=[],this.actorAdded=new n,this.actorRemoved=new n,this.directionalLight=new f(this.view)}async spawnActor(t,r,e){if(null==t)throw new Error("Cannot spawn actor with null type");if("prefab"in t){const o=await this.spawnPrefab(t.prefab,r,e),i=o.mainActor;if(null==i)throw new Error(`Prefab has no main actor or there was an error when spwaning it. Prefab: ${JSON.stringify(t.prefab)}`);return i.disposed.subscribe(()=>this.removePrefab(o)),i}const o=await this.actorFactory.create(t,r,e);return this.addActor(o,r,e),o}addActor(t,r,e){r&&t.object.position.copy(r),e&&t.object.rotation.copy(e),null==t.object.parent&&this.scene.add(t.object),this.actors.push(t),y(t,t=>t.onBeginPlay()),this.actorAdded.next(t)}removeActor(t){y(t,t=>t.onEndPlay());const r=this.actors.indexOf(t);r>=0&&this.actors.splice(r,1),t.object.removeFromParent(),t.disposed.next(!0),this.actorRemoved.next(t),this.physics.removeActor(t)}findActorByType(t,r){return this.actors.find(e=>e instanceof t&&(null==r||e.object.name==r))}findActorsByType(t,r){return this.actors.filter(e=>e instanceof t&&(null==r||e.object.name==r))}async spawnPrefab(t,r,e){if(null==this.materializer)return console.error("Internal error: Materializer is missing on World"),null;const o=new h,{object:i,actors:s,mainActor:n}=await this.materializer.createFromPrefabAsset(t.asset,{sceneObjectChain:["r-"+a()]},void 0,void 0,!1);return o.object=i,o.actors=s,o.mainActor=n,this.scene.add(i),null!=r&&i.position.copy(r),null!=e&&i.rotation.copy(e),s.forEach(t=>{this.addActor(t)}),this.physics.addFromScene(i),o}removePrefab(t){t.actors.forEach(t=>this.removeActor(t)),t.object?.removeFromParent(),this.physics.removeRemoved(t.object)}};d=t([r()],d);export{d as World};function y(t,r){return r(t),t instanceof e&&t.attachedComponents.forEach(t=>{y(t,r)}),Object.entries(t).filter(([t,r])=>r instanceof s).forEach(([t,e])=>{y(e,r)})}/*
|
|
2
2
|
* Copyright (©) 2025 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -34,6 +34,8 @@ export declare class AssetResourceLoader {
|
|
|
34
34
|
setDataDir(path: string): void;
|
|
35
35
|
private getUri;
|
|
36
36
|
private _texturePromises;
|
|
37
|
+
private _animationPromises;
|
|
38
|
+
private _animationCache;
|
|
37
39
|
/**
|
|
38
40
|
* Loads a texture for the given asset, handling concurrent calls by caching the promise
|
|
39
41
|
* based on asset.id. If a request for the same id is already in progress,
|
|
@@ -47,6 +49,11 @@ export declare class AssetResourceLoader {
|
|
|
47
49
|
getMesh(asset: Asset, options?: GetMeshOptions): Promise<LoadedMesh>;
|
|
48
50
|
private asyncAudioResults;
|
|
49
51
|
getAudio(asset: Asset): Promise<AudioBuffer>;
|
|
52
|
+
/**
|
|
53
|
+
* Loads an animation clip for the given asset. The asset should refer to
|
|
54
|
+
* a model file (glb/gltf/fbx) that contains animation clips.
|
|
55
|
+
*/
|
|
56
|
+
getAnimationClip(asset: Asset): Promise<THREE.AnimationClip | null>;
|
|
50
57
|
private collisionShapeCache;
|
|
51
58
|
private computeCollisionShapes;
|
|
52
59
|
private loadMesh;
|
|
@@ -65,6 +72,10 @@ export declare class AssetResourceLoader {
|
|
|
65
72
|
* into separate meshes per material.
|
|
66
73
|
*/
|
|
67
74
|
private extractGeometryGroups;
|
|
75
|
+
/**
|
|
76
|
+
* Load a mesh by asset using fileKey and fileFormat
|
|
77
|
+
* Used both for meshes and animations
|
|
78
|
+
*/
|
|
68
79
|
private loadByAsset;
|
|
69
80
|
/**
|
|
70
81
|
* Dispose all resource loaded.
|