add motion vectors to all shaders
[carveJwlIkooP6JGAAIwe30JlM.git] / player_physics.h
index ff8d1f7a25a921848254f2a6d1725d39713a316a..f395953932e19003e93cac528d76c538cb99531e 100644 (file)
@@ -14,6 +14,51 @@ VG_STATIC void apply_gravity( v3f vel, float const timestep )
    v3_muladds( vel, gravity, timestep, vel );
 }
 
+VG_STATIC struct 
+grind_edge *player_grind_collect_edge( v3f p0, v3f p1,
+                                       v3f c0, v3f c1, float max_dist )
+{
+   struct player_phys *phys = &player.phys;
+
+   bh_iter it;
+   bh_iter_init( 0, &it );
+
+   boxf region;
+
+   box_init_inf( region );
+   box_addpt( region, p0 );
+   box_addpt( region, p1 );
+   
+   float k_r = max_dist;
+   v3_add( (v3f){ k_r, k_r, k_r}, region[1], region[1] );
+   v3_add( (v3f){-k_r,-k_r,-k_r}, region[0], region[0] );
+
+   float closest = k_r*k_r;
+   struct grind_edge *closest_edge = NULL;
+   
+   int idx;
+   while( bh_next( world.grind_bh, &it, region, &idx ) )
+   {
+      struct grind_edge *edge = &world.grind_edges[ idx ];
+
+      float s,t;
+      v3f pa, pb;
+
+      float d2 = 
+         closest_segment_segment( p0, p1, edge->p0, edge->p1, &s,&t, pa, pb );
+
+      if( d2 < closest )
+      {
+         closest = d2;
+         closest_edge = edge;
+         v3_copy( pa, c0 );
+         v3_copy( pb, c1 );
+      }
+   }
+
+   return closest_edge;
+}
+
 /*
  * Called when launching into the air to predict and adjust trajectories
  */
@@ -21,11 +66,6 @@ VG_STATIC void player_start_air(void)
 {
    struct player_phys *phys = &player.phys;
 
-   if( phys->in_air )
-      return;
-
-   phys->in_air = 1;
-
    float pstep = VG_TIMESTEP_FIXED * 10.0f;
    float best_velocity_delta = -9999.9f;
    float k_bias = 0.96f;
@@ -39,6 +79,10 @@ VG_STATIC void player_start_air(void)
 
    for( int m=-3;m<=12; m++ )
    {
+      struct land_log *log = &player.land_log[ player.land_log_count ++ ];
+      log->count = 0;
+      log->colour = 0xff000000;
+
       float vmod = ((float)m / 15.0f)*0.09f;
 
       v3f pco, pco1, pv;
@@ -60,6 +104,9 @@ VG_STATIC void player_start_air(void)
       m3x3_mulv( vr, pv, pv );
       v3_muladds( pco, pv, pstep, pco );
 
+      struct grind_edge *best_grind = NULL;
+      float closest_grind = INFINITY;
+
       for( int i=0; i<50; i++ )
       {
          v3_copy( pco, pco1 );
@@ -75,13 +122,28 @@ VG_STATIC void player_start_air(void)
          contact.dist = v3_length( vdir );
          v3_divs( vdir, contact.dist, vdir);
 
+         v3f c0, c1;
+         struct grind_edge *ge = player_grind_collect_edge( pco, pco1,
+                                                            c0, c1, 0.4f );
+
+         if( ge && (v3_dot((v3f){0.0f,1.0f,0.0f},vdir) < -0.2f ) )
+         {
+            float d2 = v3_dist2( c0, c1 );
+            if( d2 < closest_grind )
+            {
+               closest_grind = d2;
+               best_grind = ge;
+            }
+         }
+
          if( ray_world( pco1, vdir, &contact ))
          {
             float land_delta = v3_dot( pv, contact.normal );
             u32 scolour = (u8)(vg_minf(-land_delta * 2.0f, 255.0f));
 
             /* Bias prediction towords ramps */
-            if( ray_hit_is_ramp( &contact ) )
+            if( ray_hit_material( &contact )->info.flags 
+                  & k_material_flag_skate_surface )
             {
                land_delta *= 0.1f;
                scolour |= 0x0000a000;
@@ -98,19 +160,59 @@ VG_STATIC void player_start_air(void)
                q_m3x3( vr_q, phys->vr );
             }
 
-            v3_copy( contact.pos, 
-                  player.land_target_log[player.land_log_count] );
-            player.land_target_colours[player.land_log_count] = 
-               0xff000000 | scolour;
+            v3_copy( contact.pos, log->positions[ log->count ++ ] );
+            log->colour = 0xff000000 | scolour;
+            break;
+         }
 
-            player.land_log_count ++;
+         v3_copy( pco, log->positions[ log->count ++ ] );
+      }
 
-            break;
+      if( best_grind )
+      {
+         log->colour = 0xff0000ff;
+         
+         float score = -closest_grind * 0.05f;
+
+         if( score > best_velocity_delta )
+         {
+            best_velocity_delta = score;
+            
+            m3x3_copy( vr, phys->vr_pstep );
+            q_axis_angle( vr_q, axis, vmod*0.1f );
+            q_m3x3( vr_q, phys->vr );
          }
       }
    }
 }
 
+
+VG_STATIC void player_physics_control_passive(void)
+{
+   struct player_phys *phys = &player.phys;
+   float grabt = player.input_grab->axis.value;
+
+   if( grabt > 0.5f )
+   {
+      v2_muladds( phys->grab_mouse_delta, vg.mouse_delta, 0.02f, 
+                  phys->grab_mouse_delta );
+      v2_normalize_clamp( phys->grab_mouse_delta );
+   }
+   else
+      v2_zero( phys->grab_mouse_delta );
+
+   phys->grab = vg_lerpf( phys->grab, grabt, 0.14f );
+   player.phys.pushing = 0.0f;
+
+   if( !phys->jump_charge || phys->in_air )
+   {
+      phys->jump -= k_jump_charge_speed * VG_TIMESTEP_FIXED;
+   }
+
+   phys->jump_charge = 0;
+   phys->jump = vg_clampf( phys->jump, 0.0f, 1.0f );
+}
+
 /*
  * Main friction interface model
  */
@@ -136,12 +238,7 @@ VG_STATIC void player_physics_control(void)
    phys->reverse = -vg_signf(vel[2]);
 
    float substep = VG_TIMESTEP_FIXED * 0.2f;
-
-#if 0
-   float fwd_resistance = vg_get_button( "break" )? 5.0f: k_friction_resistance;
-#else
    float fwd_resistance = k_friction_resistance;
-#endif
 
    for( int i=0; i<5; i++ )
    {
@@ -149,7 +246,7 @@ VG_STATIC void player_physics_control(void)
       vel[0] = stable_force( vel[0],vg_signf(vel[0]) * -k_friction_lat*substep);
    }
    
-   if( vg_get_button( "jump" ) )
+   if( player.input_jump->button.value )
    {
       phys->jump += VG_TIMESTEP_FIXED * k_jump_charge_speed;
 
@@ -160,15 +257,15 @@ VG_STATIC void player_physics_control(void)
    }
 
    static int push_thresh_last = 0;
-   float push_amt = vg_get_axis( "walk/push" ) * 0.5f + 0.5f;
-   int push_thresh = push_amt>0.15f? 1: 0;
+   float push = player.input_push->button.value;
+   int push_thresh = push>0.15f? 1: 0;
    
    if( push_thresh && !push_thresh_last )
       player.phys.start_push = vg.time;
 
    push_thresh_last = push_thresh;
 
-   if( !vg_get_button("break") && push_thresh )
+   if( !player.input_jump->button.value && push_thresh )
    {
       player.phys.pushing = 1.0f;
       player.phys.push_time = vg.time - player.phys.start_push;
@@ -182,25 +279,68 @@ VG_STATIC void player_physics_control(void)
       vel[2] -= new_vel * phys->reverse;
    }
 
-   /* Pumping */
-   static float previous = 0.0f;
-   float delta = previous - phys->grab,
-          pump = delta * k_pump_force * VG_TIMESTEP_FIXED;
-   previous = phys->grab;
-
-   v3f p1;
-   v3_muladds( phys->rb.co, phys->rb.up, pump, p1 );
-   vg_line( phys->rb.co, p1, 0xff0000ff );
-
-   vel[1] += pump;
-
-   
    m3x3_mulv( phys->rb.to_world, vel, phys->rb.v );
    
-   float steer = vg_get_axis( "lookh" ),
+   float input = player.input_js1h->axis.value,
+         grab  = player.input_grab->axis.value,
+         steer = input * (1.0f-(phys->jump+grab)*0.4f),
          steer_scaled = vg_signf(steer) * powf(steer,2.0f) * k_steer_ground;
 
    phys->iY -= steer_scaled * VG_TIMESTEP_FIXED;
+
+   if( !phys->jump_charge && phys->jump > 0.2f )
+   {
+      v3f jumpdir;
+      
+      /* Launch more up if alignment is up else improve velocity */
+      float aup = fabsf(v3_dot( (v3f){0.0f,1.0f,0.0f}, phys->rb.up )),
+            mod = 0.5f,
+            dir = mod + aup*(1.0f-mod);
+
+      v3_copy( phys->rb.v, jumpdir );
+      v3_normalize( jumpdir );
+      v3_muls( jumpdir, 1.0f-dir, jumpdir );
+      v3_muladds( jumpdir, phys->rb.up, dir, jumpdir );
+      v3_normalize( jumpdir );
+      
+      float force = k_jump_force*phys->jump;
+      v3_muladds( phys->rb.v, jumpdir, force, phys->rb.v );
+      phys->jump = 0.0f;
+
+      player.jump_time = vg.time;
+      
+      /* TODO: Move to audio file */
+      audio_lock();
+      audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
+      audio_player_set_position( &audio_player_extra, phys->rb.co );
+      audio_player_set_vol( &audio_player_extra, 20.0f );
+      audio_player_playclip( &audio_player_extra, &audio_jumps[rand()%2] );
+      audio_unlock();
+   }
+}
+
+VG_STATIC void player_physics_control_grind(void)
+{
+   struct player_phys *phys = &player.phys;
+   v2f steer = { player.input_js1h->axis.value,
+                 player.input_js1v->axis.value };
+
+   float l2 = v2_length2( steer );
+   if( l2 > 1.0f )
+      v2_muls( steer, 1.0f/sqrtf(l2), steer );
+
+   phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
+
+   float iX = steer[1] * phys->reverse * k_steer_air * VG_TIMESTEP_FIXED;
+
+   static float siX = 0.0f;
+   siX = vg_lerpf( siX, iX, k_steer_air_lerp );
+   
+   v4f rotate;
+   q_axis_angle( rotate, phys->rb.right, siX );
+   q_mul( rotate, phys->rb.q, phys->rb.q );
+
+   phys->slip = 0.0f;
 }
 
 /*
@@ -254,7 +394,7 @@ VG_STATIC void player_physics_control_air(void)
          limiter *= limiter;
          limiter = 1.0f-limiter;
 
-         if( angle < 0.99f )
+         if( fabsf(angle) < 0.99f )
          {
             v4f correction;
             q_axis_angle( correction, axis, 
@@ -268,153 +408,336 @@ VG_STATIC void player_physics_control_air(void)
       time_to_impact += pstep;
    }
 
-   phys->iY -= vg_get_axis( "lookh" ) * k_steer_air * VG_TIMESTEP_FIXED;
-   {
-      float iX = vg_get_axis( "lookv" ) * 
-         phys->reverse * k_steer_air * limiter * VG_TIMESTEP_FIXED;
+   v2f steer = { player.input_js1h->axis.value,
+                 player.input_js1v->axis.value };
 
-      static float siX = 0.0f;
-      siX = vg_lerpf( siX, iX, k_steer_air_lerp );
-      
-      v4f rotate;
-      q_axis_angle( rotate, phys->rb.right, siX );
-      q_mul( rotate, phys->rb.q, phys->rb.q );
-   }
+   float l2 = v2_length2( steer );
+   if( l2 > 1.0f )
+      v2_muls( steer, 1.0f/sqrtf(l2), steer );
+
+   phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
+
+   float iX = steer[1] * 
+              phys->reverse * k_steer_air * limiter * VG_TIMESTEP_FIXED;
+
+   static float siX = 0.0f;
+   siX = vg_lerpf( siX, iX, k_steer_air_lerp );
+   
+   v4f rotate;
+   q_axis_angle( rotate, phys->rb.right, siX );
+   q_mul( rotate, phys->rb.q, phys->rb.q );
    
+#if 0
    v2f target = {0.0f,0.0f};
    v2_muladds( target, (v2f){ vg_get_axis("grabh"), vg_get_axis("grabv") },
                phys->grab, target );
+#endif
 }
 
-/*
- * Entire Walking physics model
- * TODO: sleep when under certain velotiy
- */
-VG_STATIC void player_walk_physics(void)
+VG_STATIC void player_walk_update_collision(void)
 {
    struct player_phys *phys = &player.phys;
-   rigidbody *rbf = &player.collide_front,
-             *rbb = &player.collide_back;
-
-   m3x3_copy( phys->rb.to_world, player.collide_front.to_world );
-   m3x3_copy( phys->rb.to_world, player.collide_back.to_world );
-   
    float h0 = 0.3f,
          h1 = 0.9f;
 
-   m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h0,0.0f}, rbf->co );
+   rigidbody *rbf = &player.collide_front,
+             *rbb = &player.collide_back;
+
+   v3_add( phys->rb.co, (v3f){0.0f,h0,0.0f}, rbf->co );
+   v3_add( phys->rb.co, (v3f){0.0f,h1,0.0f}, rbb->co );
    v3_copy( rbf->co, rbf->to_world[3] );
-   m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h1,0.0f}, rbb->co );
    v3_copy( rbb->co, rbb->to_world[3] );
-
    m4x3_invert_affine( rbf->to_world, rbf->to_local );
    m4x3_invert_affine( rbb->to_world, rbb->to_local );
 
    rb_update_bounds( rbf );
    rb_update_bounds( rbb );
+}
 
-   rb_debug( rbf, 0xff0000ff );
-   rb_debug( rbb, 0xff0000ff );
+VG_STATIC void player_integrate(void);
+/*
+ * Entire Walking physics model
+ * TODO: sleep when under certain velotiy
+ */
+VG_STATIC void player_walk_physics(void)
+{
+   struct player_phys *phys = &player.phys;
+   rigidbody *rbf = &player.collide_front,
+             *rbb = &player.collide_back;
+
+   m3x3_identity( player.collide_front.to_world );
+   m3x3_identity( player.collide_back.to_world );
+
+   v3_zero( phys->rb.w );
+   q_axis_angle( phys->rb.q, (v3f){0.0f,1.0f,0.0f}, -player.angles[0] );
 
    rb_ct manifold[64];
-   int len = 0;
+   int len;
 
-   len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
-   len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
+   v3f forward_dir = { sinf(player.angles[0]),0.0f,-cosf(player.angles[0]) };
+   v3f right_dir = { -forward_dir[2], 0.0f, forward_dir[0] };
 
-   rb_presolve_contacts( manifold, len );
+   v2f walk = { player.input_walkh->axis.value,
+                player.input_walkv->axis.value };
+   
+   if( v2_length2(walk) > 0.001f )
+      v2_normalize_clamp( walk );
 
-   for( int j=0; j<5; j++ )
+   if( phys->in_air )
    {
+      player_walk_update_collision();
+      rb_debug( rbf, 0xff0000ff );
+      rb_debug( rbb, 0xff0000ff );
+
+      /* allow player to accelerate a bit */
+      v3f walk_3d;
+      v3_muls( forward_dir, walk[1], walk_3d );
+      v3_muladds( walk_3d, right_dir, walk[0], walk_3d );
+
+      float current_vel = fabsf(v3_dot( walk_3d, phys->rb.v )),
+            new_vel     = current_vel + VG_TIMESTEP_FIXED*k_air_accelerate,
+            clamped_new = vg_clampf( new_vel, 0.0f, k_walkspeed ),
+            vel_diff    = vg_maxf( 0.0f, clamped_new - current_vel );
+
+      v3_muladds( phys->rb.v, right_dir,   walk[0] * vel_diff, phys->rb.v );
+      v3_muladds( phys->rb.v, forward_dir, walk[1] * vel_diff, phys->rb.v );
+
+
+      len = 0;
+      len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
+      len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
+      rb_presolve_contacts( manifold, len );
+
       for( int i=0; i<len; i++ )
       {
          struct contact *ct = &manifold[i];
-         
-         /*normal */
-         float vn = -v3_dot( phys->rb.v, ct->n );
-         vn += ct->bias;
+         if( v3_dot( ct->n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f )
+            phys->in_air = 0;
+      }
 
-         float temp = ct->norm_impulse;
-         ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
-         vn = ct->norm_impulse - temp;
+      for( int j=0; j<5; j++ )
+      {
+         for( int i=0; i<len; i++ )
+         {
+            struct contact *ct = &manifold[i];
+            
+            /*normal */
+            float vn = -v3_dot( phys->rb.v, ct->n );
+            vn += ct->bias;
 
-         v3f impulse;
-         v3_muls( ct->n, vn, impulse );
+            float temp = ct->norm_impulse;
+            ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
+            vn = ct->norm_impulse - temp;
 
-         v3_add( impulse, phys->rb.v, phys->rb.v );
+            v3f impulse;
+            v3_muls( ct->n, vn, impulse );
 
-         /* friction */
-         for( int j=0; j<2; j++ )
-         {
-            float     f = k_friction * ct->norm_impulse,
-                     vt = v3_dot( phys->rb.v, ct->t[j] ),
-                 lambda = -vt;
-            
-            float temp = ct->tangent_impulse[j];
-            ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
-            lambda = ct->tangent_impulse[j] - temp;
+            v3_add( impulse, phys->rb.v, phys->rb.v );
 
-            v3_muladds( phys->rb.v, ct->t[j], lambda, phys->rb.v );
+            /* friction */
+            for( int j=0; j<2; j++ )
+            {
+               float     f = k_friction * ct->norm_impulse,
+                        vt = v3_dot( phys->rb.v, ct->t[j] ),
+                    lambda = -vt;
+               
+               float temp = ct->tangent_impulse[j];
+               ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
+               lambda = ct->tangent_impulse[j] - temp;
+
+               v3_muladds( phys->rb.v, ct->t[j], lambda, phys->rb.v );
+            }
          }
       }
+
+      player_integrate();
    }
+   else
+   {
+      player.walk = v2_length( walk );
 
-   phys->in_air = len==0?1:0;
+      if( player.input_walk->button.value )
+         v2_muls( walk, 0.5f, walk );
 
-   if( !phys->in_air )
-   {
-      float const DOWNFORCE = -k_walk_downforce*VG_TIMESTEP_FIXED;
-      v3_muladds( phys->rb.v, (v3f){0.0f,-1.0f,0.0f}, DOWNFORCE, phys->rb.v );
+      v2_muls( walk, k_walkspeed * VG_TIMESTEP_FIXED, walk );
+
+      v3f walk_apply;
+      v3_zero( walk_apply );
+
+      /* Do XY translation */
+      v3_muladds( walk_apply, right_dir,   walk[0], walk_apply );
+      v3_muladds( walk_apply, forward_dir, walk[1], walk_apply );
+      v3_add( walk_apply, phys->rb.co, phys->rb.co );
+      v3_divs( walk_apply, VG_TIMESTEP_FIXED, phys->rb.v );
+
+      /* Directly resolve collisions */
+      player_walk_update_collision();
+      rb_debug( rbf, 0xffffff00 );
+      rb_debug( rbb, 0xffffff00 );
+
+      len = 0;
+      len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
+      len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
+
+      v3f dt;
+      v3_zero( dt );
+      for( int j=0; j<3; j++ )
+      {
+         for( int i=0; i<len; i++ )
+         {
+            struct contact *ct = &manifold[i];
+
+            float p   = vg_maxf( 0.0f, ct->p - 0.00f ),
+                  cur = vg_clampf( v3_dot( ct->n, dt ), 0.0f, p );
+            v3_muladds( dt, ct->n, (p - cur) * 0.333333333f, dt );
+         }
+      }
+      v3_add( dt, phys->rb.co, phys->rb.co );
+
+      if( len )
+      {
+         struct world_material *surface_mat = world_contact_material(manifold);
+         player.surface_prop = surface_mat->info.surface_prop;
+      }
 
-      if( vg_get_button("jump") )
+      /* jump */
+      if( player.input_jump->button.value )
       {
          phys->rb.v[1] = 5.0f;
+         phys->in_air = 1;
+         return;
       }
+      
+      /* if we've put us in the air, step down slowly */
+      phys->in_air = 1;
+      float max_dist = 0.3f,
+            start_y = phys->rb.co[1];
+
+      for( int j=0; j<8; j++ )
+      {
+         for( int i=0; i<len; i++ )
+         {
+            struct contact *ct = &manifold[i];
+            if( v3_dot( ct->n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f )
+            {
+               phys->in_air = 0;
+               if( j == 0 )
+                  return;
+
+               v3f dt;
+               v3_zero( dt );
+               for( int j=0; j<3; j++ )
+               {
+                  for( int i=0; i<len; i++ )
+                  {
+                     struct contact *ct = &manifold[i];
+
+                     float p   = vg_maxf( 0.0f, ct->p - 0.0025f ),
+                           cur = vg_clampf( v3_dot( ct->n, dt ), 0.0f, p );
+                     v3_muladds( dt, ct->n, (p - cur) * 0.333333333f, dt );
+                  }
+               }
+               v3_add( dt, phys->rb.co, phys->rb.co );
+               return;
+            }
+         }
+
+         phys->rb.co[1] -= max_dist * 0.125f;
+
+         player_walk_update_collision();
+         len = 0;
+         len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
+         len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
+      }
+      
+      /* Transitioning into air mode */
+      phys->rb.co[1] = start_y;
    }
+}
+
+VG_STATIC void player_grind(void)
+{
+   struct player_phys *phys = &player.phys;
+
+   v3f closest;
+   int idx = bh_closest_point( world.grind_bh, phys->rb.co, closest, INFINITY );
+   if( idx == -1 )
+      return;
+
+   struct grind_edge *edge = &world.grind_edges[ idx ];
+
+   vg_line( phys->rb.co, closest, 0xff000000 );
+   vg_line_cross( closest, 0xff000000, 0.3f );
+   vg_line( edge->p0, edge->p1, 0xff000000 );
+
+   v3f grind_delta;
+   v3_sub( closest, phys->rb.co, grind_delta );
    
-   v3_zero( phys->rb.w );
-   q_axis_angle( phys->rb.q, (v3f){0.0f,1.0f,0.0f}, -player.angles[0] );
+   float p = v3_dot( phys->rb.forward, grind_delta );
+   v3_muladds( grind_delta, phys->rb.forward, -p, grind_delta );
+   
+   float a = vg_maxf( 0.0f, 4.0f-v3_dist2( closest, phys->rb.co ) );
+   v3_muladds( phys->rb.v, grind_delta, a*0.2f, phys->rb.v );
+}
 
-   v3f forward_dir = { sinf(player.angles[0]),0.0f,-cosf(player.angles[0]) };
+VG_STATIC int player_update_grind_collision( rb_ct *contact )
+{
+   struct player_phys *phys = &player.phys;
+
+   v3f p0, p1, c0, c1;
+   v3_muladds( phys->rb.co, phys->rb.forward,  0.5f, p0 );
+   v3_muladds( phys->rb.co, phys->rb.forward, -0.5f, p1 );
+   v3_muladds( p0, phys->rb.up, 0.125f, p0 );
+   v3_muladds( p1, phys->rb.up, 0.125f, p1 );
 
-   v3f p1;
-   v3_muladds( phys->rb.co, forward_dir, 2.0f, p1 );
-   vg_line( phys->rb.co, p1, 0xff0000ff );
+   float const k_r = 0.25f;
+   struct grind_edge *closest_edge = player_grind_collect_edge( p0, p1, 
+                                                                c0, c1, k_r );
 
-   player.walk = powf( vg_get_axis("walk/push")*0.5f + 0.5f, 4.0f );
+   
+   vg_line( p0, p1, 0xff0000ff );
 
-   if( player.walk > 0.025f )
+   if( closest_edge )
    {
-      float 
-            speed     = vg_lerpf( 0.025f*k_runspeed, k_runspeed, player.walk ),
-            amt       = k_walk_accel * VG_TIMESTEP_FIXED,
-            zvel      = v3_dot( phys->rb.v, forward_dir ),
-            new_vel   = vg_minf( zvel + amt, speed ),
-            diff      = new_vel - vg_minf( zvel, speed );
-
-      if( !phys->in_air )
+      vg_line_cross( c0, 0xff000000, 0.1f );
+      vg_line_cross( c1, 0xff000000, 0.1f );
+      vg_line( c0, c1, 0xff000000 );
+
+      v3f delta;
+      v3_sub( c1, c0, delta );
+
+      if( v3_dot( delta, phys->rb.up ) > 0.0f )
       {
-         v3_muladds( phys->rb.v, forward_dir, diff, phys->rb.v );
+         v3_copy( delta, contact->n );
+         float l = v3_length( contact->n );
+         v3_muls( contact->n, 1.0f/l, contact->n );
+         contact->p = l;
+         contact->type = k_contact_type_edge;
+         contact->element_id = 0;
+         v3_copy( c1, contact->co );
+         contact->rba = &player.phys.rb;
+         contact->rbb = &world.rb_geo;
+
+         v3f edge_dir, axis_dir;
+         v3_sub( closest_edge->p1, closest_edge->p0, edge_dir );
+         v3_normalize( edge_dir );
+         v3_cross( (v3f){0.0f,1.0f,0.0f}, edge_dir, axis_dir );
+         v3_cross( edge_dir, axis_dir, contact->n );
+
+         return 1;
       }
+      else
+         return -1;
    }
-   
-   if( !phys->in_air )
-   {
-      phys->rb.v[0] *= 1.0f - (VG_TIMESTEP_FIXED * k_walk_friction);
-      phys->rb.v[2] *= 1.0f - (VG_TIMESTEP_FIXED * k_walk_friction);
-   }
+
+   return 0;
 }
 
-/*
- * Physics collision detection, and control
- */
-VG_STATIC void player_physics(void)
+/* Manifold must be able to hold at least 64 elements */
+VG_STATIC int player_update_collision_manifold( rb_ct *manifold )
 {
    struct player_phys *phys = &player.phys;
-   /*
-    * Update collision fronts
-    */
-   
+
    rigidbody *rbf = &player.collide_front,
              *rbb = &player.collide_back;
 
@@ -438,38 +761,124 @@ VG_STATIC void player_physics(void)
    rb_debug( rbf, 0xff00ffff );
    rb_debug( rbb, 0xffffff00 );
 
-   rb_ct manifold[64];
-   int len = 0;
+   int len_f = 0,
+       len_b = 0; 
 
-   len += rb_sphere_scene( rbf, &world.rb_geo, manifold+len );
-   len += rb_sphere_scene( rbb, &world.rb_geo, manifold+len );
+   len_f = rb_sphere_scene( rbf, &world.rb_geo, manifold );
+   rb_manifold_filter_coplanar( manifold, len_f, 0.05f );
+   if( len_f > 1 )
+   {
+      rb_manifold_filter_backface( manifold, len_f );
+      rb_manifold_filter_joint_edges( manifold, len_f, 0.05f );
+      rb_manifold_filter_pairs( manifold, len_f, 0.05f );
+   }
+   len_f = rb_manifold_apply_filtered( manifold, len_f );
+   
+   rb_ct *man_b = &manifold[len_f];
+   len_b = rb_sphere_scene( rbb, &world.rb_geo, man_b );
+   rb_manifold_filter_coplanar( man_b, len_b, 0.05f );
+   if( len_b > 1 )
+   {
+      rb_manifold_filter_backface( man_b, len_b );
+      rb_manifold_filter_joint_edges( man_b, len_b, 0.05f );
+      rb_manifold_filter_pairs( man_b, len_b, 0.05f );
+   }
+   len_b = rb_manifold_apply_filtered( man_b, len_b );
 
-   rb_presolve_contacts( manifold, len );
-   v3f surface_avg = {0.0f, 0.0f, 0.0f};
+#if 0
+   /* 
+    * Preprocess collision points, and create a surface picture.
+    * we want contacts that are within our 'capsule's internal line to be 
+    * clamped so that they face the line and do not oppose, to stop the
+    * player hanging up on stuff
+    */
+   for( int i=0; i<len; i++ )
+   {
+      v3f dfront, dback;
+      v3_sub( manifold[i].co, rbf->co, dfront );
+      v3_sub( manifold[i].co, rbb->co, dback );
 
-   if( !len )
+      if( (v3_dot( dfront, phys->rb.forward ) < -0.02f) &&
+          (v3_dot( dback,  phys->rb.forward ) > 0.02f))
+      {
+         float p = v3_dot( manifold[i].n, phys->rb.forward );
+         v3_muladds( manifold[i].n, phys->rb.forward, -p, manifold[i].n );
+         v3_normalize( manifold[i].n );
+      }
+   }
+#endif
+
+   return len_f + len_b;
+}
+
+VG_STATIC void player_adhere_ground( rb_ct *manifold, int len )
+{
+   struct player_phys *phys = &player.phys;
+   int was_in_air = phys->in_air;
+
+   v3f surface_avg;
+   v3_zero( surface_avg );
+
+   if( len == 0 )
    {
-      player_start_air();
+      phys->lift_frames ++;
+
+      if( phys->lift_frames >= 8 )
+         phys->in_air = 1;
    }
    else
    {
       for( int i=0; i<len; i++ )
-      {
-         v3_add( manifold[i].n, surface_avg, surface_avg );
-      }
-
+         v3_add( surface_avg, manifold[i].n, surface_avg );
       v3_normalize( surface_avg );
-
-      if( v3_dot( phys->rb.v, surface_avg ) > 0.5f )
+      
+      if( v3_dot( phys->rb.v, surface_avg ) > 0.7f )
       {
-         player_start_air();
+         phys->lift_frames ++;
+
+         if( phys->lift_frames >= 8 )
+            phys->in_air = 1;
       }
       else
       {
          phys->in_air = 0;
+         phys->lift_frames = 0;
+         v3f projected, axis;
+
+         float const DOWNFORCE = -k_downforce*VG_TIMESTEP_FIXED;
+         v3_muladds( phys->rb.v, phys->rb.up, DOWNFORCE, phys->rb.v );
+
+         float d = v3_dot( phys->rb.forward, surface_avg );
+         v3_muladds( surface_avg, phys->rb.forward, -d, projected );
+         v3_normalize( projected );
+
+         float angle = v3_dot( phys->rb.up, projected );
+         v3_cross( phys->rb.up, projected, axis );
+
+         v3f p0, p1;
+         v3_add( phys->rb.co, projected, p0 );
+         v3_add( phys->rb.co, phys->rb.up, p1 );
+         vg_line( phys->rb.co, p0, 0xff00ff00 );
+         vg_line( phys->rb.co, p1, 0xff000fff );
+
+         if( fabsf(angle) < 0.999f )
+         {
+            v4f correction;
+            q_axis_angle( correction, axis, 
+                          acosf(angle)*4.0f*VG_TIMESTEP_FIXED );
+            q_mul( correction, phys->rb.q, phys->rb.q );
+         }
       }
    }
 
+   if( !was_in_air && phys->in_air )
+      player_start_air();
+}
+
+VG_STATIC void player_collision_response( rb_ct *manifold, int len )
+{
+   struct player_phys *phys = &player.phys;
+
    for( int j=0; j<5; j++ )
    {
       for( int i=0; i<len; i++ )
@@ -510,109 +919,12 @@ VG_STATIC void player_physics(void)
           */
          
          float wy = v3_dot( phys->rb.up, impulse ),
-               wx = v3_dot( phys->rb.right, impulse )*1.5f;
+               wx = v3_dot( phys->rb.right, impulse )*1.8f;
 
          v3_muladds( phys->rb.w, phys->rb.up, wy, phys->rb.w );
          v3_muladds( phys->rb.w, phys->rb.right, wx, phys->rb.w );
       }
    }
-
-   float grabt = vg_get_axis( "grab" )*0.5f+0.5f;
-   phys->grab = vg_lerpf( phys->grab, grabt, 0.14f );
-   player.phys.pushing = 0.0f;
-
-   if( !phys->in_air )
-   {
-#if 0
-      v3f axis;
-      float angle = v3_dot( phys->rb.up, surface_avg );
-      v3_cross( phys->rb.up, surface_avg, axis );
-
-      //float cz = v3_dot( player.rb.forward, axis );
-      //v3_muls( player.rb.forward, cz, axis );
-
-      if( angle < 0.999f )
-      {
-         v4f correction;
-         q_axis_angle( correction, axis, acosf(angle)*18.0f*VG_TIMESTEP_FIXED );
-         q_mul( correction, phys->rb.q, phys->rb.q );
-      }
-#else
-      
-      /* 20/10/22: make this only go axisways instead, may effect velocities. */
-
-      v3f projected, axis;
-
-      float d = v3_dot( phys->rb.forward, surface_avg );
-      v3_muladds( surface_avg, phys->rb.forward, -d, projected );
-      v3_normalize( projected );
-
-      float angle = v3_dot( phys->rb.up, projected );
-      v3_cross( phys->rb.up, projected, axis );
-
-      v3f p0, p1;
-      v3_add( phys->rb.co, projected, p0 );
-      v3_add( phys->rb.co, phys->rb.up, p1 );
-      vg_line( phys->rb.co, p0, 0xff00ff00 );
-      vg_line( phys->rb.co, p1, 0xff000fff );
-
-      if( fabsf(angle) < 0.999f )
-      {
-         v4f correction;
-         q_axis_angle( correction, axis, acosf(angle)*4.0f*VG_TIMESTEP_FIXED );
-         q_mul( correction, phys->rb.q, phys->rb.q );
-      }
-
-
-#endif
-
-      float const DOWNFORCE = -k_downforce*VG_TIMESTEP_FIXED;
-      v3_muladds( phys->rb.v, phys->rb.up, DOWNFORCE, phys->rb.v );
-
-      player_physics_control();
-
-      if( !phys->jump_charge && phys->jump > 0.2f )
-      {
-         v3f jumpdir;
-         
-         /* Launch more up if alignment is up else improve velocity */
-         float aup = fabsf(v3_dot( (v3f){0.0f,1.0f,0.0f}, phys->rb.up )),
-               mod = 0.5f,
-               dir = mod + aup*(1.0f-mod);
-
-         v3_copy( phys->rb.v, jumpdir );
-         v3_normalize( jumpdir );
-         v3_muls( jumpdir, 1.0f-dir, jumpdir );
-         v3_muladds( jumpdir, phys->rb.up, dir, jumpdir );
-         v3_normalize( jumpdir );
-         
-         float force = k_jump_force*phys->jump;
-         v3_muladds( phys->rb.v, jumpdir, force, phys->rb.v );
-         phys->jump = 0.0f;
-
-         player.jump_time = vg.time;
-         
-         /* TODO: Move to audio file */
-         audio_lock();
-         audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
-         audio_player_set_position( &audio_player_extra, phys->rb.co );
-         audio_player_set_vol( &audio_player_extra, 20.0f );
-         audio_player_playclip( &audio_player_extra, &audio_jumps[rand()%2] );
-         audio_unlock();
-      }
-   }
-   else
-   {
-      player_physics_control_air();
-   }
-
-   if( !phys->jump_charge )
-   {
-      phys->jump -= k_jump_charge_speed * VG_TIMESTEP_FIXED;
-   }
-
-   phys->jump_charge = 0;
-   phys->jump = vg_clampf( phys->jump, 0.0f, 1.0f );
 }
 
 VG_STATIC void player_save_frame(void)
@@ -626,12 +938,16 @@ VG_STATIC void player_restore_frame(void)
    rb_update_transform( &player.phys.rb );
 }
 
-VG_STATIC void player_do_motion(void)
+VG_STATIC void player_integrate(void)
 {
    struct player_phys *phys = &player.phys;
+   apply_gravity( phys->rb.v, VG_TIMESTEP_FIXED );
+   v3_muladds( phys->rb.co, phys->rb.v, VG_TIMESTEP_FIXED, phys->rb.co );
+}
 
-   float horizontal = vg_get_axis("horizontal"),
-         vertical = vg_get_axis("vertical");
+VG_STATIC void player_do_motion(void)
+{
+   struct player_phys *phys = &player.phys;
 
    if( world.water.enabled )
    {
@@ -648,18 +964,93 @@ VG_STATIC void player_do_motion(void)
       }
    }
 
+   v3f prevco;
+   v3_copy( phys->rb.co, prevco );
+
    if( phys->on_board )
-      player_physics();
+   {
+      rb_ct manifold[72];
+      int len = player_update_collision_manifold( manifold );
+      int grind_col = player_update_grind_collision( &manifold[len] );
+
+      static int _grind_col_pre = 0;
+
+      if( grind_col )
+      {
+         phys->grind = 1;
+         v3f up = { 0.0f, 1.0f, 0.0f };
+         float angle = v3_dot( phys->rb.up, up );
+
+         if( fabsf(angle) < 0.99f )
+         {
+            v3f axis; 
+            v3_cross( phys->rb.up, up, axis );
+
+            v4f correction;
+            q_axis_angle( correction, axis, 
+                  VG_TIMESTEP_FIXED * 10.0f * acosf(angle) );
+            q_mul( correction, phys->rb.q, phys->rb.q );
+         }
+
+         float const DOWNFORCE = -k_downforce*1.2f*VG_TIMESTEP_FIXED;
+         v3_muladds( phys->rb.v, manifold[len].n, DOWNFORCE, phys->rb.v );
+         m3x3_identity( phys->vr );
+         m3x3_identity( phys->vr_pstep );
+
+         if( !_grind_col_pre )
+         {
+            audio_lock();
+            audio_player_set_flags( &audio_player_extra, 
+                                    AUDIO_FLAG_SPACIAL_3D );
+            audio_player_set_position( &audio_player_extra, phys->rb.co );
+            audio_player_set_vol( &audio_player_extra, 20.0f );
+            audio_player_playclip( &audio_player_extra, &audio_board[5] );
+            audio_unlock();
+         }
+      }
+      else
+      {
+         phys->grind = 0;
+         player_adhere_ground( manifold, len );
+
+         if( _grind_col_pre )
+         {
+            audio_lock();
+            audio_player_set_flags( &audio_player_extra, 
+                                    AUDIO_FLAG_SPACIAL_3D );
+            audio_player_set_position( &audio_player_extra, phys->rb.co );
+            audio_player_set_vol( &audio_player_extra, 20.0f );
+            audio_player_playclip( &audio_player_extra, &audio_board[6] );
+            audio_unlock();
+         }
+      }
+
+      _grind_col_pre = grind_col;
+
+      rb_presolve_contacts( manifold, len+ VG_MAX(0,grind_col) );
+      player_collision_response( manifold, len+ VG_MAX(0,grind_col) );
+
+      player_physics_control_passive();
+
+      if( grind_col )
+      {
+         phys->in_air = 0;
+         player_physics_control_grind();
+      }
+      else
+      {
+         if( phys->in_air )
+            player_physics_control_air();
+         else
+            player_physics_control();
+      }
+
+      player_integrate();
+   }
    else
       player_walk_physics();
    
-   /* Integrate velocity */
-   v3f prevco;
-   v3_copy( phys->rb.co, prevco );
    
-   apply_gravity( phys->rb.v, VG_TIMESTEP_FIXED );
-   v3_muladds( phys->rb.co, phys->rb.v, VG_TIMESTEP_FIXED, phys->rb.co );
-
    /* Real angular velocity integration */
    v3_lerp( phys->rb.w, (v3f){0.0f,0.0f,0.0f}, 0.125f, phys->rb.w );
    if( v3_length2( phys->rb.w ) > 0.0f )
@@ -732,34 +1123,6 @@ VG_STATIC void player_do_motion(void)
    rb_update_transform( &phys->rb );
 }
 
-/*
- * Free camera movement
- */
-VG_STATIC void player_mouseview(void)
-{
-   if( ui_want_mouse() )
-      return;
-
-   static v2f mouse_last,
-              view_vel = { 0.0f, 0.0f };
-
-   if( vg_get_button_down( "primary" ) )
-      v2_copy( vg.mouse, mouse_last );
-
-   else if( vg_get_button( "primary" ) )
-   {
-      v2f delta;
-      v2_sub( vg.mouse, mouse_last, delta );
-      v2_copy( vg.mouse, mouse_last );
-
-      v2_muladds( view_vel, delta, 0.06f*vg.time_delta, view_vel );
-   }
-   
-   v2_muls( view_vel, 1.0f-4.2f*vg.time_delta, view_vel );
-   v2_add( view_vel, player.angles, player.angles );
-   player.angles[1] = vg_clampf( player.angles[1], -VG_PIf*0.5f, VG_PIf*0.5f );
-}
-
 VG_STATIC void player_freecam(void)
 {
    player_mouseview();
@@ -768,10 +1131,13 @@ VG_STATIC void player_freecam(void)
    v3f lookdir = { 0.0f, 0.0f, -1.0f },
        sidedir = { 1.0f, 0.0f,  0.0f };
    
-   m3x3_mulv( camera_mtx, lookdir, lookdir );
-   m3x3_mulv( camera_mtx, sidedir, sidedir );
+   m3x3_mulv( main_camera.transform, lookdir, lookdir );
+   m3x3_mulv( main_camera.transform, sidedir, sidedir );
    
    static v3f move_vel = { 0.0f, 0.0f, 0.0f };
+
+   /* TODO */
+#if 0
    if( vg_get_button( "forward" ) )
       v3_muladds( move_vel, lookdir, VG_TIMESTEP_FIXED * movespeed, move_vel );
    if( vg_get_button( "back" ) )
@@ -780,6 +1146,7 @@ VG_STATIC void player_freecam(void)
       v3_muladds( move_vel, sidedir, VG_TIMESTEP_FIXED *-movespeed, move_vel );
    if( vg_get_button( "right" ) )
       v3_muladds( move_vel, sidedir, VG_TIMESTEP_FIXED * movespeed, move_vel );
+#endif
 
    v3_muls( move_vel, 0.7f, move_vel );
    v3_add( move_vel, player.camera_pos, player.camera_pos );
@@ -827,6 +1194,13 @@ VG_STATIC int reset_player( int argc, char const *argv[] )
    if( !rp )
    {
       vg_error( "No spawn found\n" );
+      vg_info( "Player position: %f %f %f\n", player.phys.rb.co[0],
+                                              player.phys.rb.co[1],
+                                              player.phys.rb.co[2] );
+      vg_info( "Player velocity: %f %f %f\n", player.phys.rb.v[0],
+                                              player.phys.rb.v[1],
+                                              player.phys.rb.v[2] );
+
       if( !world.spawn_count )
          return 0;
 
@@ -835,10 +1209,20 @@ VG_STATIC int reset_player( int argc, char const *argv[] )
 
    player.is_dead = 0;
 
+   m3x3f the_long_way;
+   q_m3x3( rp->q, the_long_way );
+
+   v3f delta = {1.0f,0.0f,0.0f};
+   m3x3_mulv( the_long_way, delta, delta );
+
+   player.angles[0] = atan2f( delta[0], -delta[2] ); 
+   player.angles[1] = -asinf( delta[1] );
+
+
    v4_copy( rp->q, phys->rb.q );
    v3_copy( rp->co, phys->rb.co );
    v3_zero( phys->rb.v );
-
+   
    phys->vswitch = 1.0f;
    phys->slip_last = 0.0f;
    phys->in_air = 1;