/
havokPlugin.ts
2142 lines (1970 loc) · 98.2 KB
/
havokPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Matrix, Quaternion, TmpVectors, Vector3 } from "../../../Maths/math.vector";
import {
PhysicsShapeType,
PhysicsConstraintType,
PhysicsMotionType,
PhysicsConstraintMotorType,
PhysicsConstraintAxis,
PhysicsConstraintAxisLimitMode,
PhysicsEventType,
} from "../IPhysicsEnginePlugin";
import type {
PhysicsShapeParameters,
IPhysicsEnginePluginV2,
PhysicsMassProperties,
IPhysicsCollisionEvent,
IBasePhysicsCollisionEvent,
ConstrainedBodyPair,
} from "../IPhysicsEnginePlugin";
import type { IRaycastQuery, PhysicsRaycastResult } from "../../physicsRaycastResult";
import { Logger } from "../../../Misc/logger";
import type { PhysicsBody } from "../physicsBody";
import type { PhysicsConstraint, Physics6DoFConstraint } from "../physicsConstraint";
import type { PhysicsMaterial } from "../physicsMaterial";
import { PhysicsMaterialCombineMode } from "../physicsMaterial";
import { PhysicsShape } from "../physicsShape";
import type { BoundingBox } from "../../../Culling/boundingBox";
import type { TransformNode } from "../../../Meshes/transformNode";
import { Mesh } from "../../../Meshes/mesh";
import { InstancedMesh } from "../../../Meshes/instancedMesh";
import type { Scene } from "../../../scene";
import { VertexBuffer } from "../../../Buffers/buffer";
import { ArrayTools } from "../../../Misc/arrayTools";
import { Observable } from "../../../Misc/observable";
import type { Nullable } from "../../../types";
declare let HK: any;
/**
* Helper to keep a reference to plugin memory.
* Used to avoid https://github.com/emscripten-core/emscripten/issues/7294
* @internal
*/
interface PluginMemoryRef {
/** The offset from the beginning of the plugin's heap */
offset: number;
/** The number of identically-sized objects the buffer contains */
numObjects: number;
}
class MeshAccumulator {
/**
* Constructor of the mesh accumulator
* @param mesh - The mesh used to compute the world matrix.
* @param collectIndices - use mesh indices
* @param scene - The scene used to determine the right handed system.
*
* Merge mesh and its children so whole hierarchy can be used as a mesh shape or convex hull
*/
public constructor(mesh: Mesh, collectIndices: boolean, scene: Scene) {
this._isRightHanded = scene.useRightHandedSystem;
this._collectIndices = collectIndices;
}
/**
* Adds a mesh to the physics engine.
* @param mesh The mesh to add.
* @param includeChildren Whether to include the children of the mesh.
*
* This method adds a mesh to the physics engine by computing the world matrix,
* multiplying it with the body from world matrix, and then transforming the
* coordinates of the mesh's vertices. It also adds the indices of the mesh
* to the physics engine. If includeChildren is true, it will also add the
* children of the mesh to the physics engine, ignoring any children which
* have a physics impostor. This is useful for creating a physics engine
* that accurately reflects the mesh and its children.
*/
public addNodeMeshes(mesh: TransformNode, includeChildren: boolean): void {
// Force absoluteScaling to be computed; we're going to use that to bake
// the scale of any parent nodes into this shape, as physics engines
// usually use rigid transforms, so can't handle arbitrary scale.
mesh.computeWorldMatrix(true);
const rootScaled = TmpVectors.Matrix[0];
Matrix.ScalingToRef(mesh.absoluteScaling.x, mesh.absoluteScaling.y, mesh.absoluteScaling.z, rootScaled);
if (mesh instanceof Mesh) {
this._addMesh(mesh, rootScaled);
} else if (mesh instanceof InstancedMesh) {
this._addMesh(mesh.sourceMesh, rootScaled);
}
if (includeChildren) {
const worldToRoot = TmpVectors.Matrix[1];
mesh.computeWorldMatrix().invertToRef(worldToRoot);
const worldToRootScaled = TmpVectors.Matrix[2];
worldToRoot.multiplyToRef(rootScaled, worldToRootScaled);
const children = mesh.getChildMeshes(false);
// Ignore any children which have a physics body.
// Other plugin implementations do not have this check, which appears to be
// a bug, as otherwise, the mesh will have a duplicate collider
children
.filter((m: any) => !m.physicsBody)
.forEach((m: TransformNode) => {
const childToWorld = m.computeWorldMatrix();
const childToRootScaled = TmpVectors.Matrix[3];
childToWorld.multiplyToRef(worldToRootScaled, childToRootScaled);
if (m instanceof Mesh) {
this._addMesh(m, childToRootScaled);
} else if (m instanceof InstancedMesh) {
this._addMesh(m.sourceMesh, childToRootScaled);
}
});
}
}
private _addMesh(mesh: Mesh, meshToRoot: Matrix): void {
const vertexData = mesh.getVerticesData(VertexBuffer.PositionKind) || [];
const numVerts = vertexData.length / 3;
const indexOffset = this._vertices.length;
for (let v = 0; v < numVerts; v++) {
const pos = new Vector3(vertexData[v * 3 + 0], vertexData[v * 3 + 1], vertexData[v * 3 + 2]);
this._vertices.push(Vector3.TransformCoordinates(pos, meshToRoot));
}
if (this._collectIndices) {
const meshIndices = mesh.getIndices();
if (meshIndices) {
for (let i = 0; i < meshIndices.length; i += 3) {
// Havok wants the correct triangle winding to enable the interior triangle optimization
if (this._isRightHanded) {
this._indices.push(meshIndices[i + 0] + indexOffset);
this._indices.push(meshIndices[i + 1] + indexOffset);
this._indices.push(meshIndices[i + 2] + indexOffset);
} else {
this._indices.push(meshIndices[i + 2] + indexOffset);
this._indices.push(meshIndices[i + 1] + indexOffset);
this._indices.push(meshIndices[i + 0] + indexOffset);
}
}
}
}
}
/**
* Allocate and populate the vertex positions inside the physics plugin.
*
* @returns An array of floats, whose backing memory is inside the plugin. The array contains the
* positions of the mesh vertices, where a position is defined by three floats. You must call
* freeBuffer() on the returned array once you have finished with it, in order to free the
* memory inside the plugin..
*/
public getVertices(plugin: any): PluginMemoryRef {
const nFloats = this._vertices.length * 3;
const bytesPerFloat = 4;
const nBytes = nFloats * bytesPerFloat;
const bufferBegin = plugin._malloc(nBytes);
const ret = new Float32Array(plugin.HEAPU8.buffer, bufferBegin, nFloats);
for (let i = 0; i < this._vertices.length; i++) {
ret[i * 3 + 0] = this._vertices[i].x;
ret[i * 3 + 1] = this._vertices[i].y;
ret[i * 3 + 2] = this._vertices[i].z;
}
return { offset: bufferBegin, numObjects: nFloats };
}
public freeBuffer(plugin: any, arr: PluginMemoryRef) {
plugin._free(arr.offset);
}
/**
* Allocate and populate the triangle indices inside the physics plugin
*
* @returns A new Int32Array, whose backing memory is inside the plugin. The array contains the indices
* of the triangle positions, where a single triangle is defined by three indices. You must call
* freeBuffer() on this array once you have finished with it, to free the memory inside the plugin..
*/
public getTriangles(plugin: any): PluginMemoryRef {
const bytesPerInt = 4;
const nBytes = this._indices.length * bytesPerInt;
const bufferBegin = plugin._malloc(nBytes);
const ret = new Int32Array(plugin.HEAPU8.buffer, bufferBegin, this._indices.length);
for (let i = 0; i < this._indices.length; i++) {
ret[i] = this._indices[i];
}
return { offset: bufferBegin, numObjects: this._indices.length };
}
private _isRightHanded: boolean;
private _collectIndices: boolean;
private _vertices: Vector3[] = []; /// Vertices in body space
private _indices: number[] = [];
}
class BodyPluginData {
public constructor(bodyId: any) {
this.hpBodyId = bodyId;
this.userMassProps = { centerOfMass: undefined, mass: undefined, inertia: undefined, inertiaOrientation: undefined };
}
public hpBodyId: any;
public worldTransformOffset: number;
public userMassProps: PhysicsMassProperties;
}
/*
class ShapePath
{
public colliderId: number;
public pathData: number;
}
*/
class ContactPoint {
public bodyId: bigint = BigInt(0); //0,2
//public colliderId: number = 0; //2,4
//public shapePath: ShapePath = new ShapePath(); //4,8
public position: Vector3 = new Vector3(); //8,11
public normal: Vector3 = new Vector3(); //11,14
//public triIdx: number = 0; //14,15
}
class CollisionEvent {
public contactOnA: ContactPoint = new ContactPoint(); //1
public contactOnB: ContactPoint = new ContactPoint();
public impulseApplied: number = 0;
public type: number = 0;
static readToRef(buffer: any, offset: number, eventOut: CollisionEvent) {
const intBuf = new Int32Array(buffer, offset);
const floatBuf = new Float32Array(buffer, offset);
const offA = 2;
eventOut.contactOnA.bodyId = BigInt(intBuf[offA]); //<todo Need to get the high+low words!
eventOut.contactOnA.position.set(floatBuf[offA + 8], floatBuf[offA + 9], floatBuf[offA + 10]);
eventOut.contactOnA.normal.set(floatBuf[offA + 11], floatBuf[offA + 12], floatBuf[offA + 13]);
const offB = 18;
eventOut.contactOnB.bodyId = BigInt(intBuf[offB]);
eventOut.contactOnB.position.set(floatBuf[offB + 8], floatBuf[offB + 9], floatBuf[offB + 10]);
eventOut.contactOnB.normal.set(floatBuf[offB + 11], floatBuf[offB + 12], floatBuf[offB + 13]);
eventOut.impulseApplied = floatBuf[offB + 13 + 3];
eventOut.type = intBuf[0];
}
}
class TriggerEvent {
public bodyIdA: bigint = BigInt(0);
public bodyIdB: bigint = BigInt(0);
public type: number = 0;
static readToRef(buffer: any, offset: number, eventOut: TriggerEvent) {
const intBuf = new Int32Array(buffer, offset);
eventOut.type = intBuf[0];
eventOut.bodyIdA = BigInt(intBuf[2]);
eventOut.bodyIdB = BigInt(intBuf[6]);
}
}
/**
* The Havok Physics plugin
*/
export class HavokPlugin implements IPhysicsEnginePluginV2 {
/**
* Reference to the WASM library
*/
public _hknp: any = {};
/**
* Created Havok world which physics bodies are added to
*/
public world: any;
/**
* Name of the plugin
*/
public name: string = "HavokPlugin";
/**
* We only have a single raycast in-flight right now
*/
private _queryCollector: bigint;
private _fixedTimeStep: number = 1 / 60;
private _timeStep: number = 1 / 60;
private _tmpVec3 = ArrayTools.BuildArray(3, Vector3.Zero);
private _bodies = new Map<bigint, { body: PhysicsBody; index: number }>();
private _bodyBuffer: number;
private _bodyCollisionObservable = new Map<bigint, Observable<IPhysicsCollisionEvent>>();
// Map from constraint id to the pair of bodies, where the first is the parent and the second is the child
private _constraintToBodyIdPair = new Map<bigint, [bigint, bigint]>();
private _bodyCollisionEndedObservable = new Map<bigint, Observable<IBasePhysicsCollisionEvent>>();
/**
* Observable for collision started and collision continued events
*/
public onCollisionObservable = new Observable<IPhysicsCollisionEvent>();
/**
* Observable for collision ended events
*/
public onCollisionEndedObservable = new Observable<IBasePhysicsCollisionEvent>();
/**
* Observable for trigger entered and trigger exited events
*/
public onTriggerCollisionObservable = new Observable<IBasePhysicsCollisionEvent>();
public constructor(private _useDeltaForWorldStep: boolean = true, hpInjection: any = HK) {
if (typeof hpInjection === "function") {
Logger.Error("Havok is not ready. Please make sure you await HK() before using the plugin.");
return;
} else {
this._hknp = hpInjection;
}
if (!this.isSupported()) {
Logger.Error("Havok is not available. Please make sure you included the js file.");
return;
}
this.world = this._hknp.HP_World_Create()[1];
this._queryCollector = this._hknp.HP_QueryCollector_Create(1)[1];
}
/**
* If this plugin is supported
* @returns true if its supported
*/
public isSupported(): boolean {
return this._hknp !== undefined;
}
/**
* Sets the gravity of the physics world.
*
* @param gravity - The gravity vector to set.
*
*/
public setGravity(gravity: Vector3): void {
this._hknp.HP_World_SetGravity(this.world, this._bVecToV3(gravity));
}
/**
* Sets the fixed time step for the physics engine.
*
* @param timeStep - The fixed time step to use for the physics engine.
*
*/
public setTimeStep(timeStep: number): void {
this._fixedTimeStep = timeStep;
}
/**
* Gets the fixed time step used by the physics engine.
*
* @returns The fixed time step used by the physics engine.
*
*/
public getTimeStep(): number {
return this._fixedTimeStep;
}
/**
* Executes a single step of the physics engine.
*
* @param delta The time delta in seconds since the last step.
* @param physicsBodies An array of physics bodies to be simulated.
* @returns void
*
* This method is useful for simulating the physics engine. It sets the physics body transformation,
* steps the world, syncs the physics body, and notifies collisions. This allows for the physics engine
* to accurately simulate the physics bodies in the world.
*/
public executeStep(delta: number, physicsBodies: Array<PhysicsBody>): void {
for (const physicsBody of physicsBodies) {
if (physicsBody.disablePreStep) {
continue;
}
this.setPhysicsBodyTransformation(physicsBody, physicsBody.transformNode);
}
this._hknp.HP_World_Step(this.world, this._useDeltaForWorldStep ? delta : this._timeStep);
this._bodyBuffer = this._hknp.HP_World_GetBodyBuffer(this.world)[1];
for (const physicsBody of physicsBodies) {
this.sync(physicsBody);
}
this._notifyCollisions();
this._notifyTriggers();
}
/**
* Returns the version of the physics engine plugin.
*
* @returns The version of the physics engine plugin.
*
* This method is useful for determining the version of the physics engine plugin that is currently running.
*/
public getPluginVersion(): number {
return 2;
}
/**
* Initializes a physics body with the given position and orientation.
*
* @param body - The physics body to initialize.
* @param motionType - The motion type of the body.
* @param position - The position of the body.
* @param orientation - The orientation of the body.
* This code is useful for initializing a physics body with the given position and orientation.
* It creates a plugin data for the body and adds it to the world. It then converts the position
* and orientation to a transform and sets the body's transform to the given values.
*/
public initBody(body: PhysicsBody, motionType: PhysicsMotionType, position: Vector3, orientation: Quaternion): void {
body._pluginData = new BodyPluginData(this._hknp.HP_Body_Create()[1]);
this._internalSetMotionType(body._pluginData, motionType);
const transform = [this._bVecToV3(position), this._bQuatToV4(orientation)]; //<todo temp transform?
this._hknp.HP_Body_SetQTransform(body._pluginData.hpBodyId, transform);
this._hknp.HP_World_AddBody(this.world, body._pluginData.hpBodyId, body.startAsleep);
this._bodies.set(body._pluginData.hpBodyId[0], { body: body, index: 0 });
}
/**
* Removes a body from the world. To dispose of a body, it is necessary to remove it from the world first.
*
* @param body - The body to remove.
*/
public removeBody(body: PhysicsBody): void {
if (body._pluginDataInstances && body._pluginDataInstances.length > 0) {
for (const instance of body._pluginDataInstances) {
this._bodyCollisionObservable.delete(instance.hpBodyId[0]);
this._hknp.HP_World_RemoveBody(this.world, instance.hpBodyId);
}
}
if (body._pluginData) {
this._bodyCollisionObservable.delete(body._pluginData.hpBodyId[0]);
this._hknp.HP_World_RemoveBody(this.world, body._pluginData.hpBodyId);
}
}
/**
* Initializes the body instances for a given physics body and mesh.
*
* @param body - The physics body to initialize.
* @param motionType - How the body will be handled by the engine
* @param mesh - The mesh to initialize.
*
* This code is useful for creating a physics body from a mesh. It creates a
* body instance for each instance of the mesh and adds it to the world. It also
* sets the position of the body instance to the position of the mesh instance.
* This allows for the physics engine to accurately simulate the mesh in the
* world.
*/
public initBodyInstances(body: PhysicsBody, motionType: PhysicsMotionType, mesh: Mesh): void {
const instancesCount = mesh._thinInstanceDataStorage?.instancesCount ?? 0;
const matrixData = mesh._thinInstanceDataStorage.matrixData;
if (!matrixData) {
return; // TODO: error handling
}
this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, false);
body._pluginDataInstances.forEach((bodyId, index) => {
this._bodies.set(bodyId.hpBodyId[0], { body: body, index: index });
});
}
private _createOrUpdateBodyInstances(body: PhysicsBody, motionType: PhysicsMotionType, matrixData: Float32Array, startIndex: number, endIndex: number, update: boolean): void {
const rotation = TmpVectors.Quaternion[0];
const rotationMatrix = Matrix.Identity();
for (let i = startIndex; i < endIndex; i++) {
const position = [matrixData[i * 16 + 12], matrixData[i * 16 + 13], matrixData[i * 16 + 14]];
let hkbody;
if (!update) {
hkbody = this._hknp.HP_Body_Create()[1];
} else {
hkbody = body._pluginDataInstances[i].hpBodyId;
}
rotationMatrix.setRowFromFloats(0, matrixData[i * 16 + 0], matrixData[i * 16 + 1], matrixData[i * 16 + 2], 0);
rotationMatrix.setRowFromFloats(1, matrixData[i * 16 + 4], matrixData[i * 16 + 5], matrixData[i * 16 + 6], 0);
rotationMatrix.setRowFromFloats(2, matrixData[i * 16 + 8], matrixData[i * 16 + 9], matrixData[i * 16 + 10], 0);
Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
const transform = [position, [rotation.x, rotation.y, rotation.z, rotation.w]];
this._hknp.HP_Body_SetQTransform(hkbody, transform);
if (!update) {
const pluginData = new BodyPluginData(hkbody);
if (body._pluginDataInstances.length) {
// If an instance already exists, copy any user-provided mass properties
pluginData.userMassProps = body._pluginDataInstances[0].userMassProps;
}
this._internalSetMotionType(pluginData, motionType);
this._internalUpdateMassProperties(pluginData);
body._pluginDataInstances.push(pluginData);
this._hknp.HP_World_AddBody(this.world, hkbody, body.startAsleep);
pluginData.worldTransformOffset = this._hknp.HP_Body_GetWorldTransformOffset(hkbody)[1];
}
}
}
/**
* Update the internal body instances for a given physics body to match the instances in a mesh.
* @param body the body that will be updated
* @param mesh the mesh with reference instances
*/
public updateBodyInstances(body: PhysicsBody, mesh: Mesh): void {
const instancesCount = mesh._thinInstanceDataStorage?.instancesCount ?? 0;
const matrixData = mesh._thinInstanceDataStorage.matrixData;
if (!matrixData) {
return; // TODO: error handling
}
const pluginInstancesCount = body._pluginDataInstances.length;
const motionType = this.getMotionType(body);
if (instancesCount > pluginInstancesCount) {
this._createOrUpdateBodyInstances(body, motionType, matrixData, pluginInstancesCount, instancesCount, false);
const firstBodyShape = this._hknp.HP_Body_GetShape(body._pluginDataInstances[0].hpBodyId)[1];
for (let i = pluginInstancesCount; i < instancesCount; i++) {
this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, firstBodyShape);
this._internalUpdateMassProperties(body._pluginDataInstances[i]);
this._bodies.set(body._pluginDataInstances[i].hpBodyId[0], { body: body, index: i });
}
} else if (instancesCount < pluginInstancesCount) {
const instancesToRemove = pluginInstancesCount - instancesCount;
for (let i = 0; i < instancesToRemove; i++) {
const hkbody = body._pluginDataInstances.pop();
this._bodies.delete(hkbody.hpBodyId[0]);
this._hknp.HP_World_RemoveBody(this.world, hkbody.hpBodyId);
this._hknp.HP_Body_Release(hkbody.hpBodyId);
}
this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, true);
}
}
/**
* Synchronizes the transform of a physics body with its transform node.
* @param body - The physics body to synchronize.
*
* This function is useful for keeping the physics body's transform in sync with its transform node.
* This is important for ensuring that the physics body is accurately represented in the physics engine.
*/
sync(body: PhysicsBody): void {
this.syncTransform(body, body.transformNode);
}
/**
* Synchronizes the transform of a physics body with the transform of its
* corresponding transform node.
*
* @param body - The physics body to synchronize.
* @param transformNode - The destination Transform Node.
*
* This code is useful for synchronizing the position and orientation of a
* physics body with the position and orientation of its corresponding
* transform node. This is important for ensuring that the physics body and
* the transform node are in the same position and orientation in the scene.
* This is necessary for the physics engine to accurately simulate the
* physical behavior of the body.
*/
syncTransform(body: PhysicsBody, transformNode: TransformNode): void {
if (body._pluginDataInstances.length) {
// instances
const m = transformNode as Mesh;
const matrixData = m._thinInstanceDataStorage.matrixData;
if (!matrixData) {
return; // TODO: error handling
}
const instancesCount = body._pluginDataInstances.length;
for (let i = 0; i < instancesCount; i++) {
const bufOffset = body._pluginDataInstances[i].worldTransformOffset;
const transformBuffer = new Float32Array(this._hknp.HEAPU8.buffer, this._bodyBuffer + bufOffset, 16);
const index = i * 16;
for (let mi = 0; mi < 15; mi++) {
if ((mi & 3) != 3) {
matrixData[index + mi] = transformBuffer[mi];
}
}
matrixData[index + 15] = 1;
}
m.thinInstanceBufferUpdated("matrix");
} else {
try {
// regular
const bodyTransform = this._hknp.HP_Body_GetQTransform(body._pluginData.hpBodyId)[1];
const bodyTranslation = bodyTransform[0];
const bodyOrientation = bodyTransform[1];
const quat = TmpVectors.Quaternion[0];
quat.set(bodyOrientation[0], bodyOrientation[1], bodyOrientation[2], bodyOrientation[3]);
const parent = transformNode.parent as TransformNode;
// transform position/orientation in parent space
if (parent && !parent.getWorldMatrix().isIdentity()) {
parent.computeWorldMatrix(true);
quat.normalize();
const finalTransform = TmpVectors.Matrix[0];
const finalTranslation = TmpVectors.Vector3[0];
finalTranslation.copyFromFloats(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);
Matrix.ComposeToRef(transformNode.absoluteScaling, quat, finalTranslation, finalTransform);
const parentInverseTransform = TmpVectors.Matrix[1];
parent.getWorldMatrix().invertToRef(parentInverseTransform);
const localTransform = TmpVectors.Matrix[2];
finalTransform.multiplyToRef(parentInverseTransform, localTransform);
localTransform.decomposeToTransformNode(transformNode);
transformNode.rotationQuaternion?.normalize();
} else {
transformNode.position.set(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);
if (transformNode.rotationQuaternion) {
transformNode.rotationQuaternion.copyFrom(quat);
} else {
quat.toEulerAnglesToRef(transformNode.rotation);
}
}
} catch (e) {
console.log(`Syncing transform failed for node ${transformNode.name}: ${e.message}...`);
}
}
}
/**
* Sets the shape of a physics body.
* @param body - The physics body to set the shape for.
* @param shape - The physics shape to set.
*
* This function is used to set the shape of a physics body. It is useful for
* creating a physics body with a specific shape, such as a box or a sphere,
* which can then be used to simulate physical interactions in a physics engine.
* This function is especially useful for meshes with multiple instances, as it
* will set the shape for each instance of the mesh.
*/
public setShape(body: PhysicsBody, shape: Nullable<PhysicsShape>): void {
const shapeHandle = shape && shape._pluginData ? shape._pluginData : BigInt(0);
if (!(body.transformNode instanceof Mesh) || !body.transformNode._thinInstanceDataStorage?.matrixData) {
this._hknp.HP_Body_SetShape(body._pluginData.hpBodyId, shapeHandle);
this._internalUpdateMassProperties(body._pluginData);
return;
}
const m = body.transformNode as Mesh;
const instancesCount = m._thinInstanceDataStorage?.instancesCount ?? 0;
for (let i = 0; i < instancesCount; i++) {
this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, shapeHandle);
this._internalUpdateMassProperties(body._pluginDataInstances[i]);
}
}
/**
* Returns a reference to the first instance of the plugin data for a physics body.
* @param body
* @param instanceIndex
* @returns a reference to the first instance
*/
private _getPluginReference(body: PhysicsBody, instanceIndex?: number): BodyPluginData {
return body._pluginDataInstances?.length ? body._pluginDataInstances[instanceIndex ?? 0] : body._pluginData;
}
/**
* Gets the shape of a physics body. This will create a new shape object
*
* @param body - The physics body.
* @returns The shape of the physics body.
*
*/
public getShape(body: PhysicsBody): Nullable<PhysicsShape> {
const pluginRef = this._getPluginReference(body);
const shapePluginData = this._hknp.HP_Body_GetShape(pluginRef.hpBodyId)[1];
if (shapePluginData != 0) {
const scene = body.transformNode.getScene();
return new PhysicsShape({ pluginData: shapePluginData }, scene);
}
return null;
}
/**
* Gets the type of a physics shape.
* @param shape - The physics shape to get the type for.
* @returns The type of the physics shape.
*
*/
public getShapeType(shape: PhysicsShape): PhysicsShapeType {
if (shape.type) {
return shape.type;
} else {
//<todo This returns a native type!
return this._hknp.HP_Shape_GetType(shape._pluginData);
}
}
/**
* Sets the event mask of a physics body.
* @param body - The physics body to set the event mask for.
* @param eventMask - The event mask to set.
*
* This function is useful for setting the event mask of a physics body, which is used to determine which events the body will respond to. This is important for ensuring that the physics engine is able to accurately simulate the behavior of the body in the game world.
*/
public setEventMask(body: PhysicsBody, eventMask: number, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(bodyPluginData) => {
this._hknp.HP_Body_SetEventMask(bodyPluginData.hpBodyId, eventMask);
},
instanceIndex
);
}
/**
* Retrieves the event mask of a physics body.
*
* @param body - The physics body to retrieve the event mask from.
* @returns The event mask of the physics body.
*
*/
public getEventMask(body: PhysicsBody, instanceIndex?: number): number {
const pluginRef = this._getPluginReference(body, instanceIndex);
return this._hknp.HP_Body_GetEventMask(pluginRef.hpBodyId)[1];
}
private _fromMassPropertiesTuple(massPropsTuple: any[]): PhysicsMassProperties {
return {
centerOfMass: Vector3.FromArray(massPropsTuple[0]),
mass: massPropsTuple[1],
inertia: Vector3.FromArray(massPropsTuple[2]),
inertiaOrientation: Quaternion.FromArray(massPropsTuple[3]),
};
}
private _internalUpdateMassProperties(pluginData: BodyPluginData) {
// Recompute the mass based on the shape
const newProps = this._internalComputeMassProperties(pluginData);
const massProps = pluginData.userMassProps;
// Override the computed values with any the user has set
if (massProps.centerOfMass) {
newProps[0] = massProps.centerOfMass.asArray();
}
if (massProps.mass != undefined) {
newProps[1] = massProps.mass;
}
if (massProps.inertia) {
newProps[2] = massProps.inertia.asArray();
}
if (massProps.inertiaOrientation) {
newProps[3] = massProps.inertiaOrientation.asArray();
}
this._hknp.HP_Body_SetMassProperties(pluginData.hpBodyId, newProps);
}
public _internalSetMotionType(pluginData: BodyPluginData, motionType: PhysicsMotionType): void {
switch (motionType) {
case PhysicsMotionType.STATIC:
this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.STATIC);
break;
case PhysicsMotionType.ANIMATED:
this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.KINEMATIC);
break;
case PhysicsMotionType.DYNAMIC:
this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.DYNAMIC);
break;
}
}
public setMotionType(body: PhysicsBody, motionType: PhysicsMotionType, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginData) => {
this._internalSetMotionType(pluginData, motionType);
},
instanceIndex
);
}
public getMotionType(body: PhysicsBody, instanceIndex?: number): PhysicsMotionType {
const pluginRef = this._getPluginReference(body, instanceIndex);
const type = this._hknp.HP_Body_GetMotionType(pluginRef.hpBodyId)[1];
switch (type) {
case this._hknp.MotionType.STATIC:
return PhysicsMotionType.STATIC;
case this._hknp.MotionType.KINEMATIC:
return PhysicsMotionType.ANIMATED;
case this._hknp.MotionType.DYNAMIC:
return PhysicsMotionType.DYNAMIC;
}
throw new Error("Unknown motion type: " + type);
}
private _internalComputeMassProperties(pluginData: BodyPluginData): any[] {
const shapeRes = this._hknp.HP_Body_GetShape(pluginData.hpBodyId);
if (shapeRes[0] == this._hknp.Result.RESULT_OK) {
const shapeMass = this._hknp.HP_Shape_BuildMassProperties(shapeRes[1]);
if (shapeMass[0] == this._hknp.Result.RESULT_OK) {
return shapeMass[1];
}
}
// Failed; return a unit inertia
return [[0, 0, 0], 1, [1, 1, 1], [0, 0, 0, 1]];
}
/**
* Computes the mass properties of a physics body, from it's shape
*
* @param body - The physics body to copmute the mass properties of
*/
public computeMassProperties(body: PhysicsBody, instanceIndex?: number): PhysicsMassProperties {
const pluginRef = this._getPluginReference(body, instanceIndex);
const computed = this._internalComputeMassProperties(pluginRef);
return this._fromMassPropertiesTuple(computed);
}
/**
* Sets the mass properties of a physics body.
*
* @param body - The physics body to set the mass properties of.
* @param massProps - The mass properties to set.
* @param instanceIndex - The index of the instance to set the mass properties of. If undefined, the mass properties of all the bodies will be set.
* This function is useful for setting the mass properties of a physics body,
* such as its mass, inertia, and center of mass. This is important for
* accurately simulating the physics of the body in the physics engine.
*
*/
public setMassProperties(body: PhysicsBody, massProps: PhysicsMassProperties, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginData) => {
pluginData.userMassProps = massProps;
this._internalUpdateMassProperties(pluginData);
},
instanceIndex
);
}
/**
*
*/
public getMassProperties(body: PhysicsBody, instanceIndex?: number): PhysicsMassProperties {
const pluginRef = this._getPluginReference(body, instanceIndex);
const massPropsTuple = this._hknp.HP_Body_GetMassProperties(pluginRef.hpBodyId)[1];
return this._fromMassPropertiesTuple(massPropsTuple);
}
/**
* Sets the linear damping of the given body.
* @param body - The body to set the linear damping for.
* @param damping - The linear damping to set.
*
* This method is useful for controlling the linear damping of a body in a physics engine.
* Linear damping is a force that opposes the motion of the body, and is proportional to the velocity of the body.
* This method allows the user to set the linear damping of a body, which can be used to control the motion of the body.
*/
public setLinearDamping(body: PhysicsBody, damping: number, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginData) => {
this._hknp.HP_Body_SetLinearDamping(pluginData.hpBodyId, damping);
},
instanceIndex
);
}
/**
* Gets the linear damping of the given body.
* @param body - The body to get the linear damping from.
* @returns The linear damping of the given body.
*
* This method is useful for getting the linear damping of a body in a physics engine.
* Linear damping is a force that opposes the motion of the body and is proportional to the velocity of the body.
* It is used to simulate the effects of air resistance and other forms of friction.
*/
public getLinearDamping(body: PhysicsBody, instanceIndex?: number): number {
const pluginRef = this._getPluginReference(body, instanceIndex);
return this._hknp.HP_Body_GetLinearDamping(pluginRef.hpBodyId)[1];
}
/**
* Sets the angular damping of a physics body.
* @param body - The physics body to set the angular damping for.
* @param damping - The angular damping value to set.
*
* This function is useful for controlling the angular velocity of a physics body.
* By setting the angular damping, the body's angular velocity will be reduced over time, allowing for more realistic physics simulations.
*/
public setAngularDamping(body: PhysicsBody, damping: number, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginData) => {
this._hknp.HP_Body_SetAngularDamping(pluginData.hpBodyId, damping);
},
instanceIndex
);
}
/**
* Gets the angular damping of a physics body.
* @param body - The physics body to get the angular damping from.
* @returns The angular damping of the body.
*
* This function is useful for retrieving the angular damping of a physics body,
* which is used to control the rotational motion of the body. The angular damping is a value between 0 and 1, where 0 is no damping and 1 is full damping.
*/
public getAngularDamping(body: PhysicsBody, instanceIndex?: number): number {
const pluginRef = this._getPluginReference(body, instanceIndex);
return this._hknp.HP_Body_GetAngularDamping(pluginRef.hpBodyId)[1];
}
/**
* Sets the linear velocity of a physics body.
* @param body - The physics body to set the linear velocity of.
* @param linVel - The linear velocity to set.
*
* This function is useful for setting the linear velocity of a physics body, which is necessary for simulating
* motion in a physics engine. The linear velocity is the speed and direction of the body's movement.
*/
public setLinearVelocity(body: PhysicsBody, linVel: Vector3, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginData) => {
this._hknp.HP_Body_SetLinearVelocity(pluginData.hpBodyId, this._bVecToV3(linVel));
},
instanceIndex
);
}
/**
* Gets the linear velocity of a physics body and stores it in a given vector.
* @param body - The physics body to get the linear velocity from.
* @param linVel - The vector to store the linear velocity in.
*
* This function is useful for retrieving the linear velocity of a physics body,
* which can be used to determine the speed and direction of the body. This
* information can be used to simulate realistic physics behavior in a game.
*/
public getLinearVelocityToRef(body: PhysicsBody, linVel: Vector3, instanceIndex?: number): void {
const pluginRef = this._getPluginReference(body, instanceIndex);
const lv = this._hknp.HP_Body_GetLinearVelocity(pluginRef.hpBodyId)[1];
this._v3ToBvecRef(lv, linVel);
}
/*
* Apply an operation either to all instances of a body, if instanceIndex is not specified, or to a specific instance.
*/
private _applyToBodyOrInstances(body: PhysicsBody, fnToApply: (pluginRef: any) => void, instanceIndex?: number): void {
if (body._pluginDataInstances?.length > 0 && instanceIndex === undefined) {
for (let i = 0; i < body._pluginDataInstances.length; i++) {
fnToApply(body._pluginDataInstances[i]);
}
} else {
fnToApply(this._getPluginReference(body, instanceIndex));
}
}
/**
* Applies an impulse to a physics body at a given location.
* @param body - The physics body to apply the impulse to.
* @param impulse - The impulse vector to apply.
* @param location - The location in world space to apply the impulse.
* @param instanceIndex - The index of the instance to apply the impulse to. If not specified, the impulse will be applied to all instances.
*
* This method is useful for applying an impulse to a physics body at a given location.
* This can be used to simulate physical forces such as explosions, collisions, and gravity.
*/
public applyImpulse(body: PhysicsBody, impulse: Vector3, location: Vector3, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginRef) => {
this._hknp.HP_Body_ApplyImpulse(pluginRef.hpBodyId, this._bVecToV3(location), this._bVecToV3(impulse));
},
instanceIndex
);
}
/**
* Applies a force to a physics body at a given location.
* @param body - The physics body to apply the impulse to.
* @param force - The force vector to apply.
* @param location - The location in world space to apply the impulse.
* @param instanceIndex - The index of the instance to apply the force to. If not specified, the force will be applied to all instances.
*
* This method is useful for applying a force to a physics body at a given location.
* This can be used to simulate physical forces such as explosions, collisions, and gravity.
*/
public applyForce(body: PhysicsBody, force: Vector3, location: Vector3, instanceIndex?: number): void {
force.scaleToRef(this.getTimeStep(), this._tmpVec3[0]);
this.applyImpulse(body, this._tmpVec3[0], location, instanceIndex);
}
/**
* Sets the angular velocity of a physics body.
*
* @param body - The physics body to set the angular velocity of.
* @param angVel - The angular velocity to set.
*
* This function is useful for setting the angular velocity of a physics body in a physics engine.
* This allows for more realistic simulations of physical objects, as they can be given a rotational velocity.
*/
public setAngularVelocity(body: PhysicsBody, angVel: Vector3, instanceIndex?: number): void {
this._applyToBodyOrInstances(
body,
(pluginRef) => {
this._hknp.HP_Body_SetAngularVelocity(pluginRef.hpBodyId, this._bVecToV3(angVel));
},
instanceIndex
);
}