
Show HN: A 2D Physics Simulator in JavaScript - xchip
http://htmlpreview.github.io/?https://github.com/aguaviva/Physics/blob/master/RigidBodyChainVSstack.html
======
olegkikin
Why is this upvoted so much? In what way is it better than any of the existing
JS physics engines?

Matter.js: [http://brm.io/matter-js/](http://brm.io/matter-js/)

Cannon.js: [http://www.cannonjs.org/](http://www.cannonjs.org/)

PhysicsJS:
[http://wellcaffeinated.net/PhysicsJS/](http://wellcaffeinated.net/PhysicsJS/)

Box2DJS: [http://box2d-js.sourceforge.net/](http://box2d-js.sourceforge.net/)
(Emscripten-compiled from flash)

p2: [https://github.com/schteppe/p2.js](https://github.com/schteppe/p2.js)

Ammo.js:
[https://github.com/kripken/ammo.js/](https://github.com/kripken/ammo.js/)
(Emscripten-compiled from C++)

JPE: [https://github.com/colorhook/JPE](https://github.com/colorhook/JPE)

Oimo.js: [https://github.com/lo-th/Oimo.js/](https://github.com/lo-
th/Oimo.js/)

Planck.js:
[https://github.com/shakiba/planck.js](https://github.com/shakiba/planck.js)

~~~
xchip
All those are great physics engines. Mine is just very simple and easy to
understand, hopefully it inspires other people to get into the world of
simulations.

~~~
looki
Also thanks for the reference to Erin Catto's talk, need to check it out.
Maybe physics engines aren't magic after all.

~~~
xchip
In fact that was one of the reasons that compelled me do write my own, because
physics engines looked to me like voodoo magic. Thanks for understanding my
obsession with learning :)

------
ell0ell0
If you want to look at precedence or what other people have done successfully
in this space check out [http://brm.io/matter-js/](http://brm.io/matter-js/)
matter JS. It's pretty sweet.

~~~
xchip
pretty cool and inspiring!

------
xchip
It features collisions, collisions response and hinges-constraints.

I also wrote a tutorial on how constraints work (probably the the most
difficult part)

~~~
mobiletelephone
Cool!

Is it deterministic? Does it do destructive updates?

~~~
xchip
Thanks! What do you mean by deterministic/destructive updates?

~~~
kroltan
No idea what destructive updates are, but determinism is when you can run
multiple times in multiple environments and get the same results

~~~
xchip
then yes, it is deterministic :)

~~~
reificator
I don't mean to be rude, but if you don't know the term I'd put money on it
not being deterministic. Especially if you're running in JavaScript on
multiple browsers.

A single step that isn't consistent in behavior across every setup is enough
to make the entire process non-deterministic.

------
dkonofalski
Is this really a simulation if you can't modify any of the objects? For all we
know, this could all be pre-calculated or pre-animated. Everything moves
exactly the same way every time.

~~~
FroshKiller
It moves differently in different browsers for me. And neither instance seems
to actually make physical sense.

In Chrome, the fourth box from the top starts sliding when it hits the floor,
pushing the box to the right clear off the floor box. Every box eventually
slides along the floor and falls into the pit.

In Firefox, the fourth from the top stays put. It never pushes the box on the
right, though all the rest eventually slide into the pit.

~~~
SketchySeaBeast
In Firefox Developer Edition everything happens faster than in regular
Firefox, though they seem to end at the same result. I wonder why that is.
Animation doesn't seem much faster.

I think the "neither instance seems to actually make physical sense" is due to
a lack of friction.

~~~
xchip
The animation speed is determined by a timer, this _should_ make it run the
same in all the browsers. Is the simulation nice and smooth all the time?

Friction is a biggie that I need to add ASAP!

~~~
pjc50
I suspect you're experiencing the joy of floating-point nondeterminism.

Edit: yup, it's the same every time _per browser_ , but I can have e.g. Edge
and Chrome running next to one another doing different things.

~~~
archgoon
Hey hey hey, let's not blame floating point here ;).

Floating point is completely deterministic (as you note by getting the same
behavior every time you run the simulation in the browser). I'm looking at the
js spec, and there shouldn't be any freedom in evaluating floating point
expressions (but overly clever browser vendors may have ignored that and
reordered them anyhow).

However, I do know for a fact that the implementations of the Math.sin and
Math.cos functions are browser specific,

[https://tc39.github.io/ecma262/#sec-
math.sin](https://tc39.github.io/ecma262/#sec-math.sin)

so that alone will remove any chance at browser independent reproducibility,
without additional controls.

Be interesting to see if replacing Math.cos and Math.sin with your own
implementation would remove the cross browser dependency.

Btw, spec conforming implementation of Math.sin

    
    
      function sin(x) {
        if (   x === Infinity 
            || x === -Infinity
            || x === NaN) {
          return NaN;
        }
        return x;     
      }

------
romaniv
If you're interested in this kind of stuff, I highly recommend reading or
watching something about Ivan Sutherland's Sketchpad.

[https://www.youtube.com/watch?v=USyoT_Ha_bA](https://www.youtube.com/watch?v=USyoT_Ha_bA)

~~~
xchip
I knew that one! is fantastic isn't it!? This is one of my favourites:
[https://github.com/xibyte/jsketcher](https://github.com/xibyte/jsketcher)

------
pdm55
Thanks, good show. Another one I like is
[http://physics.weber.edu/schroeder/html5/](http://physics.weber.edu/schroeder/html5/).
See Newton's cannon etc.

------
thanatropism
This is where I show that I know nothing about physics engines:

... does it have conservation of energy? Can you track total energy somehow?

... does it obey approximately some kind of Liouville theorem?

~~~
santaclaus
> does it have conservation of energy? Can you track total energy somehow?

You're going to need a geometric integrator for that, probably an energy-
momentum integrator. In practice it is often better to conserve the symplectic
form instead of energy, though, and you can show that for fixed time-steps you
can't get all of energy/momentum/symplecticity at the same time (I haven't
looked at this for a while, a student of the school of Marsden jump in if I'm
saying anything wrong). Furthermore, these guarantees all require
integrability...

~~~
thanatropism
My (ongoing) thesis is in the field of symplectic integrators.

I was asking about these simplified physics engines (in games, etc.) that are
probably not deriving physical laws out of whole conservation- (or Noetherian
symmetry-) cloth.

~~~
santaclaus
Very cool! Game rigid body engines (to my knowledge) usually use symplectic
Euler (v^{n+1} = v^n + h M^{-1} F^n, q^{n+1} = q^n + h v^n) with a
Moreau/Stewart-Trinkle velocity level discretization of non-penetration
constraint (effectively impulses), usually lobbing off the quadratic velocity
term (so no precession). These constraints are typically solved in a
(projected) Gauss-Seidel fashion to horribly loose tolerances, with liberal
post-stabilization thrown in. Outside of rigid bodies, for the most part in
games, these days, you don't get 'simulations' that can be derived from a
variational principle, but that are instead constraint satisfaction problems
with some notion of momentum hacked in the side (see 'Position Based
Dynamics', 'Shape Matching').

The movie folks have larger compute time budgets, and I've seen various
geometric integrators used there. I know of at least one studio that uses
implicit midpoint for thin shell simulation. The Cal-Tech influence has wormed
its way into the graphics research world, at least, and you see some papers
pop up there frequently looking at geometric integrators. This Danish guy (I'm
forgetting his name) at Disney publishes papers every now and then on the
topic.

~~~
xchip
Amazing post!

------
samuraiseoul
The contact link just says <my_github_account_username>@gmail.com. I'd love to
look at some actual code if there's a github link?

~~~
xchip
There is code and there is also some quick tutorials on how constraints work,

[http://htmlpreview.github.io/?https://github.com/aguaviva/Ph...](http://htmlpreview.github.io/?https://github.com/aguaviva/Physics/blob/master/ChainSimulation.html)

this one shows how to solve a double/n pendulum, which is something that is
not explained in detail anywhere. So if you want to learn how constraints work
that should get you up to speed!

------
santaclaus
Is there friction or non-zero restitution?

~~~
xchip
There is no friction so far but I will add it whenever I have a chance!

------
dmitrygr
The only part missing? Physics...

Somehow boxes slide along a flat floor with no deceleration until they fall
off the screen

~~~
eric_h
I think the word you were looking for was "friction". This certainly looks
like a simulation that a physics professor would propose on a chalk board:
"Ignoring friction for the purpose of this exercise..."

------
laythea
Erm, no offense but:

a) physics programs are supposed to offer interactivity. Else whats the point?

b) the physics look unearthly

~~~
santaclaus
> physics programs are supposed to offer interactivity. Else whats the point?

To solve differential equations for which analytical solutions do not exist?

Edit: Differential inclusions, if inequality constraints are included in the
system (as they would here).

~~~
laythea
Of course it depends on what the goal of the program is, but something like
this should offer user interactivity. By solving whatever is necessary (or
faking it).

------
danilocesar
Out of curiosity: The chrome tab running the engine is using 55% of my CPU, an
i7-4770K running at 3.5Ghz...

Box2D with many more objects consumes 22%.

Oimo, with a 3D rendering scene with TONS of objects: 35% CPU..

Matter.js, lots of objects with mouse interaction: 15% CPU.

Plank, lots of objects: 25%

I'm wondering how/why this ended up in the front page...

~~~
xchip
Physics engines are like magic and it is pretty hard understand how the work
even if you read the paper many times. Also physics engines are interesting
not only because four the dynamics, but also for the way constraints are
solved. There are many other problems were you could apply this same
techniques. This JavaScript engine it's a couple of pages long, it's easy to
understand and potentially could give you a new vision on how to solve
problems. The reason why is uses do much CPU time is because the collision
detection algorithm compares every single pair of objects, to speed up that
part I'd need to add what is called a 'broad phase' but that would complicate
the code and the point was to write clear code and leave the low hanging fruit
for the reader.

