-
Notifications
You must be signed in to change notification settings - Fork 719
/
Copy pathBody.js
926 lines (788 loc) · 25.6 KB
/
Body.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
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
module.exports = Body;
var EventTarget = require('../utils/EventTarget');
var Shape = require('../shapes/Shape');
var Vec3 = require('../math/Vec3');
var Mat3 = require('../math/Mat3');
var Quaternion = require('../math/Quaternion');
var Material = require('../material/Material');
var AABB = require('../collision/AABB');
var Box = require('../shapes/Box');
/**
* Base class for all body types.
* @class Body
* @constructor
* @extends EventTarget
* @param {object} [options]
* @param {Vec3} [options.position]
* @param {Vec3} [options.velocity]
* @param {Vec3} [options.angularVelocity]
* @param {Quaternion} [options.quaternion]
* @param {number} [options.mass]
* @param {Material} [options.material]
* @param {number} [options.type]
* @param {number} [options.linearDamping=0.01]
* @param {number} [options.angularDamping=0.01]
* @param {boolean} [options.allowSleep=true]
* @param {number} [options.sleepSpeedLimit=0.1]
* @param {number} [options.sleepTimeLimit=1]
* @param {number} [options.collisionFilterGroup=1]
* @param {number} [options.collisionFilterMask=-1]
* @param {boolean} [options.fixedRotation=false]
* @param {Vec3} [options.linearFactor]
* @param {Vec3} [options.angularFactor]
* @param {Shape} [options.shape]
* @example
* var body = new Body({
* mass: 1
* });
* var shape = new Sphere(1);
* body.addShape(shape);
* world.addBody(body);
*/
function Body(options){
options = options || {};
EventTarget.apply(this);
this.id = Body.idCounter++;
/**
* Reference to the world the body is living in
* @property world
* @type {World}
*/
this.world = null;
/**
* Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object.
* @property preStep
* @type {Function}
* @deprecated Use World events instead
*/
this.preStep = null;
/**
* Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
* @property postStep
* @type {Function}
* @deprecated Use World events instead
*/
this.postStep = null;
this.vlambda = new Vec3();
/**
* @property {Number} collisionFilterGroup
*/
this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;
/**
* @property {Number} collisionFilterMask
*/
this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : -1;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
* @property {Number} collisionResponse
*/
this.collisionResponse = true;
/**
* World space position of the body.
* @property position
* @type {Vec3}
*/
this.position = new Vec3();
/**
* @property {Vec3} previousPosition
*/
this.previousPosition = new Vec3();
/**
* Interpolated position of the body.
* @property {Vec3} interpolatedPosition
*/
this.interpolatedPosition = new Vec3();
/**
* Initial position of the body
* @property initPosition
* @type {Vec3}
*/
this.initPosition = new Vec3();
if(options.position){
this.position.copy(options.position);
this.previousPosition.copy(options.position);
this.interpolatedPosition.copy(options.position);
this.initPosition.copy(options.position);
}
/**
* World space velocity of the body.
* @property velocity
* @type {Vec3}
*/
this.velocity = new Vec3();
if(options.velocity){
this.velocity.copy(options.velocity);
}
/**
* @property initVelocity
* @type {Vec3}
*/
this.initVelocity = new Vec3();
/**
* Linear force on the body in world space.
* @property force
* @type {Vec3}
*/
this.force = new Vec3();
var mass = typeof(options.mass) === 'number' ? options.mass : 0;
/**
* @property mass
* @type {Number}
* @default 0
*/
this.mass = mass;
/**
* @property invMass
* @type {Number}
*/
this.invMass = mass > 0 ? 1.0 / mass : 0;
/**
* @property material
* @type {Material}
*/
this.material = options.material || null;
/**
* @property linearDamping
* @type {Number}
*/
this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;
/**
* One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
* @property type
* @type {Number}
*/
this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
if(typeof(options.type) === typeof(Body.STATIC)){
this.type = options.type;
}
/**
* If true, the body will automatically fall to sleep.
* @property allowSleep
* @type {Boolean}
* @default true
*/
this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;
/**
* Current sleep state.
* @property sleepState
* @type {Number}
*/
this.sleepState = 0;
/**
* If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
* @property sleepSpeedLimit
* @type {Number}
* @default 0.1
*/
this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;
/**
* If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
* @property sleepTimeLimit
* @type {Number}
* @default 1
*/
this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;
this.timeLastSleepy = 0;
this._wakeUpAfterNarrowphase = false;
/**
* World space rotational force on the body, around center of mass.
* @property {Vec3} torque
*/
this.torque = new Vec3();
/**
* World space orientation of the body.
* @property quaternion
* @type {Quaternion}
*/
this.quaternion = new Quaternion();
/**
* @property initQuaternion
* @type {Quaternion}
*/
this.initQuaternion = new Quaternion();
/**
* @property {Quaternion} previousQuaternion
*/
this.previousQuaternion = new Quaternion();
/**
* Interpolated orientation of the body.
* @property {Quaternion} interpolatedQuaternion
*/
this.interpolatedQuaternion = new Quaternion();
if(options.quaternion){
this.quaternion.copy(options.quaternion);
this.initQuaternion.copy(options.quaternion);
this.previousQuaternion.copy(options.quaternion);
this.interpolatedQuaternion.copy(options.quaternion);
}
/**
* Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
* @property angularVelocity
* @type {Vec3}
*/
this.angularVelocity = new Vec3();
if(options.angularVelocity){
this.angularVelocity.copy(options.angularVelocity);
}
/**
* @property initAngularVelocity
* @type {Vec3}
*/
this.initAngularVelocity = new Vec3();
/**
* @property shapes
* @type {array}
*/
this.shapes = [];
/**
* Position of each Shape in the body, given in local Body space.
* @property shapeOffsets
* @type {array}
*/
this.shapeOffsets = [];
/**
* Orientation of each Shape, given in local Body space.
* @property shapeOrientations
* @type {array}
*/
this.shapeOrientations = [];
/**
* @property inertia
* @type {Vec3}
*/
this.inertia = new Vec3();
/**
* @property {Vec3} invInertia
*/
this.invInertia = new Vec3();
/**
* @property {Mat3} invInertiaWorld
*/
this.invInertiaWorld = new Mat3();
this.invMassSolve = 0;
/**
* @property {Vec3} invInertiaSolve
*/
this.invInertiaSolve = new Vec3();
/**
* @property {Mat3} invInertiaWorldSolve
*/
this.invInertiaWorldSolve = new Mat3();
/**
* Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
* @property {Boolean} fixedRotation
* @default false
*/
this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;
/**
* @property {Number} angularDamping
*/
this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;
/**
* Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
* @property {Vec3} linearFactor
*/
this.linearFactor = new Vec3(1,1,1);
if(options.linearFactor){
this.linearFactor.copy(options.linearFactor);
}
/**
* Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
* @property {Vec3} angularFactor
*/
this.angularFactor = new Vec3(1,1,1);
if(options.angularFactor){
this.angularFactor.copy(options.angularFactor);
}
/**
* World space bounding box of the body and its shapes.
* @property aabb
* @type {AABB}
*/
this.aabb = new AABB();
/**
* Indicates if the AABB needs to be updated before use.
* @property aabbNeedsUpdate
* @type {Boolean}
*/
this.aabbNeedsUpdate = true;
this.wlambda = new Vec3();
if(options.shape){
this.addShape(options.shape);
}
this.updateMassProperties();
}
Body.prototype = new EventTarget();
Body.prototype.constructor = Body;
/**
* Dispatched after two bodies collide. This event is dispatched on each
* of the two bodies involved in the collision.
* @event collide
* @param {Body} body The body that was involved in the collision.
* @param {ContactEquation} contact The details of the collision.
*/
Body.COLLIDE_EVENT_NAME = "collide";
/**
* A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
* @static
* @property DYNAMIC
* @type {Number}
*/
Body.DYNAMIC = 1;
/**
* A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
* @static
* @property STATIC
* @type {Number}
*/
Body.STATIC = 2;
/**
* A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
* @static
* @property KINEMATIC
* @type {Number}
*/
Body.KINEMATIC = 4;
/**
* @static
* @property AWAKE
* @type {number}
*/
Body.AWAKE = 0;
/**
* @static
* @property SLEEPY
* @type {number}
*/
Body.SLEEPY = 1;
/**
* @static
* @property SLEEPING
* @type {number}
*/
Body.SLEEPING = 2;
Body.idCounter = 0;
/**
* Dispatched after a sleeping body has woken up.
* @event wakeup
*/
Body.wakeupEvent = {
type: "wakeup"
};
/**
* Wake the body up.
* @method wakeUp
*/
Body.prototype.wakeUp = function(){
var s = this.sleepState;
this.sleepState = 0;
this._wakeUpAfterNarrowphase = false;
if(s === Body.SLEEPING){
this.dispatchEvent(Body.wakeupEvent);
}
};
/**
* Force body sleep
* @method sleep
*/
Body.prototype.sleep = function(){
this.sleepState = Body.SLEEPING;
this.velocity.set(0,0,0);
this.angularVelocity.set(0,0,0);
this._wakeUpAfterNarrowphase = false;
};
/**
* Dispatched after a body has gone in to the sleepy state.
* @event sleepy
*/
Body.sleepyEvent = {
type: "sleepy"
};
/**
* Dispatched after a body has fallen asleep.
* @event sleep
*/
Body.sleepEvent = {
type: "sleep"
};
/**
* Called every timestep to update internal sleep timer and change sleep state if needed.
* @method sleepTick
* @param {Number} time The world time in seconds
*/
Body.prototype.sleepTick = function(time){
if(this.allowSleep){
var sleepState = this.sleepState;
var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
this.sleepState = Body.SLEEPY; // Sleepy
this.timeLastSleepy = time;
this.dispatchEvent(Body.sleepyEvent);
} else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
this.wakeUp(); // Wake up
} else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
this.sleep(); // Sleeping
this.dispatchEvent(Body.sleepEvent);
}
}
};
/**
* If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
* @method updateSolveMassProperties
*/
Body.prototype.updateSolveMassProperties = function(){
if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
this.invMassSolve = 0;
this.invInertiaSolve.setZero();
this.invInertiaWorldSolve.setZero();
} else {
this.invMassSolve = this.invMass;
this.invInertiaSolve.copy(this.invInertia);
this.invInertiaWorldSolve.copy(this.invInertiaWorld);
}
};
/**
* Convert a world point to local body frame.
* @method pointToLocalFrame
* @param {Vec3} worldPoint
* @param {Vec3} result
* @return {Vec3}
*/
Body.prototype.pointToLocalFrame = function(worldPoint,result){
var result = result || new Vec3();
worldPoint.vsub(this.position,result);
this.quaternion.conjugate().vmult(result,result);
return result;
};
/**
* Convert a world vector to local body frame.
* @method vectorToLocalFrame
* @param {Vec3} worldPoint
* @param {Vec3} result
* @return {Vec3}
*/
Body.prototype.vectorToLocalFrame = function(worldVector, result){
var result = result || new Vec3();
this.quaternion.conjugate().vmult(worldVector,result);
return result;
};
/**
* Convert a local body point to world frame.
* @method pointToWorldFrame
* @param {Vec3} localPoint
* @param {Vec3} result
* @return {Vec3}
*/
Body.prototype.pointToWorldFrame = function(localPoint,result){
var result = result || new Vec3();
this.quaternion.vmult(localPoint,result);
result.vadd(this.position,result);
return result;
};
/**
* Convert a local body point to world frame.
* @method vectorToWorldFrame
* @param {Vec3} localVector
* @param {Vec3} result
* @return {Vec3}
*/
Body.prototype.vectorToWorldFrame = function(localVector, result){
var result = result || new Vec3();
this.quaternion.vmult(localVector, result);
return result;
};
var tmpVec = new Vec3();
var tmpQuat = new Quaternion();
/**
* Add a shape to the body with a local offset and orientation.
* @method addShape
* @param {Shape} shape
* @param {Vec3} [_offset]
* @param {Quaternion} [_orientation]
* @return {Body} The body object, for chainability.
*/
Body.prototype.addShape = function(shape, _offset, _orientation){
var offset = new Vec3();
var orientation = new Quaternion();
if(_offset){
offset.copy(_offset);
}
if(_orientation){
orientation.copy(_orientation);
}
this.shapes.push(shape);
this.shapeOffsets.push(offset);
this.shapeOrientations.push(orientation);
this.updateMassProperties();
this.updateBoundingRadius();
this.aabbNeedsUpdate = true;
shape.body = this;
// If the body is already in the world, add the shape to the map now.
if(this.world){
this.world.idToShapeMap[shape.id] = shape;
}
return this;
};
/**
* Update the bounding radius of the body. Should be done if any of the shapes are changed.
* @method updateBoundingRadius
*/
Body.prototype.updateBoundingRadius = function(){
var shapes = this.shapes,
shapeOffsets = this.shapeOffsets,
N = shapes.length,
radius = 0;
for(var i=0; i!==N; i++){
var shape = shapes[i];
shape.updateBoundingSphereRadius();
var offset = shapeOffsets[i].norm(),
r = shape.boundingSphereRadius;
if(offset + r > radius){
radius = offset + r;
}
}
this.boundingRadius = radius;
};
var computeAABB_shapeAABB = new AABB();
/**
* Updates the .aabb
* @method computeAABB
* @todo rename to updateAABB()
*/
Body.prototype.computeAABB = function(){
var shapes = this.shapes,
shapeOffsets = this.shapeOffsets,
shapeOrientations = this.shapeOrientations,
N = shapes.length,
offset = tmpVec,
orientation = tmpQuat,
bodyQuat = this.quaternion,
aabb = this.aabb,
shapeAABB = computeAABB_shapeAABB;
for(var i=0; i!==N; i++){
var shape = shapes[i];
// Get shape world position
bodyQuat.vmult(shapeOffsets[i], offset);
offset.vadd(this.position, offset);
// Get shape world quaternion
shapeOrientations[i].mult(bodyQuat, orientation);
// Get shape AABB
shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
if(i === 0){
aabb.copy(shapeAABB);
} else {
aabb.extend(shapeAABB);
}
}
this.aabbNeedsUpdate = false;
};
var uiw_m1 = new Mat3(),
uiw_m2 = new Mat3(),
uiw_m3 = new Mat3();
/**
* Update .inertiaWorld and .invInertiaWorld
* @method updateInertiaWorld
*/
Body.prototype.updateInertiaWorld = function(force){
var I = this.invInertia;
if (I.x === I.y && I.y === I.z && !force) {
// If inertia M = s*I, where I is identity and s a scalar, then
// R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
// where R is the rotation matrix.
// In other words, we don't have to transform the inertia if all
// inertia diagonal entries are equal.
} else {
var m1 = uiw_m1,
m2 = uiw_m2,
m3 = uiw_m3;
m1.setRotationFromQuaternion(this.quaternion);
m1.transpose(m2);
m1.scale(I,m1);
m1.mmult(m2,this.invInertiaWorld);
}
};
/**
* Apply force to a world point. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.torque.
* @method applyForce
* @param {Vec3} force The amount of force to add.
* @param {Vec3} relativePoint A point relative to the center of mass to apply the force on.
*/
var Body_applyForce_r = new Vec3();
var Body_applyForce_rotForce = new Vec3();
Body.prototype.applyForce = function(force,relativePoint){
if(this.type !== Body.DYNAMIC){ // Needed?
return;
}
// Compute produced rotational force
var rotForce = Body_applyForce_rotForce;
relativePoint.cross(force,rotForce);
// Add linear force
this.force.vadd(force,this.force);
// Add rotational force
this.torque.vadd(rotForce,this.torque);
};
/**
* Apply force to a local point in the body.
* @method applyLocalForce
* @param {Vec3} force The force vector to apply, defined locally in the body frame.
* @param {Vec3} localPoint A local point in the body to apply the force on.
*/
var Body_applyLocalForce_worldForce = new Vec3();
var Body_applyLocalForce_relativePointWorld = new Vec3();
Body.prototype.applyLocalForce = function(localForce, localPoint){
if(this.type !== Body.DYNAMIC){
return;
}
var worldForce = Body_applyLocalForce_worldForce;
var relativePointWorld = Body_applyLocalForce_relativePointWorld;
// Transform the force vector to world space
this.vectorToWorldFrame(localForce, worldForce);
this.vectorToWorldFrame(localPoint, relativePointWorld);
this.applyForce(worldForce, relativePointWorld);
};
/**
* Apply impulse to a world point. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
* @method applyImpulse
* @param {Vec3} impulse The amount of impulse to add.
* @param {Vec3} relativePoint A point relative to the center of mass to apply the force on.
*/
var Body_applyImpulse_r = new Vec3();
var Body_applyImpulse_velo = new Vec3();
var Body_applyImpulse_rotVelo = new Vec3();
Body.prototype.applyImpulse = function(impulse, relativePoint){
if(this.type !== Body.DYNAMIC){
return;
}
// Compute point position relative to the body center
var r = relativePoint;
// Compute produced central impulse velocity
var velo = Body_applyImpulse_velo;
velo.copy(impulse);
velo.mult(this.invMass,velo);
// Add linear impulse
this.velocity.vadd(velo, this.velocity);
// Compute produced rotational impulse velocity
var rotVelo = Body_applyImpulse_rotVelo;
r.cross(impulse,rotVelo);
/*
rotVelo.x *= this.invInertia.x;
rotVelo.y *= this.invInertia.y;
rotVelo.z *= this.invInertia.z;
*/
this.invInertiaWorld.vmult(rotVelo,rotVelo);
// Add rotational Impulse
this.angularVelocity.vadd(rotVelo, this.angularVelocity);
};
/**
* Apply locally-defined impulse to a local point in the body.
* @method applyLocalImpulse
* @param {Vec3} force The force vector to apply, defined locally in the body frame.
* @param {Vec3} localPoint A local point in the body to apply the force on.
*/
var Body_applyLocalImpulse_worldImpulse = new Vec3();
var Body_applyLocalImpulse_relativePoint = new Vec3();
Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
if(this.type !== Body.DYNAMIC){
return;
}
var worldImpulse = Body_applyLocalImpulse_worldImpulse;
var relativePointWorld = Body_applyLocalImpulse_relativePoint;
// Transform the force vector to world space
this.vectorToWorldFrame(localImpulse, worldImpulse);
this.vectorToWorldFrame(localPoint, relativePointWorld);
this.applyImpulse(worldImpulse, relativePointWorld);
};
var Body_updateMassProperties_halfExtents = new Vec3();
/**
* Should be called whenever you change the body shape or mass.
* @method updateMassProperties
*/
Body.prototype.updateMassProperties = function(){
var halfExtents = Body_updateMassProperties_halfExtents;
this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
var I = this.inertia;
var fixed = this.fixedRotation;
// Approximate with AABB box
this.computeAABB();
halfExtents.set(
(this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
(this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
(this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
);
Box.calculateInertia(halfExtents, this.mass, I);
this.invInertia.set(
I.x > 0 && !fixed ? 1.0 / I.x : 0,
I.y > 0 && !fixed ? 1.0 / I.y : 0,
I.z > 0 && !fixed ? 1.0 / I.z : 0
);
this.updateInertiaWorld(true);
};
/**
* Get world velocity of a point in the body.
* @method getVelocityAtWorldPoint
* @param {Vec3} worldPoint
* @param {Vec3} result
* @return {Vec3} The result vector.
*/
Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
var r = new Vec3();
worldPoint.vsub(this.position, r);
this.angularVelocity.cross(r, result);
this.velocity.vadd(result, result);
return result;
};
var torque = new Vec3();
var invI_tau_dt = new Vec3();
var w = new Quaternion();
var wq = new Quaternion();
/**
* Move the body forward in time.
* @param {number} dt Time step
* @param {boolean} quatNormalize Set to true to normalize the body quaternion
* @param {boolean} quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
*/
Body.prototype.integrate = function(dt, quatNormalize, quatNormalizeFast){
// Save previous position
this.previousPosition.copy(this.position);
this.previousQuaternion.copy(this.quaternion);
if(!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING){ // Only for dynamic
return;
}
var velo = this.velocity,
angularVelo = this.angularVelocity,
pos = this.position,
force = this.force,
torque = this.torque,
quat = this.quaternion,
invMass = this.invMass,
invInertia = this.invInertiaWorld,
linearFactor = this.linearFactor;
var iMdt = invMass * dt;
velo.x += force.x * iMdt * linearFactor.x;
velo.y += force.y * iMdt * linearFactor.y;
velo.z += force.z * iMdt * linearFactor.z;
var e = invInertia.elements;
var angularFactor = this.angularFactor;
var tx = torque.x * angularFactor.x;
var ty = torque.y * angularFactor.y;
var tz = torque.z * angularFactor.z;
angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);
angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);
angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz);
// Use new velocity - leap frog
pos.x += velo.x * dt;
pos.y += velo.y * dt;
pos.z += velo.z * dt;
quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);
if(quatNormalize){
if(quatNormalizeFast){
quat.normalizeFast();
} else {
quat.normalize();
}
}
this.aabbNeedsUpdate = true;
// Update world inertia
this.updateInertiaWorld();
};