@needle-tools/engine 3.3.0-alpha → 3.5.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/needle-engine.js +62620 -61118
  3. package/dist/needle-engine.min.js +434 -410
  4. package/dist/needle-engine.umd.cjs +435 -411
  5. package/lib/engine/api.d.ts +1 -0
  6. package/lib/engine/api.js +1 -0
  7. package/lib/engine/api.js.map +1 -1
  8. package/lib/engine/codegen/register_types.js +50 -2
  9. package/lib/engine/codegen/register_types.js.map +1 -1
  10. package/lib/engine/engine_context.d.ts +1 -1
  11. package/lib/engine/engine_context.js +21 -15
  12. package/lib/engine/engine_context.js.map +1 -1
  13. package/lib/engine/engine_context_registry.d.ts +5 -3
  14. package/lib/engine/engine_context_registry.js +10 -2
  15. package/lib/engine/engine_context_registry.js.map +1 -1
  16. package/lib/engine/engine_element.js.map +1 -1
  17. package/lib/engine/engine_element_loading.js +2 -3
  18. package/lib/engine/engine_element_loading.js.map +1 -1
  19. package/lib/engine/engine_gameobject.d.ts +1 -1
  20. package/lib/engine/engine_gameobject.js +4 -2
  21. package/lib/engine/engine_gameobject.js.map +1 -1
  22. package/lib/engine/engine_input.d.ts +2 -2
  23. package/lib/engine/engine_physics.d.ts +20 -93
  24. package/lib/engine/engine_physics.js +20 -892
  25. package/lib/engine/engine_physics.js.map +1 -1
  26. package/lib/engine/engine_physics.types.js.map +1 -1
  27. package/lib/engine/engine_physics_rapier.d.ts +103 -0
  28. package/lib/engine/engine_physics_rapier.js +1003 -0
  29. package/lib/engine/engine_physics_rapier.js.map +1 -0
  30. package/lib/engine/engine_three_utils.js +2 -2
  31. package/lib/engine/engine_three_utils.js.map +1 -1
  32. package/lib/engine/engine_types.d.ts +50 -1
  33. package/lib/engine/engine_types.js +8 -0
  34. package/lib/engine/engine_types.js.map +1 -1
  35. package/lib/engine-components/Animation.js +4 -0
  36. package/lib/engine-components/Animation.js.map +1 -1
  37. package/lib/engine-components/Collider.js +6 -6
  38. package/lib/engine-components/Collider.js.map +1 -1
  39. package/lib/engine-components/Joints.js +2 -2
  40. package/lib/engine-components/Joints.js.map +1 -1
  41. package/lib/engine-components/RigidBody.d.ts +0 -1
  42. package/lib/engine-components/RigidBody.js +24 -30
  43. package/lib/engine-components/RigidBody.js.map +1 -1
  44. package/lib/engine-components/codegen/components.d.ts +25 -1
  45. package/lib/engine-components/codegen/components.js +25 -1
  46. package/lib/engine-components/codegen/components.js.map +1 -1
  47. package/lib/engine-components/export/usdz/Extension.d.ts +4 -4
  48. package/lib/engine-components/export/usdz/ThreeUSDZExporter.d.ts +86 -0
  49. package/lib/engine-components/export/usdz/ThreeUSDZExporter.js +858 -0
  50. package/lib/engine-components/export/usdz/ThreeUSDZExporter.js.map +1 -0
  51. package/lib/engine-components/export/usdz/USDZExporter.d.ts +6 -3
  52. package/lib/engine-components/export/usdz/USDZExporter.js +34 -11
  53. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  54. package/lib/engine-components/export/usdz/extensions/Animation.d.ts +15 -15
  55. package/lib/engine-components/export/usdz/extensions/Animation.js +24 -29
  56. package/lib/engine-components/export/usdz/extensions/Animation.js.map +1 -1
  57. package/lib/engine-components/export/usdz/extensions/DocumentExtension.d.ts +5 -0
  58. package/lib/engine-components/export/usdz/extensions/DocumentExtension.js +7 -0
  59. package/lib/engine-components/export/usdz/extensions/DocumentExtension.js.map +1 -0
  60. package/lib/engine-components/export/usdz/extensions/USDZText.d.ts +47 -0
  61. package/lib/engine-components/export/usdz/extensions/USDZText.js +114 -0
  62. package/lib/engine-components/export/usdz/extensions/USDZText.js.map +1 -0
  63. package/lib/engine-components/export/usdz/extensions/behavior/Actions.d.ts +30 -0
  64. package/lib/engine-components/export/usdz/extensions/behavior/Actions.js +89 -0
  65. package/lib/engine-components/export/usdz/extensions/behavior/Actions.js.map +1 -0
  66. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.d.ts +23 -0
  67. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.js +114 -0
  68. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.js.map +1 -0
  69. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.d.ts +102 -0
  70. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js +458 -0
  71. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js.map +1 -0
  72. package/lib/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.d.ts +111 -0
  73. package/lib/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.js +409 -0
  74. package/lib/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.js.map +1 -0
  75. package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
  76. package/lib/engine-components/ui/BaseUIComponent.d.ts +2 -0
  77. package/lib/engine-components/ui/BaseUIComponent.js +6 -0
  78. package/lib/engine-components/ui/BaseUIComponent.js.map +1 -1
  79. package/lib/engine-components/ui/Canvas.d.ts +11 -1
  80. package/lib/engine-components/ui/Canvas.js +72 -3
  81. package/lib/engine-components/ui/Canvas.js.map +1 -1
  82. package/lib/engine-components/ui/Graphic.js.map +1 -1
  83. package/lib/engine-components/ui/Image.js +4 -4
  84. package/lib/engine-components/ui/Image.js.map +1 -1
  85. package/lib/engine-components/ui/Interfaces.d.ts +11 -0
  86. package/lib/engine-components/ui/Interfaces.js +11 -0
  87. package/lib/engine-components/ui/Interfaces.js.map +1 -1
  88. package/lib/engine-components/ui/Layout.d.ts +65 -3
  89. package/lib/engine-components/ui/Layout.js +304 -3
  90. package/lib/engine-components/ui/Layout.js.map +1 -1
  91. package/lib/engine-components/ui/RectTransform.d.ts +8 -7
  92. package/lib/engine-components/ui/RectTransform.js +66 -36
  93. package/lib/engine-components/ui/RectTransform.js.map +1 -1
  94. package/lib/engine-components/utils/LookAt.d.ts +7 -1
  95. package/lib/engine-components/utils/LookAt.js +43 -6
  96. package/lib/engine-components/utils/LookAt.js.map +1 -1
  97. package/lib/engine-components/webxr/WebXRImageTracking.d.ts +4 -3
  98. package/lib/engine-components/webxr/WebXRImageTracking.js +81 -25
  99. package/lib/engine-components/webxr/WebXRImageTracking.js.map +1 -1
  100. package/lib/tsconfig.tsbuildinfo +1 -1
  101. package/package.json +1 -1
  102. package/plugins/vite/config.js +2 -1
  103. package/plugins/vite/defines.js +30 -0
  104. package/plugins/vite/dependency-watcher.js +173 -0
  105. package/plugins/vite/editor-connection.js +37 -39
  106. package/plugins/vite/index.js +5 -1
  107. package/plugins/vite/reload.js +16 -3
  108. package/src/engine/api.ts +1 -0
  109. package/src/engine/codegen/register_types.js +50 -2
  110. package/src/engine/engine_context.ts +32 -23
  111. package/src/engine/engine_context_registry.ts +13 -6
  112. package/src/engine/engine_element.ts +2 -1
  113. package/src/engine/engine_element_loading.ts +2 -3
  114. package/src/engine/engine_gameobject.ts +3 -2
  115. package/src/engine/engine_input.ts +2 -2
  116. package/src/engine/engine_physics.ts +25 -1020
  117. package/src/engine/engine_physics.types.ts +1 -3
  118. package/src/engine/engine_physics_rapier.ts +1127 -0
  119. package/src/engine/engine_three_utils.ts +2 -2
  120. package/src/engine/engine_types.ts +66 -4
  121. package/src/engine-components/Animation.ts +4 -0
  122. package/src/engine-components/Collider.ts +6 -6
  123. package/src/engine-components/Joints.ts +2 -2
  124. package/src/engine-components/RigidBody.ts +24 -31
  125. package/src/engine-components/codegen/components.ts +25 -1
  126. package/src/engine-components/export/usdz/Extension.ts +4 -5
  127. package/src/engine-components/export/usdz/ThreeUSDZExporter.ts +1312 -0
  128. package/src/engine-components/export/usdz/USDZExporter.ts +39 -17
  129. package/src/engine-components/export/usdz/extensions/Animation.ts +37 -45
  130. package/src/engine-components/export/usdz/extensions/DocumentExtension.ts +10 -0
  131. package/src/engine-components/export/usdz/extensions/USDZText.ts +142 -0
  132. package/src/engine-components/export/usdz/extensions/behavior/Actions.ts +99 -0
  133. package/src/engine-components/export/usdz/extensions/behavior/Behaviour.ts +181 -0
  134. package/src/engine-components/export/usdz/extensions/behavior/BehaviourComponents.ts +545 -0
  135. package/src/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.ts +459 -0
  136. package/src/engine-components/postprocessing/PostProcessingHandler.ts +1 -1
  137. package/src/engine-components/ui/BaseUIComponent.ts +7 -1
  138. package/src/engine-components/ui/Canvas.ts +80 -5
  139. package/src/engine-components/ui/Graphic.ts +2 -0
  140. package/src/engine-components/ui/Image.ts +3 -3
  141. package/src/engine-components/ui/Interfaces.ts +30 -6
  142. package/src/engine-components/ui/Layout.ts +303 -4
  143. package/src/engine-components/ui/RectTransform.ts +67 -41
  144. package/src/engine-components/utils/LookAt.ts +60 -7
  145. package/src/engine-components/webxr/WebXRImageTracking.ts +100 -27
  146. package/lib/engine-components/export/usdz/types.d.ts +0 -34
  147. package/lib/engine-components/export/usdz/types.js +0 -2
  148. package/lib/engine-components/export/usdz/types.js.map +0 -1
  149. package/src/engine-components/export/usdz/types.ts +0 -39
@@ -1,47 +1,11 @@
1
- import { BasicDepthPacking, Box3, BufferAttribute, BufferGeometry, Camera, Intersection, Layers, LineBasicMaterial, LineSegments, Matrix4, Mesh, NormalAnimationBlendMode, NumberKeyframeTrack, Object3D, Quaternion, Ray, Raycaster, Sphere, Vector2, Vector3 } from 'three'
1
+ import { Box3, Camera, Intersection, Layers, Mesh, Object3D, Ray, Raycaster, Sphere, Vector2, Vector3 } from 'three'
2
2
  import { Context } from './engine_setup';
3
- import { CircularBuffer, getParam } from "./engine_utils"
4
- import { getWorldPosition, getWorldQuaternion, getWorldScale, setWorldPositionXYZ, setWorldQuaternion, setWorldQuaternionXYZW } from "./engine_three_utils"
5
- import {
6
- IComponent,
7
- ICollider,
8
- IRigidbody,
9
- Collision,
10
- ContactPoint,
11
- Vec3,
12
- IGameObject,
13
- Vec2,
14
- } from './engine_types';
15
- import { InstancingUtil } from './engine_instancing';
16
- import { foreachComponent } from './engine_gameobject';
17
-
18
- import RAPIER, { ActiveCollisionTypes, ActiveEvents, CoefficientCombineRule, Collider, ColliderDesc, EventQueue, JointData, QueryFilterFlags, RigidBody, RigidBodyType, ShapeColliderTOI, World } from '@dimforge/rapier3d-compat';
19
- import { CollisionDetectionMode, PhysicsMaterialCombine } from '../engine/engine_physics.types';
20
- import { Gizmos } from './engine_gizmos';
21
- import { Mathf } from './engine_math';
22
- import { Layer } from './extensions/NEEDLE_animator_controller_model';
23
- export type Rapier = typeof RAPIER;
24
-
3
+ import { getParam } from "./engine_utils"
4
+ import { getWorldPosition } from "./engine_three_utils"
5
+ import { Vec2, Vec3, } from './engine_types';
6
+ import { IPhysicsEngine } from './engine_types';
25
7
 
26
8
  const debugPhysics = getParam("debugphysics");
27
- const debugColliderPlacement = getParam("debugphysicscolliders");
28
- const debugCollisions = getParam("debugcollisions");
29
- const showColliders = getParam("showcolliders");
30
- const noPhysics = getParam("nophysics");
31
-
32
-
33
- declare type PhysicsBody = {
34
- translation(): { x: number, y: number, z: number }
35
- rotation(): { x: number, y: number, z: number, w: number }
36
- }
37
-
38
- /** on physics body and references the needle component */
39
- const $componentKey = Symbol("needle component");
40
- /** on needle component and references physics body */
41
- const $bodyKey = Symbol("physics body");
42
- const $colliderRigidbody = Symbol("rigidbody");
43
- // const $removed = Symbol("removed");
44
-
45
9
  const layerMaskHelper: Layers = new Layers();
46
10
 
47
11
  export class RaycastOptions {
@@ -94,26 +58,32 @@ export class SphereIntersection implements Intersection {
94
58
  }
95
59
  }
96
60
 
97
- export class SphereOverlapResult {
98
- object: Object3D;
99
- collider: ICollider;
100
- constructor(object: Object3D, collider: ICollider) {
101
- this.object = object;
102
- this.collider = collider;
61
+ export class Physics {
62
+
63
+ /**@deprecated use this.context.physics.engine.raycast */
64
+ public raycastPhysicsFast(origin: Vec2 | Vec3, direction: Vec3 | undefined = undefined, maxDistance: number = Infinity, solid: boolean = true) {
65
+ return this.context.physics.engine?.raycast(origin, direction, maxDistance, solid) ?? null;
103
66
  }
104
- }
105
67
 
106
- declare type PhysicsRaycastResult = {
107
- point: Vector3,
108
- normal?: Vector3,
109
- collider?: ICollider
110
- }
68
+ /**@deprecated use this.context.physics.engine.raycastAndGetNormal */
69
+ public raycastPhysicsFastAndGetNormal(origin: Vec2 | Vec3, direction: Vec3 | undefined = undefined, maxDistance: number = Infinity, solid: boolean = true) {
70
+ return this.context.physics.engine?.raycastAndGetNormal(origin, direction, maxDistance, solid) ?? null;
71
+ }
111
72
 
73
+ /**@deprecated use this.context.physics.engine.sphereOverlap */
74
+ public sphereOverlapPhysics(point: Vector3, radius: number) {
75
+ return this.context.physics.engine?.sphereOverlap(point, radius) ?? null;
76
+ }
112
77
 
113
- export class Physics {
114
78
 
115
- // raycasting
79
+ private readonly context: Context;
80
+ engine?: IPhysicsEngine;
116
81
 
82
+ constructor(context: Context) {
83
+ this.context = context;
84
+ }
85
+
86
+ // raycasting
117
87
  private readonly raycaster: Raycaster = new Raycaster();
118
88
  private readonly defaultRaycastOptions: RaycastOptions = new RaycastOptions();
119
89
  private readonly targetBuffer: Array<Object3D> = new Array<Object3D>(1);
@@ -248,969 +218,4 @@ export class Physics {
248
218
  }
249
219
  return results;
250
220
  }
251
-
252
- private rapierRay = new RAPIER.Ray({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 });
253
- private raycastVectorsBuffer = new CircularBuffer(() => new Vector3(), 10);
254
- /** Fast raycast against physics colliders
255
- * @param origin ray origin in screen or worldspace
256
- * @param direction ray direction in worldspace
257
- * @param maxDistance max distance to raycast
258
- * @param solid if true it will also hit the collider if origin is already inside it
259
- */
260
- public raycastPhysicsFast(origin: Vec2 | Vec3, direction: Vec3 | undefined = undefined, maxDistance: number = Infinity, solid: boolean = true)
261
- : null | { point: Vector3, collider: ICollider } {
262
-
263
- const ray = this.getPhysicsRay(this.rapierRay, origin, direction);
264
- if (!ray) return null;
265
-
266
- const hit = this.world?.castRay(ray, maxDistance, solid, undefined, undefined, undefined, undefined, (c) => {
267
- // ignore objects in the IgnoreRaycast=2 layer
268
- return !c[$componentKey]?.gameObject.layers.isEnabled(2);
269
- });
270
- if (hit) {
271
- const point = ray.pointAt(hit.toi);
272
- const vec = this.raycastVectorsBuffer.get();
273
- vec.set(point.x, point.y, point.z);
274
- return { point: vec, collider: hit.collider[$componentKey] };
275
- }
276
-
277
- return null;
278
- }
279
-
280
- public raycastPhysicsFastAndGetNormal(origin: Vec2 | Vec3, direction: Vec3 | undefined = undefined, maxDistance: number = Infinity, solid: boolean = true)
281
- : null | { point: Vector3, normal: Vector3, collider: ICollider } {
282
-
283
- const ray = this.getPhysicsRay(this.rapierRay, origin, direction);
284
- if (!ray) return null;
285
-
286
- const hit = this.world?.castRayAndGetNormal(ray, maxDistance, solid, undefined, undefined, undefined, undefined, (c) => {
287
- // ignore objects in the IgnoreRaycast=2 layer
288
- return !c[$componentKey]?.gameObject.layers.isEnabled(2);
289
- });
290
- if (hit) {
291
- const point = ray.pointAt(hit.toi);
292
- const normal = hit.normal;
293
- const vec = this.raycastVectorsBuffer.get();
294
- const nor = this.raycastVectorsBuffer.get();
295
- vec.set(point.x, point.y, point.z);
296
- nor.set(normal.x, normal.y, normal.z);
297
- return { point: vec, normal: nor, collider: hit.collider[$componentKey] };
298
- }
299
- return null;
300
- }
301
-
302
- private getPhysicsRay(ray: RAPIER.Ray, origin: Vec2 | Vec3, direction: Vec3 | undefined = undefined): RAPIER.Ray | null {
303
- const cam = this.context.mainCamera;
304
- // if we get origin in 2d space we need to project it to 3d space
305
- if (origin["z"] === undefined) {
306
- if (!cam) {
307
- console.error("Can not perform raycast from 2d point - no main camera found");
308
- return null;
309
- }
310
- const vec3 = this.raycastVectorsBuffer.get();
311
- vec3.x = origin.x;
312
- vec3.y = origin.y;
313
- vec3.z = 0;
314
- // if the origin is in screen space we need to convert it to raycaster space
315
- if (vec3.x > 1 || vec3.y > 1 || vec3.y < -1 || vec3.x < -1) {
316
- this.context.input.convertScreenspaceToRaycastSpace(vec3);
317
- }
318
- vec3.unproject(cam);
319
- origin = vec3;
320
- }
321
-
322
- const o = origin as Vec3;
323
-
324
- ray.origin.x = o.x;
325
- ray.origin.y = o.y;
326
- ray.origin.z = o.z;
327
- const vec = this.raycastVectorsBuffer.get();
328
- if (direction)
329
- vec.set(direction.x, direction.y, direction.z);
330
- else {
331
- if (!cam) {
332
- console.error("Can not perform raycast - no camera found");
333
- return null;
334
- }
335
- vec.set(ray.origin.x, ray.origin.y, ray.origin.z);
336
- const camPosition = getWorldPosition(cam);
337
- vec.sub(camPosition);
338
- }
339
- // we need to normalize the ray because our input is a max travel length and the direction may be not normalized
340
- vec.normalize();
341
- ray.dir.x = vec.x;
342
- ray.dir.y = vec.y;
343
- ray.dir.z = vec.z;
344
- // Gizmos.DrawRay(ray.origin, ray.dir, 0xff0000, Infinity);
345
- return ray;
346
- }
347
-
348
-
349
- private rapierSphere: RAPIER.Ball | null = null;
350
- private rapierColliderArray: Array<SphereOverlapResult> = [];
351
- private readonly rapierIdentityRotation = { x: 0, y: 0, z: 0, w: 1 };
352
- private readonly rapierForwardVector = { x: 0, y: 0, z: 1 };
353
- /** Precice sphere overlap detection using rapier against colliders
354
- * @param point center of the sphere in worldspace
355
- * @param radius radius of the sphere
356
- * @returns array of colliders that overlap with the sphere. Note: they currently only contain the collider and the gameobject
357
- */
358
- public sphereOverlapPhysics(point: Vector3, radius: number): Array<SphereOverlapResult> {
359
- this.rapierColliderArray.length = 0;
360
- if (!this.world) return this.rapierColliderArray;
361
- if (!this.rapierSphere)
362
- this.rapierSphere = new RAPIER.Ball(radius);
363
- this.rapierSphere.radius = radius;
364
-
365
- this.world.intersectionsWithShape(point, this.rapierIdentityRotation, this.rapierSphere, col => {
366
- const collider = col[$componentKey] as ICollider
367
- // if (collider.gameObject.layers.isEnabled(2)) return true;
368
- const intersection = new SphereOverlapResult(collider.gameObject, collider);
369
- this.rapierColliderArray.push(intersection);
370
- return true; // Return `false` instead if we want to stop searching for other colliders that contain this point.
371
- }, QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, undefined,
372
- col => {
373
- const collider = col[$componentKey] as ICollider
374
- return collider.gameObject.layers.isEnabled(2) == false
375
- }
376
- );
377
- return this.rapierColliderArray;
378
-
379
-
380
- // TODO: this only returns one hit
381
- // let filterGroups = 0xffffffff;
382
- // filterGroups &= ~(1 << 2);
383
- // const hit: ShapeColliderTOI | null = this.world.castShape(point,
384
- // this.rapierIdentityRotation,
385
- // this.rapierForwardVector,
386
- // this.rapierSphere,
387
- // 0,
388
- // QueryFilterFlags.EXCLUDE_SENSORS,
389
- // // filterGroups,
390
- // );
391
- // // console.log(hit);
392
- // if (hit) {
393
- // const collider = hit.collider[$componentKey] as ICollider
394
- // const intersection = new SphereOverlapResult(collider.gameObject);
395
- // this.rapierColliderArray.push(intersection);
396
- // // const localpt = hit.witness2;
397
- // // // const normal = hit.normal2;
398
- // // const hitPoint = new Vector3(localpt.x, localpt.y, localpt.z);
399
- // // // collider.gameObject.localToWorld(hitPoint);
400
- // // // const normalPt = new Vector3(normal.x, normal.y, normal.z);
401
- // // // const mat = new Matrix4().setPosition(point).scale(new Vector3(radius, radius, radius));
402
- // // // hitPoint.applyMatrix4(mat);
403
- // // console.log(hit.witness2)
404
- // // // hitPoint.add(point);
405
- // // const dist = hitPoint.distanceTo(point);
406
- // }
407
-
408
- // return this.rapierColliderArray;
409
- }
410
-
411
-
412
-
413
-
414
- // physics simulation
415
-
416
- enabled: boolean = true;
417
-
418
- private _tempPosition: Vector3 = new Vector3();
419
- private _tempQuaternion: Quaternion = new Quaternion();
420
- private _tempScale: Vector3 = new Vector3();
421
- private _tempMatrix: Matrix4 = new Matrix4();
422
-
423
- private static _didLoadPhysicsEngine: boolean = false;
424
-
425
- private _isUpdatingPhysicsWorld: boolean = false;
426
- get isUpdating(): boolean { return this._isUpdatingPhysicsWorld; }
427
-
428
-
429
- private context: Context;
430
- private world?: World;
431
- private _hasCreatedWorld: boolean = false;
432
- private eventQueue?: EventQueue;
433
- private collisionHandler?: PhysicsCollisionHandler;
434
-
435
-
436
- private objects: IComponent[] = [];
437
- private bodies: PhysicsBody[] = [];
438
-
439
- private _meshCache: Map<string, Float32Array> = new Map<string, Float32Array>();
440
-
441
-
442
- constructor(context: Context) {
443
- this.context = context;
444
- }
445
-
446
- async createWorld() {
447
- if (this._hasCreatedWorld) {
448
- console.error("Invalid call to create physics world: world is already created");
449
- return;
450
- }
451
- this._hasCreatedWorld = true;
452
- if (!Physics._didLoadPhysicsEngine) {
453
- await RAPIER.init().then(() => RAPIER)
454
- Physics._didLoadPhysicsEngine = true;
455
- }
456
- this.world = new World(this._gravity);
457
- if (noPhysics) this.enabled = false;
458
- }
459
-
460
- private _gravity = { x: 0.0, y: -9.81, z: 0.0 };
461
-
462
- get gravity() {
463
- return this.world?.gravity ?? this._gravity;
464
- }
465
-
466
- set gravity(value: Vec3) {
467
- if (this.world) {
468
- this.world.gravity = value;
469
- }
470
- else {
471
- this._gravity = value;
472
- }
473
- }
474
-
475
- clearCaches() {
476
- this._meshCache.clear();
477
- }
478
-
479
- addBoxCollider(collider: ICollider, center: Vector3, size: Vector3) {
480
- if (!this.enabled) {
481
- if (debugPhysics) console.warn("Physics are disabled");
482
- return;
483
- }
484
- const obj = collider.gameObject;
485
- const scale = getWorldScale(obj, this._tempPosition).multiply(size);
486
- scale.multiplyScalar(0.5);
487
-
488
- // prevent negative scale
489
- if (scale.x < 0)
490
- scale.x = Math.abs(scale.x);
491
- if (scale.y < 0)
492
- scale.y = Math.abs(scale.y);
493
- if (scale.z < 0)
494
- scale.z = Math.abs(scale.z);
495
-
496
- // prevent zero scale - seems normals are flipped otherwise
497
- if (scale.x == 0) scale.x = 0.0000001;
498
- if (scale.y == 0) scale.y = 0.0000001;
499
- if (scale.z == 0) scale.z = 0.0000001;
500
-
501
- const desc = ColliderDesc.cuboid(scale.x, scale.y, scale.z);
502
- // const objectLayerMask = collider.gameObject.layers.mask;
503
- // const mask = objectLayerMask & ~2;
504
- // TODO: https://rapier.rs/docs/user_guides/javascript/colliders/#collision-groups-and-solver-groups
505
- // desc.setCollisionGroups(objectLayerMask);
506
- this.createCollider(collider, desc, center);
507
- }
508
-
509
- addSphereCollider(collider: ICollider, center: Vector3, radius: number) {
510
- if (!this.enabled) {
511
- if (debugPhysics) console.warn("Physics are disabled");
512
- return;
513
- }
514
- const obj = collider.gameObject;
515
- const scale = getWorldScale(obj, this._tempPosition).multiplyScalar(radius);
516
- // Prevent negative scales
517
- scale.x = Math.abs(scale.x);
518
- const desc = ColliderDesc.ball(scale.x);
519
- this.createCollider(collider, desc, center);
520
- }
521
-
522
- addCapsuleCollider(collider: ICollider, center: Vector3, height: number, radius: number) {
523
- if (!this.enabled) {
524
- if (debugPhysics) console.warn("Physics are disabled");
525
- return;
526
- }
527
- const obj = collider.gameObject;
528
- const scale = getWorldScale(obj, this._tempPosition);
529
- // Prevent negative scales
530
- scale.x = Math.abs(scale.x);
531
- scale.y = Math.abs(scale.y);
532
- const desc = ColliderDesc.capsule(height * .5 * scale.y - radius, radius * scale.x);
533
- this.createCollider(collider, desc, center);
534
- }
535
-
536
- addMeshCollider(collider: ICollider, mesh: Mesh, convex: boolean, scale: Vector3) {
537
- if (!this.enabled) {
538
- if (debugPhysics) console.warn("Physics are disabled");
539
- return;
540
- }
541
- const geo = mesh.geometry;
542
- if (!geo) {
543
- if (debugPhysics) console.warn("Missing mesh geometry", mesh.name);
544
- return;
545
- }
546
-
547
- let positions = geo.getAttribute("position").array as Float32Array;
548
- const indices = geo.index?.array as Uint32Array;
549
-
550
- // console.log(geo.center())
551
-
552
- // scaling seems not supported yet https://github.com/dimforge/rapier/issues/243
553
- if (Math.abs(scale.x - 1) > 0.0001 || Math.abs(scale.y - 1) > 0.0001 || Math.abs(scale.z - 1) > 0.0001) {
554
- const key = geo.uuid + "_" + scale.x + "_" + scale.y + "_" + scale.z + "_" + convex;
555
- if (this._meshCache.has(key)) {
556
- positions = this._meshCache.get(key)!;
557
- }
558
- else {
559
- console.warn("Your model is using scaled mesh colliders which is not optimal for performance", mesh.name, Object.assign({}, scale), mesh);
560
- // showBalloonWarning("Your model is using scaled mesh colliders which is not optimal for performance: " + mesh.name + ", consider using unscaled objects");
561
- const scaledPositions = new Float32Array(positions.length);
562
- for (let i = 0; i < positions.length; i += 3) {
563
- scaledPositions[i] = positions[i] * scale.x;
564
- scaledPositions[i + 1] = positions[i + 1] * scale.y;
565
- scaledPositions[i + 2] = positions[i + 2] * scale.z;
566
- }
567
- positions = scaledPositions;
568
- this._meshCache.set(key, scaledPositions);
569
- }
570
- }
571
- const desc = convex ? ColliderDesc.convexMesh(positions) : ColliderDesc.trimesh(positions, indices);
572
- if (desc) {
573
- const col = this.createCollider(collider, desc);
574
- col.setMassProperties(1, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0, w: 1 });
575
- // rb?.setTranslation({ x: 0, y: 2, z: 0 });
576
- // col.setTranslationWrtParent(new Vector3(0,2,0));
577
-
578
- }
579
- }
580
-
581
- private createCollider(collider: ICollider, desc: ColliderDesc, center?: Vector3) {
582
- if (!this.world) throw new Error("Physics world not initialized");
583
- const matrix = this._tempMatrix;
584
- const {
585
- rigidBody,
586
- useExplicitMassProperties
587
- } = this.getRigidbody(collider, this._tempMatrix);
588
-
589
- matrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
590
- getWorldScale(collider.gameObject, this._tempScale);
591
- if (center) {
592
- center.multiply(this._tempScale);
593
- this._tempPosition.x -= center.x;
594
- this._tempPosition.y += center.y;
595
- this._tempPosition.z += center.z;
596
- }
597
- desc.setTranslation(this._tempPosition.x, this._tempPosition.y, this._tempPosition.z);
598
- desc.setRotation(this._tempQuaternion);
599
- desc.setSensor(collider.isTrigger);
600
-
601
- // TODO: we might want to update this if the material changes
602
- const physicsMaterial = collider.sharedMaterial;
603
- if (physicsMaterial) {
604
- CoefficientCombineRule
605
- desc.setRestitution(physicsMaterial.bounciness);
606
- switch (physicsMaterial.bounceCombine) {
607
- case PhysicsMaterialCombine.Average:
608
- desc.setRestitutionCombineRule(CoefficientCombineRule.Average);
609
- break;
610
- case PhysicsMaterialCombine.Maximum:
611
- desc.setRestitutionCombineRule(CoefficientCombineRule.Max);
612
- break;
613
- case PhysicsMaterialCombine.Minimum:
614
- desc.setRestitutionCombineRule(CoefficientCombineRule.Min);
615
- break;
616
- case PhysicsMaterialCombine.Multiply:
617
- desc.setRestitutionCombineRule(CoefficientCombineRule.Multiply);
618
- break;
619
- }
620
- desc.setFriction(physicsMaterial.dynamicFriction);
621
- switch (physicsMaterial.frictionCombine) {
622
- case PhysicsMaterialCombine.Average:
623
- desc.setFrictionCombineRule(CoefficientCombineRule.Average);
624
- break;
625
- case PhysicsMaterialCombine.Maximum:
626
- desc.setFrictionCombineRule(CoefficientCombineRule.Max);
627
- break;
628
- case PhysicsMaterialCombine.Minimum:
629
- desc.setFrictionCombineRule(CoefficientCombineRule.Min);
630
- break;
631
- case PhysicsMaterialCombine.Multiply:
632
- desc.setFrictionCombineRule(CoefficientCombineRule.Multiply);
633
- break;
634
- }
635
- }
636
-
637
- // if we want to use explicit mass properties, we need to set the collider density to 0
638
- // otherwise rapier will compute the mass properties based on the collider shape and density
639
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
640
- if (useExplicitMassProperties) {
641
- // desc.setDensity(0);
642
- }
643
-
644
- const col = this.world.createCollider(desc, rigidBody);
645
- col[$componentKey] = collider;
646
- collider[$bodyKey] = col;
647
- col.setActiveEvents(ActiveEvents.COLLISION_EVENTS);
648
- // We want to receive collisitons between two triggers too
649
- col.setActiveCollisionTypes(ActiveCollisionTypes.ALL);
650
-
651
- // const objectLayerMask = collider.gameObject.layers.mask;
652
- // const mask = objectLayerMask & ~2;
653
- // col.setCollisionGroups(objectLayerMask);
654
- this.objects.push(collider);
655
- this.bodies.push(col);
656
- return col;
657
- }
658
-
659
- private getRigidbody(collider: ICollider, _matrix: Matrix4): { rigidBody: RigidBody, useExplicitMassProperties: boolean } {
660
-
661
- if (!this.world) throw new Error("Physics world not initialized");
662
- let rigidBody: RigidBody | null = null;
663
- let useExplicitMassProperties = false;
664
-
665
- if (collider.attachedRigidbody) {
666
-
667
- const rb = collider.attachedRigidbody;
668
- rigidBody = rb[$bodyKey];
669
- useExplicitMassProperties = true;
670
- if (!rigidBody) {
671
- const kinematic = rb.isKinematic && !debugColliderPlacement;
672
- if (debugPhysics)
673
- console.log("Create rigidbody", kinematic);
674
- const rigidBodyDesc = kinematic ? RAPIER.RigidBodyDesc.kinematicPositionBased() : RAPIER.RigidBodyDesc.dynamic();
675
- const pos = getWorldPosition(collider.attachedRigidbody.gameObject);
676
- rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
677
- rigidBodyDesc.setRotation(getWorldQuaternion(collider.attachedRigidbody.gameObject));
678
- rigidBody = this.world.createRigidBody(rigidBodyDesc);
679
- this.bodies.push(rigidBody);
680
- this.objects.push(rb);
681
- }
682
- rigidBody[$componentKey] = rb;
683
- rb[$bodyKey] = rigidBody;
684
- this.internalUpdateProperties(rb, rigidBody);
685
- this.getRigidbodyRelativeMatrix(collider.gameObject, rb.gameObject, _matrix);
686
-
687
- }
688
- else {
689
-
690
- const rigidBodyDesc = RAPIER.RigidBodyDesc.kinematicPositionBased();
691
- const pos = getWorldPosition(collider.gameObject);
692
- rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
693
- rigidBodyDesc.setRotation(getWorldQuaternion(collider.gameObject));
694
- rigidBody = this.world.createRigidBody(rigidBodyDesc);
695
- _matrix.identity();
696
- rigidBody[$componentKey] = null;
697
-
698
- }
699
-
700
- collider[$colliderRigidbody] = rigidBody;
701
-
702
- return { rigidBody: rigidBody, useExplicitMassProperties: useExplicitMassProperties };
703
- }
704
-
705
- removeBody(obj: IComponent) {
706
- const body = obj[$bodyKey];
707
- obj[$bodyKey] = null;
708
- if (body && this.world) {
709
- const index = this.objects.findIndex(o => o === obj);
710
- if (index >= 0) {
711
- const body = this.bodies[index];
712
- this.bodies.splice(index, 1);
713
- this.objects.splice(index, 1);
714
-
715
- if (body instanceof Collider) {
716
- const collider = body as Collider;
717
- this.world?.removeCollider(collider, true);
718
-
719
- // remove the rigidbody if it doesnt have colliders anymore
720
- const rb = collider.parent();
721
- if (rb && rb.numColliders() <= 0) {
722
- this.world?.removeRigidBody(rb);
723
- }
724
- }
725
- else if (body instanceof RigidBody) {
726
- // TODO: running this code below causes a crash in rapier
727
- // const rb = body as RigidBody;
728
- // console.log("colliders", rb.numColliders())
729
- // for (let i = 0; i < rb.numColliders(); i++) {
730
- // const col = rb.collider(i);
731
- // this.world?.removeCollider(col, true);
732
- // }
733
- // console.log("colliders", rb.numColliders(), rb)
734
- // console.log(rb.handle, rb.userData);
735
- // if (rb.userData === undefined)
736
- // this.world?.removeRigidBody(rb);
737
- }
738
-
739
- // check if we need to remove the rigidbody too
740
- // const col = obj as ICollider;
741
- // if (col.isCollider && col.attachedRigidbody) {
742
- // const rb = col.attachedRigidbody[$bodyKey] as RigidBody;
743
- // if (rb && rb.numColliders() <= 0) {
744
- // // this.world?.removeRigidBody(rb);
745
- // }
746
- // }
747
- }
748
- }
749
- }
750
-
751
- updateBody(comp: ICollider | IRigidbody, translation: boolean, rotation: boolean) {
752
- if (!this.enabled) return;
753
- if (comp.destroyed || !comp.gameObject) return;
754
- if (!translation && !rotation) return;
755
-
756
- if ((comp as ICollider).isCollider === true) {
757
- // const collider = comp as ICollider;
758
- console.warn("TODO: implement updating collider position");
759
- }
760
- else {
761
- const rigidbody = comp as IRigidbody;
762
- const body = rigidbody[$bodyKey];
763
- if (body) {
764
- this.syncPhysicsBody(rigidbody.gameObject, body, translation, rotation);
765
- }
766
- }
767
- }
768
-
769
- updateProperties(rigidbody: IRigidbody) {
770
- const physicsBody = rigidbody[$bodyKey]
771
- if (physicsBody) {
772
- this.internalUpdateProperties(rigidbody, physicsBody);
773
- }
774
- }
775
-
776
- internal_getRigidbody(rb: IRigidbody): RigidBody | null {
777
- return rb[$bodyKey] as RigidBody;
778
- }
779
-
780
- private internalUpdateProperties(rb: IRigidbody, rigidbody: RigidBody) {
781
- // continuous collision detection
782
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#continuous-collision-detection
783
- rigidbody.enableCcd(rb.collisionDetectionMode !== CollisionDetectionMode.Discrete);
784
- rigidbody.setLinearDamping(rb.drag);
785
- rigidbody.setAngularDamping(rb.angularDrag);
786
- rigidbody.setGravityScale(rb.useGravity ? rb.gravityScale : 0, true);
787
-
788
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
789
- // rigidbody.setAdditionalMass(rb.mass, true);
790
- // for (let i = 0; i < rigidbody.numColliders(); i++) {
791
- // const collider = rigidbody.collider(i);
792
- // if (collider) {
793
- // collider.setMass(rb.mass);
794
- // // const density = rb.mass / collider.shape.computeMassProperties().mass;
795
- // }
796
- // }
797
-
798
- // lock rotations
799
- rigidbody.setEnabledRotations(!rb.lockRotationX, !rb.lockRotationY, !rb.lockRotationZ, true);
800
- rigidbody.setEnabledTranslations(!rb.lockPositionX, !rb.lockPositionY, !rb.lockPositionZ, true);
801
-
802
- if (rb.isKinematic) {
803
- rigidbody.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased);
804
- }
805
- else {
806
- rigidbody.setBodyType(RAPIER.RigidBodyType.Dynamic);
807
- }
808
- }
809
-
810
- // private _lastStepTime: number | undefined = 0;
811
- private lines?: LineSegments;
812
-
813
- public step(dt?: number) {
814
- if (!this.world) return;
815
- if (!this.enabled) return;
816
- this._isUpdatingPhysicsWorld = true;
817
- if (!this.eventQueue) {
818
- this.eventQueue = new EventQueue(false);
819
- }
820
- if (dt) {
821
- // if we make to sudden changes to the timestep the physics can get unstable
822
- // https://rapier.rs/docs/user_guides/javascript/integration_parameters/#dt
823
- this.world.timestep = Mathf.lerp(this.world.timestep, dt, 0.8);
824
- }
825
- this.world.step(this.eventQueue);
826
- this._isUpdatingPhysicsWorld = false;
827
- this.updateDebugRendering(this.world);
828
- }
829
-
830
- private updateDebugRendering(world: World) {
831
- if (debugPhysics || debugColliderPlacement || showColliders) {
832
- if (!this.lines) {
833
- const material = new LineBasicMaterial({
834
- color: 0x227700,
835
- // vertexColors: THREE.VertexColors
836
- });
837
- const geometry = new BufferGeometry();
838
- this.lines = new LineSegments(geometry, material);
839
- this.context.scene.add(this.lines);
840
- }
841
- const buffers = world.debugRender();
842
- this.lines.geometry.setAttribute('position', new BufferAttribute(buffers.vertices, 3));
843
- this.lines.geometry.setAttribute('color', new BufferAttribute(buffers.colors, 4));
844
- }
845
- }
846
-
847
- public postStep() {
848
- if (!this.world) return;
849
- if (!this.enabled) return;
850
- this._isUpdatingPhysicsWorld = true;
851
- this.syncObjects();
852
- this._isUpdatingPhysicsWorld = false;
853
-
854
- if (this.eventQueue && !this.collisionHandler) {
855
- this.collisionHandler = new PhysicsCollisionHandler(this.world, this.eventQueue);
856
- }
857
- if (this.collisionHandler) {
858
- this.collisionHandler.handleCollisionEvents();
859
- this.collisionHandler.update();
860
- }
861
- }
862
-
863
- /** sync rendered objects with physics world (except for colliders without rigidbody) */
864
- private syncObjects() {
865
- if (debugColliderPlacement) return;
866
- for (let i = 0; i < this.bodies.length; i++) {
867
- const obj = this.objects[i];
868
- const body = this.bodies[i] as Collider;
869
-
870
- // if the collider is not attached to a rigidbody
871
- // it means that its kinematic so we need to update its position
872
- const col = (obj as ICollider);
873
- if (col?.isCollider === true && !col.attachedRigidbody) {
874
- const rigidbody = body.parent();
875
- if (rigidbody)
876
- this.syncPhysicsBody(obj.gameObject, rigidbody, true, true);
877
- continue;
878
- }
879
-
880
-
881
- // sync
882
- const pos = body.translation();
883
- const rot = body.rotation();
884
- // make sure to keep the collider offset
885
- const center = obj["center"] as Vector3;
886
- if (center && center.isVector3) {
887
- this._tempQuaternion.set(rot.x, rot.y, rot.z, rot.w);
888
- const offset = this._tempPosition.copy(center).applyQuaternion(this._tempQuaternion);
889
- const scale = getWorldScale(obj.gameObject);
890
- offset.multiply(scale);
891
- pos.x -= offset.x;
892
- pos.y -= offset.y;
893
- pos.z -= offset.z;
894
- }
895
- setWorldPositionXYZ(obj.gameObject, pos.x, pos.y, pos.z);
896
- setWorldQuaternionXYZW(obj.gameObject, rot.x, rot.y, rot.z, rot.w);
897
- }
898
- }
899
-
900
- private syncPhysicsBody(obj: Object3D, body: RigidBody, translation: boolean, rotation: boolean) {
901
-
902
- // const bodyType = body.bodyType();
903
- // const previous = physicsBody.translation();
904
- // const vel = physicsBody.linvel();
905
-
906
- const worldPosition = getWorldPosition(obj, this._tempPosition);
907
- const worldQuaternion = getWorldQuaternion(obj, this._tempQuaternion);
908
- const type = body.bodyType();
909
- switch (type) {
910
- case RigidBodyType.Fixed:
911
- case RigidBodyType.KinematicPositionBased:
912
- case RigidBodyType.KinematicVelocityBased:
913
- if (translation)
914
- body.setNextKinematicTranslation(worldPosition);
915
- if (rotation)
916
- body.setNextKinematicRotation(worldQuaternion);
917
- break;
918
- default:
919
- if (translation)
920
- body.setTranslation(worldPosition, false);
921
- if (rotation)
922
- body.setRotation(worldQuaternion, false);
923
- break;
924
-
925
- }
926
- body.wakeUp();
927
- // physicsBody.setBodyType(RAPIER.RigidBodyType.Fixed);
928
- // physicsBody.setLinvel(vel, false);
929
-
930
- // update velocity
931
- // const pos = physicsBody.translation();
932
- // pos.x -= previous.x;
933
- // pos.y -= previous.y;
934
- // pos.z -= previous.z;
935
- // // threhold
936
- // const t = 1;
937
- // const canUpdateVelocity = Math.abs(pos.x) < t && Math.abs(pos.y) < t && Math.abs(pos.z) < t;
938
- // if (canUpdateVelocity) {
939
- // const damping = 1 + this.context.time.deltaTime;
940
- // vel.x *= damping;
941
- // vel.y *= damping;
942
- // vel.z *= damping;
943
- // vel.x += pos.x;
944
- // vel.y += pos.y;
945
- // vel.z += pos.z;
946
- // console.log(vel);
947
- // physicsBody.setLinvel(vel, true);
948
- // }
949
- // else if(debugPhysics) console.warn("Movement exceeded threshold, not updating velocity", pos);
950
-
951
- // body.setBodyType(bodyType);
952
- }
953
-
954
- private static _matricesBuffer: Matrix4[] = [];
955
- private getRigidbodyRelativeMatrix(comp: Object3D, rigidbody: Object3D, mat: Matrix4, matrices?: Matrix4[]): Matrix4 {
956
- // collect all matrices to the rigidbody and then build the rigidbody relative matrix
957
- if (matrices === undefined) {
958
- matrices = Physics._matricesBuffer;
959
- matrices.length = 0;
960
- }
961
- if (comp === rigidbody) {
962
- const scale = getWorldScale(comp, this._tempPosition);
963
- mat.makeScale(scale.x, scale.y, scale.z);
964
- for (let i = matrices.length - 1; i >= 0; i--) {
965
- mat.multiply(matrices[i]);
966
- }
967
- return mat;
968
- }
969
- matrices.push(comp.matrix);
970
- if (comp.parent) {
971
- this.getRigidbodyRelativeMatrix(comp.parent, rigidbody, mat, matrices);
972
- }
973
- return mat;
974
- }
975
-
976
- private static centerConnectionPos = { x: 0, y: 0, z: 0 };
977
- private static centerConnectionRot = { x: 0, y: 0, z: 0, w: 1 };
978
-
979
-
980
-
981
- addFixedJoint(body1: IRigidbody, body2: IRigidbody) {
982
- if (!this.world) {
983
- console.error("Physics world not initialized");
984
- return;
985
- }
986
- const b1 = body1[$bodyKey] as RigidBody;
987
- const b2 = body2[$bodyKey] as RigidBody;
988
-
989
- this.calculateJointRelativeMatrices(body1.gameObject, body2.gameObject, this._tempMatrix);
990
- this._tempMatrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
991
-
992
- const params = JointData.fixed(
993
- Physics.centerConnectionPos, Physics.centerConnectionRot,
994
- this._tempPosition, this._tempQuaternion,
995
- );
996
- const joint = this.world.createImpulseJoint(params, b1, b2, true);
997
- if (debugPhysics)
998
- console.log("ADD FIXED JOINT", joint)
999
- }
1000
-
1001
-
1002
- /** The joint prevents any relative movement between two rigid-bodies, except for relative rotations along one axis. This is typically used to simulate wheels, fans, etc. They are characterized by one local anchor as well as one local axis on each rigid-body. */
1003
- addHingeJoint(body1: IRigidbody, body2: IRigidbody, anchor: { x: number, y: number, z: number }, axis: { x: number, y: number, z: number }) {
1004
- if (!this.world) {
1005
- console.error("Physics world not initialized");
1006
- return;
1007
- }
1008
- const b1 = body1[$bodyKey] as RigidBody;
1009
- const b2 = body2[$bodyKey] as RigidBody;
1010
-
1011
- this.calculateJointRelativeMatrices(body1.gameObject, body2.gameObject, this._tempMatrix);
1012
- this._tempMatrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
1013
-
1014
- let params = RAPIER.JointData.revolute(anchor, this._tempPosition, axis);
1015
- let joint = this.world.createImpulseJoint(params, b1, b2, true);
1016
- if (debugPhysics)
1017
- console.log("ADD HINGE JOINT", joint)
1018
- }
1019
-
1020
-
1021
- private calculateJointRelativeMatrices(body1: IGameObject, body2: IGameObject, mat: Matrix4) {
1022
- body1.updateWorldMatrix(true, false);
1023
- body2.updateWorldMatrix(true, false);
1024
- const world1 = body1.matrixWorld;
1025
- const world2 = body2.matrixWorld;
1026
- // set scale to 1
1027
- world1.elements[0] = 1;
1028
- world1.elements[5] = 1;
1029
- world1.elements[10] = 1;
1030
- world2.elements[0] = 1;
1031
- world2.elements[5] = 1;
1032
- world2.elements[10] = 1;
1033
- mat.copy(world2).premultiply(world1.invert()).invert();
1034
- }
1035
- }
1036
-
1037
-
1038
-
1039
- /** responsible of processing collision events for the component system */
1040
- class PhysicsCollisionHandler {
1041
-
1042
- readonly world: World;
1043
- readonly eventQueue: EventQueue;
1044
-
1045
- constructor(world: World, eventQueue: EventQueue) {
1046
- this.world = world;
1047
- this.eventQueue = eventQueue;
1048
- }
1049
-
1050
- private activeCollisions: Array<{ collider: ICollider, component: IComponent, collision: Collision }> = [];
1051
- private activeCollisionsStay: Array<{ collider: ICollider, component: IComponent, collision: Collision }> = [];
1052
- private activeTriggers: Array<{ collider: ICollider, component: IComponent, otherCollider: ICollider }> = [];
1053
-
1054
- handleCollisionEvents() {
1055
- if (!this.eventQueue) return;
1056
- if (!this.world) return;
1057
- this.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
1058
- const col1 = this.world!.getCollider(handle1);
1059
- const col2 = this.world!.getCollider(handle2);
1060
- const colliderComponent1 = col1[$componentKey];
1061
- const colliderComponent2 = col2[$componentKey];
1062
- if (debugCollisions)
1063
- console.log("EVT", colliderComponent1.name, colliderComponent2.name, started, col1, col2);
1064
- if (colliderComponent1 && colliderComponent2) {
1065
- if (started) {
1066
- this.onCollisionStarted(colliderComponent1, col1, colliderComponent2, col2);
1067
- this.onCollisionStarted(colliderComponent2, col2, colliderComponent1, col1);
1068
- }
1069
- else {
1070
- this.onCollisionEnded(colliderComponent1, colliderComponent2);
1071
- this.onCollisionEnded(colliderComponent2, colliderComponent1);
1072
- }
1073
- }
1074
- });
1075
- }
1076
-
1077
- update() {
1078
- this.onHandleCollisionStay();
1079
- }
1080
-
1081
- private onCollisionStarted(self: ICollider, selfBody: Collider, other: ICollider, otherBody: Collider) {
1082
- let collision: Collision | null = null;
1083
-
1084
- // if one is a trigger we dont get collisions but want to raise the trigger events
1085
- if (self.isTrigger || other.isTrigger) {
1086
- foreachComponent(self.gameObject, (c: IComponent) => {
1087
- if (c.onTriggerEnter && !c.destroyed) {
1088
- c.onTriggerEnter(other);
1089
- }
1090
- this.activeTriggers.push({ collider: self, component: c, otherCollider: other });
1091
- });
1092
- }
1093
- else {
1094
- const object = self.gameObject;
1095
- // TODO: we dont respect the flip value here!
1096
- this.world.contactPair(selfBody, otherBody, (manifold, _flipped) => {
1097
- foreachComponent(object, (c: IComponent) => {
1098
- if(c.destroyed) return;
1099
- const hasDeclaredEventMethod = c.onCollisionEnter || c.onCollisionStay || c.onCollisionExit;
1100
- if (hasDeclaredEventMethod || debugCollisions) {
1101
- if (!collision) {
1102
- const contacts: Array<ContactPoint> = [];
1103
- const normal = manifold.normal();
1104
- for (let i = 0; i < manifold.numSolverContacts(); i++) {
1105
- // solver points are in world space
1106
- // https://rapier.rs/docs/user_guides/javascript/advanced_collision_detection_js#the-contact-graph
1107
- const pt = manifold.solverContactPoint(i);
1108
- const impulse = manifold.contactImpulse(i);
1109
- if (pt) {
1110
- const dist = manifold.contactDist(i);
1111
- const friction = manifold.solverContactFriction(i);
1112
- const contact = new ContactPoint(pt, dist, normal, impulse, friction);
1113
- contacts.push(contact);
1114
- if (debugCollisions) {
1115
- Gizmos.DrawDirection(pt, normal, 0xff0000, 3, true);
1116
- }
1117
- }
1118
- }
1119
- collision = new Collision(object, other, contacts);
1120
- }
1121
-
1122
- // we only need to keep track if any event exists
1123
- if (hasDeclaredEventMethod) {
1124
- const info = { collider: self, component: c, collision };
1125
-
1126
- this.activeCollisions.push(info);
1127
- if (c.onCollisionStay) {
1128
- this.activeCollisionsStay.push(info);
1129
- }
1130
-
1131
- c.onCollisionEnter?.call(c, collision);
1132
- }
1133
-
1134
- }
1135
- });
1136
- });
1137
- }
1138
- }
1139
-
1140
- private onHandleCollisionStay() {
1141
- for (const active of this.activeCollisionsStay) {
1142
- const c = active.component;
1143
- if(c.destroyed) continue;
1144
- if (c.activeAndEnabled && c.onCollisionStay) {
1145
- const arg = active.collision;
1146
- c.onCollisionStay(arg);
1147
- }
1148
- }
1149
- for (const active of this.activeTriggers) {
1150
- const c = active.component;
1151
- if(c.destroyed) continue;
1152
- if (c.activeAndEnabled && c.onTriggerStay) {
1153
- const arg = active.otherCollider;
1154
- c.onTriggerStay(arg);
1155
- }
1156
- }
1157
- }
1158
-
1159
- private onCollisionEnded(self: ICollider, other: ICollider) {
1160
- if(self.destroyed || other.destroyed) return;
1161
- for (let i = 0; i < this.activeCollisions.length; i++) {
1162
- const active = this.activeCollisions[i];
1163
- const collider = active.collider;
1164
- if(collider.destroyed) {
1165
- this.activeCollisions.splice(i, 1);
1166
- i--;
1167
- continue;
1168
- }
1169
- if (collider === self && active.collision.collider === other) {
1170
- const c = active.component;
1171
- this.activeCollisions.splice(i, 1);
1172
- i--;
1173
- if (c.activeAndEnabled && c.onCollisionExit) {
1174
- const collision = active.collision;
1175
- c.onCollisionExit(collision);
1176
- }
1177
- }
1178
- }
1179
- for (let i = 0; i < this.activeCollisionsStay.length; i++) {
1180
- const active = this.activeCollisionsStay[i];
1181
- const collider = active.collider;
1182
- if(collider.destroyed) {
1183
- this.activeCollisionsStay.splice(i, 1);
1184
- i--;
1185
- continue;
1186
- }
1187
- if (collider === self && active.collision.collider === other) {
1188
- const c = active.component;
1189
- this.activeCollisionsStay.splice(i, 1);
1190
- i--;
1191
- if (c.activeAndEnabled && c.onCollisionExit) {
1192
- const collision = active.collision;
1193
- c.onCollisionExit(collision);
1194
- }
1195
- }
1196
- }
1197
- for (let i = 0; i < this.activeTriggers.length; i++) {
1198
- const active = this.activeTriggers[i];
1199
- const collider = active.collider;
1200
- if(collider.destroyed) {
1201
- this.activeTriggers.splice(i, 1);
1202
- i--;
1203
- continue;
1204
- }
1205
- if (collider === self && active.otherCollider === other) {
1206
- const c = active.component;
1207
- this.activeTriggers.splice(i, 1);
1208
- i--;
1209
- if (c.activeAndEnabled && c.onTriggerExit) {
1210
- const collision = active.otherCollider;
1211
- c.onTriggerExit(collision);
1212
- }
1213
- }
1214
- }
1215
- }
1216
221
  }