@fred3d/physics
v0.0.2
Published
A robust, type-safe abstraction layer for integrating multiple physics engines in the Fred3D framework.
Downloads
9
Readme
Physics Abstraction Layer
A robust, type-safe abstraction layer for integrating multiple physics engines in the Fred3D framework.
Features
- Type-safe interfaces for physics interactions
- Support for multiple physics engines (Ammo.js and Cannon.js)
- Event-based collision and trigger detection
- Comprehensive error handling with detailed error codes
- Runtime type validation for physics configurations
Usage
Basic Setup
import { createPhysicsEngine, PhysicsEngineType } from '@fred3d/physics';
// Create a physics engine instance (Ammo.js or Cannon.js)
const physics = await createPhysicsEngine({
type: PhysicsEngineType.AMMO,
gravity: new Vector3(0, -9.81, 0)
});
// Initialize the physics world
await physics.init();
// Start simulation
physics.start();Working with Rigid Bodies
// Create a rigid body
const bodyConfig = {
type: RigidBodyType.DYNAMIC,
mass: 1.0,
position: new Vector3(0, 5, 0)
};
const rigidBody = physics.createRigidBody(bodyConfig);
// Add a collider to the rigid body
const colliderConfig = {
type: ColliderShapeType.BOX,
size: new Vector3(1, 1, 1)
};
const collider = physics.createCollider(rigidBody, colliderConfig);
// Apply forces and impulses
rigidBody.applyForce(new Vector3(0, 0, 10));
rigidBody.applyImpulse(new Vector3(5, 0, 0));Collision Events
// Listen for collision events
physics.on(PhysicsEventType.COLLISION_BEGIN, (data) => {
const { bodyA, bodyB, contacts } = data;
console.debug(`Collision between ${bodyA.id} and ${bodyB.id}`);
console.debug(`Contact point: ${contacts[0].point}`);
});
// Listen for trigger events
physics.on(PhysicsEventType.TRIGGER_ENTER, (data) => {
const { trigger, body } = data;
console.debug(`Body ${body.id} entered trigger ${trigger.id}`);
});Advanced Features
Feature Detection
// Check if a specific feature is supported
if (physics.isFeatureSupported(PhysicsFeature.SOFT_BODIES)) {
// Use soft body functionality
}
// Get information about the engine
const info = physics.getEngineInfo();
console.debug(`Using ${info.name} version ${info.version}`);Joint Constraints
// Create a hinge joint between two bodies
const jointConfig = {
type: JointType.HINGE,
bodyA: bodyA,
bodyB: bodyB,
pivotA: new Vector3(0, 1, 0),
pivotB: new Vector3(0, -1, 0),
axisA: new Vector3(0, 0, 1),
axisB: new Vector3(0, 0, 1)
};
const joint = physics.createJoint(jointConfig);Optional Tools Module
The physics package includes an optional tools module that provides higher-level utilities for working with physics objects:
import { Tools } from '@fred3d/physics';
// Access the tools
const { PhysicsObjectFactory, PhysicsObjectManager, PhysicsMaterialLibrary } = Tools;
// Create a physics object factory
const factory = new PhysicsObjectFactory(physics);
// Create a box with predefined material
const boxObject = factory.createBox(
new Vector3(0, 5, 0), // position
new Vector3(1, 1, 1), // size
RigidBodyType.DYNAMIC, // body type
Tools.SurfaceType.WOOD // material
);
// Create a physics object manager
const manager = new PhysicsObjectManager(physics, physics.getWorld(), scene);
// Add the box to the manager
const boxId = manager.addObject(boxObject, boxMesh, 'box_01', 'dynamic_objects').id;
// In your game loop
function gameLoop() {
physics.getWorld().step(1/60);
manager.updateTransforms(); // Updates all object transforms
requestAnimationFrame(gameLoop);
}See the Tools Module Documentation for more details.
Type Guards
For runtime validation, the package provides a set of type guards:
import { isValidRigidBodyConfig, isValidColliderConfig } from '@fred3d/physics';
// Validate user input
function createBodyFromUserInput(input: unknown) {
if (isValidRigidBodyConfig(input)) {
// Input is valid, safe to use
return physics.createRigidBody(input);
} else {
throw new Error('Invalid rigid body configuration');
}
}Error Codes Reference
The physics package uses a standardized error code system for better debugging and error handling.
| Error Code | Error Type | Description | |------------|------------|-------------| | PE000 | PhysicsError | Generic physics error | | PE001 | PhysicsInitializationError | Failed to initialize physics engine | | PE002 | PhysicsConfigurationError | Invalid configuration provided | | PE003 | PhysicsNotInitializedError | Operation attempted before initialization | | PE004 | PhysicsUnsupportedOperationError | Attempted to use unsupported feature | | PE005 | PhysicsInvalidParameterError | Invalid parameter provided to method | | PE006 | PhysicsNotFoundError | Required object not found |
Error Handling Example
try {
// Physics operation that might fail
physics.createRigidBody(config);
} catch (error) {
if (error instanceof PhysicsConfigurationError) {
console.error(`Configuration error (${error.code}): ${error.message}`);
} else if (error instanceof PhysicsError) {
console.error(`Physics error (${error.code}): ${error.message}`);
} else {
throw error; // Re-throw unknown errors
}
}API Reference
For complete API documentation, see the API Reference generated with TypeDoc.
Testing
Run tests with:
# Run all tests
npm test
# Run tests with coverage report
npm run test:coverage
# Run tests in watch mode during development
npm run test:watchLicense
This package is part of the Fred3D framework and is covered by the same license.
