avbd-babylon
v0.4.6
Published
GPU AVBD rigid-body physics with a Babylon.js aggregate API
Maintainers
Readme
AVBD for Babylon.js
TRY ME!!! babylon-avbd.netlify.app
avbd-babylon runs AVBD rigid-body physics and collision detection on WebGPU,
with an aggregate/body API that follows familiar Babylon.js conventions.
The package bundles its solver and shaders, with no Babylon runtime dependency.
Automatic GPU work sharing and collision selection are enabled by default.
AVBD calculates collisions, movement, rotation and friction. Babylon renders
the resulting poses; AvbdPhysics owns the physics world and its GPU solver.
Jump to:
- Benchmark sample code
- Demo source and initialization
- Install
- What this package adds
- Feature coverage
- Playable feature demos
- Screenshot gallery
- Gallery: destruction and large scenes
- Gallery: cloth and connected bodies
- Gallery: colliders, controls and rendering
- Complete falling-box example
- World and body settings
- Mixed collider gallery
- Brick wall and reusable cannonball
- Large pile with thin instances
- Direct GPU rendering
- Native physics with any renderer
- Choose a solver backend once
- Backend differences and benchmarks
- Native 3D world
- Native 2D world
- Bulk edits and GPU dispatches
- Reading selected bodies and contacts
- Joints, welds, springs, ropes and ragdolls
- Ball joints, welds and springs
- Ropes and ragdolls
- Tearable cloth
- Controlling bodies
- Contact recycling and paired benchmarks
- Bounce, triggers, masks and sleeping
- 3D hinges, angle stops and motors
- Queries, callbacks and sleeping
- 2D GPU physics
- 2D sleeping and hinge stops
- Slingshot siege demo
- Manual stepping and cleanup
- Worker integration
- Static terrain: hills, caves and overhangs
- Ships, water and destruction
- Worker and shared-memory benchmarks
- Reusable GPU and worker utilities
- D20 particle capacity
- Benchmark replication
- Babylon renderer comparison
- Script-tag usage
- Build and run the repository
- Validation and attribution
- First release checks
Benchmark sample code
Start here: Benchmark replication contains copyable
JavaScript examples. Run npm start, then open the
browser benchmark page to run the scenes yourself.
| What you want to reproduce | Sample code and runnable source | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Physics timings, including the AVBD paper scenes | Copyable physics example, scene measurement code, package timing examples, package runner | | Scene setup: piles, walls, joints, cloth and stress tests | Demo scene registry and builders, browser benchmark controller | | Babylon rendering versus direct GPU rendering | Rendering examples and commands, measurement code, runner | | Main thread versus dedicated worker and shared memory | Copyable worker example and commands, worker page, worker runner | | Batched body edits, pose reads and queries | Bulk-edit examples, measurement code, runner | | CPU compatibility versus WebGPU | Settings and results, measurement code, runner | | Sleeping and waking in large connected scenes | Sleeping example, per-scene on/off runner, connected-wall runner | | Sleeping stability while grabbing and settling | 28K ring check, jointed-drop timing and view check, saved jointed-drop results | | Ships, buoyancy and water | Scene explanation, scene builder, runner | | Grid versus HPLOC++ collisions | Collision guide, paired scene measurements, tree refit runner | | D20 particle collisions | Capacity benchmark, runner, reusable GPU particles, collision shader | | Movement solver and GPU scheduling | Movement runner, color-bucket runner, small-group runner | | Relative-motion contact recycling | Paired GPU scene runner, behavior checks, saved comparison | | Uploads and command batching | GPU upload runner, command encoding runner |
This README includes package-usage examples and benchmark console snippets;
each benchmark snippet names the page where it runs. Files under tests/
implement the browser measurements; files under scripts/ run those measurements
and save results. tests/README.md lists the validation and
benchmark commands. Saved reports and screenshots live in test-results/.
Demo source and initialization
Demo source guide lists each demo's configuration, builder, controls and shaders. Each demo has its own folder: for example, Galton board, ships, slingshot, terrain and tearable cloth.
Open scene.js to change bodies, constraints and solver settings; index.js
initializes demos with their own controls. The lab registry
selects scenes, while the shared runtime
initializes their solver and renderer for workers. Related size or feature presets
share a scenes.js builder. Rendering and execution helpers live in demo/shared/.
Build the bodies and constraints together, create one solver, and reuse its GPU
buffers. Initial shapes and sensors select the required shaders before compilation;
disabled collision groups are excluded from the initial contact-capacity estimate.
The startup check initializes every demo in a
paused worker with --all and records setup times separately from simulation
performance. Shader caches, device checks and scene size affect those times.
The scene view shows loading messages during setup, even with its performance
panel collapsed, and stays visible until the first GPU frame completes. Worker
startup reports also list the time spent in each setup phase.
The web demo loads the selected demo and renderer on demand. Worker controls use
a small generated scene catalogue; scene construction and physics stay in the
worker. First use still includes GPU device setup and shader compilation.
Install
With a published release and your project's ESM bundler:
npm install avbd-babylon @babylonjs/coreFor local development, run npm install and npm run build in this repository,
then run npm install /absolute/path/to/avbd in your Babylon project. npm pack
creates an installable archive named for the current package version too.
The package includes ESM, TypeScript declarations and a browser global build.
Babylon 9 is an optional peer dependency; integration examples are checked with
9.13.0. Installing AVBD alone does not install Babylon. For TypeScript Babylon
projects, install @babylonjs/core alongside AVBD as shown above.
For portable 2D/3D physics without Babylon, import from avbd-babylon/native.
That entry includes AvbdScene2D, AvbdScene3D, createSolverPipeline and createWebGPUDevice, with
independent declarations. Current TypeScript DOM libraries include the WebGPU
types; older compilers may need @webgpu/types in the project's types setting.
Your application does not need a WGSL loader or the repository's TypeScript sources.
WebGPU requires a supported browser on localhost or HTTPS. Small-scene drawing
can use Babylon's WebGL or WebGPU engine. WebGPU is the default physics backend;
native worlds also offer CPU compatibility. The repository demos include an
experimental WebGL2 solver, which is excluded from the npm package.
The scene browser runs a small 3D floor-contact check once per GPU device before
opening a 3D GPU scene. A box, sphere and capsule must settle on a thin floor.
GPUs that pass keep the normal batched execution and scene-based collision
selection. If it fails, the check tests GPU compatibility alternatives for contact
data, contact calculations, work sharing and collision search. It uses a path only after it
passes the same physics checks. These compatibility paths keep the equations,
timestep and iterations unchanged. The check runs at startup; it adds no
readbacks during normal simulation.
If every path fails, the demo stops and offers a diagnostic report under
GPU contact check in the sidebar. The report includes contact results, GPU
limits, collision counts, contact forces, solver dispatches and browser details.
It also checks whether the contact inputs and calculated forces agree on the GPU.
npm run test:mobile-contacts checks the same physics
with eight and nine storage bindings and checks the mobile layout with both
renderers; testing the layout does not substitute for testing a phone's GPU.
The physical-phone floor check verifies
boxes, spheres and capsules in Android Brave. npm run test:connected-phone
checks 2D/3D collisions, joints, bounce, triggers, masks, sleeping and queries
on an authorized, unlocked Android phone running the local demo.
The current Galaxy S23 GPU checks
cover both 2D and 3D in Brave. The phone scene checks
include hinges, sensors, terrain, cloth and 40,000-marble flow, with screenshots
and short measurements. Run these with npm run test:connected-demos.
AvbdPhysics.create() prepares its device automatically. Native 3D applications
can qualify a new device when creating it, or prepare a renderer-owned device
once before creating any solvers. A failed check throws instead of running
physics with broken contacts. 2D does not need the 3D check.
import { createWebGPUDevice, prepareWebGPUDevice3D } from "avbd-babylon/native";
const { device } = await createWebGPUDevice({
validate3D: true,
preferredLimits: { maxStorageBuffersPerShaderStage: 9 },
});
// Or, for an existing renderer-owned device:
await prepareWebGPUDevice3D(rendererDevice);
// scene3D.createSolver(device) now uses the verified GPU path.Direct renderer on a mobile layout · Babylon renderer on a mobile layout.
What this package adds
The package builds on the upstream AVBD solver with GPU collision detection, portable 2D/3D APIs and a Babylon integration:
- GPU collision trees and automatic selection. The HPLOC++ path builds a hierarchy of nearby objects, updates its bounds every step and periodically rebuilds it. Automatic selection uses a grid for uniform piles and walls, and the tree for large scenes with varied object sizes or linked thin plates. Both feed the same contact solver. The tree uses a portable hierarchical PLOC implementation with GPU treelet clustering and stackless traversal. See the algorithm, selection rules and benchmarks.
- A broad 2D and 3D feature set. Both GPU APIs provide rounded primitives, custom convex hulls, bounce, collision masks, non-solving triggers, contact events, filtered ray/shape casts and live body commands. Both support anchors, breakable joints, springs, hinge limits and torque-limited motors. 3D helpers also build ropes, ragdolls and elastic or tearable fabric. The table below records differences and limits; the playable demos show the features together.
- GPU execution for large scenes. Scene-dependent work layouts and contact scheduling share work across the GPU while retaining the selected AVBD equations, timestep and iteration count. Direct GPU pose buffers let a compatible renderer draw many bodies without downloading every pose. When CPU poses are needed, callers can request only the bodies they use. Large 2D and 3D worlds automatically use bitsets to group bodies for solving, reducing GPU scheduling work while preserving body order. Large rigid 3D scenes also update a contact's points in parallel. The shared contact-point layout stores only the needed entries of symmetric body matrices, reducing movement-solver work with the same contacts and equations. It also groups frequently read pose fields during solving, then restores the public body-buffer format before rendering, queries or body edits. Closed jointless 3D worlds of up to 32 bodies batch all movement iterations in one workgroup with shared body poses and the same reductions and equations. CPU command setup reuses settings and offset storage, uploads only changed step/sleep/bounce settings and skips repeated buffer bindings within a compute pass.
- Sleeping and live editing. Per-body sleep permission, support checks and impact checks allow resting objects to sleep and wake again. Large desktop 3D worlds track connected groups so impacts can wake a wall without waking unrelated walls on the same floor. Velocities, impulses, teleports, filters and motor targets can change during simulation. Welds capture their rest rotation from live GPU poses, and released constraint slots can be reused.
- Babylon and portable integration. Aggregate/body handles, automatic scene stepping and disposal, fixed-step control, module-worker compatibility, TypeScript declarations and ESM/CDN builds are included. Babylon remains an optional peer dependency. The portable APIs create physics without creating rendering meshes. Native 2D and 3D body handles share velocity, impulse, teleport, trigger, restitution, mask and sleep controls. Bulk edits reuse GPU upload buffers and group commands by body.
- Validation and reproducible measurements. GPU tests check physical behavior, collider pair coverage, queries, constraints, sleeping and failure recovery. Collision overflow or conflicting parallel groups hold a step and report the problem instead of silently dropping work. Browser tests cover all 69 scenes, controls, screenshots and stage timings; replication examples distinguish physics, drawing and the paper's measurements.
The underlying solver and retained upstream code are credited in Validation and attribution.
Feature coverage
The package includes both the Babylon aggregate API and portable GPU scene
builders (AvbdScene3D and AvbdScene2D). Integration examples use package exports;
benchmark replication also uses the repository's browser test harness.
It is an alternative physics integration, not a drop-in Havok/Physics V2
plugin: use AvbdPhysicsAggregate, rather than Babylon's PhysicsAggregate
and scene.enablePhysics().
| Feature | 3D GPU | 2D GPU | Babylon / package usage |
| ------------------------------------------------------ | --------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Static and dynamic bodies, rotation, inertia, friction | Yes | Yes | Aggregates in 3D; native 2D boxes, circles and capsules. |
| Boxes | Yes | Yes | Native collision shapes. |
| Spheres / circles | Analytic | Analytic | 3D addSphere(); 2D addCircle(). Exact rounded surfaces. |
| Capsules | Analytic | Analytic | 3D local Y, 2D local X. Full height / length includes both caps. |
| Finite lines / infinite planes | Use static colliders | Yes | 2D addSegment() is two-sided; addPlane() defines a solid half-space. |
| Cylinders | Convex hulls | No | Polygonal 3D approximations from mesh vertices. |
| Custom convex hulls | Yes | Yes | addHull() in both dimensions. Up to 32 boundary vertices. |
| Static heightfields and concave mesh terrain | Tiled convex contacts | Use static segments / hulls | Native and Babylon addHeightfield() / addStaticMesh(). Each triangle becomes a small static prism, preserving openings and overhangs. |
| Body velocity, forces, impulses and teleporting | Yes | Yes | Native gpu.body() handles or indexed solver methods in both dimensions; live GPU poses. |
| Batched body commands and packed velocity edits | Yes | Yes | editBodies() groups motion and property edits; packed linear/angular updates use one dispatch. |
| Automatic Babylon stepping and disposal | Yes | Yes | AvbdPhysics or native gpu.attachToScene(scene) in either dimension. |
| Manual fixed steps / worker execution | Yes | Yes | No renderer or DOM dependency in either solver. |
| Mobile browsers with WebGPU | Yes | Yes | Verified on Android Brave. Babylon's async factory and the scene browser prepare 3D automatically; native 3D apps use validate3D:true or prepareWebGPUDevice3D(). Requires WebGPU and HTTPS or localhost. |
| Automatic grid / HPLOC++ choice | Yes | Grid | 3D auto selection uses body sizes and workload. |
| GPU work sharing | Yes | Yes | Retains the configured physics and iteration counts. |
| Mesh / instance rendering | Yes | Yes | Use batch drawing for large scenes; portable builders do not create meshes. |
| Direct GPU pose drawing | Yes | Yes | Renderer and solver must share a GPUDevice. Body layouts differ by dimension. |
| Ball joints / planar hinges | Yes | Yes | 3D addJoint(); 2D joint with free angular row. |
| World anchors | Yes | Yes | Null body A in 3D; body index -1 in 2D. |
| Welds and breakable joints | Yes | Yes | 3D addWeld(); 2D joint with all three rows locked and optional breakForce. |
| Springs, linked ropes and ragdolls | Yes | Yes | 3D helpers; 2D bodies linked with joints/springs. |
| Hinges | Axis + angle limits | Planar + angle limits | addHinge() in both dimensions; optional angle bounds relative to creation. |
| Torque-limited motors | Yes | Yes | Both dimensions expose motor handles and live gpu.setMotor() controls. |
| Elastic / tearable fabric | Yes | Build spring networks | 3D addFabric() has point collisions and tensile fracture. The demo preserves material after tearing. |
| Relative-motion contact recycling | Yes, GPU and CPU | Yes, 2D and 3D | Boxes and convex hulls; rounded shapes refresh. Configurable distance and rotation limits; separation updates each step. |
| Per-body sleeping / waking | Yes | Yes | World sleeping, body allowSleep, live setSleepEnabled(); supported bodies rest, impacts wake them. |
| Restitution / bounce | Yes | Yes | Coefficient 0..1. Zero adds no bounce passes. |
| Collision masks | Yes | Yes | Both bodies must allow the pair. Includes sensors. |
| Contact / trigger events | Yes | Yes | Babylon onContact(); native gpu.watchContacts() + readContactEvents() in both dimensions. |
| Non-solving triggers | Yes | Yes | isTrigger:true; no contact forces. Static–static pairs are not scanned. |
| Raycasts | Yes | Yes | physics.raycast() or portable gpu.raycast(); masks and ignored bodies. |
| Sphere / circle casts | Yes | Yes | 3D sphereCast(); 2D circleCast(); exact rounded corner tests. |
| Continuous collision detection | No | No | Discrete contacts; timestep matters for fast objects. |
| Full Babylon Physics V2 / Havok plugin | No | No | Use AVBD aggregates, rather than scene.enablePhysics(). |
See the API reference and GPU validation guide for supported methods, numerical checks and limitations.
Playable feature demos
Also try ships, waves and sinking, hills, caves and overhangs and the interactive worker comparison.
Three more physics playgrounds offer thousands of independently simulated bodies:
| Playground | What you can do | | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Tornado town | Send swirling wind through twenty houses made from 4,400 breakable pieces. Stop the wind and let debris settle. The visible funnel marks an analytic wind field. | | Domino spiral | Start a chain reaction through 2,048 tiles, or drag tiles to make your own branches. | | Galton board | Open the visible hopper to release 40,000 marbles through twenty staggered rows of pegs into thirty-three bins in a shallow board. Gravity and collisions control the discharge and spread. Watch the live bin chart, shake the board or reset it. |
These scenes support direct WebGPU and Babylon thin-instance drawing, dedicated
workers and optional shared input. The force-field demo adds one GPU pass to the
existing physics command buffer; positions stay on the GPU. CPU compatibility
also retains the actions, with the expected cost of simulating thousands of bodies.
The main scene browser and the naval demo default to a dedicated worker when
OffscreenCanvas is available. Physics and drawing run in the worker while the
scene selector and controls stay on the page. Choose Main thread, or add
scope=main to the scene URL, to compare execution. Specialized scene editors
are available through the scene editing link in the sidebar.
Every AVBD example has a Sleeping toggle for comparing the same scene with and
without sleeping. Demo defaults use paired measurements of sleeping on and off;
size alone does not mean sleeping is faster. The per-scene results
show active and later physics costs on an RTX 4070 Laptop GPU. Run
npm run benchmark:scene-sleep to repeat the comparison and regenerate the
demo presets. These defaults affect the demos; package callers choose their
world's sleeping policy. Add sleeping=1 or
sleeping=0 to choose explicitly; moving water and wind still keep affected
bodies awake. The half-million wall demos keep the original two-ball benchmark
until you click Bowl every row, which launches balls into all sixteen lanes.
The Galton board runs fixed physics steps against elapsed time, catching up
across frames when needed. Catch-up is bounded when the GPU is overloaded.
Click or tap a peg to retract it; its coral cap restores it. Restore all pegs
returns the original layout without releasing the hopper or resuming a paused
simulation. Peg movements and collision-filter changes are batched GPU edits.
Playground checks cover standing structures,
chain propagation, the 40,000-marble distribution and worker rendering. Run npm run test:playgrounds.

Run npm start and open the links below. Every scene uses GPU physics. The
scene browser and benchmark
includes all presets and lets you play them before measuring performance.
The scene check report contains
screenshots and results after npm run test:web.
| Features to try | 2D example | 3D example | | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rounded colliders, custom hulls, friction and bounce | Mixed colliders | Mixed gallery, hulls | | Hinges, angle limits and motors | Reverse or brake the motors | Reverse or brake the motors | | Triggers, collision masks and live filter changes | Toggle shelf collisions and detection | Toggle shelf collisions and detection | | Filtered ray and circle/sphere casts | Cast buttons | Cast buttons | | Anchors, ropes, springs, ragdolls, fracture and live impulses | Slingshot siege | Ropes, rigid net and ragdolls | | Welded construction and breakable joints | Slingshot forts | Castle siege | | Sleeping and waking | Resting pile, slingshot impacts | 100K rook impact | | Deformable fabric and persistent tearing | Spring networks in slingshot siege | Tearable cloth, fabric and blocks | | Large collision workloads and batch rendering | 100K pile | 100K columns, half-million walls |
The ragdoll net and 100K columns use five solver iterations. Individual scenes keep their own timestep and iteration count; the benchmark records those settings. Native builders create physics bodies without rendering objects. Babylon integration, workers, disposal and body commands are covered by the usage examples below and package tests rather than separate visual scenes.
The Voronoi demolition adds a suspended wrecking ball, irregular convex stone pieces and breakable face welds. The pieces extend through the wall thickness and remain in the scene after breaking loose.
Screenshot gallery
These captures come directly from the browser test results. Click an image to open the full-size screenshot. Use the playable demo links to explore the scenes yourself. The saved runs use an RTX 4070 Laptop GPU. Timing overlays show a captured step; the solver performance report contains the repeated measurements and hardware details.
| Intact Voronoi stone wall | Wrecking-ball fracture |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
216 convex stones fill a bounded Voronoi partition; shared faces carry breakable welds. |
Play the demolition. Released stones remain physical debris. |
| Mixed collider gallery | Chain-mail ring spacing |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Babylon meshes follow the GPU poses, with visible contacts and shadows. |
Ring sizes follow the link spacing. The net uses jointed rigid proxies; the donuts are decorative geometry. |
Destruction and large scenes
| Castle siege | 100,000-brick impact |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Breakable mortar holds the castle together until a cannonball hits. |
After six simulated seconds, fallen bricks fill the opening while the outer wall remains standing. |
| 110K brick ring | Half-million brick walls |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
A circular masonry wall with a localized impact. |
505,923 bodies, four solver iterations and the HPLOC++ collision tree. |
| 100K box columns | 32K box pile |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
Five solver iterations, batch drawing and optional enhanced colors and lighting. |
A dense contact workload for GPU collision detection and solving. |
| 2D slingshot siege | 100K 2D collision stress test |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Breakable forts, ropes, springs, powered gates, sensors and ragdolls. |
100,000 touching boxes with gravity, friction and GPU drawing. |
Cloth and connected bodies
| Ragdolls on a rigid net | Persistent torn fabric |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Linked rigid plates catch the ragdolls; this scene uses five solver iterations. |
The detached patch falls and remains visible and physical, with no automatic lifetime. |
| Deformable cloth and 35K blocks | Flag in the wind |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
A spring-based fabric workload with point-sampled collisions. |
Connected bodies form a flexible flag. |
| Chain mail | Jointed bridge |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
A network of rigid bodies connected by joints. |
Anchored bodies and joints carry the bridge load. |
| 3D rope | 2D soft body |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
A rope built from connected rigid bodies. |
Compliant constraints connect the bodies into a deformable structure. |
Colliders, controls and rendering
| 3D convex hulls | Mixed 2D colliders |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Custom hull geometry participates in the GPU contact solver. |
Rounded and polygonal shapes share the same 2D world. |
| 3D hinges and motors | 2D hinges and motors |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Angle stops, torque-limited motors and live reverse/brake controls. |
The same motor and limit controls in a planar world. |
| 3D triggers and masks | 2D triggers and masks |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
Non-solving overlap detection, collision filtering and ray/sphere casts. |
Live mask changes, trigger events and ray/circle casts. |
| D20 collision benchmark | Direct GPU pose rendering |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
GPU particles are drawn as sprites around the rotating collision target. |
The rendering example below draws 4,096 boxes without downloading their poses. |
Complete falling-box example
Add this HTML to a bundled Babylon application and use src/main.js as its entry:
<style>
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
</style>
<canvas id="canvas"></canvas>
<script type="module" src="/src/main.js"></script>// src/main.js
import {
Engine,
Scene,
ArcRotateCamera,
HemisphericLight,
MeshBuilder,
Vector3,
} from "@babylonjs/core";
import { AvbdPhysics, AvbdPhysicsAggregate, AvbdShapeType } from "avbd-babylon";
const canvas = document.getElementById("canvas");
const engine = new Engine(canvas, true);
const scene = new Scene(engine);
const camera = new ArcRotateCamera(
"camera",
-Math.PI / 2,
Math.PI / 3,
12,
new Vector3(0, 2, 0),
scene,
);
camera.attachControl(canvas, true);
new HemisphericLight("light", new Vector3(0, 1, 0), scene);
const physics = await AvbdPhysics.create({
scene,
gravity: new Vector3(0, -9.81, 0),
timeStep: 1 / 60,
iterations: 10,
capacity: 64,
});
const floor = MeshBuilder.CreateBox(
"floor",
{ width: 20, height: 1, depth: 20 },
scene,
);
floor.position.y = -0.5;
new AvbdPhysicsAggregate(floor, AvbdShapeType.BOX, { mass: 0 }, scene);
const box = MeshBuilder.CreateBox("box", { size: 1 }, scene);
box.position.y = 4;
const fallingBox = new AvbdPhysicsAggregate(
box,
AvbdShapeType.BOX,
{ mass: 2, friction: 0.6 },
scene,
);
fallingBox.body.setAngularVelocity(new Vector3(0, 1, 0.5));
engine.runRenderLoop(() => scene.render());
const resize = () => engine.resize();
window.addEventListener("resize", resize);
window.addEventListener(
"pagehide",
() => {
window.removeEventListener("resize", resize);
scene.dispose(); // also disposes its AVBD world
engine.dispose();
},
{ once: true },
);The world attaches fixed-step simulation and disposal to the scene. The render
loop only calls scene.render(); do not also call physics.step() there.
Pose synchronization is asynchronous, with one outstanding copy and at most
three catch-up physics steps per rendered frame.
Create all aggregates before the first step or initialize(). Reading
bodyBuffer, body.gpuIndex or solverDecision also initializes the world.
Reserve reusable bodies for objects you plan to launch later.
World and body settings
| World option | Default | Use |
| ----------------- | --------------- | -------------------------------------------------------- |
| scene | None | Attach updates and disposal to a Babylon scene. |
| gravity | [0, -10, 0] | Vector3 or a three-component array; y up by default. |
| timeStep | 1 / 60 | Simulated seconds advanced by each step(). |
| iterations | 10 | Solving rounds per fixed step. |
| capacity | 4096 | Aggregate count, including static and reserved bodies. |
| autoAttach | true | Set false for a manually managed loop. |
| syncMeshes | true | Asynchronously mirror GPU poses to Babylon meshes. |
| maxSyncedBodies | 2048 | Guard against mirroring a huge scene one mesh at a time. |
| broadphase | "auto" | Automatic, or explicit "grid" / "hploc". |
| solverMode | "auto" | Automatic GPU implementation selection. |
| contactRecycling | false | Reuse barely moving contacts; true or { distance, maxAngle }. |
| bvh | {} | Tree options such as { rebuildInterval: 64 }. |
| device | Created by AVBD | Optional caller-owned GPUDevice. |
Aggregate options include mass (default 1), friction (0.6), restitution
(0, valid range 0–1), `isTrig
