Hacker News new | comments | show | ask | jobs | submit login
Matter.js – A 2D rigid body physics engine for the web (brm.io)
545 points by brbcoding on Jan 19, 2015 | hide | past | web | favorite | 62 comments



This is very impressive! The most advanced JS 2d rigid body physics engine to date! You can do a lot of optimization though, probably double the speed. Tip: V8 loves objects and hates parsing strings.

Your functional spaghetti style is a bit weird though. I hate using the "find in file" function in my editor. I wanted to "rip" some of the functionality, but it's so entangled I would probably need all your other functions too to make it work. But maybe that's intended :P

Many people, me included, would be willing to pay for an engine like this. I tried your "Game physics for beginners" but I'm too stupid to understand all the articles from math professors. I could probably learn, but I rather pay someone who understands.

But for me to use your engine, the API needs to be much easier! Something like this:

  var box1 = new Body(size, position);
  var world = new World({gravity: 9.8});
  world.add(box1);
  world.render();

  console.log('New position: ' + box1.position);


It is more advanced than Box2D [0]? What makes you say that?

http://blog.sethladd.com/2011/09/box2d-javascript-example-wa...


Box2D is ported from C++ to Flash and then from ActionScript to JavaScript. So it might be slow to get updates and bug fixes.

But it looks usable and seems to have the same features as Matter.js


This person has produced some pretty incredible things with HTML/JS/CSS (including Matter.js).

http://brm.io/work/


I'm especially impressed by the time scaling. Back when I fiddled around with physics collision/physics libraries years ago (ODE), have a fixed timestep was a fundamental design decision and changing that led to weird and unpredictable behaviour.

Things have come quite a long way :)

Edit: still has problems with squishiness of stacked solid objects though :\


When I was evaluating engines for Hype Pro's [1] physics system, I compared based on file size, commit/project activity, how easy it would be to modify and integrate, and the license (for obvious reasons). I looked at Matter.js, Verlet, PhysicsJS, p2.js, JPE, Newton, and box2d-js. While many have their respective strengths, overall Matter.js stood a notch above the rest. The code has been easy to work with and Liam has also been responsive in fixing bugs or accepting patches. It is truly a gem of a project.

[1] http://tumult.com/hype-pro/


Pros: The samples play well, look fun, and it looks like a great solution to small physics demos in JS. Great job!

Cons: Playing with the Stress demos (especially #2) really shows the slowdowns and downsides to using a JS based engine. At 450 boxes (+ 4 bounding walls), it runs at 20fps on my Macbook and thats with a lot of jitter and overlap. Not as fun.

Edit: Significantly better w/ WebGL render, @32fps, and with sleeping+WebGL render @34fps.

I wish I could see a physics engine using WebGL and GPU acceleration for the web. This one is a great start if the author were to take it further and implement some of the logic with shaders.


How does it compare to, say, Box2D ported to JS using Emscripten?

http://kripken.github.io/box2d.js/webgl_demo/box2d.html


Good question. I also wonder how it compares to other popular 2D js physics engines:

p2.js: http://schteppe.github.io/p2.js/

PhysicsJS: http://wellcaffeinated.net/PhysicsJS/


> Cons: Playing with the Stress demos (especially #2) really shows the slowdowns and downsides to using a JS based engine. At 450 boxes (+ 4 bounding walls), it runs at 20fps on my Macbook and thats with a lot of jitter and overlap. Not as fun.

Have you tried enabling sleeping? Even most AAA games don't actually have even remotely close to that number of bodies active in a game at once. Sure, the engines can handle it, but having a stack of bodies like the stress demos is the absolute worst case, as you normally have to resolve a chain of contacts, in this case a few hundred, iteratively. Most physics engines also benefit hugely from multithreading, something which JS doesn't provide.

> I wish I could see a physics engine using WebGL and GPU acceleration for the web. This one is a great start if the author were to take it further and implement some of the logic with shaders.

That was tried on PC and consoles and most game developers are going back to using the CPU for physics calculation, and using the GPU for rendering. Using WebGL with this particular demo shouldn't increase the performance if the bottleneck is the physics simulation.


This JS physics engine isn't multi-threaded but it does run the physics on a separate thread

http://chandlerprall.github.io/Physijs/


GPU acceleration isn't going to be practical until >WebGL2, when we get access to compute shaders.

You can technically do compute now by expressing your data as textures and performing rendering passes over it, but trying to do anything non-trivial that way will quickly lead to madness.


I mean, this is what I'm looking for. Sure it would be madness, but if you have 450 bodies represented by, say, 10 floats each (random number), that comes to about 4500 pixels of values- something a GPU is fine at.


in 3d you normally represent by a 4x4 matrix, which can be easily reduced to 6 floats (x y z translation, and x y z rotations). The problem with doing that little work is you'll very quickly be bottlenecked by copying memory to/from the GPU. If you want to do any raycasts for instance, or query for occlusion/bounds testing, you need to upload data to the GPU, run a (potentialy very slow, serial) query, then copy the result back. The results normally aren't worth it.


The question then becomes how slow is copying to/from the GPU versus doing the computation on the CPU when it comes to 100s/1000s of active bodies.

I agree that normally (small examples) it wouldn't be worth it, but for any large simulations, and say, video games of the future, I have yet to see someone attempt to do this. Perhaps it truly isn't beneficial enough... but who knows.


> The question then becomes how slow is copying to/from the GPU versus doing the computation on the CPU when it comes to 100s/1000s of active bodies.

The amount of time spent inside a GPGPU kernel for updating 1000 rigid bodies wouldn't even be as much as the length of time to copy the data back and forth. You've also got to consider the acceleration structure used for the collision detection. If you have a hierarchical tree-like structure (BVH, BSP tree) then how do you update it in parallel. you need to spin off thousands of tasks for it to be worth running on the GPU. If you have that many dynamic bodies, you're probably going to be draw call limited in trying to render them, unless they're exceptionally simple objects (Particles for example, which are already GPU accelerated in modern Game Engines).

> I agree that normally (small examples) it wouldn't be worth it, but for any large simulations, and say, video games of the future, I have yet to see someone attempt to do this. Perhaps it truly isn't beneficial enough... but who knows.

In modern AAA video games, the active body count in a scene would be no greater than the hundreds. Think of a scene from Assassin's Creed, or Battlefield, and think about how many truly dynamic things there are in the level. Chances are, there's you(the player), a handful of other players, a handful of explosive barrels, maybe 5-10 vehicles, and a few extras for bodies. For something like Assasin's creed, the computation is most likely in the animation, where hundreds of physics raycasts from the players hands to the various "climbable" points are performed, and the updating of the very detailed skeletal mesh. Modern games utilise almost 100% of the GPU time already on rendering for lighting, AA, shadows, ambient occlusion, transparency, reflections. To add more stress to the GPU is unnecessary really, considering that the computations are so short for a few hundred bodies that the bottleneck will be copying the data over and back.

I wrote my masters thesis on GPGPU accelerated Bounding Volume Hierarchies (A common structure used in Raytracing and in Collision Detection). The overhead of a small copy stalling the GPU is quite severe. It's worth it if you can do all your work on the GPU without having to copy back, but that's currently not feasible for interactive simulations.


Thanks for the insights :)


You don't have to wait for video games for the future, GPU physics is commonplace in games. See eg https://en.wikipedia.org/wiki/List_of_games_with_hardware-ac... though that list hasn't been kept up to date.


Anything that uses NVidia Physx will have GPU physics in some sense, but very few (if any) of those actually use GPU acceleration for their rigid body simulations


Have you seen PixiJS? http://www.pixijs.com/ It's used by PhaserJS, a very promising JS Game Framework


Pixi is the rendering engine used by Phaser. More relevant is the different physics engine Phaser supports (Box2D, P2 and its own lightweight arcade physics engine). Also Phaser is Typescript but distributed as JS. You can link it directly with Typescript too though which is why I like it a lot.


Phaser.js was at some point in the past written in TypeScript, the current version is implemented in JS and you can use it from TS if you wish. (Also, they will probably ditch the Pixi renderer in the next Phaser version and use their own.)


Was it written from scratch or inspired by Box 2D?


This would have to start talking about the problems with previous attempts (box2d...)


There are some bugs with "enable sleeping" turned on. Occasionally an object that is sleeping seems to fail to have external forces act upon it. For example, you can end up with a sleeping object sitting on top of another object, and when the object falls out from under it, the sleeping object stays stuck in midair. I can reliably make this happen by toggling "enable sleeping" on and off (example: load up "wrecking ball", stop the wrecking ball before it hits the pile, turn on "enable sleeping", wait for all the blocks in the pile to go to sleep, then turn "enable sleeping" back off and you now have a stack of immovable blocks which the wrecking ball bounces off of, and which will hover if you remove the bricks below them), but I saw the bug occur even when I wasn't flipping this setting back and forth.


Enabling sleeping is a difficult thing to actually do, especially in a stack of bodies. You have to enforce a minimum movement threshold over a series of frames usually, and group bodies together to go to sleep, and also wake the same group up when there's motion. It's not always easy to do


I've used this a lot in the past few weeks. It's really amazing. It has some trouble with triangles. But having a physics engine completely written in Javascript from the ground up using good JS principles is refreshing. One of the coolest features is mobile demo. Buttery smooth on my iPhone.


I am familiar with P2 JS, looked through PhysicsJS and the two very basic arcade engines grown within Phaser JS. Matter JS seems to have the exact same feature set like any other library. I haven't seen any 2D web engine, besides the JS ports of Box2D, which supports continuous collision detection (CCD), which would prevent a lot of tunneling, especially on slower mobile phones.

Why is that? CCD doesn't look more complex in theory than any other concept in a 2d physics engine.

P2JS: https://github.com/schteppe/p2.js PhysicsJS: http://wellcaffeinated.net/PhysicsJS/ Phaser: http://phaser.io/


I wonder how it compares with P2.js. Another nice pure JavaScript 2D physics library. https://schteppe.github.io/p2.js/


I spent a good deal of last week comparing these two for a side project. I found that while p2.js supports a bit more that I need (specifically compound objects) It was harder to get going since you have to handle your own rendering. Whereas matter.js has it's own swappable rendering engine.


Why all those "physics engines" are so jittery? Are there no ways to solve such a system with perceptually exact accurancy in realtime?

Those kinds of approximations are the source of some of the most hilarious bugs in games over last deacade or so.

Please don't read this as a critique of this particular project which is pretty good at what it's trying to do.

I just wonder why AAA games use pretty much the same math? Are there no better math?

I mean CAD systems obviously do something better... Is that the same thing as with drawing triangles vs. raytracing?


Animation is an illusion of motion caused by a sequence of still images. The way a physics engine works is by computing those still images -- the frames -- for each iteration in a mathematical model (the physics you want.)

If you want 60 frames per second for a smooth animation, you have to compute the whole frame less than 1/60th of a second. The more complicated your physics model is, the harder it is to do this.

>I just wonder why AAA games use pretty much the same math? Are there no better math?

The math they use is just standard physics, often using some simplifications or optimizations to speed up the calculation. "Better math" is a curious term. If you want more accuracy, you have to give up speed. You can't have both. You either get jittery/jerky motion or you get unrealistic effects. Of course, running on a faster machine or finding a better optimization will help, but that also requires a ton of expertise and is sometimes plain infeasible.

>I mean CAD systems obviously do something better... Is that the same thing as with drawing triangles vs. raytracing?

CAD systems with physics engines do the same thing as above, and they have to make the same kinds of decisions. Usually, CAD software is meant for design, so it would opt for higher precision. This isn't suitable for games except on very high-end machines, which would exclude a lot of people from buying your game.

As for ray tracing vs rasterization: Yes, it is the same kind of trade-off. Ray tracing can be made very accurate and do some amazing things, but the frame rate is usually so low that you have to pre-render the whole animation beforehand. That is, if you want high quality.

Rasterization gives medium-low quality at very high framerates. It is very common because it is 'good enough looking' for most purposes, where an equivalent quality ray tracer would be very slow. Of course, a physics engine is independent of your rendering method: you will have to compute physics for your scene whether you use ray tracing or rasterization, so you have to take both into account for determining how jittery your animation will look.


The math is not just standard physics. That undermines the essences of the difficulties of doing physical simulations. Many of the design choices have to do with numerics, discretization of time, collision detection, etc.

Physics doesn't concern itself, for example, with how to represent polyhedral shapes, or how to compute their intersections. In the world of computer simulation, there are surely more algorithmic developments to be made. Even if the physics hasn't changed (much) for the last 300 years, there are new ways to precondition systems, and solve them, and so on. I think that's what is meant by "better math".

I think you make a good point about the trade-off difference between CAD and games. In addition to requiring that games be simulated in real-time, you also want the simulation to be causal. In a CAD tool, you can take advantage of being able to do "multiple passes" through time to refine your simulation. In a game, once you've computed the quantities pertinent to a frame, you don't get to go back and recompute those quantities and present them.


> "Better math" is a curious term. If you want more accuracy, you have to give up speed.

What I mean is for example to integrate something numerically you can just add small increments but this will lead often to crap unstable solutions. Or you can use Runge-Kutta and get very accurate stable result.


Stiff springs. Look it up.


http://i.imgur.com/QcKoWLj.png

Doesn't seem to render correctly on Chrome 39. Works fine on latest Firefox.


Same for me (chrome 39.0.2171.99, win 7) But it seems to work using webgl renderer !


Indeed, changing that makes it work for me too, using canvas is broken. ( In the settings to the right, Renderer -> renderer )


Worked perfectly at 60FPS on my 13" rMBP (Intel 5000, I think?) in the latest Safari, of all browsers! I was super impressed.


It looks ok on my Chrome 39.0.2171.99 m on Win7.


Replying to my own post to add details.

Windows 7 AMD HD 7970 3GB


demo request:

I want a demo where the user can control a soft body ball such that the ball is comprised of chain segments, connected with string constant k. The pressure of the ball would be calculated depending on the area enclosed by the chain's polygon and would be applied to each segment equally, to the outwards side. Controls would be left/right as a simple added force to all segments of the ball. Jump would be increased air amount (target surface area) and crouch would be decreased k. In my imagination, the ball would be low friction and would grow throughout the game, to take on bigger adversaries.

(Sharing it here cause I didn't get to code it in years but I would really love to see if the control would work.)



When I saw Gish for the first time, I thought the same but I bet they fake a lot of physics.


Maybe this is something like what you described: try the 'Blob Test' example from Box2D-html5

https://code.google.com/p/box2d-html5/


You probably want a soft body physics engine, not a rigid body one. Something that could use Verlet + pressure-based techniques, for example.


Well, I was precisely interested if it could be modeled with a chain. Otherwise thank you for you pointers.


This is really impressive! Just a small bug report:

http://brm.io/matter-js-demo/#bridge somehow had some things fall through to the ground the first time in loaded.


Pretty slick. I think I might be using this at Global Game Jam this weekend.

On a side note though, it seems that there are some issues if you get things moving fast enough. I was consistently able to fling shapes through the walls on the first demo.


Impressive - on the face of it, it seems both versatile and stable.


Really nice, noticed a few jitter issues on the bridge example, that's possibly one of the hardest thing to do in a physics engine (that and fast moving objects).


Very nice. But strange things happen in the "car" demo if you put one car on top of the other: they try to throw off each other like horses.


Nice work. As someone who built physics engines years ago, it makes me kind of happy that solving stacking is still no trivial task.


It looks simply great. The efforts put together for creating this library are commendable.


Does not seem to work good in Chrome or Opera for me, all movement leaves trails.


How is the cloth demo done? Is it with partial differential equations



Very cool, love the variety of demos. :)


This is amazing!


Fun!


Physics and collision detection in JS. One can only imagine the horror.


lol




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: