remove PhyscisBody, PhysicsShape concepts, directly use RigidBodyComponent, CollidersComopnent; add Constraints.

This commit is contained in:
Leslie
2019-02-22 14:40:49 +08:00
parent 6967926a74
commit a83b1a7bdf
12 changed files with 628 additions and 651 deletions
+6 -6
View File
@@ -20,11 +20,11 @@ export class PhysicsMaterial extends Asset {
* If non-negative, it will be used instead of the friction given by ContactMaterials.
* If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
*/
get friction() {
get friction () {
return this._friction;
}
set friction(value) {
set friction (value) {
this._friction = value;
this._cannonMaterial.friction = value;
}
@@ -34,21 +34,21 @@ export class PhysicsMaterial extends Asset {
* If non-negative, it will be used instead of the restitution given by ContactMaterials.
* If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used
*/
get restitution() {
get restitution () {
return this._restitution;
}
set restitution(value) {
set restitution (value) {
this._restitution = value;
this._cannonMaterial.restitution = value;
}
constructor() {
constructor () {
super();
this._cannonMaterial = new CANNON.Material('');
}
public _getImpl() {
public _getImpl () {
return this._cannonMaterial;
}
}
+1 -2
View File
@@ -28,7 +28,7 @@ import AnimationComponent from './animation-component';
import { CameraComponent } from './camera-component';
import LightComponent from './light-component';
import { ModelComponent } from './model-component';
import { BoxColliderComponent, SphereColliderComponent, ColliderComponentBase } from './physics/collider-component';
import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component';
import { RigidBodyComponent } from './physics/rigid-body-component';
import SkinningModelComponent from './skinning-model-component';
import SkyboxComponent from './skybox-component';
@@ -56,7 +56,6 @@ cc.SkinningModelComponent = SkinningModelComponent;
cc.SkyboxComponent = SkyboxComponent;
cc.RigidBodyComponent = RigidBodyComponent;
cc.ColliderComponentBase = ColliderComponentBase;
cc.BoxColliderComponent = BoxColliderComponent;
cc.SphereColliderComponent = SphereColliderComponent;
cc.ParticleSystemComponent = ParticleSystemComponent;
-475
View File
@@ -1,475 +0,0 @@
import CANNON from 'cannon';
import { Quat } from '../../../core/value-types';
import Vec3 from '../../../core/value-types/vec3';
import { vec3 } from '../../../core/vmath';
import { Node } from '../../../scene-graph/node';
import { PhysicsMaterial as PhysicsMaterial } from '../../assets/physics/material';
import { getWrap, setWrap } from './util';
export enum DataFlow {
PUSHING,
PULLING,
}
export class PhysicsBody {
private _node: Node | null = null;
private _material: PhysicsMaterial | null = null;
private _cannonBody: CANNON.Body;
private _onCollidedListener: (event: CANNON.ICollisionEvent) => any;
private _onWorldBeforeStepListener: ((event: CANNON.IEvent) => any) | null = null;
private _onWorldPostStepListener: ((event: CANNON.IEvent) => any) | null = null;
private _cancelGravityListener: ((event: CANNON.IEvent) => any);
private _shapes: Set<PhysicsShape> = new Set();
private _dataflow: DataFlow = DataFlow.PULLING;
private _useGravity = true;
private _velocity = new Vec3();
constructor () {
const cannonBodyOptions: CANNON.IBodyOptions = {
mass: 0,
// material: new CANNON.Material(''),
};
this._cannonBody = new CANNON.Body(cannonBodyOptions);
setWrap<PhysicsBody>(this._cannonBody, this);
this._onCollidedListener = this._onCollided.bind(this);
this._cannonBody.addEventListener('collide', this._onCollidedListener);
this._cancelGravityListener = (event) => {
const gravity = this._cannonBody.world.gravity;
vec3.scaleAndAdd(this._cannonBody.force, this._cannonBody.force, gravity, this.mass * -1);
};
}
public bind (node: Node) {
this._node = node;
this.pullTransform();
}
public destroy () {
this._cannonBody.removeEventListener('collide', this._onCollidedListener);
}
public _onAdded () {
this.pullTransform();
this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this);
this._cannonBody.world.addEventListener('beforeStep', this._onWorldBeforeStepListener);
this._onWorldPostStepListener = this._onWorldPostStep.bind(this);
this._cannonBody.world.addEventListener('postStep', this._onWorldPostStepListener);
}
public _onRemoved () {
if (this._cannonBody.world) {
if (this._onWorldPostStepListener) {
this._cannonBody.world.removeEventListener('postStep', this._onWorldPostStepListener);
}
if (this._onWorldBeforeStepListener) {
this._cannonBody.world.removeEventListener('beforeStep', this._onWorldBeforeStepListener);
}
this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener);
}
}
public _getCannonBody () {
return this._cannonBody;
}
public addShape (shape: PhysicsShape) {
// if (this._node) {
// shape.__debugNodeName = this._node.name;
// }
if (this._node) {
shape.scale = this._node.getWorldScale();
}
this._shapes.add(shape);
this._cannonBody.addShape(shape._getCannonShape());
this.commitShapesUpdate();
}
public removeShape (shape: PhysicsShape) {
throw new Error(`not impl`);
}
public getCenter (shape: PhysicsShape) {
const iShape = this._cannonBody.shapes.indexOf(shape._getCannonShape());
if (iShape >= 0) {
const shapeOffset = this._cannonBody.shapeOffsets[iShape];
return new Vec3(shapeOffset.x, shapeOffset.y, shapeOffset.z);
}
throw new Error(`shape not found.`);
}
get velocity () {
vec3.copy(this._velocity, this._cannonBody.velocity);
return this._velocity;
}
set velocity (value: Vec3) {
vec3.set(this._velocity, value.x, value.y, value.z);
vec3.copy(this._cannonBody.velocity, this._velocity);
}
get force () {
return this._cannonBody.force;
}
public applyForce (force: Vec3, position?: Vec3) {
if (!position) {
position = this._cannonBody.position;
}
this._cannonBody.applyForce(force, position);
}
get material () {
return this._material;
}
set material (value) {
this._material = value;
if (!this._material) {
return;
}
this._cannonBody.material = this._material._getImpl();
}
get mass () {
return this._cannonBody.mass;
}
set mass (value) {
this._cannonBody.mass = value;
this._cannonBody.updateMassProperties();
if (this._cannonBody.type !== CANNON.Body.KINEMATIC) {
this._resetBodyTypeAccordingMess();
this._onBodyTypeUpdated();
}
}
get isKinematic () {
return this._cannonBody.type === CANNON.Body.KINEMATIC;
}
set isKinematic (value) {
if (value) {
this._cannonBody.type = CANNON.Body.KINEMATIC;
} else {
this._resetBodyTypeAccordingMess();
}
this._onBodyTypeUpdated();
}
get useGravity () {
return this._useGravity;
}
set useGravity (value) {
this._useGravity = value;
if (this._useGravity) {
this._cannonBody.world.removeEventListener('beforeStep', this._cancelGravityListener);
} else {
this._cannonBody.world.addEventListener('beforeStep', this._cancelGravityListener);
}
}
get freezeRotation () {
return this._cannonBody.fixedRotation;
}
set freezeRotation (value) {
this._cannonBody.fixedRotation = value;
this._cannonBody.updateMassProperties();
}
get linearDamping () {
return this._cannonBody.linearDamping;
}
set linearDamping (value) {
this._cannonBody.linearDamping = value;
}
get angularDamping () {
return this._cannonBody.angularDamping;
}
set angularDamping (value) {
this._cannonBody.angularDamping = value;
}
get isTrigger () {
return this._cannonBody.collisionResponse;
}
set isTrigger (value) {
this._cannonBody.collisionResponse = value;
}
get dataFlow () {
return this._dataflow;
}
/**
* Set the collision filter of this body, remember that they are tested bitwise.
* @param {number} group The group which this body will be put into.
* @param {number} mask The groups which this body can collide with.
*/
public setCollisionFilter (group: number, mask: number) {
this._cannonBody.collisionFilterGroup = group;
this._cannonBody.collisionFilterMask = mask;
}
public setWorldPosition (position: Vec3) {
this._cannonBody.position.set(position.x, position.y, position.z);
}
public setWorldScale (scale: Vec3) {
this._pullScale(scale);
}
public setWorldRotation (rotation: Quat) {
this._cannonBody.quaternion.set(rotation.x, rotation.y, rotation.z, rotation.w);
}
public pullTransform () {
if (!this._node) {
return;
}
// @ts-ignore
this.setWorldPosition(this._node.getWorldPosition());
// @ts-ignore
this.setWorldScale(this._node.getWorldScale());
// @ts-ignore
this.setWorldRotation(this._node.getWorldRotation());
}
/**
* Is this body currently in contact with the specified body?
* @param {CannonBody} body The body to test against.
*/
public isInContactWith (body: PhysicsBody) {
if (!this._cannonBody.world) {
return false;
}
return this._cannonBody.world.collisionMatrix.get(
this._cannonBody.id, body._cannonBody.id) > 0;
}
public commitShapesUpdate () {
this._cannonBody.updateBoundingRadius();
}
private _onCollided (event: CANNON.ICollisionEvent) {
if (!this._node) {
return;
}
this._node.emit('collided', {});
// console.log(`Collided {${getWrap<PhysicsBody>(event.body)._node.name}} and {${getWrap<PhysicsBody>(event.target)._node.name}}.`);
}
private _onWorldBeforeStep (event: CANNON.IEvent) {
if (this._dataflow === DataFlow.PULLING) {
this._pull();
}
}
private _onWorldPostStep (event: CANNON.IEvent) {
if (this._dataflow === DataFlow.PUSHING) {
this._push();
}
}
/**
* Pull node's transform information into rigidbody.
*/
private _pull () {
if (!this._node) {
return;
}
if (!this._node._hasChanged) {
return;
}
this.pullTransform();
}
private _pullScale (scale: Vec3) {
let shapeUpdated = false;
this._shapes.forEach((shape) => {
let calcShapeOffset = false;
if (shape._centerChanged) {
shape._centerChanged = false;
calcShapeOffset = true;
}
if (!vec3.exactEquals(scale, shape.scale)) {
shape.scale = scale;
shapeUpdated = true;
calcShapeOffset = true;
}
if (calcShapeOffset) {
const iShape = this._cannonBody.shapes.findIndex((cannonShape) => cannonShape === shape._getCannonShape());
if (iShape >= 0) {
const shapeOffset = this._cannonBody.shapeOffsets[iShape];
vec3.multiply(shapeOffset, shape.center, scale);
}
}
});
if (shapeUpdated) {
this.commitShapesUpdate();
}
}
/**
* Push the rigidbody's transform information back to node.
*/
private _push () {
if (!this._node) {
return;
}
const p = this._cannonBody.position;
this._node.setWorldPosition(p.x, p.y, p.z);
if (!this._cannonBody.fixedRotation) {
const q = this._cannonBody.quaternion;
this._node.setWorldRotation(q.x, q.y, q.z, q.w);
}
}
private _resetBodyTypeAccordingMess () {
if (this.mass <= 0) {
this._cannonBody.type = CANNON.Body.STATIC;
} else {
this._cannonBody.type = CANNON.Body.DYNAMIC;
}
}
private _onBodyTypeUpdated () {
if (this._cannonBody.type !== CANNON.Body.STATIC) {
this._dataflow = DataFlow.PUSHING;
} else {
this._dataflow = DataFlow.PULLING;
}
}
}
export class PhysicsShape {
public get center () {
return this._center;
}
public set center (value) {
vec3.copy(this._center, value);
}
public get scale () {
return this._scale;
}
public set scale (value) {
vec3.copy(this._scale, value);
this._onShapeParamUpdated();
}
public _centerChanged = true;
// public __debugNodeName: string = '';
private _scale: Vec3 = new Vec3(1.0, 1.0, 1.0);
private _center: Vec3 = new Vec3(0, 0, 0);
constructor (private _cannonShape: CANNON.Shape) {
setWrap<PhysicsShape>(this._cannonShape, this);
}
public _getCannonShape<T extends CANNON.Shape> () {
return this._cannonShape as T;
}
protected _onShapeParamUpdated () {
}
}
export class PhysicsBoxShape extends PhysicsShape {
private _size: Vec3;
constructor (size: Vec3) {
super(new CANNON.Box(new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2)));
this._size = new Vec3(size.x, size.y, size.z);
}
public get size () {
return this._size;
}
public set size (value) {
vec3.copy(this._size, value);
this._onShapeParamUpdated();
}
protected _onShapeParamUpdated () {
const shape = this._getCannonShape<CANNON.Box>();
if (!shape.halfExtents) {
shape.halfExtents = new CANNON.Vec3();
}
const newHalfExtents = shape.halfExtents;
vec3.multiply(newHalfExtents, this._size, this.scale);
vec3.scale(newHalfExtents, newHalfExtents, 0.5);
// shape.updateBoundingSphereRadius();
shape.updateConvexPolyhedronRepresentation();
// console.log(`Set ${this.__debugNodeName} halfExtents to ${shape.halfExtents.x}, ${shape.halfExtents.y},${shape.halfExtents.z}.`);
}
}
export class PhysicsSphereShape extends PhysicsShape {
private _radius: number;
constructor (radius: number) {
super(new CANNON.Sphere(radius));
this._radius = radius;
}
public get radius () {
return this._radius;
}
public set radius (value) {
this._radius = value;
this._onShapeParamUpdated();
}
protected _onShapeParamUpdated () {
const shape = this._getCannonShape<CANNON.Sphere>();
shape.radius = this._radius * maxComponent(this.scale);
// shape.updateBoundingSphereRadius();
// console.log(`Set ${this.__debugNodeName} radius to ${shape.radius}.`);
}
}
function maxComponent (v: { x: number, y: number, z: number }) {
return Math.max(v.x, Math.max(v.y, v.z));
}
@@ -1,4 +1,3 @@
import {
ccclass,
executeInEditMode,
@@ -7,24 +6,30 @@ import {
property,
} from '../../../core/data/class-decorator';
import Vec3 from '../../../core/value-types/vec3';
import { PhysicsBoxShape, PhysicsShape, PhysicsSphereShape } from './body';
import { vec3 } from '../../../core/vmath';
import { PhysicsBasedComponent } from './detail/physics-based-component';
@ccclass('cc.ColliderComponentBase')
export class ColliderComponentBase extends PhysicsBasedComponent {
protected _shape: PhysicsShape;
/**
* The center of the collider, in local space.
*/
@property({type: Vec3})
get center () {
return this._center;
}
set center (value: Vec3) {
vec3.copy(this._center, value);
if (this.sharedBody) {
this.sharedBody.updateCollidier(this);
}
}
@property
private _center: Vec3 = new cc.Vec3(0, 0, 0);
constructor (shape: PhysicsShape) {
constructor () {
super();
this._center = new Vec3(0, 0, 0);
this._shape = shape;
}
public get body () {
return this._body;
}
public onLoad () {
@@ -33,25 +38,12 @@ export class ColliderComponentBase extends PhysicsBasedComponent {
}
public onEnable () {
super.onEnable();
this._body!.addShape(this._shape);
this.sharedBody!.addCollider(this);
}
public onDisable () {
super.onDisable();
this._body!.removeShape(this._shape);
}
@property({
type: Vec3,
})
get center () {
return this._center;
}
set center (value: Vec3) {
this._center = new Vec3(value.x, value.y, value.z);
this._shape.center = value;
// throw new Error(`Not impl!`);
// this._body!.removeShape(this._impl);
}
}
@@ -64,7 +56,7 @@ export class BoxColliderComponent extends ColliderComponentBase {
private _size: Vec3 = new Vec3(0, 0, 0);
constructor () {
super(new PhysicsBoxShape(new Vec3(0, 0, 0)));
super();
}
public onLoad () {
@@ -72,21 +64,19 @@ export class BoxColliderComponent extends ColliderComponentBase {
this.size = this._size;
}
@property({
type: Vec3,
})
/**
* The size of the box, in local space.
* @note Shall not specify size with component 0.
*/
@property({type: Vec3})
get size () {
return this._size;
}
/**
* Note, shall not specify size with component 0
*/
set size (value) {
this._size = value;
(this._shape as PhysicsBoxShape).size = this._size;
if (this._body) {
this._body.commitShapesUpdate();
vec3.copy(this._size, value);
if (this.sharedBody) {
this.sharedBody.updateCollidier(this);
}
}
}
@@ -100,7 +90,7 @@ export class SphereColliderComponent extends ColliderComponentBase {
private _radius: number = 0;
constructor () {
super(new PhysicsSphereShape(0));
super();
}
public onLoad () {
@@ -108,6 +98,9 @@ export class SphereColliderComponent extends ColliderComponentBase {
this.radius = this._radius;
}
/**
* The radius of the sphere.
*/
@property
get radius () {
return this._radius;
@@ -115,9 +108,8 @@ export class SphereColliderComponent extends ColliderComponentBase {
set radius (value) {
this._radius = value;
(this._shape as PhysicsSphereShape).radius = value;
if (this._body) {
this._body.commitShapesUpdate();
if (this.sharedBody) {
this.sharedBody.updateCollidier(this);
}
}
}
+149
View File
@@ -0,0 +1,149 @@
import CANNON from 'cannon';
import { Vec3 } from '../../../core/value-types';
import { PhysicsBody } from './body';
import { getWrap, setWrap, toCannonVec3 } from './util';
/**
* Constraint options.
*/
export interface IConstraintOptions {
/**
* Set to true if you want the bodies to collide when they are connected.
* @default true
*/
collideConnected?: boolean;
/**
* @default true
*/
wakeUpBodies?: boolean;
}
/**
* Base class for Constraint classes.
*/
export class Constraint {
protected _cannonConstraint: CANNON.Constraint;
/**
* @param first The first body.
* @param second The second body.
* @param options Options.
*/
protected constructor (cannonConstraint: CANNON.Constraint) {
this._cannonConstraint = cannonConstraint;
setWrap<Constraint>(this._cannonConstraint, this);
}
get first () {
return getWrap<PhysicsBody>(this._cannonConstraint.bodyA);
}
get second () {
return getWrap<PhysicsBody>(this._cannonConstraint.bodyB);
}
public enable () {
this._cannonConstraint.enable();
}
public disable () {
this._cannonConstraint.disable();
}
public update () {
this._cannonConstraint.update();
}
public _getImpl () {
return this._cannonConstraint;
}
}
/**
* DistanceConstraint options.
*/
export interface IDistanceConstraintOptions {
/**
* The maximum force that should be applied to constrain the bodies.
*/
maxForce?: number;
}
/**
* Constrains two bodies to be at a constant distance from each others center of mass.
*/
export class DistanceConstraint extends Constraint {
/**
* @param first The first body.
* @param second The second body.
* @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.
* @param options Options.
*/
constructor (first: PhysicsBody, second: PhysicsBody, distance?: number, options?: IDistanceConstraintOptions) {
super(new CANNON.DistanceConstraint(
first._getCannonBody(),
second._getCannonBody(),
distance!,
options === undefined ? undefined : options.maxForce));
}
}
/**
* PointToPointConstraint options.
*/
export interface IPointToPointConstraintOptions {
/**
* The maximum force that should be applied to constrain the bodies.
*/
maxForce?: number;
}
/**
* Connects two bodies at given offset points.
*/
export class PointToPointConstraint extends Constraint {
/**
* @param first The first body.
* @param firstPivot The point relative to the center of mass of the first body which the first body is constrained to.
* @param second The second body.
* @param secondPivot The point relative to the center of mass of the second body which the second body is constrained to.
* @param options Options.
*/
constructor (first: PhysicsBody, firstPivot: Vec3, second: PhysicsBody, secondPivot: Vec3, options?: IPointToPointConstraintOptions) {
super(new CANNON.PointToPointConstraint(
first._getCannonBody(),
toCannonVec3(firstPivot),
second._getCannonBody(),
toCannonVec3(secondPivot),
options === undefined ? undefined : options.maxForce));
}
}
/**
* LockConstraint options.
*/
export interface ILockConstraintOptions {
/**
* The maximum force that should be applied to constrain the bodies.
*/
maxForce?: number;
}
/**
* The Lock constraint will remove all degrees of freedom between the bodies.
*/
export class LockConstraint extends Constraint {
/**
* @param first The first body.
* @param second The second body.
* @param options Options.
*/
constructor (first: PhysicsBody, second: PhysicsBody, options?: ILockConstraintOptions) {
super(new CANNON.LockConstraint(
first._getCannonBody(),
second._getCannonBody(),
options));
}
}
+22 -20
View File
@@ -4,7 +4,7 @@ import { PhysicsMaterial } from '../../assets/physics/material';
export class ContactMaterial {
private _cannonContactMaterial: CANNON.ContactMaterial;
constructor(lhs: PhysicsMaterial, rhs: PhysicsMaterial) {
constructor (lhs: PhysicsMaterial, rhs: PhysicsMaterial) {
const opts: CANNON.IContactMaterialOptions = {
friction: 0.3,
restitution: 0.3,
@@ -19,70 +19,72 @@ export class ContactMaterial {
/**
* Friction coefficient. Default value 0.3.
*/
get friction() {
return this._cannonContactMaterial.friction;
get friction () {
return this._cannonContactMaterial.friction;
}
set friction(value) {
set friction (value) {
this._cannonContactMaterial.friction = value;
}
/**
* Restitution coefficient. Default value 0.3.
*/
get restitution() {
return this._cannonContactMaterial.restitution;
get restitution () {
return this._cannonContactMaterial.restitution;
}
set restitution(value) {
set restitution (value) {
this._cannonContactMaterial.restitution = value;
}
/**
* Stiffness of the produced contact equations. Default value 1e7.
*/
get contactEquationStiffness() {
return this._cannonContactMaterial.contactEquationStiffness;
get contactEquationStiffness () {
return this._cannonContactMaterial.contactEquationStiffness;
}
set contactEquationStiffness(value) {
set contactEquationStiffness (value) {
this._cannonContactMaterial.contactEquationStiffness = value;
}
/**
* Relaxation time of the produced contact equations. Default value 0.3.
*/
get contactEquationRelaxation() {
return this._cannonContactMaterial.contactEquationRelaxation;
get contactEquationRelaxation () {
return this._cannonContactMaterial.contactEquationRelaxation;
}
set contactEquationRelaxation(value) {
set contactEquationRelaxation (value) {
this._cannonContactMaterial.contactEquationRelaxation = value;
}
/**
* Stiffness of the produced friction equations. Default value 1e7.
*/
get frictionEquationStiffness() {
return this._cannonContactMaterial.frictionEquationStiffness;
get frictionEquationStiffness () {
return this._cannonContactMaterial.frictionEquationStiffness;
}
set frictionEquationStiffness(value) {
set frictionEquationStiffness (value) {
this._cannonContactMaterial.frictionEquationStiffness = value;
}
/**
* Relaxation time of the produced friction equations. Default value 3.
*/
get frictionEquationRelaxation() {
get frictionEquationRelaxation () {
return this._cannonContactMaterial.frictionEquationRelaxation;
}
set frictionEquationRelaxation(value) {
set frictionEquationRelaxation (value) {
this._cannonContactMaterial.frictionEquationRelaxation = value;
}
public _getImpl() {
public _getImpl () {
return this._cannonContactMaterial;
}
}
}
cc.ContactMaterial = ContactMaterial;
@@ -1,65 +1,258 @@
import CANNON from 'cannon';
import { Component } from '../../../../components/component';
import { ccclass } from '../../../../core/data/class-decorator';
import { PhysicsBody } from '../body';
import { Quat, Vec3 } from '../../../../core/value-types';
import { quat, vec3 } from '../../../../core/vmath';
import { Node } from '../../../../scene-graph/node';
import { BoxColliderComponent, ColliderComponentBase, SphereColliderComponent } from '../collider-component';
import { setWrap } from '../util';
import { PhysicsWorld } from '../world';
@ccclass('cc.PhysicsBasedComponent')
export class PhysicsBasedComponent extends Component {
private _sharedBody: SharedRigidBody | null = null;
constructor() {
super();
}
protected get _body() {
protected get _body () {
return this._sharedBody ? this._sharedBody.body : null;
}
public onLoad() {
this._sharedBody = this._getSharedBody();
this._sharedBody.body.bind(this.node);
protected get sharedBody () {
return this._sharedBody;
}
private _sharedBody: SharedRigidBody | null = null;
constructor () {
super();
}
public onEnable() {
if (this._sharedBody!.enable()) {
cc.director._physicsSystem.world.addBody(this._body);
public onLoad () {
this._refSharedBody();
}
public start () {
this._sharedBody!.syncPhysWithScene();
}
public destroy () {
if (this._sharedBody) {
this._sharedBody.deref();
this._sharedBody = null;
}
}
public onDisable() {
if (this._sharedBody!.disable()) {
cc.director._physicsSystem.world.removeBody(this._body);
public syncPhysWithScene () {
if (this.sharedBody) {
this.sharedBody.syncPhysWithScene();
}
}
private _getSharedBody() {
let component = this.getComponent(PhysicsBasedComponent) as (PhysicsBasedComponent | null);
if (!component) {
component = this;
private _refSharedBody () {
if (this._sharedBody) {
return;
}
if (!component._sharedBody) {
component._sharedBody = new SharedRigidBody();
const physicsBasedComponents = this.node.getComponents(PhysicsBasedComponent);
let sharedBody: SharedRigidBody | null = null;
for (const physicsBasedComponent of physicsBasedComponents) {
if (physicsBasedComponent._sharedBody) {
sharedBody = physicsBasedComponent._sharedBody;
break;
}
}
return component._sharedBody!;
if (!sharedBody) {
sharedBody = new SharedRigidBody(this.node, cc.director._physicsSystem.world);
}
sharedBody.ref();
this._sharedBody = sharedBody;
}
}
export enum TransformSource {
Scene,
Phycis,
}
type Collider = ColliderComponentBase;
function isBoxCollider (collider: Collider): collider is BoxColliderComponent {
return 'size' in collider;
}
function isSphereCollider (collider: Collider): collider is SphereColliderComponent {
return 'radius' in collider;
}
class SharedRigidBody {
public body: PhysicsBody;
private _body: CANNON.Body;
private _enableCount = 0;
private _onCollidedListener: (event: CANNON.ICollisionEvent) => any;
constructor() {
this.body = new PhysicsBody();
private _cancelGravityListener: (event: CANNON.IEvent) => any;
private _onWorldBeforeStepListener: (event: CANNON.IEvent) => any;
private _onWorldPostStepListener: (event: CANNON.IEvent) => any;
private _refCount = 0;
private _world: PhysicsWorld;
private _node: Node;
private _transformSource: TransformSource = TransformSource.Scene;
private _colliders: Map<Collider, number> = new Map();
private _worldScale: Vec3 = new Vec3(1, 1, 1);
constructor (node: Node, world: PhysicsWorld) {
this._body = new CANNON.Body();
this._node = node;
setWrap<Node>(this._body, this._node);
this._world = world;
this._onCollidedListener = this._onCollided.bind(this);
this._onWorldBeforeStepListener = this._onWorldBeforeStep.bind(this);
this._onWorldPostStepListener = this._onWorldPostStep.bind(this);
this._cancelGravityListener = (event) => {
if (this._body) {
const gravity = this._body.world.gravity;
vec3.scaleAndAdd(this._body.force, this._body.force, gravity, this._body.mass * -1);
}
};
}
public enable() {
++this._enableCount;
return this._enableCount === 1;
public get body () {
return this._body;
}
public disable() {
--this._enableCount;
return this._enableCount === 0;
public get transformSource () {
return this._transformSource;
}
public set transformSource (value) {
this._transformSource = value;
}
public ref () {
if (!this._refCount) {
this._activeBody();
}
++this._refCount;
}
public deref () {
--this._refCount;
if (!this._refCount) {
this._deactiveBody();
}
}
public addCollider (collider: Collider) {
let shape: CANNON.Shape | undefined;
if (isBoxCollider(collider)) {
shape = new CANNON.Box(new CANNON.Vec3());
} else if (isSphereCollider(collider)) {
shape = new CANNON.Sphere(0);
}
if (!shape) {
return;
}
setWrap(shape, collider);
const ishape = this.body.shapes.length;
this.body.addShape(shape);
this._colliders.set(collider, ishape);
this.updateCollidier(collider);
}
public updateCollidier (collider: Collider) {
const ishape = this._colliders.get(collider);
if (ishape === undefined) {
return;
}
if (isBoxCollider(collider)) {
const shape = this.body.shapes[ishape] as CANNON.Box;
vec3.scale(shape.halfExtents, collider.size, 0.5);
vec3.multiply(shape.halfExtents, shape.halfExtents, this._worldScale);
shape.updateConvexPolyhedronRepresentation();
shape.updateBoundingSphereRadius();
} else if (isSphereCollider(collider)) {
const shape = this.body.shapes[ishape] as CANNON.Sphere;
shape.radius = collider.radius * maxComponent(this._worldScale);
shape.updateBoundingSphereRadius();
}
const center = this.body.shapeOffsets[ishape];
vec3.multiply(center, center, this._worldScale);
this.body.updateBoundingRadius();
}
public syncPhysWithScene () {
vec3.copy(this._body.position, this._node.getWorldPosition());
quat.copy(this._body.quaternion, this._node.getWorldRotation());
// Because we sync the scale, we should update shape parameters.
this._node.getWorldScale(this._worldScale);
this._colliders.forEach((shape, collider) => {
this.updateCollidier(collider);
});
}
public setUseGravity (value: boolean) {
if (value) {
this._body.world.removeEventListener('beforeStep', this._cancelGravityListener);
} else {
this._body.world.addEventListener('beforeStep', this._cancelGravityListener);
}
}
/**
* Push the rigidbody's transform information back to node.
*/
private _syncSceneWithPhys () {
if (!this._node) {
return;
}
const p = this._body.position;
this._node.setWorldPosition(p.x, p.y, p.z);
if (!this._body.fixedRotation) {
const q = this._body.quaternion;
this._node.setWorldRotation(q.x, q.y, q.z, q.w);
}
}
private _activeBody () {
this._world.addBody(this._body);
this._body.addEventListener('collide', this._onCollidedListener);
this._body.world.addEventListener('beforeStep', this._onWorldBeforeStepListener);
this._body.world.addEventListener('postStep', this._onWorldPostStepListener);
}
private _deactiveBody () {
this._world.removeBody(this._body);
this._body.removeEventListener('collide', this._onCollidedListener);
this._body.world.removeEventListener('postStep', this._onWorldPostStepListener);
this._body.world.removeEventListener('beforeStep', this._onWorldBeforeStepListener);
}
private _onCollided (event: CANNON.ICollisionEvent) {
if (!this._node) {
return;
}
this._node.emit('collided', {});
// console.log(`Collided {${getWrap<PhysicsBody>(event.body)._node.name}} and {${getWrap<PhysicsBody>(event.target)._node.name}}.`);
}
private _onWorldBeforeStep (event: CANNON.IEvent) {
// if (this._transformSource === TransformSource.Scene) {
// this.syncPhysWithScene();
// }
}
private _onWorldPostStep (event: CANNON.IEvent) {
if (this._transformSource === TransformSource.Phycis) {
this._syncSceneWithPhys();
}
}
}
function maxComponent (v: Vec3) {
return Math.max(v.x, Math.max(v.y, v.z));
}
+1 -23
View File
@@ -1,25 +1,3 @@
import { PhysicsBoxShape, PhysicsSphereShape, PhysicsBody } from './body';
import { ContactMaterial } from './contact-material';
export {
PhysicsBoxShape,
PhysicsSphereShape,
PhysicsBody,
ContactMaterial,
};
export { ContactMaterial } from './contact-material';
export * from './physics-system';
export * from './world';
// @ts-ignore
cc.PhysicsBody = PhysicsBody;
// @ts-ignore
cc.PhysicsBoxShape = PhysicsBoxShape;
// @ts-ignore
cc.PhysicsSphereShape = PhysicsSphereShape;
// @ts-ignore
cc.ContactMaterial = ContactMaterial;
// namespace cc {
// export const PhysicalBody = PhysicalBody;
// export const PhysicalBoxShape = PhysicalBoxShape;
// export const PhysicalSphereShape = PhysicalSphereShape;
// }
+4 -4
View File
@@ -3,18 +3,18 @@ import { PhysicsWorld } from './world';
export class PhysicsSystem {
private _world: PhysicsWorld;
constructor() {
constructor () {
this._world = new PhysicsWorld();
}
public update(deltaTime: number) {
public update (deltaTime: number) {
if (CC_EDITOR) {
return;
}
this._world.step(deltaTime);
}
get world() {
get world () {
return this._world;
}
}
}
@@ -1,4 +1,5 @@
import CANNON from 'cannon';
import {
ccclass,
executeInEditMode,
@@ -6,8 +7,11 @@ import {
menu,
property,
} from '../../../core/data/class-decorator';
import { Quat, Vec3 } from '../../../core/value-types';
import { vec3 } from '../../../core/vmath';
import { PhysicsMaterial } from '../../assets/physics/material';
import { PhysicsBasedComponent } from './detail/physics-based-component';
import { PhysicsBasedComponent, TransformSource } from './detail/physics-based-component';
import { toCannonVec3 } from './util';
const NonRigidBodyProperties = {
mass: 0,
@@ -32,27 +36,35 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
@property
private _angularDamping: number = NonRigidBodyProperties.angularDamping;
@property
private _fixedRotation: boolean = true;
@property
private _triggered: boolean = true;
@property
private _isKinematic: boolean = false;
@property
private _useGravity: boolean = true;
private _velocity: Vec3 = new Vec3();
constructor () {
super();
}
public get body () {
return this._body;
}
public onLoad () {
super.onLoad();
}
public onEnable () {
super.onEnable();
this.mass = this._mass;
this.linearDamping = this._linearDamping;
this.angularDamping = this._angularDamping;
}
public onDisable () {
super.onDisable();
this.mass = NonRigidBodyProperties.mass;
this.linearDamping = NonRigidBodyProperties.linearDamping;
this.angularDamping = NonRigidBodyProperties.angularDamping;
@@ -68,7 +80,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
set material (value) {
this._material = value;
if (this._body) {
this._body.material = this._material;
this._body.material = this._material ? this._material._getImpl() : null;
}
}
@@ -81,6 +93,40 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
this._mass = value;
if (this._body) {
this._body.mass = value;
this._body.updateMassProperties();
if (this._body.type !== CANNON.Body.KINEMATIC) {
this._resetBodyTypeAccordingMess();
this._onBodyTypeUpdated();
}
}
}
@property
get isKinematic () {
return this._isKinematic;
}
set isKinematic (value) {
this._isKinematic = value;
if (this._body) {
if (value) {
this._body.type = CANNON.Body.KINEMATIC;
} else {
this._resetBodyTypeAccordingMess();
}
this._onBodyTypeUpdated();
}
}
@property
get useGravity () {
return this._useGravity;
}
set useGravity (value) {
this._useGravity = value;
if (this.sharedBody) {
this.sharedBody.setUseGravity(value);
}
}
@@ -108,9 +154,93 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
}
}
public pullTransform () {
get fixedRotation () {
return this._fixedRotation;
}
set fixedRotation (value) {
this._fixedRotation = value;
if (this._body) {
this._body.pullTransform();
this._body.fixedRotation = value;
this._body.updateMassProperties();
}
}
get isTrigger () {
return this._triggered;
}
set isTrigger (value) {
this._triggered = value;
if (this._body) {
this._body.collisionResponse = value;
}
}
get velocity () {
if (this._body) {
vec3.copy(this._velocity, this._body!.velocity);
}
return this._velocity;
}
set velocity (value: Vec3) {
vec3.copy(this._velocity, value);
if (this._body) {
vec3.copy(this._body.velocity, this._velocity);
}
}
public applyForce (force: Vec3, position?: Vec3) {
if (!position) {
position = new Vec3();
vec3.copy(position, this._body!.position);
}
this._body!.applyForce(toCannonVec3(force), toCannonVec3(position));
}
/**
* Set the collision filter of this body, remember that they are tested bitwise.
* @param {number} group The group which this body will be put into.
* @param {number} mask The groups which this body can collide with.
*/
public setCollisionFilter (group: number, mask: number) {
if (this._body) {
this._body.collisionFilterGroup = group;
this._body.collisionFilterMask = mask;
}
}
// /**
// * Is this body currently in contact with the specified body?
// * @param {CannonBody} body The body to test against.
// */
// public isInContactWith (body: PhysicsBody) {
// if (!this._cannonBody.world) {
// return false;
// }
// return this._cannonBody.world.collisionMatrix.get(
// this._cannonBody.id, body._cannonBody.id) > 0;
// }
private _resetBodyTypeAccordingMess () {
if (this._body) {
if (this.mass <= 0) {
this._body.type = CANNON.Body.STATIC;
} else {
this._body.type = CANNON.Body.DYNAMIC;
}
}
}
private _onBodyTypeUpdated () {
if (this.sharedBody) {
if (this.sharedBody.body.type === CANNON.Body.STATIC) {
this.sharedBody.transformSource = TransformSource.Scene;
} else {
this.sharedBody.transformSource = TransformSource.Phycis;
}
}
}
}
+10 -5
View File
@@ -1,19 +1,24 @@
import { Vec3 } from '../../../core/value-types';
export interface IWrappedCANNON<T> {
__cc_wrapper__: T;
}
export function setWrap<Wrapper>(cannonObject: any, wrapper: Wrapper) {
export function setWrap<Wrapper> (cannonObject: any, wrapper: Wrapper) {
(cannonObject as unknown as IWrappedCANNON<Wrapper>).__cc_wrapper__ = wrapper;
}
export function getWrap<Wrapper>(cannonObject: any) {
export function getWrap<Wrapper> (cannonObject: any) {
return (cannonObject as unknown as IWrappedCANNON<Wrapper>).__cc_wrapper__;
}
export function toCannonOptions<T>(options: any, optionsRename?: { [x: string] : string; }) {
export function toCannonVec3 (value: Vec3) {
return new CANNON.Vec3(value.x, value.y, value.z);
}
export function toCannonOptions<T> (options: any, optionsRename?: { [x: string]: string; }) {
const result = {};
for (const key in options) {
for (const key of Object.keys(options)) {
let destKey = key;
if (optionsRename) {
const rename = optionsRename[key];
@@ -24,4 +29,4 @@ export function toCannonOptions<T>(options: any, optionsRename?: { [x: string] :
result[destKey] = options[key];
}
return result as T;
}
}
+33 -29
View File
@@ -1,11 +1,13 @@
import CANNON from 'cannon';
import { Component } from '../../../components/component';
import { Vec3 } from '../../../core/value-types';
import { Node } from '../../../scene-graph/node';
import { PhysicsMaterial } from '../../assets/physics/material';
import { DataFlow, PhysicsBody, PhysicsShape } from './body';
import { Constraint } from './constraints';
import { ContactMaterial } from './contact-material';
import { getWrap, setWrap, toCannonOptions } from './util';
import { Vec3 } from '../../../core/value-types';
export interface RaycastOptions {
export interface IRaycastOptions {
collisionFilterMask?: number;
collisionFilterGroup?: number;
queryTriggerInteraction?: boolean;
@@ -14,24 +16,24 @@ export interface RaycastOptions {
export class RaycastResult {
public _cannonResult: CANNON.RaycastResult = new CANNON.RaycastResult();
get hit() {
get hit () {
return this._cannonResult.hasHit;
}
get hitPoint() {
get hitPoint () {
return this._cannonResult.hitPointWorld;
}
get distance() {
get distance () {
return this._cannonResult.distance;
}
get shape() {
return getWrap<PhysicsShape>(this._cannonResult.shape);
get shape () {
return getWrap<Component>(this._cannonResult.shape);
}
get body() {
return getWrap<PhysicsBody>(this._cannonResult.body);
get body () {
return getWrap<Node>(this._cannonResult.body);
}
}
@@ -39,12 +41,11 @@ export class PhysicsWorld {
private _cannonWorld: CANNON.World;
private _defaultMaterial: PhysicsMaterial;
private _defaultContactMaterial: ContactMaterial;
private _bodys: Set<PhysicsBody>;
private _beforeStepEvent: CANNON.IEvent = {
type: 'beforeStep',
};
constructor() {
constructor () {
this._defaultMaterial = new PhysicsMaterial();
const mtl = new PhysicsMaterial();
mtl.friction = 0.3;
@@ -57,26 +58,21 @@ export class PhysicsWorld {
this._cannonWorld.broadphase = new CANNON.NaiveBroadphase();
this._cannonWorld.defaultMaterial = this._defaultMaterial._getImpl();
this._cannonWorld.defaultContactMaterial = this._defaultContactMaterial._getImpl();
this._bodys = new Set();
}
get defaultContactMaterial() {
get defaultContactMaterial () {
return this._defaultContactMaterial;
}
public addBody(body: PhysicsBody) {
this._bodys.add(body);
this._cannonWorld.addBody(body._getCannonBody());
body._onAdded();
public addBody (body: CANNON.Body) {
this._cannonWorld.addBody(body);
}
public removeBody(body: PhysicsBody) {
body._onRemoved();
this._cannonWorld.remove(body._getCannonBody());
this._bodys.delete(body);
public removeBody (body: CANNON.Body) {
this._cannonWorld.remove(body);
}
public step(deltaTime: number) {
public step (deltaTime: number) {
this._cannonWorld.dispatchEvent(this._beforeStepEvent);
this._cannonWorld.step(deltaTime);
}
@@ -85,7 +81,7 @@ export class PhysicsWorld {
* Ray cast, and return information of the closest hit.
* @return True if any body was hit.
*/
public raycastClosest(from: Vec3, to: Vec3, options: RaycastOptions, result: RaycastResult): boolean {
public raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
const hit = (this._cannonWorld as any).raycastClosest(from, to, toCannonRaycastOptions(options), result._cannonResult);
return hit;
}
@@ -94,7 +90,7 @@ export class PhysicsWorld {
* Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
* @return True if any body was hit.
*/
public raycastAny(from: Vec3, to: Vec3, options: RaycastOptions, result: RaycastResult): boolean {
public raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
const hit = (this._cannonWorld as any).raycastAny(from, to, toCannonRaycastOptions(options), result._cannonResult);
return hit;
}
@@ -103,7 +99,7 @@ export class PhysicsWorld {
* Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
* @return True if any body was hit.
*/
public raycastAll(from: Vec3, to: Vec3, options: RaycastOptions, callback: (result: RaycastResult) => void): boolean {
public raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResult) => void): boolean {
return (this._cannonWorld as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => {
const result = new RaycastResult();
result._cannonResult = cannonResult;
@@ -111,19 +107,27 @@ export class PhysicsWorld {
});
}
public addContactMaterial(contactMaterial: ContactMaterial) {
public addContactMaterial (contactMaterial: ContactMaterial) {
this._cannonWorld.addContactMaterial(contactMaterial._getImpl());
}
public addConstraint (constraint: Constraint) {
this._cannonWorld.addConstraint(constraint._getImpl());
}
public removeConstraint (constraint: Constraint) {
this._cannonWorld.removeConstraint(constraint._getImpl());
}
}
interface CANNONRaycastOptions {
interface ICANNONRaycastOptions {
collisionFilterMask?: number;
collisionFilterGroup?: number;
checkCollisionResponse?: boolean;
skipBackfaces?: boolean;
}
function toCannonRaycastOptions(options: RaycastOptions): CANNONRaycastOptions {
function toCannonRaycastOptions (options: IRaycastOptions): ICANNONRaycastOptions {
return toCannonOptions(options, {
queryTriggerInteraction: 'checkCollisionResponse',
});