physics revision
[carveJwlIkooP6JGAAIwe30JlM.git] / rigidbody.h
index 4318d8c1f294d117622c5421b840b239b2b74134..c00b0f04f75817ad21072755ed983ce098094bfb 100644 (file)
@@ -3,37 +3,84 @@
  *            qu3e  - Randy Gaul
  */
 
+#include "common.h"
+#include "bvh.h"
+
+static void rb_tangent_basis( v3f n, v3f tx, v3f ty );
+static bh_system bh_system_rigidbodies;
+
 #ifndef RIGIDBODY_H
 #define RIGIDBODY_H
 
 #define RB_DEPR 
-
-#include "vg/vg.h"
-#include "scene.h"
-
-#define k_rb_delta (1.0f/60.0f)
+#define k_rb_rate  60.0f
+#define k_rb_delta (1.0f/k_rb_rate)
 
 typedef struct rigidbody rigidbody;
+typedef struct contact rb_ct;
+
 struct rigidbody
 {
-   v3f co, v, I;
+   v3f co, v, w;
    v4f q;
-   boxf bbx;
-   float inv_mass;
 
-   struct contact
+   enum rb_shape
    {
-      v3f co, n, delta;
-      v3f t[2];
-      float bias, norm_impulse, tangent_impulse[2];
+      k_rb_shape_box,
+      k_rb_shape_sphere,
+      k_rb_shape_capsule
+   } 
+   type;
+   
+   union
+   {
+      struct rb_sphere
+      {
+         float radius;
+      }
+      sphere;
+
+      struct rb_capsule
+      {
+         float height, radius;
+      } 
+      capsule;
    }
-   manifold[4];
-   int manifold_count;
+   inf;
+
+   v3f right, up, forward;
+   
+   int is_world;
+
+   boxf bbx, bbx_world;
+   float inv_mass;
 
    v3f delta;  /* where is the origin of this in relation to a parent body */
    m4x3f to_world, to_local;
 };
 
+static rigidbody rb_static_null = 
+{
+   .co={0.0f,0.0f,0.0f},
+   .q={0.0f,0.0f,0.0f,1.0f},
+   .v={0.0f,0.0f,0.0f},
+   .w={0.0f,0.0f,0.0f},
+   .is_world = 1,
+   .inv_mass = 0.0f
+};
+
+static void rb_debug( rigidbody *rb, u32 colour );
+
+static struct contact
+{
+   rigidbody *rba, *rbb;
+   v3f co, n;
+   v3f t[2];
+   float mass_total, p, bias, norm_impulse, tangent_impulse[2];
+}
+rb_contact_buffer[256];
+static int rb_contact_count = 0;
+
 static void rb_update_transform( rigidbody *rb )
 {
    q_normalize( rb->q );
@@ -41,18 +88,60 @@ static void rb_update_transform( rigidbody *rb )
    v3_copy( rb->co, rb->to_world[3] );
 
    m4x3_invert_affine( rb->to_world, rb->to_local );
+
+   box_copy( rb->bbx, rb->bbx_world );
+   m4x3_transform_aabb( rb->to_world, rb->bbx_world );
+
+   m3x3_mulv( rb->to_world, (v3f){1.0f,0.0f, 0.0f}, rb->right );
+   m3x3_mulv( rb->to_world, (v3f){0.0f,1.0f, 0.0f}, rb->up );
+   m3x3_mulv( rb->to_world, (v3f){0.0f,0.0f,-1.0f}, rb->forward );
+}
+
+static float sphere_volume( float radius )
+{
+   float r3 = radius*radius*radius;
+   return (4.0f/3.0f) * VG_PIf * r3;
 }
 
 static void rb_init( rigidbody *rb )
 {
-   q_identity( rb->q );
-   v3_zero( rb->v );
-   v3_zero( rb->I );
+   float volume = 1.0f;
+
+   if( rb->type == k_rb_shape_box )
+   {
+      v3f dims;
+      v3_sub( rb->bbx[1], rb->bbx[0], dims );
+      volume = dims[0]*dims[1]*dims[2];
+   }
+   else if( rb->type == k_rb_shape_sphere )
+   {
+      volume = sphere_volume( rb->inf.sphere.radius );
+      v3_fill( rb->bbx[0], -rb->inf.sphere.radius );
+      v3_fill( rb->bbx[1],  rb->inf.sphere.radius );
+   }
+   else if( rb->type == k_rb_shape_capsule )
+   {
+      float r = rb->inf.capsule.radius,
+            h = rb->inf.capsule.height;
+      volume = sphere_volume( r ) + VG_PIf * r*r * (h - r*2.0f);
+
+      v3_fill( rb->bbx[0], -rb->inf.sphere.radius );
+      v3_fill( rb->bbx[1],  rb->inf.sphere.radius );
+      rb->bbx[0][1] = -h;
+      rb->bbx[1][1] =  h;
+   }
 
-   v3f dims;
-   v3_sub( rb->bbx[1], rb->bbx[0], dims );
+   if( rb->is_world )
+   {
+      rb->inv_mass = 0.0f;
+   }
+   else
+   {
+      rb->inv_mass = 1.0f/(8.0f*volume);
+   }
 
-   rb->inv_mass = 1.0f/(8.0f*dims[0]*dims[1]*dims[2]);
+   v3_zero( rb->v );
+   v3_zero( rb->w );
 
    rb_update_transform( rb );
 }
@@ -64,15 +153,14 @@ static void rb_iter( rigidbody *rb )
 
    /* intergrate velocity */
    v3_muladds( rb->co, rb->v, k_rb_delta, rb->co );
-
-   v3_lerp( rb->I, (v3f){0.0f,0.0f,0.0f}, 0.0025f, rb->I );
+   v3_lerp( rb->w, (v3f){0.0f,0.0f,0.0f}, 0.0025f, rb->w );
 
    /* inegrate inertia */
-   if( v3_length2( rb->I ) > 0.0f )
+   if( v3_length2( rb->w ) > 0.0f )
    {
       v4f rotation;
       v3f axis;
-      v3_copy( rb->I, axis );
+      v3_copy( rb->w, axis );
       
       float mag = v3_length( axis );
       v3_divs( axis, mag, axis );
@@ -83,7 +171,7 @@ static void rb_iter( rigidbody *rb )
 
 static void rb_torque( rigidbody *rb, v3f axis, float mag )
 {
-   v3_muladds( rb->I, axis, mag*k_rb_delta, rb->I );
+   v3_muladds( rb->w, axis, mag*k_rb_delta, rb->w );
 }
 
 static void rb_tangent_basis( v3f n, v3f tx, v3f ty )
@@ -106,7 +194,455 @@ static void rb_tangent_basis( v3f n, v3f tx, v3f ty )
    v3_cross( n, tx, ty );
 }
 
-static void rb_build_manifold( rigidbody *rb, scene *sc )
+static void rb_solver_reset(void);
+static void rb_build_manifold_terrain( rigidbody *rb );
+static void rb_build_manifold_terrain_sphere( rigidbody *rb );
+static void rb_solve_contacts(void);
+
+/* 
+ * These closest point tests were learned from Real-Time Collision Detection by 
+ * Christer Ericson 
+ */
+static float closest_segment_segment( v3f p1, v3f q1, v3f p2, v3f q2, 
+   float *s, float *t, v3f c1, v3f c2)
+{
+   v3f d1,d2,r;
+   v3_sub( q1, p1, d1 );
+   v3_sub( q2, p2, d2 );
+   v3_sub( p1, p2, r );
+
+   float a = v3_length2( d1 ),
+         e = v3_length2( d2 ),
+         f = v3_dot( d2, r );
+
+   const float kEpsilon = 0.0001f;
+
+   if( a <= kEpsilon && e <= kEpsilon )
+   {
+      *s = 0.0f;
+      *t = 0.0f;
+      v3_copy( p1, c1 );
+      v3_copy( p2, c2 );
+
+      v3f v0;
+      v3_sub( c1, c2, v0 );
+
+      return v3_length2( v0 );
+   }
+   
+   if( a<= kEpsilon )
+   {
+      *s = 0.0f;
+      *t = vg_clampf( f / e, 0.0f, 1.0f );
+   }
+   else
+   {
+      float c = v3_dot( d1, r );
+      if( e <= kEpsilon )
+      {
+         *t = 0.0f;
+         *s = vg_clampf( -c / a, 0.0f, 1.0f );
+      }
+      else
+      {
+         float b = v3_dot(d1,d2),
+               d = a*e-b*b;
+
+         if( d != 0.0f )
+         {
+            *s = vg_clampf((b*f - c*e)/d, 0.0f, 1.0f);
+         }
+         else
+         {
+            *s = 0.0f;
+         }
+
+         *t = (b*(*s)+f) / e;
+
+         if( *t < 0.0f )
+         {
+            *t = 0.0f;
+            *s = vg_clampf( -c / a, 0.0f, 1.0f );
+         }
+         else if( *t > 1.0f )
+         {
+            *t = 1.0f;
+            *s = vg_clampf((b-c)/a,0.0f,1.0f);
+         }
+      }
+   }
+
+   v3_muladds( p1, d1, *s, c1 );
+   v3_muladds( p2, d2, *t, c2 );
+
+   v3f v0;
+   v3_sub( c1, c2, v0 );
+   return v3_length2( v0 );
+}
+
+static void closest_point_aabb( v3f p, boxf box, v3f dest )
+{
+   v3_maxv( p, box[0], dest );
+   v3_minv( dest, box[1], dest );
+}
+
+static void closest_point_obb( v3f p, rigidbody *rb, v3f dest )
+{
+   v3f local;
+   m4x3_mulv( rb->to_local, p, local );
+   closest_point_aabb( local, rb->bbx, local );
+   m4x3_mulv( rb->to_world, local, dest );
+}
+
+static void closest_point_segment( v3f a, v3f b, v3f point, v3f dest )
+{
+   v3f v0, v1;
+   v3_sub( b, a, v0 );
+   v3_sub( point, a, v1 );
+
+   float t = v3_dot( v1, v0 ) / v3_length2(v0);
+   v3_muladds( a, v0, vg_clampf(t,0.0f,1.0f), dest );
+}
+
+static void closest_on_triangle( v3f p, v3f tri[3], v3f dest )
+{
+   v3f ab, ac, ap;
+   float d1, d2;
+
+   /* Region outside A */
+   v3_sub( tri[1], tri[0], ab );
+   v3_sub( tri[2], tri[0], ac );
+   v3_sub( p, tri[0], ap );
+   
+   d1 = v3_dot(ab,ap);
+   d2 = v3_dot(ac,ap);
+   if( d1 <= 0.0f && d2 <= 0.0f ) 
+   {
+      v3_copy( tri[0], dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+
+   /* Region outside B */
+   v3f bp;
+   float d3, d4;
+
+   v3_sub( p, tri[1], bp );
+   d3 = v3_dot( ab, bp );
+   d4 = v3_dot( ac, bp );
+
+   if( d3 >= 0.0f && d4 <= d3 )
+   {
+      v3_copy( tri[1], dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+   
+   /* Edge region of AB */
+   float vc = d1*d4 - d3*d2;
+   if( vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f )
+   {
+      float v = d1 / (d1-d3);
+      v3_muladds( tri[0], ab, v, dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+
+   /* Region outside C */
+   v3f cp;
+   float d5, d6;
+   v3_sub( p, tri[2], cp );
+   d5 = v3_dot(ab, cp);
+   d6 = v3_dot(ac, cp);
+   
+   if( d6 >= 0.0f && d5 <= d6 )
+   {
+      v3_copy( tri[2], dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+
+   /* Region of AC */
+   float vb = d5*d2 - d1*d6;
+   if( vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f )
+   {
+      float w = d2 / (d2-d6);
+      v3_muladds( tri[0], ac, w, dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+
+   /* Region of BC */
+   float va = d3*d6 - d5*d4;
+   if( va <= 0.0f && (d4-d3) >= 0.0f && (d5-d6) >= 0.0f )
+   {
+      float w = (d4-d3) / ((d4-d3) + (d5-d6));
+      v3f bc;
+      v3_sub( tri[2], tri[1], bc );
+      v3_muladds( tri[1], bc, w, dest );
+      v3_copy( (v3f){INFINITY,INFINITY,INFINITY}, dest );
+      return;
+   }
+
+   /* P inside region, Q via barycentric coordinates uvw */
+   float d = 1.0f/(va+vb+vc),
+         v = vb*d,
+         w = vc*d;
+
+   v3_muladds( tri[0], ab, v, dest );
+   v3_muladds( dest, ac, w, dest );
+}
+
+/*
+ * Contact generators
+ *
+ * These do not automatically allocate contacts, an appropriately sized 
+ * buffer must be supplied. The function returns the size of the manifold
+ * which was generated.
+ *
+ * The values set on the contacts are: n, co, p, rba, rbb
+ */
+
+static void rb_debug_contact( rb_ct *ct )
+{
+   v3f p1;
+   v3_muladds( ct->co, ct->n, 0.2f, p1 );
+   vg_line_pt3( ct->co, 0.1f, 0xff0000ff );
+   vg_line( ct->co, p1, 0xffffffff );
+}
+
+static int rb_sphere_vs_box( rigidbody *rba, rigidbody *rbb, rb_ct *buf )
+{
+   v3f co, delta;
+
+   closest_point_obb( rba->co, rbb, co );
+   v3_sub( rba->co, co, delta );
+
+   float d2 = v3_length2(delta),
+          r = rba->inf.sphere.radius;
+
+   if( d2 <= r*r )
+   {
+      float d;
+      if( d2 <= 0.0001f )
+      {
+         v3_sub( rbb->co, rba->co, delta );
+         d2 = v3_length2(delta);
+      }
+
+      d = sqrtf(d2);
+
+      rb_ct *ct = buf;
+      v3_muls( delta, 1.0f/d, ct->n );
+      v3_copy( co, ct->co );
+      ct->p = r-d;
+      ct->rba = rba;
+      ct->rbb = rbb;
+      return 1;
+   }
+
+   return 0;
+}
+
+static int rb_sphere_vs_sphere( rigidbody *rba, rigidbody *rbb, rb_ct *buf )
+{
+   v3f delta;
+   v3_sub( rba->co, rbb->co, delta );
+
+   float d2 = v3_length2(delta),
+          r = rba->inf.sphere.radius + rbb->inf.sphere.radius;
+
+   if( d2 < r*r )
+   {
+      float d = sqrtf(d2);
+
+      rb_ct *ct = buf;
+      v3_muls( delta, -1.0f/d, ct->n );
+
+      v3f p0, p1;
+      v3_muladds( rba->co, ct->n, rba->inf.sphere.radius, p0 );
+      v3_muladds( rbb->co, ct->n,-rbb->inf.sphere.radius, p1 );
+      v3_add( p0, p1, ct->co );
+      v3_muls( ct->co, 0.5f, ct->co );
+      ct->p = r-d;
+      ct->rba = rba;
+      ct->rbb = rbb;
+      return 1;
+   }
+
+   return 0;
+}
+
+static int rb_box_vs_sphere( rigidbody *rba, rigidbody *rbb, rb_ct *buf )
+{
+   return rb_sphere_vs_box( rbb, rba, buf );
+}
+
+static int rb_box_vs_box( rigidbody *rba, rigidbody *rbb, rb_ct *buf )
+{
+   /* TODO: Generating a stable quad manifold, lots of clipping */
+   return 0;
+}
+
+/* 
+ * This function does not accept triangle as a dynamic object, it is assumed
+ * to always be static.
+ * 
+ * The triangle is also assumed to be one sided for better detection
+ */
+static int rb_sphere_vs_triangle( rigidbody *rba, v3f tri[3], rb_ct *buf )
+{
+   v3f delta, co;
+
+   closest_on_triangle( rba->co, tri, co );
+   v3_sub( rba->co, co, delta );
+
+   float d2 = v3_length2( delta ),
+          r = rba->inf.sphere.radius;
+
+   if( d2 < r*r )
+   {
+      v3f ab, ac, tn;
+      v3_sub( tri[1], tri[0], ab );
+      v3_sub( tri[2], tri[0], ac );
+      v3_cross( ac, ab, tn );
+
+      if( v3_dot( delta, tn ) > 0.0f )
+         v3_muls( delta, -1.0f, delta );
+
+      float d = sqrtf(d2);
+
+      rb_ct *ct = buf;
+      v3_muls( delta, 1.0f/d, ct->n );
+      v3_copy( co, ct->co );
+      ct->p = r-d;
+      ct->rba = rba;
+      ct->rbb = &rb_static_null;
+      return 1;
+   }
+
+   return 0;
+}
+
+
+/*
+ * Generic functions
+ */
+
+RB_DEPR
+static int sphere_vs_triangle( v3f c, float r, v3f tri[3], 
+      v3f co, v3f norm, float *p )
+{
+   v3f delta;
+   closest_on_triangle( c, tri, co );
+
+   v3_sub( c, co, delta );
+
+
+   float d = v3_length2( delta );
+   if( d < r*r )
+   {
+      v3f ab, ac, tn;
+      v3_sub( tri[1], tri[0], ab );
+      v3_sub( tri[2], tri[0], ac );
+      v3_cross( ac, ab, tn );
+
+      if( v3_dot( delta, tn ) > 0.0f )
+         v3_muls( delta, -1.0f, delta );
+
+      vg_line_pt3( co, 0.05f, 0xff00ff00 );
+
+      d = sqrtf(d);
+      v3_muls( delta, 1.0f/d, norm );
+
+      *p = r-d;
+      return 1;
+   }
+
+   return 0;
+}
+
+#include "world.h"
+
+static void rb_solver_reset(void)
+{
+   rb_contact_count = 0;
+}
+
+static rb_ct *rb_global_ct(void)
+{
+   return rb_contact_buffer + rb_contact_count;
+}
+
+static struct contact *rb_start_contact(void)
+{
+   if( rb_contact_count == vg_list_size(rb_contact_buffer) )
+   {
+      vg_error( "rigidbody: too many contacts generated (%u)\n", 
+            rb_contact_count );
+      return NULL;
+   }
+
+   return &rb_contact_buffer[ rb_contact_count ];
+}
+
+static void rb_commit_contact( struct contact *ct, float p )
+{
+   ct->bias = -0.2f*k_rb_rate*vg_minf(0.0f,-p+0.04f);
+   rb_tangent_basis( ct->n, ct->t[0], ct->t[1] );
+
+   ct->norm_impulse = 0.0f;
+   ct->tangent_impulse[0] = 0.0f;
+   ct->tangent_impulse[1] = 0.0f;
+
+   rb_contact_count ++;
+}
+
+static void rb_build_manifold_terrain_sphere( rigidbody *rb )
+{
+   u32 geo[256];
+   v3f tri[3];
+   int len = bh_select( &world.geo.bhtris, rb->bbx_world, geo, 256 );
+   
+   for( int i=0; i<len; i++ )
+   {
+      u32 *ptri = &world.geo.indices[ geo[i]*3 ];
+
+      for( int j=0; j<3; j++ )
+         v3_copy( world.geo.verts[ptri[j]].co, tri[j] );
+
+      vg_line(tri[0],tri[1],0xff00ff00 );
+      vg_line(tri[1],tri[2],0xff00ff00 );
+      vg_line(tri[2],tri[0],0xff00ff00 );
+
+      v3f co, norm;
+      float p;
+
+      for( int j=0; j<2; j++ )
+      {
+         if( sphere_vs_triangle( rb->co, rb->inf.sphere.radius, tri,co,norm,&p))
+         {
+            struct contact *ct = rb_start_contact();
+
+            if( !ct )
+               return;
+
+            v3f p1;
+            v3_muladds( rb->co, norm, p, p1 );
+            vg_line( rb->co, p1, 0xffffffff );
+
+            ct->rba = rb;
+            v3_copy( co, ct->co );
+            v3_copy( norm, ct->n );
+            rb_commit_contact( ct, p );
+         }
+      }
+   }
+
+}
+
+RB_DEPR
+static void rb_build_manifold_terrain( rigidbody *rb )
 {
    v3f *box = rb->bbx;
    v3f pts[8]; 
@@ -132,88 +668,144 @@ static void rb_build_manifold( rigidbody *rb, scene *sc )
    m4x3_mulv( rb->to_world, p110, p110 );
    m4x3_mulv( rb->to_world, p111, p111 );
 
-   rb->manifold_count = 0;
+   int count = 0;
 
    for( int i=0; i<8; i++ )
    {
       float *point = pts[i];
-      struct contact *ct = &rb->manifold[rb->manifold_count];
+      struct contact *ct = rb_start_contact();
+
+      if( !ct )
+         return;
+
+      ct->rba = rb;
       
       v3f surface;
-
       v3_copy( point, surface );
+      surface[1] += 4.0f;
 
       ray_hit hit;
-      bvh_scene_sample( sc, surface, &hit );
-      v3_copy( hit.normal, ct->n );
+      hit.dist = INFINITY;
+      if( !ray_world( surface, (v3f){0.0f,-1.0f,0.0f}, &hit ))
+         continue;
+
+      v3_copy( hit.pos, surface );
 
       float p = vg_minf( surface[1] - point[1], 1.0f );
 
       if( p > 0.0f )
       {
+         v3_copy( hit.normal, ct->n );
          v3_add( point, surface, ct->co );
          v3_muls( ct->co, 0.5f, ct->co );
 
-         //vg_line_pt3( ct->co, 0.0125f, 0xff0000ff );
+         rb_commit_contact( ct, p );
+         count ++;
+         if( count == 4 )
+            break;
+      }
+   }
+}
 
-         v3_sub( ct->co, rb->co, ct->delta );
-         ct->bias = -0.2f * (1.0f/k_rb_delta) * vg_minf( 0.0f, -p+0.04f );
-         rb_tangent_basis( ct->n, ct->t[0], ct->t[1] );
+/*
+ * Initializing things like tangent vectors
+ */
+static void rb_presolve_contacts(void)
+{
+   for( int i=0; i<rb_contact_count; i++ )
+   {
+      rb_ct *ct = &rb_contact_buffer[i];
 
-         ct->norm_impulse = 0.0f;
-         ct->tangent_impulse[0] = 0.0f;
-         ct->tangent_impulse[1] = 0.0f;
+      ct->bias = -0.2f * k_rb_rate * vg_minf(0.0f,-ct->p+0.04f);
+      rb_tangent_basis( ct->n, ct->t[0], ct->t[1] );
 
-         rb->manifold_count ++;
-         if( rb->manifold_count == 4 )
-            break;
-      }
+      ct->norm_impulse = 0.0f;
+      ct->tangent_impulse[0] = 0.0f;
+      ct->tangent_impulse[1] = 0.0f;
+      ct->mass_total = 1.0f/(ct->rba->inv_mass + ct->rbb->inv_mass);
+
+      rb_debug_contact( ct );
    }
 }
 
-static void rb_constraint_manifold( rigidbody *rb )
+/*
+ * Creates relative contact velocity vector, and offsets between each body */
+static void rb_rcv( rb_ct *ct, v3f rv, v3f da, v3f db )
+{
+   rigidbody *rba = ct->rba,
+             *rbb = ct->rbb;
+
+   v3_sub( rba->co, ct->co, da );
+   v3_sub( rbb->co, ct->co, db );
+   
+   v3f rva, rvb;
+   v3_cross( rba->w, da, rva );
+   v3_add( rba->v, rva, rva );
+
+   v3_cross( rbb->w, db, rvb );
+   v3_add( rbb->v, rvb, rvb );
+   v3_add( rva, rvb, rv );
+}
+
+static void rb_standard_impulse( rb_ct *ct, v3f da, v3f db, v3f impulse )
+{
+   rigidbody *rba = ct->rba,
+             *rbb = ct->rbb;
+
+   /* response */
+   v3_muladds( rba->v, impulse, ct->mass_total * rba->inv_mass, rba->v );
+   v3_muladds( rbb->v, impulse, ct->mass_total * rbb->inv_mass, rbb->v );
+   
+   /* Angular velocity */
+   v3f wa, wb;
+   v3_cross( da, impulse, wa );
+   v3_cross( db, impulse, wb );
+   v3_muladds( rba->w, wa, ct->mass_total * rba->inv_mass, rba->w );
+   v3_muladds( rbb->w, wb, ct->mass_total * rbb->inv_mass, rbb->w );
+}
+
+static void rb_solve_contacts(void)
 {
    float k_friction = 0.1f;
 
+   /* TODO: second object
+    *       Static objects route to static element */
+
    /* Friction Impulse */
-   for( int i=0; i<rb->manifold_count; i++ )
+   for( int i=0; i<rb_contact_count; i++ )
    {
-      struct contact *ct = &rb->manifold[i];
+      struct contact *ct = &rb_contact_buffer[i];
+      rigidbody *rb = ct->rba;
 
-      v3f dv;
-      v3_cross( rb->I, ct->delta, dv );
-      v3_add( rb->v, dv, dv );
+      v3f rv, da, db;
+      rb_rcv( ct, rv, da, db );
       
       for( int j=0; j<2; j++ )
       {
-         float vt = vg_clampf( -v3_dot( dv, ct->t[j] ), 
-               -k_friction, k_friction );
-
-         vt = -v3_dot( dv, ct->t[j] );
+         float f = k_friction * ct->norm_impulse,
+              vt = -v3_dot( rv, ct->t[j] );
          
          float temp = ct->tangent_impulse[j];
-         ct->tangent_impulse[j] = vg_clampf( temp+vt, -k_friction, k_friction );
+         ct->tangent_impulse[j] = vg_clampf( temp+vt, -f, f );
          vt = ct->tangent_impulse[j] - temp;
 
          v3f impulse;
-
          v3_muls( ct->t[j], vt, impulse );
-         v3_add( impulse, rb->v, rb->v );
-         v3_cross( ct->delta, impulse, impulse );
-         v3_add( impulse, rb->I, rb->I );
+         rb_standard_impulse( ct, da, db, impulse );
       }
    }
 
    /* Normal Impulse */
-   for( int i=0; i<rb->manifold_count; i++ )
+   for( int i=0; i<rb_contact_count; i++ )
    {
-      struct contact *ct = &rb->manifold[i];
+      struct contact *ct = &rb_contact_buffer[i];
+      rigidbody *rba = ct->rba,
+                *rbb = ct->rbb;
 
-      v3f dv;
-      v3_cross( rb->I, ct->delta, dv );
-      v3_add( rb->v, dv, dv );
+      v3f rv, da, db;
+      rb_rcv( ct, rv, da, db );
 
-      float vn = -v3_dot( dv, ct->n );
+      float vn = -v3_dot( rv, ct->n );
       vn += ct->bias;
 
       float temp = ct->norm_impulse;
@@ -221,11 +813,8 @@ static void rb_constraint_manifold( rigidbody *rb )
       vn = ct->norm_impulse - temp;
 
       v3f impulse;
-
       v3_muls( ct->n, vn, impulse );
-      v3_add( impulse, rb->v, rb->v );
-      v3_cross( ct->delta, impulse, impulse );
-      v3_add( impulse, rb->I, rb->I );
+      rb_standard_impulse( ct, da, db, impulse );
    }
 }
 
@@ -236,8 +825,7 @@ struct rb_angle_limit
    float impulse, bias;
 };
 
-static int rb_angle_limit_force( 
-                                  rigidbody *rba, v3f va, 
+static int rb_angle_limit_force(  rigidbody *rba, v3f va, 
                                   rigidbody *rbb, v3f vb,
                                   float max )
 {
@@ -273,7 +861,6 @@ static void rb_constraint_angle_limit( struct rb_angle_limit *limit )
 
 }
 
-
 RB_DEPR
 static void rb_constraint_angle( rigidbody *rba, v3f va,
                                  rigidbody *rbb, v3f vb, 
@@ -288,8 +875,8 @@ static void rb_constraint_angle( rigidbody *rba, v3f va,
 
    v3f axis;
    v3_cross( wva, wvb, axis );
-   v3_muladds( rba->I, axis,  ang*spring*0.5f, rba->I );
-   v3_muladds( rbb->I, axis, -ang*spring*0.5f, rbb->I );
+   v3_muladds( rba->w, axis,  ang*spring*0.5f, rba->w );
+   v3_muladds( rbb->w, axis, -ang*spring*0.5f, rbb->w );
 
    return;
    
@@ -319,8 +906,8 @@ static void rb_relative_velocity( rigidbody *ra, v3f lca,
    v3_sub( ra->v, rb->v, rcv );
 
    v3f rcv_Ra, rcv_Rb;
-   v3_cross( ra->I, wca, rcv_Ra );
-   v3_cross( rb->I, wcb, rcv_Rb );
+   v3_cross( ra->w, wca, rcv_Ra );
+   v3_cross( rb->w, wcb, rcv_Rb );
    v3_add( rcv_Ra, rcv, rcv );
    v3_sub( rcv, rcv_Rb, rcv );
 }
@@ -345,8 +932,8 @@ static void rb_constraint_position( rigidbody *ra, v3f lca,
    v3_sub( ra->v, rb->v, rcv );
 
    v3f rcv_Ra, rcv_Rb;
-   v3_cross( ra->I, wca, rcv_Ra );
-   v3_cross( rb->I, wcb, rcv_Rb );
+   v3_cross( ra->w, wca, rcv_Ra );
+   v3_cross( rb->w, wcb, rcv_Rb );
    v3_add( rcv_Ra, rcv, rcv );
    v3_sub( rcv, rcv_Rb, rcv );
 
@@ -360,70 +947,278 @@ static void rb_constraint_position( rigidbody *ra, v3f lca,
    v3_muls( rcv, 1.0f, impulse );
    v3_muladds( rb->v, impulse, mass_b/total_mass, rb->v );
    v3_cross( wcb, impulse, impulse );
-   v3_add( impulse, rb->I, rb->I );
+   v3_add( impulse, rb->w, rb->w );
 
    v3_muls( rcv, -1.0f, impulse );
    v3_muladds( ra->v, impulse, mass_a/total_mass, ra->v );
    v3_cross( wca, impulse, impulse );
-   v3_add( impulse, ra->I, ra->I );
+   v3_add( impulse, ra->w, ra->w );
 
 #if 0
+   /*
+    * this could be used for spring joints
+    * its not good for position constraint
+    */
    v3f impulse;
    v3_muls( delta, 0.5f*spring, impulse );
 
    v3_add( impulse, ra->v, ra->v );
    v3_cross( wca, impulse, impulse );
-   v3_add( impulse, ra->I, ra->I );
+   v3_add( impulse, ra->w, ra->w );
 
    v3_muls( delta, -0.5f*spring, impulse );
 
    v3_add( impulse, rb->v, rb->v );
    v3_cross( wcb, impulse, impulse );
-   v3_add( impulse, rb->I, rb->I );
+   v3_add( impulse, rb->w, rb->w );
 #endif
 }
 
+static void debug_sphere( m4x3f m, float radius, u32 colour )
+{
+   v3f ly = { 0.0f, 0.0f, radius },
+       lx = { 0.0f, radius, 0.0f },
+       lz = { 0.0f, 0.0f, radius };
+   
+   for( int i=0; i<16; i++ )
+   {
+      float t = ((float)(i+1) * (1.0f/16.0f)) * VG_PIf * 2.0f,
+            s = sinf(t),
+            c = cosf(t);
+
+      v3f py = { s*radius, 0.0f, c*radius },
+          px = { s*radius, c*radius, 0.0f },
+          pz = { 0.0f, s*radius, c*radius };
+
+      v3f p0, p1, p2, p3, p4, p5;
+      m4x3_mulv( m, py, p0 );
+      m4x3_mulv( m, ly, p1 );
+      m4x3_mulv( m, px, p2 );
+      m4x3_mulv( m, lx, p3 );
+      m4x3_mulv( m, pz, p4 );
+      m4x3_mulv( m, lz, p5 );
+
+      vg_line( p0, p1, colour == 0x00? 0xff00ff00: colour );
+      vg_line( p2, p3, colour == 0x00? 0xff0000ff: colour );
+      vg_line( p4, p5, colour == 0x00? 0xffff0000: colour );
+
+      v3_copy( py, ly );
+      v3_copy( px, lx );
+      v3_copy( pz, lz );
+   }
+}
+
 static void rb_debug( rigidbody *rb, u32 colour )
 {
-   v3f *box = rb->bbx;
-   v3f p000, p001, p010, p011, p100, p101, p110, p111;
+   if( rb->type == k_rb_shape_box )
+   {
+      v3f *box = rb->bbx;
+      vg_line_boxf_transformed( rb->to_world, rb->bbx, colour );
+   }
+   else if( rb->type == k_rb_shape_sphere )
+   {
+      debug_sphere( rb->to_world, rb->inf.sphere.radius, colour );
+   }
+}
 
-   p000[0]=box[0][0];p000[1]=box[0][1];p000[2]=box[0][2];
-   p001[0]=box[0][0];p001[1]=box[0][1];p001[2]=box[1][2];
-   p010[0]=box[0][0];p010[1]=box[1][1];p010[2]=box[0][2];
-   p011[0]=box[0][0];p011[1]=box[1][1];p011[2]=box[1][2];
+/*
+ * out penetration distance, normal
+ */
+static int rb_point_in_body( rigidbody *rb, v3f pos, float *pen, v3f normal )
+{
+   v3f local;
+   m4x3_mulv( rb->to_local, pos, local );
 
-   p100[0]=box[1][0];p100[1]=box[0][1];p100[2]=box[0][2];
-   p101[0]=box[1][0];p101[1]=box[0][1];p101[2]=box[1][2];
-   p110[0]=box[1][0];p110[1]=box[1][1];p110[2]=box[0][2];
-   p111[0]=box[1][0];p111[1]=box[1][1];p111[2]=box[1][2];
+   if( local[0] > rb->bbx[0][0] && local[0] < rb->bbx[1][0] &&
+       local[1] > rb->bbx[0][1] && local[1] < rb->bbx[1][1] &&
+       local[2] > rb->bbx[0][2] && local[2] < rb->bbx[1][2] )
+   {
+      v3f area, com, comrel;
+      v3_add( rb->bbx[0], rb->bbx[1], com );
+      v3_muls( com, 0.5f, com );
 
-   m4x3_mulv( rb->to_world, p000, p000 );
-   m4x3_mulv( rb->to_world, p001, p001 );
-   m4x3_mulv( rb->to_world, p010, p010 );
-   m4x3_mulv( rb->to_world, p011, p011 );
-   m4x3_mulv( rb->to_world, p100, p100 );
-   m4x3_mulv( rb->to_world, p101, p101 );
-   m4x3_mulv( rb->to_world, p110, p110 );
-   m4x3_mulv( rb->to_world, p111, p111 );
+      v3_sub( rb->bbx[1], rb->bbx[0], area );
+      v3_sub( local, com, comrel );
+      v3_div( comrel, area, comrel );
+
+      int axis = 0;
+      float max_mag = fabsf(comrel[0]);
+      
+      if( fabsf(comrel[1]) > max_mag )
+      {
+         axis = 1;
+         max_mag = fabsf(comrel[1]);
+      }
+      if( fabsf(comrel[2]) > max_mag )
+      {
+         axis = 2;
+         max_mag = fabsf(comrel[2]);
+      }
+      
+      v3_zero( normal );
+      normal[axis] = vg_signf(comrel[axis]);
+
+      if( normal[axis] < 0.0f )
+         *pen = local[axis] - rb->bbx[0][axis];
+      else
+         *pen = rb->bbx[1][axis] - local[axis];
+
+      m3x3_mulv( rb->to_world, normal, normal );
+      return 1;
+   }
+
+   return 0;
+}
+
+#if 0
+static void rb_build_manifold_rb_static( rigidbody *ra, rigidbody *rb_static )
+{
+   v3f verts[8];
+
+   v3f a, b;
+   v3_copy( ra->bbx[0], a );
+   v3_copy( ra->bbx[1], b );
    
-   vg_line( p000, p001, colour );
-   vg_line( p001, p011, colour );
-   vg_line( p011, p010, colour );
-   vg_line( p010, p000, colour );
+       m4x3_mulv( ra->to_world, (v3f){ a[0], a[1], a[2] }, verts[0] );
+       m4x3_mulv( ra->to_world, (v3f){ a[0], b[1], a[2] }, verts[1] );
+       m4x3_mulv( ra->to_world, (v3f){ b[0], b[1], a[2] }, verts[2] );
+       m4x3_mulv( ra->to_world, (v3f){ b[0], a[1], a[2] }, verts[3] );
+       m4x3_mulv( ra->to_world, (v3f){ a[0], a[1], b[2] }, verts[4] );
+       m4x3_mulv( ra->to_world, (v3f){ a[0], b[1], b[2] }, verts[5] );
+       m4x3_mulv( ra->to_world, (v3f){ b[0], b[1], b[2] }, verts[6] );
+       m4x3_mulv( ra->to_world, (v3f){ b[0], a[1], b[2] }, verts[7] );
+
+   vg_line_boxf_transformed( rb_static->to_world, rb_static->bbx, 0xff0000ff );
 
-   vg_line( p100, p101, colour );
-   vg_line( p101, p111, colour );
-   vg_line( p111, p110, colour );
-   vg_line( p110, p100, colour );
+   int count = 0;
 
-   vg_line( p100, p000, colour );
-   vg_line( p101, p001, colour );
-   vg_line( p110, p010, colour );
-   vg_line( p111, p011, colour );
+   for( int i=0; i<8; i++ )
+   {
+      if( ra->manifold_count == vg_list_size(ra->manifold) )
+         return;
+
+      struct contact *ct = &ra->manifold[ ra->manifold_count ];
+      
+      float p;
+      v3f normal;
+
+      if( rb_point_in_body( rb_static, verts[i], &p, normal ))
+      {
+         v3_copy( normal, ct->n );
+         v3_muladds( verts[i], ct->n, p*0.5f, ct->co );
+         v3_sub( ct->co, ra->co, ct->delta );
 
-   vg_line( p000, p110, colour );
-   vg_line( p100, p010, colour );
+         vg_line_pt3( ct->co, 0.0125f, 0xffff00ff );
+         
+         ct->bias = -0.2f * (1.0f/k_rb_delta) * vg_minf( 0.0f, -p+0.04f );
+         rb_tangent_basis( ct->n, ct->t[0], ct->t[1] );
+
+         ct->norm_impulse = 0.0f;
+         ct->tangent_impulse[0] = 0.0f;
+         ct->tangent_impulse[1] = 0.0f;
+
+         ra->manifold_count ++;
+         count ++;
+         if( count == 4 )
+            return;
+      }
+   }
 }
+#endif
+
+/* 
+ * Capsule phyics
+ */
+
+static void debug_capsule( m4x3f m, float height, float radius, u32 colour )
+{
+   v3f last = { 0.0f, 0.0f, radius };
+   m4x3f lower, upper;
+   m3x3_copy( m, lower );
+   m3x3_copy( m, upper );
+   m4x3_mulv( m, (v3f){0.0f,-height*0.5f+radius,0.0f}, lower[3] );
+   m4x3_mulv( m, (v3f){0.0f, height*0.5f-radius,0.0f}, upper[3] );
+   
+   for( int i=0; i<16; i++ )
+   {
+      float t = ((float)(i+1) * (1.0f/16.0f)) * VG_PIf * 2.0f,
+            s = sinf(t),
+            c = cosf(t);
+
+      v3f p = { s*radius, 0.0f, c*radius };
+
+      v3f p0, p1;
+      m4x3_mulv( lower, p, p0 );
+      m4x3_mulv( lower, last, p1 );
+      vg_line( p0, p1, colour );
+
+      m4x3_mulv( upper, p, p0 );
+      m4x3_mulv( upper, last, p1 );
+      vg_line( p0, p1, colour );
+
+      v3_copy( p, last );
+   }
+
+   for( int i=0; i<4; i++ )
+   {
+      float t = ((float)(i) * (1.0f/4.0f)) * VG_PIf * 2.0f,
+            s = sinf(t),
+            c = cosf(t);
+
+      v3f p = { s*radius, 0.0f, c*radius };
+
+      v3f p0, p1;
+      m4x3_mulv( lower, p, p0 );
+      m4x3_mulv( upper, p, p1 );
+      vg_line( p0, p1, colour );
+
+      m4x3_mulv( lower, (v3f){0.0f,-radius,0.0f}, p0 );
+      m4x3_mulv( upper, (v3f){0.0f, radius,0.0f}, p1 );
+      vg_line( p0, p1, colour );
+   }
+}
+
+/*
+ * BVH implementation, this is ONLY for static rigidbodies, its to slow for
+ * realtime use.
+ */
+
+static void rb_bh_expand_bound( void *user, boxf bound, u32 item_index )
+{
+   rigidbody *rb = &((rigidbody *)user)[ item_index ];
+   box_concat( bound, rb->bbx_world );
+}
+
+static float rb_bh_centroid( void *user, u32 item_index, int axis )
+{
+   rigidbody *rb = &((rigidbody *)user)[ item_index ];
+   return (rb->bbx_world[axis][0] + rb->bbx_world[1][axis]) * 0.5f;
+}
+
+static void rb_bh_swap( void *user, u32 ia, u32 ib )
+{
+   rigidbody temp, *rba, *rbb;
+   rba = &((rigidbody *)user)[ ia ];
+   rbb = &((rigidbody *)user)[ ib ];
+
+   temp = *rba;
+   *rba = *rbb;
+   *rbb = temp;
+}
+
+static void rb_bh_debug( void *user, u32 item_index )
+{
+   rigidbody *rb = &((rigidbody *)user)[ item_index ];
+   rb_debug( rb, 0xff00ffff );
+}
+
+static bh_system bh_system_rigidbodies =
+{
+   .expand_bound = rb_bh_expand_bound,
+   .item_centroid = rb_bh_centroid,
+   .item_swap = rb_bh_swap,
+   .item_debug = rb_bh_debug,
+   .cast_ray = NULL
+};
 
 #endif /* RIGIDBODY_H */