Convert Figma logo to code with AI

kripken logoammo.js

Direct port of the Bullet physics engine to JavaScript using Emscripten

4,134
556
4,134
173

Top Related Projects

12,417

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

💣 A lightweight 3D physics engine written in JavaScript.

2,639

JavaScript 2D physics library

16,610

a 2D rigid body physics engine for the web ▲● ■

3,047

Lightweight 3d physics engine for javascript

Quick Overview

Ammo.js is a direct port of the Bullet physics engine to JavaScript using Emscripten. It provides a powerful and efficient physics simulation library for web-based 3D applications, allowing developers to add realistic physics interactions to their web projects.

Pros

  • High performance physics simulation in the browser
  • Compatible with popular 3D libraries like Three.js
  • Supports a wide range of physics features, including rigid body dynamics and soft body simulation
  • Actively maintained and regularly updated

Cons

  • Steep learning curve for developers new to physics engines
  • Large file size compared to simpler physics libraries
  • Limited documentation and examples compared to the original Bullet physics engine
  • Performance may be slower than native implementations for complex simulations

Code Examples

  1. Creating a rigid body:
var transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(0, 10, 0));

var motionState = new Ammo.btDefaultMotionState(transform);
var mass = 1;
var localInertia = new Ammo.btVector3(0, 0, 0);

var shape = new Ammo.btSphereShape(0.5);
shape.calculateLocalInertia(mass, localInertia);

var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
var body = new Ammo.btRigidBody(rbInfo);

physicsWorld.addRigidBody(body);
  1. Applying force to a rigid body:
var force = new Ammo.btVector3(10, 0, 0);
body.applyCentralForce(force);
  1. Stepping the physics simulation:
var deltaTime = 1 / 60;
physicsWorld.stepSimulation(deltaTime, 10);

Getting Started

  1. Include Ammo.js in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ammo.js/2.0.0/ammo.js"></script>
  1. Initialize Ammo.js:
Ammo().then(function(Ammo) {
  // Create physics world
  var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
  var overlappingPairCache = new Ammo.btDbvtBroadphase();
  var solver = new Ammo.btSequentialImpulseConstraintSolver();
  var physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
  
  // Set gravity
  physicsWorld.setGravity(new Ammo.btVector3(0, -9.8, 0));

  // Your physics code here
});

Competitor Comparisons

12,417

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

Pros of Bullet3

  • Native C++ implementation, offering potentially better performance
  • More comprehensive physics simulation features
  • Wider range of platforms and rendering backends supported

Cons of Bullet3

  • Steeper learning curve due to more complex API
  • Larger codebase and potentially higher memory footprint
  • May require more setup and configuration for basic usage

Code Comparison

Ammo.js (JavaScript):

var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
var overlappingPairCache = new Ammo.btDbvtBroadphase();
var solver = new Ammo.btSequentialImpulseConstraintSolver();
var dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

Bullet3 (C++):

btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase();
btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

Both examples show similar setup processes, but Bullet3 uses C++ syntax and pointers, while Ammo.js uses JavaScript object creation.

💣 A lightweight 3D physics engine written in JavaScript.

Pros of cannon-es

  • Lightweight and optimized for web browsers
  • Easier to integrate with modern JavaScript frameworks
  • Better documentation and examples for web-based projects

Cons of cannon-es

  • Less feature-rich compared to Ammo.js
  • May not perform as well for complex simulations
  • Smaller community and fewer resources available

Code Comparison

cannon-es:

import * as CANNON from 'cannon-es';

const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);

const sphereShape = new CANNON.Sphere(1);
const sphereBody = new CANNON.Body({
  mass: 5,
  shape: sphereShape
});

Ammo.js:

Ammo().then(function(Ammo) {
  const collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  const dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
  const broadphase = new Ammo.btDbvtBroadphase();
  const solver = new Ammo.btSequentialImpulseConstraintSolver();
  const physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
});

The code comparison shows that cannon-es has a more straightforward API and is easier to set up, while Ammo.js requires more boilerplate code but offers more fine-grained control over the physics simulation.

2,639

JavaScript 2D physics library

Pros of p2.js

  • Lightweight and focused on 2D physics, making it more efficient for 2D games and simulations
  • Easier to learn and use, with simpler API and documentation
  • Better performance for 2D scenarios due to specialized optimization

Cons of p2.js

  • Limited to 2D physics, lacking support for 3D simulations
  • Smaller community and ecosystem compared to Ammo.js
  • Less comprehensive feature set for complex physics simulations

Code Comparison

p2.js:

var world = new p2.World();
var boxShape = new p2.Box({ width: 1, height: 1 });
var boxBody = new p2.Body({ mass: 1, position: [0, 5] });
boxBody.addShape(boxShape);
world.addBody(boxBody);

Ammo.js:

var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
var overlappingPairCache = new Ammo.btDbvtBroadphase();
var solver = new Ammo.btSequentialImpulseConstraintSolver();
var dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

The code comparison shows that p2.js has a more straightforward setup process for creating a physics world and adding objects, while Ammo.js requires more complex initialization steps due to its more comprehensive feature set and 3D capabilities.

16,610

a 2D rigid body physics engine for the web ▲● ■

Pros of Matter.js

  • Lightweight and easy to use, with a focus on 2D physics
  • Excellent documentation and examples
  • Built-in rendering and visualization tools

Cons of Matter.js

  • Limited to 2D physics simulations
  • Less powerful for complex, high-performance simulations
  • Smaller community and ecosystem compared to Ammo.js

Code Comparison

Matter.js example:

var engine = Matter.Engine.create();
var box = Matter.Bodies.rectangle(200, 200, 80, 80);
Matter.World.add(engine.world, box);
Matter.Engine.run(engine);

Ammo.js example:

var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
var overlappingPairCache = new Ammo.btDbvtBroadphase();
var solver = new Ammo.btSequentialImpulseConstraintSolver();
var dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

Matter.js is more straightforward for simple 2D physics, while Ammo.js offers more control and complexity for 3D simulations. Matter.js is ideal for web-based 2D games and interactive visualizations, whereas Ammo.js is better suited for more advanced 3D physics applications and games requiring high performance.

3,047

Lightweight 3d physics engine for javascript

Pros of Oimo.js

  • Lightweight and optimized for web-based physics simulations
  • Easier to integrate with JavaScript projects, especially for web developers
  • Simpler API, making it more accessible for beginners

Cons of Oimo.js

  • Less feature-rich compared to Ammo.js
  • May not be as suitable for complex or high-performance physics simulations
  • Smaller community and fewer resources available

Code Comparison

Oimo.js:

var world = new OIMO.World({ 
    timestep: 1/60, 
    iterations: 8, 
    broadphase: 2,
    worldscale: 1, 
    random: true 
});

Ammo.js:

var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
var overlappingPairCache = new Ammo.btDbvtBroadphase();
var solver = new Ammo.btSequentialImpulseConstraintSolver();
var dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

The code comparison shows that Oimo.js has a more straightforward setup process, while Ammo.js offers more granular control over the physics world configuration. Oimo.js is designed for simplicity, whereas Ammo.js provides a more comprehensive set of options for advanced users.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ammo.js

Demos

Overview

Example code to give you an idea of the API:

ammo.js is a direct port of the Bullet physics engine to JavaScript, using Emscripten. The source code is translated directly to JavaScript, without human rewriting, so functionality should be identical to the original Bullet.

'ammo' stands for "Avoided Making My Own js physics engine by compiling bullet from C++" ;)

ammo.js is zlib licensed, just like Bullet.

Discussion takes place on IRC at #emscripten on Mozilla's server (irc.mozilla.org)

Instructions

builds/ammo.js contains a prebuilt version of ammo.js. This is probably what you want.

You can also build ammo.js yourself.

Usage

The most straightforward thing is if you want to write your code in C++, and run that on the web. If so, then you can build your C++ code with emscripten normally and either build and link Bullet using

https://emscripten.org/docs/compiling/Building-Projects.html

or you can use Bullet directly from emscripten-ports, with -s USE_BULLET=1. In both cases, you don't need ammo.js, just plain Bullet.

If, on the other hand, you want to write code in JavaScript, you can use the autogenerated binding code in ammo.js. A complete example appears in

examples/hello_world.js

That is HelloWorld.cpp from Bullet, translated to JavaScript. Other examples in that directory might be useful as well. In particular see the WebGL demo code in

examples/webgl_demo/ammo.html

Bindings API

ammo.js autogenerates its API from the Bullet source code, so it should be basically identical. There are however some differences and things to be aware of:

  • See https://github.com/kripken/emscripten/wiki/WebIDL-Binder for a description of the bindings tool we use here, which includes instructions for how to use the wrapped objects.

  • All ammo.js elements should be accessed through Ammo.*. For example, Ammo.btVector3, etc., as you can see in the example code.

  • Member variables of structs and classes can be accessed through setter and getter functions, that are prefixed with |get_| or |set_|. For example,

    rayCallback.get_m_rayToWorld()

    will get m_rayToWorld from say a ClosestRayResultCallback. Native JavaScript getters and setters could give a slightly nicer API here, however their performance is potentially problematic.

  • Functions returning or getting float& or btScalar& are converted to float. The reason is that float& is basically float* with nicer syntax in C++, but from JavaScript you would need to write to the heap every time you call such a function, making usage very ugly. With this change, you can do |new btVector3(5, 6, 7)| and it will work as expected. If you find a case where you need the float& method, please file an issue.

  • Not all classes are exposed, as only what is described in ammo.idl is wrapped. Please submit pull requests with extra stuff that you need and add.

  • There is experimental support for binding operator functions. The following might work:

    OperatorName in JS
    =op_set
    +op_add
    -op_sub
    *op_mul
    /op_div
    []op_get
    ==op_eq

Building

In order to build ammo.js yourself, you will need Emscripten and cmake.

For more information about setting up Emscripten, see the getting started guide.

To configure and build ammo into the builds directory, run the following:

$ cmake -B builds
$ cmake --build builds

There are also some key options that can be specified during cmake configuration, for example:

$ cmake -B builds -DCLOSURE=1                # compile with closure
$ cmake -B builds -DTOTAL_MEMORY=268435456   # allocate a 256MB heap
$ cmake -B builds -DALLOW_MEMORY_GROWTH=1    # enable a resizable heap

On windows, you can build using cmake's mingw generator:

> cmake -B builds -G 'MinGW Makefiles'
> cmake --build builds

Note that if you have not installed emscripten via the emsdk, you can configure its location with -DEMSCRIPTEN_ROOT.

Building using Docker

ammo.js can also be built with Docker. This offers many advantages (keeping its native environment clean, portability, etc.). To do this, you just have to install Docker and run:

$ docker-compose build        # to create the Docker image
$ docker-compose up           # to create the Docker container and build ammo.js
$ docker-compose run builder  # to build again the ammojs targets after any modification

If you want to add arguments to cmake, you have to edit the docker-compose.yml file.

Reducing Build Size

The size of the ammo.js builds can be reduced in several ways:

  • Removing uneeded interfaces from ammo.idl. Some good examples of this are btIDebugDraw and DebugDrawer, which are both only needed if visual debug rendering is desired.

  • Removing methods from the -s EXPORTED_RUNTIME_METHODS=[] argument in make.py. For example, UTF8ToString is only needed if printable error messages are desired from DebugDrawer.

Testing

You can run the automatic tests with npm test, which in turn will run ava against both the javascript and WebAssembly builds:

$ npm run test-js      # --> AMMO_PATH=builds/ammo.js ava
$ npm run test-wasm    # --> AMMO_PATH=builds/ammo.wasm.js ava

It's also possible to run ava directly for more options:

$ npx ava --verbose
$ npx ava --node-arguments inspect

When no AMMO_PATH is defined, builds/ammo.js is tested by default.

Running the Examples

http-server is included as a dev dependency as an easy way to run the examples. Make sure to serve everything from the repo root so that the examples can find ammo in the builds directory:

$ npx http-server -p 3000 .

Troubleshooting

  • It's easy to forget to write |new| when creating an object, for example

    var vec = Ammo.btVector3(1,2,3); // This is wrong! Need 'new'!

    This can lead to error messages like the following:

    Cannot read property 'a' of undefined Cannot read property 'ptr' of undefined

    This is an annoying aspect of JavaScript, sadly.

Reporting Issues

If you find a bug in ammo.js and file an issue, please include a script that reproduces the problem. That way it is easier to debug, and we can then include that script in our automatic tests.

Release Process

Pushing a new build in builds/ammo.js should be done only after the following steps:

  • Configure with closure enabled: cmake -B builds -DCLOSURE=1

  • Build both the asm.js and wasm libraries: cmake --build builds

  • Make sure they pass all automatic tests: npm test

  • Run the WebGL demo in examples/webgl_demo and make sure it looks ok, using something like firefox examples/webgl_demo/ammo.html (chrome will need a webserver as it doesn't like file:// urls)

Upstream Version

Bullet 2.82 patched with raycast fix from 2.83

NPM DownloadsLast 30 Days