walk stability
[carveJwlIkooP6JGAAIwe30JlM.git] / player_physics.h
1 /*
2 * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 */
4
5 #ifndef PLAYER_PHYSICS_H
6 #define PLAYER_PHYSICS_H
7
8 #include "player.h"
9 #include "camera.h"
10
11 VG_STATIC void apply_gravity( v3f vel, float const timestep )
12 {
13 v3f gravity = { 0.0f, -9.6f, 0.0f };
14 v3_muladds( vel, gravity, timestep, vel );
15 }
16
17 VG_STATIC struct
18 grind_edge *player_grind_collect_edge( v3f p0, v3f p1,
19 v3f c0, v3f c1, float max_dist )
20 {
21 struct player_phys *phys = &player.phys;
22
23 bh_iter it;
24 bh_iter_init( 0, &it );
25
26 boxf region;
27
28 box_init_inf( region );
29 box_addpt( region, p0 );
30 box_addpt( region, p1 );
31
32 float k_r = max_dist;
33 v3_add( (v3f){ k_r, k_r, k_r}, region[1], region[1] );
34 v3_add( (v3f){-k_r,-k_r,-k_r}, region[0], region[0] );
35
36 float closest = k_r*k_r;
37 struct grind_edge *closest_edge = NULL;
38
39 int idx;
40 while( bh_next( world.grind_bh, &it, region, &idx ) )
41 {
42 struct grind_edge *edge = &world.grind_edges[ idx ];
43
44 float s,t;
45 v3f pa, pb;
46
47 float d2 =
48 closest_segment_segment( p0, p1, edge->p0, edge->p1, &s,&t, pa, pb );
49
50 if( d2 < closest )
51 {
52 closest = d2;
53 closest_edge = edge;
54 v3_copy( pa, c0 );
55 v3_copy( pb, c1 );
56 }
57 }
58
59 return closest_edge;
60 }
61
62 /*
63 * Cast a sphere from a to b and see what time it hits
64 */
65 VG_STATIC int spherecast_world( v3f pa, v3f pb, float r, float *t, v3f n )
66 {
67 struct player_phys *phys = &player.phys;
68
69 bh_iter it;
70 bh_iter_init( 0, &it );
71
72 boxf region;
73 box_init_inf( region );
74 box_addpt( region, pa );
75 box_addpt( region, pb );
76
77 v3_add( (v3f){ r, r, r}, region[1], region[1] );
78 v3_add( (v3f){-r,-r,-r}, region[0], region[0] );
79
80 v3f dir;
81 v3_sub( pb, pa, dir );
82
83 int hit = -1;
84 float min_t = 1.0f;
85
86 int idx;
87 while( bh_next( world.geo_bh, &it, region, &idx ) )
88 {
89 u32 *ptri = &world.scene_geo->arrindices[ idx*3 ];
90 v3f tri[3];
91
92 boxf box;
93 box_init_inf( box );
94
95 for( int j=0; j<3; j++ )
96 {
97 v3_copy( world.scene_geo->arrvertices[ptri[j]].co, tri[j] );
98 box_addpt( box, tri[j] );
99 }
100
101 v3_add( (v3f){ r, r, r}, box[1], box[1] );
102 v3_add( (v3f){-r,-r,-r}, box[0], box[0] );
103 if( !ray_aabb( box, pa, dir, 1.0f ) )
104 continue;
105
106 float t;
107 v3f n1;
108 if( spherecast_triangle( tri, pa, dir, r, &t, n1 ) )
109 {
110 if( t < min_t )
111 {
112 min_t = t;
113 hit = idx;
114 v3_copy( n1, n );
115 }
116 }
117 }
118
119 *t = min_t;
120 return hit;
121 }
122
123 /*
124 * Trace a path given a velocity rotation.
125 * Closest to 0 is best.
126 */
127 VG_STATIC void player_predict_land( m3x3f vr,
128 struct land_prediction *prediction )
129 {
130 struct player_phys *phys = &player.phys;
131
132 float pstep = VG_TIMESTEP_FIXED * 10.0f;
133 float k_bias = 0.96f;
134
135 v3f pco, pco1, pv;
136 v3_copy( phys->rb.co, pco );
137 v3_muls( phys->rb.v, k_bias, pv );
138
139 m3x3_mulv( vr, pv, pv );
140 v3_muladds( pco, pv, pstep, pco );
141
142 struct grind_edge *best_grind = NULL;
143 float closest_grind = INFINITY;
144
145 float grind_score = INFINITY,
146 air_score = INFINITY;
147
148 prediction->log_length = 0;
149
150 for( int i=0; i<vg_list_size(prediction->log); i++ )
151 {
152 v3_copy( pco, pco1 );
153 apply_gravity( pv, pstep );
154
155 m3x3_mulv( vr, pv, pv );
156 v3_muladds( pco, pv, pstep, pco );
157
158 v3f vdir;
159
160 v3_sub( pco, pco1, vdir );
161
162 float l = v3_length( vdir );
163 v3_muls( vdir, 1.0f/l, vdir );
164
165 v3f c0, c1;
166 struct grind_edge *ge = player_grind_collect_edge( pco, pco1,
167 c0, c1, 0.4f );
168
169 if( ge && (v3_dot((v3f){0.0f,1.0f,0.0f},vdir) < -0.2f ) )
170 {
171 float d2 = v3_dist2( c0, c1 );
172 if( d2 < closest_grind )
173 {
174 closest_grind = d2;
175 best_grind = ge;
176 grind_score = closest_grind * 0.05f;
177 }
178 }
179
180 v3f n1;
181
182 float t1;
183 int idx = spherecast_world( pco1, pco, 0.4f, &t1, n1 );
184 if( idx != -1 )
185 {
186 v3_copy( n1, prediction->n );
187 air_score = -v3_dot( pv, n1 );
188
189 u32 vert_index = world.scene_geo->arrindices[ idx*3 ];
190 struct world_material *mat = world_tri_index_material( vert_index );
191
192 /* Bias prediction towords ramps */
193 if( mat->info.flags & k_material_flag_skate_surface )
194 air_score *= 0.1f;
195
196 v3_lerp( pco1, pco, t1, prediction->log[ prediction->log_length ++ ] );
197 break;
198 }
199
200 v3_copy( pco, prediction->log[ prediction->log_length ++ ] );
201 }
202
203 if( grind_score < air_score )
204 {
205 prediction->score = grind_score;
206 prediction->type = k_prediction_grind;
207 }
208 else if( air_score < INFINITY )
209 {
210 prediction->score = air_score;
211 prediction->type = k_prediction_land;
212 }
213 else
214 {
215 prediction->score = INFINITY;
216 prediction->type = k_prediction_none;
217 }
218 }
219
220 /*
221 * Called when launching into the air to predict and adjust trajectories
222 */
223 VG_STATIC void player_start_air(void)
224 {
225 struct player_phys *phys = &player.phys;
226
227 float pstep = VG_TIMESTEP_FIXED * 10.0f;
228 float best_velocity_delta = -9999.9f;
229
230 v3f axis;
231 v3_cross( phys->rb.up, phys->rb.v, axis );
232 v3_normalize( axis );
233 player.prediction_count = 0;
234
235 m3x3_identity( phys->vr );
236
237 float
238 best_vmod = 0.0f,
239 min_score = INFINITY,
240 max_score = -INFINITY;
241
242 /*
243 * Search a broad selection of futures
244 */
245 for( int m=-3;m<=12; m++ )
246 {
247 struct land_prediction *p =
248 &player.predictions[ player.prediction_count ++ ];
249
250 float vmod = ((float)m / 15.0f)*0.09f;
251
252 m3x3f vr;
253 v4f vr_q;
254
255 q_axis_angle( vr_q, axis, vmod );
256 q_m3x3( vr_q, vr );
257
258 player_predict_land( vr, p );
259
260 if( p->type != k_prediction_none )
261 {
262 if( p->score < min_score )
263 {
264 min_score = p->score;
265 best_vmod = vmod;
266 }
267
268 if( p->score > max_score )
269 max_score = p->score;
270 }
271 }
272
273 v4f vr_q;
274 q_axis_angle( vr_q, axis, best_vmod*0.1f );
275 q_m3x3( vr_q, phys->vr );
276
277 q_axis_angle( vr_q, axis, best_vmod );
278 q_m3x3( vr_q, phys->vr_pstep );
279
280 /*
281 * Logging
282 */
283 for( int i=0; i<player.prediction_count; i ++ )
284 {
285 struct land_prediction *p = &player.predictions[i];
286
287 float l = p->score;
288
289 if( l < 0.0f )
290 {
291 vg_error( "negative score! (%f)\n", l );
292 }
293
294 l -= min_score;
295 l /= (max_score-min_score);
296 l = 1.0f - l;
297 l *= 255.0f;
298
299 p->colour = l;
300 p->colour <<= 8;
301 p->colour |= 0xff000000;
302 }
303 }
304
305
306 VG_STATIC void player_physics_control_passive(void)
307 {
308 struct player_phys *phys = &player.phys;
309 float grabt = player.input_grab->axis.value;
310
311 if( grabt > 0.5f )
312 {
313 v2_muladds( phys->grab_mouse_delta, vg.mouse_delta, 0.02f,
314 phys->grab_mouse_delta );
315 v2_normalize_clamp( phys->grab_mouse_delta );
316
317 if( freecam )
318 v2_zero( phys->grab_mouse_delta );
319 }
320 else
321 v2_zero( phys->grab_mouse_delta );
322
323 phys->grab = vg_lerpf( phys->grab, grabt, 0.14f );
324 player.phys.pushing = 0.0f;
325
326 if( !phys->jump_charge || phys->in_air )
327 {
328 phys->jump -= k_jump_charge_speed * VG_TIMESTEP_FIXED;
329 }
330
331 phys->jump_charge = 0;
332 phys->jump = vg_clampf( phys->jump, 0.0f, 1.0f );
333 }
334
335 /*
336 * Main friction interface model
337 */
338 VG_STATIC void player_physics_control(void)
339 {
340 struct player_phys *phys = &player.phys;
341
342 /*
343 * Computing localized friction forces for controlling the character
344 * Friction across X is significantly more than Z
345 */
346
347 v3f vel;
348 m3x3_mulv( phys->rb.to_local, phys->rb.v, vel );
349 float slip = 0.0f;
350
351 if( fabsf(vel[2]) > 0.01f )
352 slip = fabsf(-vel[0] / vel[2]) * vg_signf(vel[0]);
353
354 if( fabsf( slip ) > 1.2f )
355 slip = vg_signf( slip ) * 1.2f;
356 phys->slip = slip;
357 phys->reverse = -vg_signf(vel[2]);
358
359 float substep = VG_TIMESTEP_FIXED * 0.2f;
360 float fwd_resistance = k_friction_resistance;
361
362 for( int i=0; i<5; i++ )
363 {
364 vel[2] = stable_force( vel[2],vg_signf(vel[2]) * -fwd_resistance*substep);
365 vel[0] = stable_force( vel[0],vg_signf(vel[0]) * -k_friction_lat*substep);
366 }
367
368 if( player.input_jump->button.value )
369 {
370 phys->jump += VG_TIMESTEP_FIXED * k_jump_charge_speed;
371
372 if( !phys->jump_charge )
373 phys->jump_dir = phys->reverse > 0.0f? 1: 0;
374
375 phys->jump_charge = 1;
376 }
377
378 static int push_thresh_last = 0;
379 float push = player.input_push->button.value;
380 int push_thresh = push>0.15f? 1: 0;
381
382 if( push_thresh && !push_thresh_last )
383 player.phys.start_push = vg.time;
384
385 push_thresh_last = push_thresh;
386
387 if( !player.input_jump->button.value && push_thresh )
388 {
389 player.phys.pushing = 1.0f;
390 player.phys.push_time = vg.time - player.phys.start_push;
391
392 float cycle_time = player.phys.push_time*k_push_cycle_rate,
393 amt = k_push_accel * (sinf(cycle_time)*0.5f+0.5f)*VG_TIMESTEP_FIXED,
394 current = v3_length( vel ),
395 new_vel = vg_minf( current + amt, k_max_push_speed );
396
397 new_vel -= vg_minf(current, k_max_push_speed);
398 vel[2] -= new_vel * phys->reverse;
399 }
400
401 m3x3_mulv( phys->rb.to_world, vel, phys->rb.v );
402
403 float input = player.input_js1h->axis.value,
404 grab = player.input_grab->axis.value,
405 steer = input * (1.0f-(phys->jump+grab)*0.4f),
406 steer_scaled = vg_signf(steer) * powf(steer,2.0f) * k_steer_ground;
407
408 phys->iY -= steer_scaled * VG_TIMESTEP_FIXED;
409
410 if( !phys->jump_charge && phys->jump > 0.2f )
411 {
412 v3f jumpdir;
413
414 /* Launch more up if alignment is up else improve velocity */
415 float aup = fabsf(v3_dot( (v3f){0.0f,1.0f,0.0f}, phys->rb.up )),
416 mod = 0.5f,
417 dir = mod + aup*(1.0f-mod);
418
419 v3_copy( phys->rb.v, jumpdir );
420 v3_normalize( jumpdir );
421 v3_muls( jumpdir, 1.0f-dir, jumpdir );
422 v3_muladds( jumpdir, phys->rb.up, dir, jumpdir );
423 v3_normalize( jumpdir );
424
425 float force = k_jump_force*phys->jump;
426 v3_muladds( phys->rb.v, jumpdir, force, phys->rb.v );
427 phys->jump = 0.0f;
428
429 player.jump_time = vg.time;
430
431 /* TODO: Move to audio file */
432 audio_lock();
433 audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
434 audio_player_set_position( &audio_player_extra, phys->rb.co );
435 audio_player_set_vol( &audio_player_extra, 20.0f );
436 audio_player_playclip( &audio_player_extra, &audio_jumps[rand()%2] );
437 audio_unlock();
438 }
439 }
440
441 VG_STATIC void player_physics_control_grind(void)
442 {
443 struct player_phys *phys = &player.phys;
444 v2f steer = { player.input_js1h->axis.value,
445 player.input_js1v->axis.value };
446
447 float l2 = v2_length2( steer );
448 if( l2 > 1.0f )
449 v2_muls( steer, 1.0f/sqrtf(l2), steer );
450
451 phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
452
453 float iX = steer[1] * phys->reverse * k_steer_air * VG_TIMESTEP_FIXED;
454
455 static float siX = 0.0f;
456 siX = vg_lerpf( siX, iX, k_steer_air_lerp );
457
458 v4f rotate;
459 q_axis_angle( rotate, phys->rb.right, siX );
460 q_mul( rotate, phys->rb.q, phys->rb.q );
461
462 phys->slip = 0.0f;
463 }
464
465 /*
466 * Air control, no real physics
467 */
468 VG_STATIC void player_physics_control_air(void)
469 {
470 struct player_phys *phys = &player.phys;
471
472 m3x3_mulv( phys->vr, phys->rb.v, phys->rb.v );
473 //vg_line_cross( player.land_target, 0xff0000ff, 0.25f );
474
475 ray_hit hit;
476
477 /*
478 * Prediction
479 */
480 float pstep = VG_TIMESTEP_FIXED * 1.0f;
481 float k_bias = 0.98f;
482
483 v3f pco, pco1, pv;
484 v3_copy( phys->rb.co, pco );
485 v3_muls( phys->rb.v, 1.0f, pv );
486
487 float time_to_impact = 0.0f;
488 float limiter = 1.0f;
489
490 struct grind_edge *best_grind = NULL;
491 float closest_grind = INFINITY;
492
493 v3f target_normal = { 0.0f, 1.0f, 0.0f };
494 int has_target = 0;
495
496 for( int i=0; i<250; i++ )
497 {
498 v3_copy( pco, pco1 );
499 m3x3_mulv( phys->vr, pv, pv );
500 apply_gravity( pv, pstep );
501 v3_muladds( pco, pv, pstep, pco );
502
503 ray_hit contact;
504 v3f vdir;
505
506 v3_sub( pco, pco1, vdir );
507 contact.dist = v3_length( vdir );
508 v3_divs( vdir, contact.dist, vdir);
509
510 v3f c0, c1;
511 struct grind_edge *ge = player_grind_collect_edge( pco, pco1,
512 c0, c1, 0.4f );
513
514 if( ge && (v3_dot((v3f){0.0f,1.0f,0.0f},vdir) < -0.2f ) )
515 {
516 vg_line( ge->p0, ge->p1, 0xff0000ff );
517 vg_line_cross( pco, 0xff0000ff, 0.25f );
518 has_target = 1;
519 break;
520 }
521
522 float orig_dist = contact.dist;
523 if( ray_world( pco1, vdir, &contact ) )
524 {
525 v3_copy( contact.normal, target_normal );
526 has_target = 1;
527 time_to_impact += (contact.dist/orig_dist)*pstep;
528 vg_line_cross( contact.pos, 0xffff0000, 0.25f );
529 break;
530 }
531 time_to_impact += pstep;
532 }
533
534 if( has_target )
535 {
536 float angle = v3_dot( phys->rb.up, target_normal );
537 v3f axis;
538 v3_cross( phys->rb.up, target_normal, axis );
539
540 limiter = vg_minf( 5.0f, time_to_impact )/5.0f;
541 limiter = 1.0f-limiter;
542 limiter *= limiter;
543 limiter = 1.0f-limiter;
544
545 if( fabsf(angle) < 0.99f )
546 {
547 v4f correction;
548 q_axis_angle( correction, axis,
549 acosf(angle)*(1.0f-limiter)*3.0f*VG_TIMESTEP_FIXED );
550 q_mul( correction, phys->rb.q, phys->rb.q );
551 }
552 }
553
554 v2f steer = { player.input_js1h->axis.value,
555 player.input_js1v->axis.value };
556
557 float l2 = v2_length2( steer );
558 if( l2 > 1.0f )
559 v2_muls( steer, 1.0f/sqrtf(l2), steer );
560
561 phys->iY -= steer[0] * k_steer_air * VG_TIMESTEP_FIXED;
562
563 float iX = steer[1] *
564 phys->reverse * k_steer_air * limiter * VG_TIMESTEP_FIXED;
565
566 static float siX = 0.0f;
567 siX = vg_lerpf( siX, iX, k_steer_air_lerp );
568
569 v4f rotate;
570 q_axis_angle( rotate, phys->rb.right, siX );
571 q_mul( rotate, phys->rb.q, phys->rb.q );
572
573 #if 0
574 v2f target = {0.0f,0.0f};
575 v2_muladds( target, (v2f){ vg_get_axis("grabh"), vg_get_axis("grabv") },
576 phys->grab, target );
577 #endif
578 }
579
580 VG_STATIC void player_walk_collider_configuration(void)
581 {
582 struct player_phys *phys = &player.phys;
583 float h0 = 0.3f,
584 h1 = 0.9f;
585
586 rigidbody *rbf = &player.collide_front,
587 *rbb = &player.collide_back;
588
589 v3_add( phys->rb.co, (v3f){0.0f,h0,0.0f}, rbf->co );
590 v3_add( phys->rb.co, (v3f){0.0f,h1,0.0f}, rbb->co );
591 v3_copy( rbf->co, rbf->to_world[3] );
592 v3_copy( rbb->co, rbb->to_world[3] );
593 m4x3_invert_affine( rbf->to_world, rbf->to_local );
594 m4x3_invert_affine( rbb->to_world, rbb->to_local );
595
596 rb_update_bounds( rbf );
597 rb_update_bounds( rbb );
598 }
599
600 VG_STATIC void player_regular_collider_configuration(void)
601 {
602 struct player_phys *phys = &player.phys;
603
604 /* Standard ground configuration */
605 rigidbody *rbf = &player.collide_front,
606 *rbb = &player.collide_back;
607
608 m3x3_copy( phys->rb.to_world, player.collide_front.to_world );
609 m3x3_copy( phys->rb.to_world, player.collide_back.to_world );
610
611 player.air_blend = vg_lerpf( player.air_blend, phys->in_air, 0.1f );
612 float h = player.air_blend*0.0f;
613
614 m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h,-k_board_length}, rbf->co );
615 v3_copy( rbf->co, rbf->to_world[3] );
616 m4x3_mulv( phys->rb.to_world, (v3f){0.0f,h, k_board_length}, rbb->co );
617 v3_copy( rbb->co, rbb->to_world[3] );
618
619 m4x3_invert_affine( rbf->to_world, rbf->to_local );
620 m4x3_invert_affine( rbb->to_world, rbb->to_local );
621
622 rb_update_bounds( rbf );
623 rb_update_bounds( rbb );
624 }
625
626 VG_STATIC void player_integrate(void);
627
628 VG_STATIC int player_walk_surface_standable( v3f n )
629 {
630 return v3_dot( n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f;
631 }
632
633 VG_STATIC void player_walk_stepdown(void)
634 {
635 struct player_phys *phys = &player.phys;
636 float max_dist = 0.4f;
637
638 v3f pa, pb;
639 v3_copy( phys->rb.co, pa );
640 pa[1] += 0.3f;
641
642 v3_muladds( pa, (v3f){0.01f,1.0f,0.01f}, -max_dist, pb );
643 vg_line( pa, pb, 0xff000000 );
644
645 /* TODO: Make #define */
646 float r = 0.3f,
647 t;
648
649 v3f n;
650 if( spherecast_world( pa, pb, r, &t, n ) != -1 )
651 {
652 if( player_walk_surface_standable( n ) )
653 {
654 phys->in_air = 0;
655 v3_lerp( pa, pb, t+0.001f, phys->rb.co );
656 phys->rb.co[1] -= 0.3f;
657 }
658 }
659 }
660
661 VG_STATIC int player_update_collision_manifold( rb_ct *manifold );
662 VG_STATIC void player_walk_physics(void)
663 {
664 struct player_phys *phys = &player.phys;
665 rigidbody *rbf = &player.collide_front,
666 *rbb = &player.collide_back;
667
668 m3x3_identity( player.collide_front.to_world );
669 m3x3_identity( player.collide_back.to_world );
670
671 v3_zero( phys->rb.w );
672 q_axis_angle( phys->rb.q, (v3f){0.0f,1.0f,0.0f}, -player.angles[0] );
673
674 rb_ct manifold[64];
675 int len;
676
677 v3f forward_dir = { sinf(player.angles[0]),0.0f,-cosf(player.angles[0]) };
678 v3f right_dir = { -forward_dir[2], 0.0f, forward_dir[0] };
679
680 v2f walk = { player.input_walkh->axis.value,
681 player.input_walkv->axis.value };
682
683 if( freecam )
684 v2_zero( walk );
685
686 if( v2_length2(walk) > 0.001f )
687 v2_normalize_clamp( walk );
688
689 if( phys->in_air )
690 {
691 player_walk_collider_configuration();
692
693 /* allow player to accelerate a bit */
694 v3f walk_3d;
695 v3_muls( forward_dir, walk[1], walk_3d );
696 v3_muladds( walk_3d, right_dir, walk[0], walk_3d );
697
698 float current_vel = fabsf(v3_dot( walk_3d, phys->rb.v )),
699 new_vel = current_vel + VG_TIMESTEP_FIXED*k_air_accelerate,
700 clamped_new = vg_clampf( new_vel, 0.0f, k_walkspeed ),
701 vel_diff = vg_maxf( 0.0f, clamped_new - current_vel );
702
703 v3_muladds( phys->rb.v, right_dir, walk[0] * vel_diff, phys->rb.v );
704 v3_muladds( phys->rb.v, forward_dir, walk[1] * vel_diff, phys->rb.v );
705
706
707 len = player_update_collision_manifold( manifold );
708 rb_presolve_contacts( manifold, len );
709
710 for( int i=0; i<len; i++ )
711 {
712 struct contact *ct = &manifold[i];
713 if( v3_dot( ct->n, (v3f){0.0f,1.0f,0.0f} ) > 0.5f )
714 phys->in_air = 0;
715 }
716
717 for( int j=0; j<5; j++ )
718 {
719 for( int i=0; i<len; i++ )
720 {
721 struct contact *ct = &manifold[i];
722
723 /*normal */
724 float vn = -v3_dot( phys->rb.v, ct->n );
725 vn += ct->bias;
726
727 float temp = ct->norm_impulse;
728 ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
729 vn = ct->norm_impulse - temp;
730
731 v3f impulse;
732 v3_muls( ct->n, vn, impulse );
733
734 v3_add( impulse, phys->rb.v, phys->rb.v );
735
736 /* friction */
737 for( int j=0; j<2; j++ )
738 {
739 float f = k_friction * ct->norm_impulse,
740 vt = v3_dot( phys->rb.v, ct->t[j] ),
741 lambda = -vt;
742
743 float temp = ct->tangent_impulse[j];
744 ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
745 lambda = ct->tangent_impulse[j] - temp;
746
747 v3_muladds( phys->rb.v, ct->t[j], lambda, phys->rb.v );
748 }
749 }
750 }
751
752 player_integrate();
753 }
754 else
755 {
756 player.walk = v2_length( walk );
757
758 if( player.input_walk->button.value )
759 v2_muls( walk, 0.5f, walk );
760
761 v2_muls( walk, k_walkspeed * VG_TIMESTEP_FIXED, walk );
762
763 /* Do XY translation */
764 v3f walk_apply, walk_measured;
765 v3_zero( walk_apply );
766 v3_muladds( walk_apply, right_dir, walk[0], walk_apply );
767 v3_muladds( walk_apply, forward_dir, walk[1], walk_apply );
768 v3_add( walk_apply, phys->rb.co, phys->rb.co );
769
770 /* Directly resolve collisions */
771 player_walk_collider_configuration();
772 len = player_update_collision_manifold( manifold );
773
774 v3f dt;
775 v3_zero( dt );
776 for( int j=0; j<8; j++ )
777 {
778 for( int i=0; i<len; i++ )
779 {
780 struct contact *ct = &manifold[i];
781
782 float resolved_amt = v3_dot( ct->n, dt ),
783 remaining = (ct->p-k_penetration_slop) - resolved_amt,
784 apply = vg_maxf( remaining, 0.0f ) * 0.3f;
785
786 v3_muladds( dt, ct->n, apply, dt );
787 }
788 }
789 v3_add( dt, phys->rb.co, phys->rb.co );
790
791 v3_add( dt, walk_apply, walk_measured );
792 v3_divs( walk_measured, VG_TIMESTEP_FIXED, phys->rb.v );
793
794 if( len )
795 {
796 struct world_material *surface_mat = world_contact_material(manifold);
797 player.surface_prop = surface_mat->info.surface_prop;
798 }
799
800 /* jump */
801 if( player.input_jump->button.value )
802 {
803 phys->rb.v[1] = 5.0f;
804 phys->in_air = 1;
805 return;
806 }
807
808 /* Check if grounded by current manifold */
809 phys->in_air = 1;
810 for( int i=0; i<len; i++ )
811 {
812 struct contact *ct = &manifold[i];
813 if( player_walk_surface_standable( ct->n ) )
814 phys->in_air = 0;
815 }
816
817 /* otherwise... */
818 if( phys->in_air )
819 player_walk_stepdown();
820 }
821 }
822
823 VG_STATIC void player_grind(void)
824 {
825 struct player_phys *phys = &player.phys;
826
827 v3f closest;
828 int idx = bh_closest_point( world.grind_bh, phys->rb.co, closest, INFINITY );
829 if( idx == -1 )
830 return;
831
832 struct grind_edge *edge = &world.grind_edges[ idx ];
833
834 vg_line( phys->rb.co, closest, 0xff000000 );
835 vg_line_cross( closest, 0xff000000, 0.3f );
836 vg_line( edge->p0, edge->p1, 0xff000000 );
837
838 v3f grind_delta;
839 v3_sub( closest, phys->rb.co, grind_delta );
840
841 float p = v3_dot( phys->rb.forward, grind_delta );
842 v3_muladds( grind_delta, phys->rb.forward, -p, grind_delta );
843
844 float a = vg_maxf( 0.0f, 4.0f-v3_dist2( closest, phys->rb.co ) );
845 v3_muladds( phys->rb.v, grind_delta, a*0.2f, phys->rb.v );
846 }
847
848 VG_STATIC int player_update_grind_collision( rb_ct *contact )
849 {
850 struct player_phys *phys = &player.phys;
851
852 v3f p0, p1, c0, c1;
853 v3_muladds( phys->rb.co, phys->rb.forward, 0.5f, p0 );
854 v3_muladds( phys->rb.co, phys->rb.forward, -0.5f, p1 );
855 v3_muladds( p0, phys->rb.up, 0.125f-0.15f, p0 );
856 v3_muladds( p1, phys->rb.up, 0.125f-0.15f, p1 );
857
858 float const k_r = 0.25f;
859 struct grind_edge *closest_edge = player_grind_collect_edge( p0, p1,
860 c0, c1, k_r );
861
862
863 vg_line( p0, p1, 0xff0000ff );
864
865 if( closest_edge )
866 {
867 vg_line_cross( c0, 0xff000000, 0.1f );
868 vg_line_cross( c1, 0xff000000, 0.1f );
869 vg_line( c0, c1, 0xff000000 );
870
871 v3f delta;
872 v3_sub( c1, c0, delta );
873
874 if( v3_dot( delta, phys->rb.up ) > 0.0001f )
875 {
876 contact->p = v3_length( delta );
877 contact->type = k_contact_type_edge;
878 contact->element_id = 0;
879 v3_copy( c1, contact->co );
880 contact->rba = &player.phys.rb;
881 contact->rbb = &world.rb_geo;
882
883 v3f edge_dir, axis_dir;
884 v3_sub( closest_edge->p1, closest_edge->p0, edge_dir );
885 v3_normalize( edge_dir );
886 v3_cross( (v3f){0.0f,1.0f,0.0f}, edge_dir, axis_dir );
887 v3_cross( edge_dir, axis_dir, contact->n );
888
889 #if 0
890 vg_info( "%f %f\n", v3_length( contact->n ), contact->p );
891 #endif
892
893 return 1;
894 }
895 else
896 return -1;
897 }
898
899 return 0;
900 }
901
902 /* Manifold must be able to hold at least 64 elements */
903 VG_STATIC int player_update_collision_manifold( rb_ct *manifold )
904 {
905 struct player_phys *phys = &player.phys;
906
907 rigidbody *rbf = &player.collide_front,
908 *rbb = &player.collide_back;
909
910 rb_debug( rbf, 0xff00ffff );
911 rb_debug( rbb, 0xffffff00 );
912
913
914 #if 0
915 phys->rise = vg_lerpf( phys->rise, phys->in_air? -0.25f: 0.0f,
916 VG_TIMESTEP_FIXED );
917 #endif
918
919 int len_f = 0,
920 len_b = 0;
921
922 len_f = rb_sphere_scene( rbf, &world.rb_geo, manifold );
923 rb_manifold_filter_coplanar( manifold, len_f, 0.05f );
924 if( len_f > 1 )
925 {
926 rb_manifold_filter_backface( manifold, len_f );
927 rb_manifold_filter_joint_edges( manifold, len_f, 0.05f );
928 rb_manifold_filter_pairs( manifold, len_f, 0.05f );
929 }
930 int new_len_f = rb_manifold_apply_filtered( manifold, len_f );
931 if( len_f && !new_len_f )
932 len_f = 1;
933 else
934 len_f = new_len_f;
935
936 rb_ct *man_b = &manifold[len_f];
937 len_b = rb_sphere_scene( rbb, &world.rb_geo, man_b );
938 rb_manifold_filter_coplanar( man_b, len_b, 0.05f );
939 if( len_b > 1 )
940 {
941 rb_manifold_filter_backface( man_b, len_b );
942 rb_manifold_filter_joint_edges( man_b, len_b, 0.05f );
943 rb_manifold_filter_pairs( man_b, len_b, 0.05f );
944 }
945 int new_len_b = rb_manifold_apply_filtered( man_b, len_b );
946 if( len_b && !new_len_b )
947 len_b = 1;
948 else
949 len_b = new_len_b;
950
951 return len_f + len_b;
952 }
953
954 VG_STATIC void player_adhere_ground( rb_ct *manifold, int len )
955 {
956 struct player_phys *phys = &player.phys;
957 int was_in_air = phys->in_air;
958
959 v3f surface_avg;
960 v3_zero( surface_avg );
961
962 if( len == 0 )
963 {
964 phys->lift_frames ++;
965
966 if( phys->lift_frames >= 8 )
967 phys->in_air = 1;
968 }
969 else
970 {
971 for( int i=0; i<len; i++ )
972 v3_add( surface_avg, manifold[i].n, surface_avg );
973 v3_normalize( surface_avg );
974
975 if( v3_dot( phys->rb.v, surface_avg ) > 0.7f )
976 {
977 phys->lift_frames ++;
978
979 if( phys->lift_frames >= 8 )
980 phys->in_air = 1;
981 }
982 else
983 {
984 phys->in_air = 0;
985 phys->lift_frames = 0;
986 v3f projected, axis;
987
988 float const DOWNFORCE = -k_downforce*VG_TIMESTEP_FIXED;
989 v3_muladds( phys->rb.v, phys->rb.up, DOWNFORCE, phys->rb.v );
990
991 float d = v3_dot( phys->rb.forward, surface_avg );
992 v3_muladds( surface_avg, phys->rb.forward, -d, projected );
993 v3_normalize( projected );
994
995 float angle = v3_dot( phys->rb.up, projected );
996 v3_cross( phys->rb.up, projected, axis );
997
998 v3f p0, p1;
999 v3_add( phys->rb.co, projected, p0 );
1000 v3_add( phys->rb.co, phys->rb.up, p1 );
1001 vg_line( phys->rb.co, p0, 0xff00ff00 );
1002 vg_line( phys->rb.co, p1, 0xff000fff );
1003
1004 if( fabsf(angle) < 0.999f )
1005 {
1006 v4f correction;
1007 q_axis_angle( correction, axis,
1008 acosf(angle)*4.0f*VG_TIMESTEP_FIXED );
1009 q_mul( correction, phys->rb.q, phys->rb.q );
1010 }
1011 }
1012 }
1013
1014 if( !was_in_air && phys->in_air )
1015 player_start_air();
1016 }
1017
1018 VG_STATIC void player_collision_response( rb_ct *manifold, int len )
1019 {
1020 struct player_phys *phys = &player.phys;
1021
1022 for( int j=0; j<5; j++ )
1023 {
1024 for( int i=0; i<len; i++ )
1025 {
1026 struct contact *ct = &manifold[i];
1027
1028 v3f dv, delta;
1029 v3_sub( ct->co, phys->rb.co, delta );
1030 v3_cross( phys->rb.w, delta, dv );
1031 v3_add( phys->rb.v, dv, dv );
1032
1033 float vn = -v3_dot( dv, ct->n );
1034 vn += ct->bias;
1035
1036 float temp = ct->norm_impulse;
1037 ct->norm_impulse = vg_maxf( temp + vn, 0.0f );
1038 vn = ct->norm_impulse - temp;
1039
1040 v3f impulse;
1041 v3_muls( ct->n, vn, impulse );
1042
1043 if( fabsf(v3_dot( impulse, phys->rb.forward )) > 10.0f ||
1044 fabsf(v3_dot( impulse, phys->rb.up )) > 50.0f )
1045 {
1046 player_kill();
1047 return;
1048 }
1049
1050 v3_add( impulse, phys->rb.v, phys->rb.v );
1051 v3_cross( delta, impulse, impulse );
1052
1053 /*
1054 * W Impulses are limited to the Y and X axises, we don't really want
1055 * roll angular velocities being included.
1056 *
1057 * Can also tweak the resistance of each axis here by scaling the wx,wy
1058 * components.
1059 */
1060
1061 float wy = v3_dot( phys->rb.up, impulse ) * 0.8f,
1062 wx = v3_dot( phys->rb.right, impulse )*1.0f;
1063
1064 v3_muladds( phys->rb.w, phys->rb.up, wy, phys->rb.w );
1065 v3_muladds( phys->rb.w, phys->rb.right, wx, phys->rb.w );
1066 }
1067 }
1068 }
1069
1070 VG_STATIC void player_save_frame(void)
1071 {
1072 player.phys_gate_frame = player.phys;
1073 }
1074
1075 VG_STATIC void player_restore_frame(void)
1076 {
1077 player.phys = player.phys_gate_frame;
1078 rb_update_transform( &player.phys.rb );
1079 }
1080
1081 VG_STATIC void player_integrate(void)
1082 {
1083 struct player_phys *phys = &player.phys;
1084 apply_gravity( phys->rb.v, VG_TIMESTEP_FIXED );
1085 v3_muladds( phys->rb.co, phys->rb.v, VG_TIMESTEP_FIXED, phys->rb.co );
1086 }
1087
1088 VG_STATIC void player_do_motion(void)
1089 {
1090 struct player_phys *phys = &player.phys;
1091
1092 if( world.water.enabled )
1093 {
1094 if( (phys->rb.co[1] < 0.0f) && !player.is_dead )
1095 {
1096 audio_lock();
1097 audio_player_set_flags( &audio_player_extra, AUDIO_FLAG_SPACIAL_3D );
1098 audio_player_set_position( &audio_player_extra, phys->rb.co );
1099 audio_player_set_vol( &audio_player_extra, 20.0f );
1100 audio_player_playclip( &audio_player_extra, &audio_splash );
1101 audio_unlock();
1102
1103 player_kill();
1104 }
1105 }
1106
1107 v3f prevco;
1108 v3_copy( phys->rb.co, prevco );
1109
1110 if( phys->on_board )
1111 {
1112 rb_ct manifold[72];
1113
1114 player_regular_collider_configuration();
1115 int len = player_update_collision_manifold( manifold );
1116 int grind_col = player_update_grind_collision( &manifold[len] );
1117
1118 static int _grind_col_pre = 0;
1119
1120 if( grind_col )
1121 {
1122 phys->grind = 1;
1123 v3f up = { 0.0f, 1.0f, 0.0f };
1124 float angle = v3_dot( phys->rb.up, up );
1125
1126 if( fabsf(angle) < 0.99f )
1127 {
1128 v3f axis;
1129 v3_cross( phys->rb.up, up, axis );
1130
1131 v4f correction;
1132 q_axis_angle( correction, axis,
1133 VG_TIMESTEP_FIXED * 10.0f * acosf(angle) );
1134 q_mul( correction, phys->rb.q, phys->rb.q );
1135 }
1136
1137 float const DOWNFORCE = -k_downforce*1.2f*VG_TIMESTEP_FIXED;
1138 v3_muladds( phys->rb.v, manifold[len].n, DOWNFORCE, phys->rb.v );
1139 m3x3_identity( phys->vr );
1140 m3x3_identity( phys->vr_pstep );
1141
1142 if( !_grind_col_pre )
1143 {
1144 audio_lock();
1145 audio_player_set_flags( &audio_player_extra,
1146 AUDIO_FLAG_SPACIAL_3D );
1147 audio_player_set_position( &audio_player_extra, phys->rb.co );
1148 audio_player_set_vol( &audio_player_extra, 20.0f );
1149 audio_player_playclip( &audio_player_extra, &audio_board[5] );
1150 audio_unlock();
1151 }
1152 }
1153 else
1154 {
1155 phys->grind = 0;
1156 player_adhere_ground( manifold, len );
1157
1158 if( _grind_col_pre )
1159 {
1160 audio_lock();
1161 audio_player_set_flags( &audio_player_extra,
1162 AUDIO_FLAG_SPACIAL_3D );
1163 audio_player_set_position( &audio_player_extra, phys->rb.co );
1164 audio_player_set_vol( &audio_player_extra, 20.0f );
1165 audio_player_playclip( &audio_player_extra, &audio_board[6] );
1166 audio_unlock();
1167 }
1168 }
1169
1170 _grind_col_pre = grind_col;
1171
1172 rb_presolve_contacts( manifold, len+ VG_MAX(0,grind_col) );
1173 player_collision_response( manifold, len+ VG_MAX(0,grind_col) );
1174
1175 player_physics_control_passive();
1176
1177 if( grind_col )
1178 {
1179 phys->in_air = 0;
1180 player_physics_control_grind();
1181 }
1182 else
1183 {
1184 if( phys->in_air )
1185 player_physics_control_air();
1186 else
1187 player_physics_control();
1188 }
1189
1190 player_integrate();
1191 }
1192 else
1193 player_walk_physics();
1194
1195
1196 /* Real angular velocity integration */
1197 v3_lerp( phys->rb.w, (v3f){0.0f,0.0f,0.0f}, 0.125f*0.5f, phys->rb.w );
1198 if( v3_length2( phys->rb.w ) > 0.0f )
1199 {
1200 v4f rotation;
1201 v3f axis;
1202 v3_copy( phys->rb.w, axis );
1203
1204 float mag = v3_length( axis );
1205 v3_divs( axis, mag, axis );
1206 q_axis_angle( rotation, axis, mag*k_rb_delta );
1207 q_mul( rotation, phys->rb.q, phys->rb.q );
1208 }
1209
1210 /* Faux angular velocity */
1211 v4f rotate;
1212
1213 float lerpq = phys->in_air? 0.04f: 0.3f;
1214 phys->siY = vg_lerpf( phys->siY, phys->iY, lerpq );
1215
1216 q_axis_angle( rotate, phys->rb.up, phys->siY );
1217 q_mul( rotate, phys->rb.q, phys->rb.q );
1218 phys->iY = 0.0f;
1219
1220 /*
1221 * Gate intersection, by tracing a line over the gate planes
1222 */
1223 for( int i=0; i<world.gate_count; i++ )
1224 {
1225 struct route_gate *rg = &world.gates[i];
1226 teleport_gate *gate = &rg->gate;
1227
1228 if( gate_intersect( gate, phys->rb.co, prevco ) )
1229 {
1230 m4x3_mulv( gate->transport, phys->rb.co, phys->rb.co );
1231 m3x3_mulv( gate->transport, phys->rb.v, phys->rb.v );
1232 m3x3_mulv( gate->transport, phys->vl, phys->vl );
1233 m3x3_mulv( gate->transport, phys->v_last, phys->v_last );
1234 m3x3_mulv( gate->transport, phys->m, phys->m );
1235 m3x3_mulv( gate->transport, phys->bob, phys->bob );
1236
1237 /* Pre-emptively edit the camera matrices so that the motion vectors
1238 * are correct */
1239 m4x3f transport_i;
1240 m4x4f transport_4;
1241 m4x3_invert_affine( gate->transport, transport_i );
1242 m4x3_expand( transport_i, transport_4 );
1243 m4x4_mul( main_camera.mtx.pv, transport_4, main_camera.mtx.pv );
1244 m4x4_mul( main_camera.mtx.v, transport_4, main_camera.mtx.v );
1245
1246 v4f transport_rotation;
1247 m3x3_q( gate->transport, transport_rotation );
1248 q_mul( transport_rotation, phys->rb.q, phys->rb.q );
1249
1250 world_routes_activate_gate( i );
1251
1252 if( !phys->on_board )
1253 {
1254 v3f fwd_dir = {cosf(player.angles[0]),
1255 0.0f,
1256 sinf(player.angles[0])};
1257 m3x3_mulv( gate->transport, fwd_dir, fwd_dir );
1258
1259 player.angles[0] = atan2f( fwd_dir[2], fwd_dir[0] );
1260 }
1261
1262 player.rewind_length = 0;
1263 player.rewind_total_length = 0.0f;
1264 player.rewind_incrementer = 10000;
1265 player_save_frame();
1266
1267 audio_lock();
1268 audio_play_oneshot( &audio_gate_pass, 1.0f );
1269 audio_unlock();
1270 break;
1271 }
1272 }
1273
1274 rb_update_transform( &phys->rb );
1275 }
1276
1277 VG_STATIC void player_freecam(void)
1278 {
1279 player_mouseview();
1280
1281 float movespeed = fc_speed * VG_TIMESTEP_FIXED;
1282 v3f lookdir = { 0.0f, 0.0f, -1.0f },
1283 sidedir = { 1.0f, 0.0f, 0.0f };
1284
1285 m3x3_mulv( main_camera.transform, lookdir, lookdir );
1286 m3x3_mulv( main_camera.transform, sidedir, sidedir );
1287
1288 static v3f move_vel = { 0.0f, 0.0f, 0.0f };
1289
1290 v2f steer = { player.input_js1h->axis.value,
1291 player.input_js1v->axis.value };
1292
1293 v3_muladds( move_vel, sidedir, movespeed*steer[0], move_vel );
1294 v3_muladds( move_vel, lookdir, -movespeed*steer[1], move_vel );
1295
1296 v3_muls( move_vel, 0.7f, move_vel );
1297 v3_add( move_vel, player.camera_pos, player.camera_pos );
1298 }
1299
1300 VG_STATIC int kill_player( int argc, char const *argv[] )
1301 {
1302 player_kill();
1303 return 0;
1304 }
1305
1306 VG_STATIC int reset_player( int argc, char const *argv[] )
1307 {
1308 struct player_phys *phys = &player.phys;
1309 struct respawn_point *rp = NULL, *r;
1310
1311 if( argc == 1 )
1312 {
1313 for( int i=0; i<world.spawn_count; i++ )
1314 {
1315 r = &world.spawns[i];
1316 if( !strcmp( r->name, argv[0] ) )
1317 {
1318 rp = r;
1319 break;
1320 }
1321 }
1322
1323 if( !rp )
1324 vg_warn( "No spawn named '%s'\n", argv[0] );
1325 }
1326
1327 if( !rp )
1328 {
1329 float min_dist = INFINITY;
1330
1331 for( int i=0; i<world.spawn_count; i++ )
1332 {
1333 r = &world.spawns[i];
1334 float d = v3_dist2( r->co, phys->rb.co );
1335
1336 vg_info( "Dist %s : %f\n", r->name, d );
1337 if( d < min_dist )
1338 {
1339 min_dist = d;
1340 rp = r;
1341 }
1342 }
1343 }
1344
1345 if( !rp )
1346 {
1347 vg_error( "No spawn found\n" );
1348 vg_info( "Player position: %f %f %f\n", player.phys.rb.co[0],
1349 player.phys.rb.co[1],
1350 player.phys.rb.co[2] );
1351 vg_info( "Player velocity: %f %f %f\n", player.phys.rb.v[0],
1352 player.phys.rb.v[1],
1353 player.phys.rb.v[2] );
1354
1355 if( !world.spawn_count )
1356 return 0;
1357
1358 rp = &world.spawns[0];
1359 }
1360
1361 player.is_dead = 0;
1362
1363 m3x3f the_long_way;
1364 q_m3x3( rp->q, the_long_way );
1365
1366 v3f delta = {1.0f,0.0f,0.0f};
1367 m3x3_mulv( the_long_way, delta, delta );
1368
1369 if( !freecam )
1370 {
1371 player.angles[0] = atan2f( delta[0], -delta[2] );
1372 player.angles[1] = -asinf( delta[1] );
1373 }
1374
1375 v4_copy( rp->q, phys->rb.q );
1376 v3_copy( rp->co, phys->rb.co );
1377 v3_zero( phys->rb.v );
1378
1379 phys->vswitch = 1.0f;
1380 phys->slip_last = 0.0f;
1381 phys->in_air = 1;
1382 phys->on_board = 0;
1383 m3x3_identity( phys->vr );
1384
1385 player.mdl.shoes[0] = 1;
1386 player.mdl.shoes[1] = 1;
1387
1388 rb_update_transform( &phys->rb );
1389 player_save_frame();
1390 return 1;
1391 }
1392
1393 VG_STATIC void reset_player_poll( int argc, char const *argv[] )
1394 {
1395 if( argc == 1 )
1396 {
1397 for( int i=0; i<world.spawn_count; i++ )
1398 {
1399 struct respawn_point *r = &world.spawns[i];
1400
1401 console_suggest_score_text( r->name, argv[argc-1], 0 );
1402 }
1403 }
1404 }
1405
1406 #endif /* PLAYER_PHYSICS_H */