/
component.js
733 lines (641 loc) · 22.4 KB
/
component.js
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
import { Quat } from '../../../core/math/quat.js';
import { Vec3 } from '../../../core/math/vec3.js';
import { Asset } from '../../asset/asset.js';
import { Component } from '../component.js';
const _vec3 = new Vec3();
const _quat = new Quat();
/**
* A collision volume. Use this in conjunction with a {@link RigidBodyComponent} to make a
* collision volume that can be simulated using the physics engine.
*
* If the {@link Entity} does not have a {@link RigidBodyComponent} then this collision volume will
* act as a trigger volume. When an entity with a dynamic or kinematic body enters or leaves an
* entity with a trigger volume, both entities will receive trigger events.
*
* The following table shows all the events that can be fired between two Entities:
*
* | | Rigid Body (Static) | Rigid Body (Dynamic or Kinematic) | Trigger Volume |
* | ------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------- |
* | **Rigid Body (Static)** | | <ul><li>contact</li><li>collisionstart</li><li>collisionend</li></ul> | |
* | **Rigid Body (Dynamic or Kinematic)** | <ul><li>contact</li><li>collisionstart</li><li>collisionend</li></ul> | <ul><li>contact</li><li>collisionstart</li><li>collisionend</li></ul> | <ul><li>triggerenter</li><li>triggerleave</li></ul> |
* | **Trigger Volume** | | <ul><li>triggerenter</li><li>triggerleave</li></ul> | |
*
* @category Physics
*/
class CollisionComponent extends Component {
/**
* Fired when a contact occurs between two rigid bodies. The handler is passed a
* {@link ContactResult} object which contains details of the contact between the two rigid
* bodies.
*
* @event
* @example
* entity.collision.on('contact', (result) => {
* console.log(`Contact between ${entity.name} and ${result.other.name}`);
* });
*/
static EVENT_CONTACT = 'contact';
/**
* Fired when two rigid bodies start touching. The handler is passed the {@link ContactResult}
* object which contains details of the contact between the two rigid bodies.
*
* @event
* @example
* entity.collision.on('collisionstart', (result) => {
* console.log(`${entity.name} started touching ${result.other.name}`);
* });
*/
static EVENT_COLLISIONSTART = 'collisionstart';
/**
* Fired two rigid-bodies stop touching. The handler is passed an {@link Entity} that
* represents the other rigid body involved in the collision.
*
* @event
* @example
* entity.collision.on('collisionend', (other) => {
* console.log(`${entity.name} stopped touching ${other.name}`);
* });
*/
static EVENT_COLLISIONEND = 'collisionend';
/**
* Fired when a rigid body enters a trigger volume. The handler is passed an {@link Entity}
* representing the rigid body that entered this collision volume.
*
* @event
* @example
* entity.collision.on('triggerenter', (other) => {
* console.log(`${other.name} entered trigger volume ${entity.name}`);
* });
*/
static EVENT_TRIGGERENTER = 'triggerenter';
/**
* Fired when a rigid body exits a trigger volume. The handler is passed an {@link Entity}
* representing the rigid body that exited this collision volume.
*
* @event
* @example
* entity.collision.on('triggerleave', (other) => {
* console.log(`${other.name} exited trigger volume ${entity.name}`);
* });
*/
static EVENT_TRIGGERLEAVE = 'triggerleave';
/**
* Create a new CollisionComponent.
*
* @param {import('./system.js').CollisionComponentSystem} system - The ComponentSystem that
* created this Component.
* @param {import('../../entity.js').Entity} entity - The Entity that this Component is
* attached to.
*/
constructor(system, entity) {
super(system, entity);
/** @private */
this._compoundParent = null;
this._hasOffset = false;
this.entity.on('insert', this._onInsert, this);
this.on('set_type', this.onSetType, this);
this.on('set_convexHull', this.onSetModel, this);
this.on('set_halfExtents', this.onSetHalfExtents, this);
this.on('set_linearOffset', this.onSetOffset, this);
this.on('set_angularOffset', this.onSetOffset, this);
this.on('set_radius', this.onSetRadius, this);
this.on('set_height', this.onSetHeight, this);
this.on('set_axis', this.onSetAxis, this);
this.on('set_asset', this.onSetAsset, this);
this.on('set_renderAsset', this.onSetRenderAsset, this);
this.on('set_model', this.onSetModel, this);
this.on('set_render', this.onSetRender, this);
}
// TODO: Remove this override in upgrading component
/**
* @type {import('./data.js').CollisionComponentData}
* @ignore
*/
get data() {
const record = this.system.store[this.entity.getGuid()];
return record ? record.data : null;
}
/**
* @type {boolean}
*/
set enabled(arg) {
this._setValue('enabled', arg);
}
get enabled() {
return this.data.enabled;
}
/**
* The type of the collision volume. Can be:
*
* - "box": A box-shaped collision volume.
* - "capsule": A capsule-shaped collision volume.
* - "compound": A compound shape. Any descendant entities with a collision component of type
* box, capsule, cone, cylinder or sphere will be combined into a single, rigid shape.
* - "cone": A cone-shaped collision volume. - "cylinder": A cylinder-shaped collision volume.
* - "mesh": A collision volume that uses a model asset as its shape.
* - "sphere": A sphere-shaped collision volume.
*
* Defaults to "box".
*
* @type {string}
*/
set type(arg) {
this._setValue('type', arg);
}
get type() {
return this.data.type;
}
/**
* The half-extents of the box-shaped collision volume in the x, y and z axes. Defaults to
* [0.5, 0.5, 0.5].
*
* @type {Vec3}
*/
set halfExtents(arg) {
this._setValue('halfExtents', arg);
}
get halfExtents() {
return this.data.halfExtents;
}
/**
* The positional offset of the collision shape from the Entity position along the local axes.
* Defaults to [0, 0, 0].
*
* @type {Vec3}
*/
set linearOffset(arg) {
this._setValue('linearOffset', arg);
}
get linearOffset() {
return this.data.linearOffset;
}
/**
* The rotational offset of the collision shape from the Entity rotation in local space.
* Defaults to identity.
*
* @type {Quat}
*/
set angularOffset(arg) {
this._setValue('angularOffset', arg);
}
get angularOffset() {
return this.data.angularOffset;
}
/**
* The radius of the sphere, capsule, cylinder or cone-shaped collision volumes.
* Defaults to 0.5.
*
* @type {number}
*/
set radius(arg) {
this._setValue('radius', arg);
}
get radius() {
return this.data.radius;
}
/**
* The local space axis with which the capsule, cylinder or cone-shaped collision volume's
* length is aligned. 0 for X, 1 for Y and 2 for Z. Defaults to 1 (Y-axis).
*
* @type {number}
*/
set axis(arg) {
this._setValue('axis', arg);
}
get axis() {
return this.data.axis;
}
/**
* The total height of the capsule, cylinder or cone-shaped collision volume from tip to tip.
* Defaults to 2.
*
* @type {number}
*/
set height(arg) {
this._setValue('height', arg);
}
get height() {
return this.data.height;
}
/**
* The asset for the model of the mesh collision volume - can also be an asset id. Defaults to
* null.
*
* @type {Asset}
*/
set asset(arg) {
this._setValue('asset', arg);
}
get asset() {
return this.data.asset;
}
/**
* The render asset of the mesh collision volume - can also be an asset id. Defaults to null.
* If not set then the asset property will be checked instead.
*
* @type {Asset | number}
*/
set renderAsset(arg) {
this._setValue('renderAsset', arg);
}
get renderAsset() {
return this.data.renderAsset;
}
/**
* Whether the collision mesh should be treated as a convex hull. When false, the mesh can only
* be used with a static body. When true, the mesh can be used with a static, dynamic or
* kinematic body. Defaults to `false`.
*
* @type {boolean}
*/
set convexHull(arg) {
this._setValue('convexHull', arg);
}
get convexHull() {
return this.data.convexHull;
}
/**
* @type {any}
* @ignore
*/
set shape(arg) {
this._setValue('shape', arg);
}
get shape() {
return this.data.shape;
}
/**
* The model that is added to the scene graph for the mesh collision volume.
*
* @type {import('../../../scene/model.js').Model | null}
*/
set model(arg) {
this._setValue('model', arg);
}
get model() {
return this.data.model;
}
/**
* @type {any}
* @ignore
*/
set render(arg) {
this._setValue('render', arg);
}
get render() {
return this.data.render;
}
/**
* Enable checking for duplicate vertices.
*
* @type {boolean}
*/
set checkVertexDuplicates(arg) {
this._setValue('checkVertexDuplicates', arg);
}
get checkVertexDuplicates() {
return this.data.checkVertexDuplicates;
}
/** @ignore */
_setValue(name, value) {
const data = this.data;
const oldValue = data[name];
data[name] = value;
this.fire('set', name, oldValue, value);
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetType(name, oldValue, newValue) {
if (oldValue !== newValue) {
this.system.changeType(this, oldValue, newValue);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetHalfExtents(name, oldValue, newValue) {
const t = this.data.type;
if (this.data.initialized && t === 'box') {
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetOffset(name, oldValue, newValue) {
this._hasOffset =
!this.data.linearOffset.equals(Vec3.ZERO) ||
!this.data.angularOffset.equals(Quat.IDENTITY);
if (this.data.initialized) {
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetRadius(name, oldValue, newValue) {
const t = this.data.type;
if (this.data.initialized && (t === 'sphere' || t === 'capsule' || t === 'cylinder' || t === 'cone')) {
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetHeight(name, oldValue, newValue) {
const t = this.data.type;
if (this.data.initialized && (t === 'capsule' || t === 'cylinder' || t === 'cone')) {
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetAxis(name, oldValue, newValue) {
const t = this.data.type;
if (this.data.initialized && (t === 'capsule' || t === 'cylinder' || t === 'cone')) {
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetAsset(name, oldValue, newValue) {
const assets = this.system.app.assets;
if (oldValue) {
// Remove old listeners
const asset = assets.get(oldValue);
if (asset) {
asset.off('remove', this.onAssetRemoved, this);
}
}
if (newValue) {
if (newValue instanceof Asset) {
this.data.asset = newValue.id;
}
const asset = assets.get(this.data.asset);
if (asset) {
// make sure we don't subscribe twice
asset.off('remove', this.onAssetRemoved, this);
asset.on('remove', this.onAssetRemoved, this);
}
}
if (this.data.initialized && this.data.type === 'mesh') {
if (!newValue) {
// if asset is null set model to null
// so that it's going to be removed from the simulation
this.data.model = null;
}
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetRenderAsset(name, oldValue, newValue) {
const assets = this.system.app.assets;
if (oldValue) {
// Remove old listeners
const asset = assets.get(oldValue);
if (asset) {
asset.off('remove', this.onRenderAssetRemoved, this);
}
}
if (newValue) {
if (newValue instanceof Asset) {
this.data.renderAsset = newValue.id;
}
const asset = assets.get(this.data.renderAsset);
if (asset) {
// make sure we don't subscribe twice
asset.off('remove', this.onRenderAssetRemoved, this);
asset.on('remove', this.onRenderAssetRemoved, this);
}
}
if (this.data.initialized && this.data.type === 'mesh') {
if (!newValue) {
// if render asset is null set render to null
// so that it's going to be removed from the simulation
this.data.render = null;
}
this.system.recreatePhysicalShapes(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetModel(name, oldValue, newValue) {
if (this.data.initialized && this.data.type === 'mesh') {
// recreate physical shapes skipping loading the model
// from the 'asset' as the model passed in newValue might
// have been created procedurally
this.system.implementations.mesh.doRecreatePhysicalShape(this);
}
}
/**
* @param {string} name - Property name.
* @param {*} oldValue - Previous value of the property.
* @param {*} newValue - New value of the property.
* @private
*/
onSetRender(name, oldValue, newValue) {
this.onSetModel(name, oldValue, newValue);
}
/**
* @param {Asset} asset - Asset that was removed.
* @private
*/
onAssetRemoved(asset) {
asset.off('remove', this.onAssetRemoved, this);
if (this.data.asset === asset.id) {
this.asset = null;
}
}
/**
* @param {Asset} asset - Asset that was removed.
* @private
*/
onRenderAssetRemoved(asset) {
asset.off('remove', this.onRenderAssetRemoved, this);
if (this.data.renderAsset === asset.id) {
this.renderAsset = null;
}
}
/**
* @param {*} shape - Ammo shape.
* @returns {number|null} The shape's index in the child array of the compound shape.
* @private
*/
_getCompoundChildShapeIndex(shape) {
const compound = this.data.shape;
const shapes = compound.getNumChildShapes();
for (let i = 0; i < shapes; i++) {
const childShape = compound.getChildShape(i);
if (childShape.ptr === shape.ptr) {
return i;
}
}
return null;
}
/**
* @param {import('../../../scene/graph-node.js').GraphNode} parent - The parent node.
* @private
*/
_onInsert(parent) {
// TODO
// if is child of compound shape
// and there is no change of compoundParent, then update child transform
// once updateChildTransform is exposed in ammo.js
if (typeof Ammo === 'undefined') {
return;
}
if (this._compoundParent) {
this.system.recreatePhysicalShapes(this);
} else if (!this.entity.rigidbody) {
let ancestor = this.entity.parent;
while (ancestor) {
if (ancestor.collision && ancestor.collision.type === 'compound') {
if (ancestor.collision.shape.getNumChildShapes() === 0) {
this.system.recreatePhysicalShapes(ancestor.collision);
} else {
this.system.recreatePhysicalShapes(this);
}
break;
}
ancestor = ancestor.parent;
}
}
}
/** @private */
_updateCompound() {
const entity = this.entity;
if (entity._dirtyWorld) {
let dirty = entity._dirtyLocal;
let parent = entity;
while (parent && !dirty) {
if (parent.collision && parent.collision === this._compoundParent) {
break;
}
if (parent._dirtyLocal) {
dirty = true;
}
parent = parent.parent;
}
if (dirty) {
entity.forEach(this.system.implementations.compound._updateEachDescendantTransform, entity);
const bodyComponent = this._compoundParent.entity.rigidbody;
if (bodyComponent) {
bodyComponent.activate();
}
}
}
}
/**
* @description Returns the world position for the collision shape taking into account of any offsets.
* @returns {Vec3} The world position for the collision shape.
*/
getShapePosition() {
const pos = this.entity.getPosition();
if (this._hasOffset) {
const rot = this.entity.getRotation();
const lo = this.data.linearOffset;
_quat.copy(rot).transformVector(lo, _vec3);
return _vec3.add(pos);
}
return pos;
}
/**
* @description Returns the world rotation for the collision shape taking into account of any offsets.
* @returns {Quat} The world rotation for the collision.
*/
getShapeRotation() {
const rot = this.entity.getRotation();
if (this._hasOffset) {
return _quat.copy(rot).mul(this.data.angularOffset);
}
return rot;
}
onEnable() {
if (this.data.type === 'mesh' && (this.data.asset || this.data.renderAsset) && this.data.initialized) {
const asset = this.system.app.assets.get(this.data.asset || this.data.renderAsset);
// recreate the collision shape if the model asset is not loaded
// or the shape does not exist
if (asset && (!asset.resource || !this.data.shape)) {
this.system.recreatePhysicalShapes(this);
return;
}
}
if (this.entity.rigidbody) {
if (this.entity.rigidbody.enabled) {
this.entity.rigidbody.enableSimulation();
}
} else if (this._compoundParent && this !== this._compoundParent) {
if (this._compoundParent.shape.getNumChildShapes() === 0) {
this.system.recreatePhysicalShapes(this._compoundParent);
} else {
const transform = this.system._getNodeTransform(this.entity, this._compoundParent.entity);
this._compoundParent.shape.addChildShape(transform, this.data.shape);
Ammo.destroy(transform);
if (this._compoundParent.entity.rigidbody) {
this._compoundParent.entity.rigidbody.activate();
}
}
} else if (this.entity.trigger) {
this.entity.trigger.enable();
}
}
onDisable() {
if (this.entity.rigidbody) {
this.entity.rigidbody.disableSimulation();
} else if (this._compoundParent && this !== this._compoundParent) {
if (!this._compoundParent.entity._destroying) {
this.system._removeCompoundChild(this._compoundParent, this.data.shape);
if (this._compoundParent.entity.rigidbody) {
this._compoundParent.entity.rigidbody.activate();
}
}
} else if (this.entity.trigger) {
this.entity.trigger.disable();
}
}
/** @private */
onBeforeRemove() {
if (this.asset) {
this.asset = null;
}
if (this.renderAsset) {
this.renderAsset = null;
}
this.entity.off('insert', this._onInsert, this);
this.off();
}
}
export { CollisionComponent };