## 2008/07/20

### Dejeweled Engine constraint functions

Today I dusted off my calculus hat and got to work on the math behind the Dejeweled physics engine (specifically the projection gradient functions for the constraint solver).

If you're curious, the physics engine I'm working on is based on the approach described in Position Based Dynamics (excellent paper), which provides an algorithm for simulating particle physics with any sort of constraint you can imagine. You just need to do a bit of vector calculus first. :)

Here's what I've come up with: (may contain errors)

Notation Notes!
• Uppercase letters are vectors, lowercase letters are scalars
• | V | = length of vector V
• U . V = dot product of vectors U and V

Rod Constraint (P1, P2, d)
a simple rod of distance d with endpoints P1 and P2
• Constraint function C = | P1 - P2 | - d
• Gradient function P1C = ( P1 - P2 ) / | P1 - P2 |
• Gradient function P2C = ( P2 - P1 ) / | P1 - P2 |

Pin Constraint (P0, P1, P2, f, d)
a connection of distance d between pin P0 and the point Pf at fraction f along the line from point P1 to P2
• Intermediate point Pf = (1-f)P1 + (f)P2
• Constraint function C = | P0 - Pf | - d
• Gradient function P0C = ( P0 - Pf ) / | P0 - Pf |
• Gradient function P1C = (f-1)( P0 - Pf ) / | P0 - Pf |
• Gradient function P2C = (-f)( P0 - Pf ) / | P0 - Pf |

Wall Constraint (P0, P1, N, d)
a separation of distance d between point P0 and the surface of a wall at point P1 with surface normal N
• Constraint function C = ( P0 - Pf ) . N - d
• Gradient function P0C = N
• Gradient function P1C = -N

Door Constraint (P0, P1, P2, d)
a hinge centered on point P0 between endpoints P1 and P2 at an angle corresponding to dot product d
• Constraint function C = ( P0 - P1 ) . ( P0 - P2 ) - d
• Gradient function P0C = ( P0 - P1 ) + ( P0 - P2 )
• Gradient function P1C = ( P2 - P0 )
• Gradient function P2C = ( P1 - P0 )

Those four constraint types should be plenty, at least for now.