rigidbody math corrections & ragdoll tweaks for stability
[carveJwlIkooP6JGAAIwe30JlM.git] / rigidbody.h
1 /*
2 * Copyright (C) 2021-2023 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 */
4
5 /*
6 * Resources: Box2D - Erin Catto
7 * qu3e - Randy Gaul
8 */
9
10 #include "vg/vg_console.h"
11 #include "bvh.h"
12 #include "scene.h"
13
14 #include <math.h>
15
16 static bh_system bh_system_rigidbodies;
17
18 #ifndef RIGIDBODY_H
19 #define RIGIDBODY_H
20
21 /*
22 * -----------------------------------------------------------------------------
23 * (K)onstants
24 * -----------------------------------------------------------------------------
25 */
26
27 static const float
28 k_rb_rate = (1.0/VG_TIMESTEP_FIXED),
29 k_rb_delta = (1.0/k_rb_rate),
30 k_friction = 0.4f,
31 k_damp_linear = 0.1f, /* scale velocity 1/(1+x) */
32 k_damp_angular = 0.1f, /* scale angular 1/(1+x) */
33 k_penetration_slop = 0.01f,
34 k_inertia_scale = 4.0f,
35 k_phys_baumgarte = 0.2f,
36 k_gravity = 9.6f;
37
38 static float
39 k_limit_bias = 0.02f,
40 k_joint_correction = 0.01f,
41 k_joint_impulse = 1.0f,
42 k_joint_bias = 0.08f; /* positional joints */
43
44 static void rb_register_cvar(void){
45 VG_VAR_F32( k_limit_bias, flags=VG_VAR_CHEAT );
46 VG_VAR_F32( k_joint_bias, flags=VG_VAR_CHEAT );
47 VG_VAR_F32( k_joint_correction, flags=VG_VAR_CHEAT );
48 VG_VAR_F32( k_joint_impulse, flags=VG_VAR_CHEAT );
49 }
50
51 /*
52 * -----------------------------------------------------------------------------
53 * structure definitions
54 * -----------------------------------------------------------------------------
55 */
56
57 typedef struct rigidbody rigidbody;
58 typedef struct rb_object rb_object;
59 typedef struct contact rb_ct;
60 typedef struct rb_sphere rb_sphere;
61 typedef struct rb_capsule rb_capsule;
62 typedef struct rb_scene rb_scene;
63
64 struct rb_sphere{
65 float radius;
66 };
67
68 struct rb_capsule{
69 float height, radius;
70 };
71
72 struct rb_scene{
73 bh_tree *bh_scene;
74 };
75
76 struct rigidbody{
77 v3f co, v, w;
78 v4f q;
79
80 boxf bbx, bbx_world;
81 float inv_mass;
82
83 /* inertia model and inverse world tensor */
84 m3x3f iI, iIw;
85 m4x3f to_world, to_local;
86 };
87
88 /* simple objects */
89 struct rb_object{
90 rigidbody rb;
91 enum rb_shape{
92 k_rb_shape_box = 0,
93 k_rb_shape_sphere = 1,
94 k_rb_shape_capsule = 2,
95 k_rb_shape_scene = 3
96 }
97 type;
98
99 union{
100 struct rb_sphere sphere;
101 struct rb_capsule capsule;
102 struct rb_scene scene;
103 }
104 inf;
105 };
106
107 static struct contact{
108 rigidbody *rba, *rbb;
109 v3f co, n;
110 v3f t[2];
111 float p, bias, norm_impulse, tangent_impulse[2],
112 normal_mass, tangent_mass[2];
113
114 u32 element_id;
115
116 enum contact_type type;
117 }
118 rb_contact_buffer[256];
119 static int rb_contact_count = 0;
120
121 typedef struct rb_constr_pos rb_constr_pos;
122 typedef struct rb_constr_swingtwist rb_constr_swingtwist;
123
124 struct rb_constr_pos{
125 rigidbody *rba, *rbb;
126 v3f lca, lcb;
127 };
128
129 struct rb_constr_swingtwist{
130 rigidbody *rba, *rbb;
131
132 v4f conevx, conevy; /* relative to rba */
133 v3f view_offset, /* relative to rba */
134 coneva, conevxb;/* relative to rbb */
135
136 int tangent_violation, axis_violation;
137 v3f axis, tangent_axis, tangent_target, axis_target;
138
139 float conet;
140 float tangent_mass, axis_mass;
141
142 f32 conv_tangent, conv_axis;
143 };
144
145 /*
146 * -----------------------------------------------------------------------------
147 * Debugging
148 * -----------------------------------------------------------------------------
149 */
150
151 static void rb_debug_contact( rb_ct *ct ){
152 v3f p1;
153 v3_muladds( ct->co, ct->n, 0.05f, p1 );
154
155 if( ct->type == k_contact_type_default ){
156 vg_line_point( ct->co, 0.0125f, 0xff0000ff );
157 vg_line( ct->co, p1, 0xffffffff );
158 }
159 else if( ct->type == k_contact_type_edge ){
160 vg_line_point( ct->co, 0.0125f, 0xff00ffc0 );
161 vg_line( ct->co, p1, 0xffffffff );
162 }
163 }
164
165
166 static void rb_object_debug( rb_object *obj, u32 colour ){
167 if( obj->type == k_rb_shape_box ){
168 v3f *box = obj->rb.bbx;
169 vg_line_boxf_transformed( obj->rb.to_world, obj->rb.bbx, colour );
170 }
171 else if( obj->type == k_rb_shape_sphere ){
172 vg_line_sphere( obj->rb.to_world, obj->inf.sphere.radius, colour );
173 }
174 else if( obj->type == k_rb_shape_capsule ){
175 m4x3f m0, m1;
176 float h = obj->inf.capsule.height,
177 r = obj->inf.capsule.radius;
178
179 vg_line_capsule( obj->rb.to_world, r, h, colour );
180 }
181 else if( obj->type == k_rb_shape_scene ){
182 vg_line_boxf( obj->rb.bbx, colour );
183 }
184 }
185
186 /*
187 * -----------------------------------------------------------------------------
188 * Integration
189 * -----------------------------------------------------------------------------
190 */
191
192 /*
193 * Update world space bounding box based on local one
194 */
195 static void rb_update_bounds( rigidbody *rb ){
196 box_init_inf( rb->bbx_world );
197 m4x3_expand_aabb_aabb( rb->to_world, rb->bbx_world, rb->bbx );
198 }
199
200 /*
201 * Commit transform to rigidbody. Updates matrices
202 */
203 static void rb_update_transform( rigidbody *rb )
204 {
205 q_normalize( rb->q );
206 q_m3x3( rb->q, rb->to_world );
207 v3_copy( rb->co, rb->to_world[3] );
208
209 m4x3_invert_affine( rb->to_world, rb->to_local );
210
211 /* I = R I_0 R^T */
212 m3x3_mul( rb->to_world, rb->iI, rb->iIw );
213 m3x3_mul( rb->iIw, rb->to_local, rb->iIw );
214
215 rb_update_bounds( rb );
216 }
217
218 /*
219 * Extrapolate rigidbody into a transform based on vg accumulator.
220 * Useful for rendering
221 */
222 static void rb_extrapolate( rigidbody *rb, v3f co, v4f q )
223 {
224 float substep = vg.time_fixed_extrapolate;
225 v3_muladds( rb->co, rb->v, k_rb_delta*substep, co );
226
227 if( v3_length2( rb->w ) > 0.0f ){
228 v4f rotation;
229 v3f axis;
230 v3_copy( rb->w, axis );
231
232 float mag = v3_length( axis );
233 v3_divs( axis, mag, axis );
234 q_axis_angle( rotation, axis, mag*k_rb_delta*substep );
235 q_mul( rotation, rb->q, q );
236 q_normalize( q );
237 }
238 else{
239 v4_copy( rb->q, q );
240 }
241 }
242
243 /*
244 * Initialize rigidbody and calculate masses, inertia
245 */
246 static void rb_init_object( rb_object *obj, f32 inertia_scale ){
247 float volume = 1.0f;
248 int inert = 0;
249
250 if( obj->type == k_rb_shape_box ){
251 v3f dims;
252 v3_sub( obj->rb.bbx[1], obj->rb.bbx[0], dims );
253 volume = dims[0]*dims[1]*dims[2];
254 }
255 else if( obj->type == k_rb_shape_sphere ){
256 volume = vg_sphere_volume( obj->inf.sphere.radius );
257 v3_fill( obj->rb.bbx[0], -obj->inf.sphere.radius );
258 v3_fill( obj->rb.bbx[1], obj->inf.sphere.radius );
259 }
260 else if( obj->type == k_rb_shape_capsule ){
261 float r = obj->inf.capsule.radius,
262 h = obj->inf.capsule.height;
263 volume = vg_sphere_volume( r ) + VG_PIf * r*r * (h - r*2.0f);
264
265 v3_fill( obj->rb.bbx[0], -r );
266 v3_fill( obj->rb.bbx[1], r );
267 obj->rb.bbx[0][1] = -h;
268 obj->rb.bbx[1][1] = h;
269 }
270 else if( obj->type == k_rb_shape_scene ){
271 inert = 1;
272 box_copy( obj->inf.scene.bh_scene->nodes[0].bbx, obj->rb.bbx );
273 }
274
275 if( inert ){
276 obj->rb.inv_mass = 0.0f;
277 m3x3_zero( obj->rb.iI );
278 }
279 else{
280 f32 mass = 8.0f*volume;
281 obj->rb.inv_mass = 1.0f/mass;
282
283 v3f extent, com;
284 v3_sub( obj->rb.bbx[1], obj->rb.bbx[0], extent );
285 v3_muladds( obj->rb.bbx[0], extent, 0.5f, com );
286
287 /* local intertia tensor */
288 f32 ex2 = extent[0]*extent[0],
289 ey2 = extent[1]*extent[1],
290 ez2 = extent[2]*extent[2];
291
292 /* compute inertia tensor */
293 v3f I;
294
295 if( obj->type == k_rb_shape_box ){
296 I[0] = inertia_scale * (ey2+ez2) * mass * (1.0f/12.0f);
297 I[1] = inertia_scale * (ex2+ez2) * mass * (1.0f/12.0f);
298 I[2] = inertia_scale * (ex2+ey2) * mass * (1.0f/12.0f);
299 }
300 else if( obj->type == k_rb_shape_sphere ){
301 f32 r = obj->inf.sphere.radius;
302 v3_fill( I, inertia_scale * r*r * mass * (2.0f/5.0f) );
303 }
304 else if( obj->type == k_rb_shape_capsule ){
305 f32 r = obj->inf.capsule.radius;
306 I[1] = inertia_scale * r*r * mass * (2.0f/5.0f);
307 I[0] = inertia_scale * (ey2+ez2) * mass * (1.0f/12.0f);
308 I[2] = inertia_scale * (ey2+ex2) * mass * (1.0f/12.0f);
309 }
310 else {
311 vg_fatal_error( "" );
312 }
313
314 m3x3f i;
315 m3x3_identity( i );
316 m3x3_setdiagonalv3( i, I );
317
318 /* compute translation */
319 m3x3f i_t, i_t_outer, i_t_scale;
320 m3x3_diagonal( i_t, v3_dot(com,com) );
321 m3x3_outer_product( i_t_outer, com, com );
322 m3x3_sub( i_t, i_t_outer, i_t );
323 m3x3_diagonal( i_t_scale, mass );
324 m3x3_mul( i_t_scale, i_t, i_t );
325
326 /* TODO: compute rotation */
327
328 /* add Ic and Ict */
329 m3x3_add( i, i_t, i );
330
331 /* store as inverted */
332 m3x3_inv( i, obj->rb.iI );
333 }
334
335 rb_update_transform( &obj->rb );
336 }
337
338 static void rb_iter( rigidbody *rb ){
339 if( !vg_validf( rb->v[0] ) ||
340 !vg_validf( rb->v[1] ) ||
341 !vg_validf( rb->v[2] ) )
342 {
343 vg_fatal_error( "NaN velocity" );
344 }
345
346 v3f gravity = { 0.0f, -9.8f, 0.0f };
347 v3_muladds( rb->v, gravity, k_rb_delta, rb->v );
348
349 /* intergrate velocity */
350 v3_muladds( rb->co, rb->v, k_rb_delta, rb->co );
351 v3_lerp( rb->w, (v3f){0.0f,0.0f,0.0f}, 0.0025f, rb->w );
352
353 /* inegrate inertia */
354 if( v3_length2( rb->w ) > 0.0f )
355 {
356 v4f rotation;
357 v3f axis;
358 v3_copy( rb->w, axis );
359
360 float mag = v3_length( axis );
361 v3_divs( axis, mag, axis );
362 q_axis_angle( rotation, axis, mag*k_rb_delta );
363 q_mul( rotation, rb->q, rb->q );
364 }
365
366 #if 0
367 /* damping */
368 v3_muls( rb->v, 1.0f/(1.0f+k_rb_delta*k_damp_linear), rb->v );
369 v3_muls( rb->w, 1.0f/(1.0f+k_rb_delta*k_damp_angular), rb->w );
370 #endif
371 }
372
373
374 /*
375 * -----------------------------------------------------------------------------
376 * Boolean shape overlap functions
377 * -----------------------------------------------------------------------------
378 */
379
380 /*
381 * Project AABB, and triangle interval onto axis to check if they overlap
382 */
383 static int rb_box_triangle_interval( v3f extent, v3f axis, v3f tri[3] ){
384 float
385
386 r = extent[0] * fabsf(axis[0]) +
387 extent[1] * fabsf(axis[1]) +
388 extent[2] * fabsf(axis[2]),
389
390 p0 = v3_dot( axis, tri[0] ),
391 p1 = v3_dot( axis, tri[1] ),
392 p2 = v3_dot( axis, tri[2] ),
393
394 e = vg_maxf(-vg_maxf(p0,vg_maxf(p1,p2)), vg_minf(p0,vg_minf(p1,p2)));
395
396 if( e > r ) return 0;
397 else return 1;
398 }
399
400 /*
401 * Seperating axis test box vs triangle
402 */
403 static int rb_box_triangle_sat( v3f extent, v3f center,
404 m4x3f to_local, v3f tri_src[3] ){
405 v3f tri[3];
406
407 for( int i=0; i<3; i++ ){
408 m4x3_mulv( to_local, tri_src[i], tri[i] );
409 v3_sub( tri[i], center, tri[i] );
410 }
411
412 v3f f0,f1,f2,n;
413 v3_sub( tri[1], tri[0], f0 );
414 v3_sub( tri[2], tri[1], f1 );
415 v3_sub( tri[0], tri[2], f2 );
416
417
418 v3f axis[9];
419 v3_cross( (v3f){1.0f,0.0f,0.0f}, f0, axis[0] );
420 v3_cross( (v3f){1.0f,0.0f,0.0f}, f1, axis[1] );
421 v3_cross( (v3f){1.0f,0.0f,0.0f}, f2, axis[2] );
422 v3_cross( (v3f){0.0f,1.0f,0.0f}, f0, axis[3] );
423 v3_cross( (v3f){0.0f,1.0f,0.0f}, f1, axis[4] );
424 v3_cross( (v3f){0.0f,1.0f,0.0f}, f2, axis[5] );
425 v3_cross( (v3f){0.0f,0.0f,1.0f}, f0, axis[6] );
426 v3_cross( (v3f){0.0f,0.0f,1.0f}, f1, axis[7] );
427 v3_cross( (v3f){0.0f,0.0f,1.0f}, f2, axis[8] );
428
429 for( int i=0; i<9; i++ )
430 if(!rb_box_triangle_interval( extent, axis[i], tri )) return 0;
431
432 /* u0, u1, u2 */
433 if(!rb_box_triangle_interval( extent, (v3f){1.0f,0.0f,0.0f}, tri )) return 0;
434 if(!rb_box_triangle_interval( extent, (v3f){0.0f,1.0f,0.0f}, tri )) return 0;
435 if(!rb_box_triangle_interval( extent, (v3f){0.0f,0.0f,1.0f}, tri )) return 0;
436
437 /* normal */
438 v3_cross( f0, f1, n );
439 if(!rb_box_triangle_interval( extent, n, tri )) return 0;
440
441 return 1;
442 }
443
444 /*
445 * -----------------------------------------------------------------------------
446 * Manifold
447 * -----------------------------------------------------------------------------
448 */
449
450 static int rb_manifold_apply_filtered( rb_ct *man, int len ){
451 int k = 0;
452
453 for( int i=0; i<len; i++ ){
454 rb_ct *ct = &man[i];
455
456 if( ct->type == k_contact_type_disabled )
457 continue;
458
459 man[k ++] = man[i];
460 }
461
462 return k;
463 }
464
465 /*
466 * Merge two contacts if they are within radius(r) of eachother
467 */
468 static void rb_manifold_contact_weld( rb_ct *ci, rb_ct *cj, float r ){
469 if( v3_dist2( ci->co, cj->co ) < r*r ){
470 cj->type = k_contact_type_disabled;
471 ci->p = (ci->p + cj->p) * 0.5f;
472
473 v3_add( ci->co, cj->co, ci->co );
474 v3_muls( ci->co, 0.5f, ci->co );
475
476 v3f delta;
477 v3_sub( ci->rba->co, ci->co, delta );
478
479 float c0 = v3_dot( ci->n, delta ),
480 c1 = v3_dot( cj->n, delta );
481
482 if( c0 < 0.0f || c1 < 0.0f ){
483 /* error */
484 ci->type = k_contact_type_disabled;
485 }
486 else{
487 v3f n;
488 v3_muls( ci->n, c0, n );
489 v3_muladds( n, cj->n, c1, n );
490 v3_normalize( n );
491 v3_copy( n, ci->n );
492 }
493 }
494 }
495
496 /*
497 *
498 */
499 static void rb_manifold_filter_joint_edges( rb_ct *man, int len, float r ){
500 for( int i=0; i<len-1; i++ ){
501 rb_ct *ci = &man[i];
502 if( ci->type != k_contact_type_edge )
503 continue;
504
505 for( int j=i+1; j<len; j++ ){
506 rb_ct *cj = &man[j];
507 if( cj->type != k_contact_type_edge )
508 continue;
509
510 rb_manifold_contact_weld( ci, cj, r );
511 }
512 }
513 }
514
515 /*
516 * Resolve overlapping pairs
517 */
518 static void rb_manifold_filter_pairs( rb_ct *man, int len, float r ){
519 for( int i=0; i<len-1; i++ ){
520 rb_ct *ci = &man[i];
521 int similar = 0;
522
523 if( ci->type == k_contact_type_disabled ) continue;
524
525 for( int j=i+1; j<len; j++ ){
526 rb_ct *cj = &man[j];
527
528 if( cj->type == k_contact_type_disabled ) continue;
529
530 if( v3_dist2( ci->co, cj->co ) < r*r ){
531 cj->type = k_contact_type_disabled;
532 v3_add( cj->n, ci->n, ci->n );
533 ci->p += cj->p;
534 similar ++;
535 }
536 }
537
538 if( similar ){
539 float n = 1.0f/((float)similar+1.0f);
540 v3_muls( ci->n, n, ci->n );
541 ci->p *= n;
542
543 if( v3_length2(ci->n) < 0.1f*0.1f )
544 ci->type = k_contact_type_disabled;
545 else
546 v3_normalize( ci->n );
547 }
548 }
549 }
550
551 /*
552 * Remove contacts that are facing away from A
553 */
554 static void rb_manifold_filter_backface( rb_ct *man, int len ){
555 for( int i=0; i<len; i++ ){
556 rb_ct *ct = &man[i];
557 if( ct->type == k_contact_type_disabled )
558 continue;
559
560 v3f delta;
561 v3_sub( ct->co, ct->rba->co, delta );
562
563 if( v3_dot( delta, ct->n ) > -0.001f )
564 ct->type = k_contact_type_disabled;
565 }
566 }
567
568 /*
569 * Filter out duplicate coplanar results. Good for spheres.
570 */
571 static void rb_manifold_filter_coplanar( rb_ct *man, int len, float w ){
572 for( int i=0; i<len; i++ ){
573 rb_ct *ci = &man[i];
574 if( ci->type == k_contact_type_disabled ||
575 ci->type == k_contact_type_edge )
576 continue;
577
578 float d1 = v3_dot( ci->co, ci->n );
579
580 for( int j=0; j<len; j++ ){
581 if( j == i )
582 continue;
583
584 rb_ct *cj = &man[j];
585 if( cj->type == k_contact_type_disabled )
586 continue;
587
588 float d2 = v3_dot( cj->co, ci->n ),
589 d = d2-d1;
590
591 if( fabsf( d ) <= w ){
592 cj->type = k_contact_type_disabled;
593 }
594 }
595 }
596 }
597
598 /*
599 * -----------------------------------------------------------------------------
600 * Collision matrix
601 * -----------------------------------------------------------------------------
602 */
603
604 /*
605 * Contact generators
606 *
607 * These do not automatically allocate contacts, an appropriately sized
608 * buffer must be supplied. The function returns the size of the manifold
609 * which was generated.
610 *
611 * The values set on the contacts are: n, co, p, rba, rbb
612 */
613
614 /*
615 * By collecting the minimum(time) and maximum(time) pairs of points, we
616 * build a reduced and stable exact manifold.
617 *
618 * tx: time at point
619 * rx: minimum distance of these points
620 * dx: the delta between the two points
621 *
622 * pairs will only ammend these if they are creating a collision
623 */
624 typedef struct capsule_manifold capsule_manifold;
625 struct capsule_manifold{
626 float t0, t1;
627 float r0, r1;
628 v3f d0, d1;
629 };
630
631 /*
632 * Expand a line manifold with a new pair. t value is the time along segment
633 * on the oriented object which created this pair.
634 */
635 static void rb_capsule_manifold( v3f pa, v3f pb, float t, float r,
636 capsule_manifold *manifold ){
637 v3f delta;
638 v3_sub( pa, pb, delta );
639
640 if( v3_length2(delta) < r*r ){
641 if( t < manifold->t0 ){
642 v3_copy( delta, manifold->d0 );
643 manifold->t0 = t;
644 manifold->r0 = r;
645 }
646
647 if( t > manifold->t1 ){
648 v3_copy( delta, manifold->d1 );
649 manifold->t1 = t;
650 manifold->r1 = r;
651 }
652 }
653 }
654
655 static void rb_capsule_manifold_init( capsule_manifold *manifold ){
656 manifold->t0 = INFINITY;
657 manifold->t1 = -INFINITY;
658 }
659
660 static int rb_capsule__manifold_done( m4x3f mtx, rb_capsule *c,
661 capsule_manifold *manifold,
662 rb_ct *buf ){
663 v3f p0, p1;
664 v3_muladds( mtx[3], mtx[1], -c->height*0.5f+c->radius, p0 );
665 v3_muladds( mtx[3], mtx[1], c->height*0.5f-c->radius, p1 );
666
667 int count = 0;
668 if( manifold->t0 <= 1.0f ){
669 rb_ct *ct = buf;
670
671 v3f pa;
672 v3_muls( p0, 1.0f-manifold->t0, pa );
673 v3_muladds( pa, p1, manifold->t0, pa );
674
675 float d = v3_length( manifold->d0 );
676 v3_muls( manifold->d0, 1.0f/d, ct->n );
677 v3_muladds( pa, ct->n, -c->radius, ct->co );
678
679 ct->p = manifold->r0 - d;
680 ct->type = k_contact_type_default;
681 count ++;
682 }
683
684 if( (manifold->t1 >= 0.0f) && (manifold->t0 != manifold->t1) ){
685 rb_ct *ct = buf+count;
686
687 v3f pa;
688 v3_muls( p0, 1.0f-manifold->t1, pa );
689 v3_muladds( pa, p1, manifold->t1, pa );
690
691 float d = v3_length( manifold->d1 );
692 v3_muls( manifold->d1, 1.0f/d, ct->n );
693 v3_muladds( pa, ct->n, -c->radius, ct->co );
694
695 ct->p = manifold->r1 - d;
696 ct->type = k_contact_type_default;
697
698 count ++;
699 }
700
701 /*
702 * Debugging
703 */
704
705 if( count == 2 )
706 vg_line( buf[0].co, buf[1].co, 0xff0000ff );
707
708 return count;
709 }
710
711 static int rb_capsule_sphere( rb_object *obja, rb_object *objb, rb_ct *buf ){
712 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
713 float h = obja->inf.capsule.height,
714 ra = obja->inf.capsule.radius,
715 rb = objb->inf.sphere.radius;
716
717 v3f p0, p1;
718 v3_muladds( rba->co, rba->to_world[1], -h*0.5f+ra, p0 );
719 v3_muladds( rba->co, rba->to_world[1], h*0.5f-ra, p1 );
720
721 v3f c, delta;
722 closest_point_segment( p0, p1, rbb->co, c );
723 v3_sub( c, rbb->co, delta );
724
725 float d2 = v3_length2(delta),
726 r = ra + rb;
727
728 if( d2 < r*r ){
729 float d = sqrtf(d2);
730
731 rb_ct *ct = buf;
732 v3_muls( delta, 1.0f/d, ct->n );
733 ct->p = r-d;
734
735 v3f p0, p1;
736 v3_muladds( c, ct->n, -ra, p0 );
737 v3_muladds( rbb->co, ct->n, rb, p1 );
738 v3_add( p0, p1, ct->co );
739 v3_muls( ct->co, 0.5f, ct->co );
740
741 ct->rba = rba;
742 ct->rbb = rbb;
743 ct->type = k_contact_type_default;
744
745 return 1;
746 }
747
748 return 0;
749 }
750
751 static int rb_capsule__capsule( m4x3f mtxA, rb_capsule *ca,
752 m4x3f mtxB, rb_capsule *cb, rb_ct *buf ){
753 float ha = ca->height,
754 hb = cb->height,
755 ra = ca->radius,
756 rb = cb->radius,
757 r = ra+rb;
758
759 v3f p0, p1, p2, p3;
760 v3_muladds( mtxA[3], mtxA[1], -ha*0.5f+ra, p0 );
761 v3_muladds( mtxA[3], mtxA[1], ha*0.5f-ra, p1 );
762 v3_muladds( mtxB[3], mtxB[1], -hb*0.5f+rb, p2 );
763 v3_muladds( mtxB[3], mtxB[1], hb*0.5f-rb, p3 );
764
765 capsule_manifold manifold;
766 rb_capsule_manifold_init( &manifold );
767
768 v3f pa, pb;
769 float ta, tb;
770 closest_segment_segment( p0, p1, p2, p3, &ta, &tb, pa, pb );
771 rb_capsule_manifold( pa, pb, ta, r, &manifold );
772
773 ta = closest_point_segment( p0, p1, p2, pa );
774 tb = closest_point_segment( p0, p1, p3, pb );
775 rb_capsule_manifold( pa, p2, ta, r, &manifold );
776 rb_capsule_manifold( pb, p3, tb, r, &manifold );
777
778 closest_point_segment( p2, p3, p0, pa );
779 closest_point_segment( p2, p3, p1, pb );
780 rb_capsule_manifold( p0, pa, 0.0f, r, &manifold );
781 rb_capsule_manifold( p1, pb, 1.0f, r, &manifold );
782
783 return rb_capsule__manifold_done( mtxA, ca, &manifold, buf );
784 }
785
786 static int rb_sphere_box( rb_object *obja, rb_object *objb, rb_ct *buf ){
787 v3f co, delta;
788 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
789
790 closest_point_obb( rba->co, rbb->bbx, rbb->to_world, rbb->to_local, co );
791 v3_sub( rba->co, co, delta );
792
793 float d2 = v3_length2(delta),
794 r = obja->inf.sphere.radius;
795
796 if( d2 <= r*r ){
797 float d;
798
799 rb_ct *ct = buf;
800 if( d2 <= 0.0001f ){
801 v3_sub( rba->co, rbb->co, delta );
802
803 /*
804 * some extra testing is required to find the best axis to push the
805 * object back outside the box. Since there isnt a clear seperating
806 * vector already, especially on really high aspect boxes.
807 */
808 float lx = v3_dot( rbb->to_world[0], delta ),
809 ly = v3_dot( rbb->to_world[1], delta ),
810 lz = v3_dot( rbb->to_world[2], delta ),
811 px = rbb->bbx[1][0] - fabsf(lx),
812 py = rbb->bbx[1][1] - fabsf(ly),
813 pz = rbb->bbx[1][2] - fabsf(lz);
814
815 if( px < py && px < pz )
816 v3_muls( rbb->to_world[0], vg_signf(lx), ct->n );
817 else if( py < pz )
818 v3_muls( rbb->to_world[1], vg_signf(ly), ct->n );
819 else
820 v3_muls( rbb->to_world[2], vg_signf(lz), ct->n );
821
822 v3_muladds( rba->co, ct->n, -r, ct->co );
823 ct->p = r;
824 }
825 else{
826 d = sqrtf(d2);
827 v3_muls( delta, 1.0f/d, ct->n );
828 ct->p = r-d;
829 v3_copy( co, ct->co );
830 }
831
832 ct->rba = rba;
833 ct->rbb = rbb;
834 ct->type = k_contact_type_default;
835 return 1;
836 }
837
838 return 0;
839 }
840
841 static int rb_sphere_sphere( rb_object *obja, rb_object *objb, rb_ct *buf ){
842 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
843 v3f delta;
844 v3_sub( rba->co, rbb->co, delta );
845
846 float d2 = v3_length2(delta),
847 r = obja->inf.sphere.radius + objb->inf.sphere.radius;
848
849 if( d2 < r*r ){
850 float d = sqrtf(d2);
851
852 rb_ct *ct = buf;
853 v3_muls( delta, 1.0f/d, ct->n );
854
855 v3f p0, p1;
856 v3_muladds( rba->co, ct->n,-obja->inf.sphere.radius, p0 );
857 v3_muladds( rbb->co, ct->n, objb->inf.sphere.radius, p1 );
858 v3_add( p0, p1, ct->co );
859 v3_muls( ct->co, 0.5f, ct->co );
860 ct->type = k_contact_type_default;
861 ct->p = r-d;
862 ct->rba = rba;
863 ct->rbb = rbb;
864 return 1;
865 }
866
867 return 0;
868 }
869
870 static int rb_sphere__triangle( m4x3f mtxA, rb_sphere *b,
871 v3f tri[3], rb_ct *buf ){
872 v3f delta, co;
873 enum contact_type type = closest_on_triangle_1( mtxA[3], tri, co );
874
875 v3_sub( mtxA[3], co, delta );
876
877 float d2 = v3_length2( delta ),
878 r = b->radius;
879
880 if( d2 <= r*r ){
881 rb_ct *ct = buf;
882
883 v3f ab, ac, tn;
884 v3_sub( tri[2], tri[0], ab );
885 v3_sub( tri[1], tri[0], ac );
886 v3_cross( ac, ab, tn );
887 v3_copy( tn, ct->n );
888
889 if( v3_length2( ct->n ) <= 0.00001f ){
890 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
891 vg_error( "Zero area triangle!\n" );
892 #endif
893 return 0;
894 }
895
896 v3_normalize( ct->n );
897
898 float d = sqrtf(d2);
899
900 v3_copy( co, ct->co );
901 ct->type = type;
902 ct->p = r-d;
903 return 1;
904 }
905
906 return 0;
907 }
908
909 static int rb_sphere__scene( m4x3f mtxA, rb_sphere *b,
910 m4x3f mtxB, rb_scene *s, rb_ct *buf,
911 u16 ignore ){
912 scene_context *sc = s->bh_scene->user;
913
914 int count = 0;
915
916 float r = b->radius + 0.1f;
917 boxf box;
918 v3_sub( mtxA[3], (v3f){ r,r,r }, box[0] );
919 v3_add( mtxA[3], (v3f){ r,r,r }, box[1] );
920
921 bh_iter it;
922 i32 idx;
923 bh_iter_init_box( 0, &it, box );
924
925 while( bh_next( s->bh_scene, &it, &idx ) ){
926 u32 *ptri = &sc->arrindices[ idx*3 ];
927 v3f tri[3];
928
929 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
930
931 for( int j=0; j<3; j++ )
932 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
933
934 buf[ count ].element_id = ptri[0];
935
936 vg_line( tri[0],tri[1],0x70ff6000 );
937 vg_line( tri[1],tri[2],0x70ff6000 );
938 vg_line( tri[2],tri[0],0x70ff6000 );
939
940 int contact = rb_sphere__triangle( mtxA, b, tri, &buf[count] );
941 count += contact;
942
943 if( count == 16 ){
944 vg_warn( "Exceeding sphere_vs_scene capacity. Geometry too dense!\n" );
945 return count;
946 }
947 }
948
949 return count;
950 }
951
952 static int rb_box__scene( m4x3f mtxA, boxf bbx,
953 m4x3f mtxB, rb_scene *s, rb_ct *buf, u16 ignore ){
954 scene_context *sc = s->bh_scene->user;
955 v3f tri[3];
956
957 v3f extent, center;
958 v3_sub( bbx[1], bbx[0], extent );
959 v3_muls( extent, 0.5f, extent );
960 v3_add( bbx[0], extent, center );
961
962 float r = v3_length(extent);
963 boxf world_bbx;
964 v3_fill( world_bbx[0], -r );
965 v3_fill( world_bbx[1], r );
966 for( int i=0; i<2; i++ ){
967 v3_add( center, world_bbx[i], world_bbx[i] );
968 v3_add( mtxA[3], world_bbx[i], world_bbx[i] );
969 }
970
971 m4x3f to_local;
972 m4x3_invert_affine( mtxA, to_local );
973
974 bh_iter it;
975 bh_iter_init_box( 0, &it, world_bbx );
976 int idx;
977 int count = 0;
978
979 vg_line_boxf( world_bbx, VG__RED );
980
981 while( bh_next( s->bh_scene, &it, &idx ) ){
982 u32 *ptri = &sc->arrindices[ idx*3 ];
983 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
984
985 for( int j=0; j<3; j++ )
986 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
987
988 if( rb_box_triangle_sat( extent, center, to_local, tri ) ){
989 vg_line(tri[0],tri[1],0xff50ff00 );
990 vg_line(tri[1],tri[2],0xff50ff00 );
991 vg_line(tri[2],tri[0],0xff50ff00 );
992 }
993 else{
994 vg_line(tri[0],tri[1],0xff0000ff );
995 vg_line(tri[1],tri[2],0xff0000ff );
996 vg_line(tri[2],tri[0],0xff0000ff );
997 continue;
998 }
999
1000 v3f v0,v1,n;
1001 v3_sub( tri[1], tri[0], v0 );
1002 v3_sub( tri[2], tri[0], v1 );
1003 v3_cross( v0, v1, n );
1004
1005 if( v3_length2( n ) <= 0.00001f ){
1006 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
1007 vg_error( "Zero area triangle!\n" );
1008 #endif
1009 return 0;
1010 }
1011
1012 v3_normalize( n );
1013
1014 /* find best feature */
1015 float best = v3_dot( mtxA[0], n );
1016 int axis = 0;
1017
1018 for( int i=1; i<3; i++ ){
1019 float c = v3_dot( mtxA[i], n );
1020
1021 if( fabsf(c) > fabsf(best) ){
1022 best = c;
1023 axis = i;
1024 }
1025 }
1026
1027 v3f manifold[4];
1028
1029 if( axis == 0 ){
1030 float px = best > 0.0f? bbx[0][0]: bbx[1][0];
1031 manifold[0][0] = px;
1032 manifold[0][1] = bbx[0][1];
1033 manifold[0][2] = bbx[0][2];
1034 manifold[1][0] = px;
1035 manifold[1][1] = bbx[1][1];
1036 manifold[1][2] = bbx[0][2];
1037 manifold[2][0] = px;
1038 manifold[2][1] = bbx[1][1];
1039 manifold[2][2] = bbx[1][2];
1040 manifold[3][0] = px;
1041 manifold[3][1] = bbx[0][1];
1042 manifold[3][2] = bbx[1][2];
1043 }
1044 else if( axis == 1 ){
1045 float py = best > 0.0f? bbx[0][1]: bbx[1][1];
1046 manifold[0][0] = bbx[0][0];
1047 manifold[0][1] = py;
1048 manifold[0][2] = bbx[0][2];
1049 manifold[1][0] = bbx[1][0];
1050 manifold[1][1] = py;
1051 manifold[1][2] = bbx[0][2];
1052 manifold[2][0] = bbx[1][0];
1053 manifold[2][1] = py;
1054 manifold[2][2] = bbx[1][2];
1055 manifold[3][0] = bbx[0][0];
1056 manifold[3][1] = py;
1057 manifold[3][2] = bbx[1][2];
1058 }
1059 else{
1060 float pz = best > 0.0f? bbx[0][2]: bbx[1][2];
1061 manifold[0][0] = bbx[0][0];
1062 manifold[0][1] = bbx[0][1];
1063 manifold[0][2] = pz;
1064 manifold[1][0] = bbx[1][0];
1065 manifold[1][1] = bbx[0][1];
1066 manifold[1][2] = pz;
1067 manifold[2][0] = bbx[1][0];
1068 manifold[2][1] = bbx[1][1];
1069 manifold[2][2] = pz;
1070 manifold[3][0] = bbx[0][0];
1071 manifold[3][1] = bbx[1][1];
1072 manifold[3][2] = pz;
1073 }
1074
1075 for( int j=0; j<4; j++ )
1076 m4x3_mulv( mtxA, manifold[j], manifold[j] );
1077
1078 vg_line( manifold[0], manifold[1], 0xffffffff );
1079 vg_line( manifold[1], manifold[2], 0xffffffff );
1080 vg_line( manifold[2], manifold[3], 0xffffffff );
1081 vg_line( manifold[3], manifold[0], 0xffffffff );
1082
1083 for( int j=0; j<4; j++ ){
1084 rb_ct *ct = buf+count;
1085
1086 v3_copy( manifold[j], ct->co );
1087 v3_copy( n, ct->n );
1088
1089 float l0 = v3_dot( tri[0], n ),
1090 l1 = v3_dot( manifold[j], n );
1091
1092 ct->p = (l0-l1)*0.5f;
1093 if( ct->p < 0.0f )
1094 continue;
1095
1096 ct->type = k_contact_type_default;
1097 count ++;
1098
1099 if( count >= 12 )
1100 return count;
1101 }
1102 }
1103 return count;
1104 }
1105
1106 static int rb_capsule__triangle( m4x3f mtxA, rb_capsule *c,
1107 v3f tri[3], rb_ct *buf ){
1108 v3f pc, p0w, p1w;
1109 v3_muladds( mtxA[3], mtxA[1], -c->height*0.5f+c->radius, p0w );
1110 v3_muladds( mtxA[3], mtxA[1], c->height*0.5f-c->radius, p1w );
1111
1112 capsule_manifold manifold;
1113 rb_capsule_manifold_init( &manifold );
1114
1115 v3f v0, v1, n;
1116 v3_sub( tri[1], tri[0], v0 );
1117 v3_sub( tri[2], tri[0], v1 );
1118 v3_cross( v0, v1, n );
1119
1120 if( v3_length2( n ) <= 0.00001f ){
1121 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
1122 vg_error( "Zero area triangle!\n" );
1123 #endif
1124 return 0;
1125 }
1126
1127 v3_normalize( n );
1128
1129 #if 1
1130 /* deep penetration recovery. for when we clip through the triangles. so its
1131 * not very 'correct' */
1132 f32 dist;
1133 if( ray_tri( tri, p0w, mtxA[1], &dist, 1 ) ){
1134 f32 l = c->height - c->radius*2.0f;
1135 if( (dist >= 0.0f) && (dist < l) ){
1136 v3f co;
1137 v3_muladds( p0w, mtxA[1], dist, co );
1138 vg_line_point( co, 0.02f, 0xffffff00 );
1139
1140 v3f d0, d1;
1141 v3_sub( p0w, co, d0 );
1142 v3_sub( p1w, co, d1 );
1143
1144 f32 p = vg_minf( v3_dot( n, d0 ), v3_dot( n, d1 ) ) - c->radius;
1145
1146 rb_ct *ct = buf;
1147 ct->p = -p;
1148 ct->type = k_contact_type_default;
1149 v3_copy( n, ct->n );
1150 v3_muladds( co, n, p, ct->co );
1151
1152 return 1;
1153 }
1154 }
1155 #endif
1156
1157 v3f c0, c1;
1158 closest_on_triangle_1( p0w, tri, c0 );
1159 closest_on_triangle_1( p1w, tri, c1 );
1160
1161 v3f d0, d1, da;
1162 v3_sub( c0, p0w, d0 );
1163 v3_sub( c1, p1w, d1 );
1164 v3_sub( p1w, p0w, da );
1165
1166 v3_normalize(d0);
1167 v3_normalize(d1);
1168 v3_normalize(da);
1169
1170 /* the two balls at the ends */
1171 if( v3_dot( da, d0 ) <= 0.01f )
1172 rb_capsule_manifold( p0w, c0, 0.0f, c->radius, &manifold );
1173 if( v3_dot( da, d1 ) >= -0.01f )
1174 rb_capsule_manifold( p1w, c1, 1.0f, c->radius, &manifold );
1175
1176 /* the edges to edges */
1177 for( int i=0; i<3; i++ ){
1178 int i0 = i,
1179 i1 = (i+1)%3;
1180
1181 v3f ca, cb;
1182 float ta, tb;
1183 closest_segment_segment( p0w, p1w, tri[i0], tri[i1], &ta, &tb, ca, cb );
1184 rb_capsule_manifold( ca, cb, ta, c->radius, &manifold );
1185 }
1186
1187 int count = rb_capsule__manifold_done( mtxA, c, &manifold, buf );
1188 for( int i=0; i<count; i++ )
1189 v3_copy( n, buf[i].n );
1190
1191 return count;
1192 }
1193
1194 /* mtxB is defined only for tradition; it is not used currently */
1195 static int rb_capsule__scene( m4x3f mtxA, rb_capsule *c,
1196 m4x3f mtxB, rb_scene *s,
1197 rb_ct *buf, u16 ignore ){
1198 int count = 0;
1199
1200 boxf bbx;
1201 v3_sub( mtxA[3], (v3f){ c->height, c->height, c->height }, bbx[0] );
1202 v3_add( mtxA[3], (v3f){ c->height, c->height, c->height }, bbx[1] );
1203
1204 scene_context *sc = s->bh_scene->user;
1205
1206 bh_iter it;
1207 bh_iter_init_box( 0, &it, bbx );
1208 i32 idx;
1209 while( bh_next( s->bh_scene, &it, &idx ) ){
1210 u32 *ptri = &sc->arrindices[ idx*3 ];
1211 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
1212
1213 v3f tri[3];
1214 for( int j=0; j<3; j++ )
1215 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
1216
1217 buf[ count ].element_id = ptri[0];
1218
1219 int contact = rb_capsule__triangle( mtxA, c, tri, &buf[count] );
1220 count += contact;
1221
1222 if( count >= 16 ){
1223 vg_warn("Exceeding capsule_vs_scene capacity. Geometry too dense!\n");
1224 return count;
1225 }
1226 }
1227
1228 return count;
1229 }
1230
1231 static int rb_global_has_space( void ){
1232 if( rb_contact_count + 16 > vg_list_size(rb_contact_buffer) )
1233 return 0;
1234
1235 return 1;
1236 }
1237
1238 static rb_ct *rb_global_buffer( void ){
1239 return &rb_contact_buffer[ rb_contact_count ];
1240 }
1241
1242 /*
1243 * -----------------------------------------------------------------------------
1244 * Dynamics
1245 * -----------------------------------------------------------------------------
1246 */
1247
1248 static void rb_solver_reset(void){
1249 rb_contact_count = 0;
1250 }
1251
1252 static rb_ct *rb_global_ct(void){
1253 return rb_contact_buffer + rb_contact_count;
1254 }
1255
1256 static void rb_prepare_contact( rb_ct *ct, float timestep ){
1257 ct->bias = -k_phys_baumgarte * (timestep*3600.0f)
1258 * vg_minf( 0.0f, -ct->p+k_penetration_slop );
1259
1260 v3_tangent_basis( ct->n, ct->t[0], ct->t[1] );
1261 ct->norm_impulse = 0.0f;
1262 ct->tangent_impulse[0] = 0.0f;
1263 ct->tangent_impulse[1] = 0.0f;
1264 }
1265
1266 /* calculate total move. manifold should belong to ONE object only */
1267 static void rb_depenetrate( rb_ct *manifold, int len, v3f dt ){
1268 v3_zero( dt );
1269
1270 for( int j=0; j<7; j++ )
1271 {
1272 for( int i=0; i<len; i++ )
1273 {
1274 struct contact *ct = &manifold[i];
1275
1276 float resolved_amt = v3_dot( ct->n, dt ),
1277 remaining = (ct->p-k_penetration_slop) - resolved_amt,
1278 apply = vg_maxf( remaining, 0.0f ) * 0.4f;
1279
1280 v3_muladds( dt, ct->n, apply, dt );
1281 }
1282 }
1283 }
1284
1285 /*
1286 * Initializing things like tangent vectors
1287 */
1288 static void rb_presolve_contacts( rb_ct *buffer, int len ){
1289 for( int i=0; i<len; i++ ){
1290 rb_ct *ct = &buffer[i];
1291 rb_prepare_contact( ct, k_rb_delta );
1292
1293 v3f ra, rb, raCn, rbCn, raCt, rbCt;
1294 v3_sub( ct->co, ct->rba->co, ra );
1295 v3_sub( ct->co, ct->rbb->co, rb );
1296 v3_cross( ra, ct->n, raCn );
1297 v3_cross( rb, ct->n, rbCn );
1298
1299 /* orient inverse inertia tensors */
1300 v3f raCnI, rbCnI;
1301 m3x3_mulv( ct->rba->iIw, raCn, raCnI );
1302 m3x3_mulv( ct->rbb->iIw, rbCn, rbCnI );
1303
1304 ct->normal_mass = ct->rba->inv_mass + ct->rbb->inv_mass;
1305 ct->normal_mass += v3_dot( raCn, raCnI );
1306 ct->normal_mass += v3_dot( rbCn, rbCnI );
1307 ct->normal_mass = 1.0f/ct->normal_mass;
1308
1309 for( int j=0; j<2; j++ ){
1310 v3f raCtI, rbCtI;
1311 v3_cross( ct->t[j], ra, raCt );
1312 v3_cross( ct->t[j], rb, rbCt );
1313 m3x3_mulv( ct->rba->iIw, raCt, raCtI );
1314 m3x3_mulv( ct->rbb->iIw, rbCt, rbCtI );
1315
1316 ct->tangent_mass[j] = ct->rba->inv_mass + ct->rbb->inv_mass;
1317 ct->tangent_mass[j] += v3_dot( raCt, raCtI );
1318 ct->tangent_mass[j] += v3_dot( rbCt, rbCtI );
1319 ct->tangent_mass[j] = 1.0f/ct->tangent_mass[j];
1320 }
1321
1322 rb_debug_contact( ct );
1323 }
1324 }
1325
1326 /*
1327 * Creates relative contact velocity vector
1328 */
1329 static void rb_rcv( rigidbody *rba, rigidbody *rbb, v3f ra, v3f rb, v3f rv ){
1330 v3f rva, rvb;
1331 v3_cross( rba->w, ra, rva );
1332 v3_add( rba->v, rva, rva );
1333 v3_cross( rbb->w, rb, rvb );
1334 v3_add( rbb->v, rvb, rvb );
1335
1336 v3_sub( rva, rvb, rv );
1337 }
1338
1339 static void rb_contact_restitution( rb_ct *ct, float cr ){
1340 v3f rv, ra, rb;
1341 v3_sub( ct->co, ct->rba->co, ra );
1342 v3_sub( ct->co, ct->rbb->co, rb );
1343 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1344
1345 float v = v3_dot( rv, ct->n );
1346
1347 if( v < -1.0f ){
1348 ct->bias += -cr * v;
1349 }
1350 }
1351
1352 /*
1353 * Apply impulse to object
1354 */
1355 static void rb_linear_impulse( rigidbody *rb, v3f delta, v3f impulse ){
1356 /* linear */
1357 v3_muladds( rb->v, impulse, rb->inv_mass, rb->v );
1358
1359 /* Angular velocity */
1360 v3f wa;
1361 v3_cross( delta, impulse, wa );
1362
1363 m3x3_mulv( rb->iIw, wa, wa );
1364 v3_add( rb->w, wa, rb->w );
1365 }
1366
1367 /*
1368 * One iteration to solve the contact constraint
1369 */
1370 static void rb_solve_contacts( rb_ct *buf, int len ){
1371 for( int i=0; i<len; i++ ){
1372 struct contact *ct = &buf[i];
1373
1374 v3f rv, ra, rb;
1375 v3_sub( ct->co, ct->rba->co, ra );
1376 v3_sub( ct->co, ct->rbb->co, rb );
1377 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1378
1379 /* Friction */
1380 for( int j=0; j<2; j++ ){
1381 float f = k_friction * ct->norm_impulse,
1382 vt = v3_dot( rv, ct->t[j] ),
1383 lambda = ct->tangent_mass[j] * -vt;
1384
1385 float temp = ct->tangent_impulse[j];
1386 ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
1387 lambda = ct->tangent_impulse[j] - temp;
1388
1389 v3f impulse;
1390 v3_muls( ct->t[j], lambda, impulse );
1391 rb_linear_impulse( ct->rba, ra, impulse );
1392
1393 v3_muls( ct->t[j], -lambda, impulse );
1394 rb_linear_impulse( ct->rbb, rb, impulse );
1395 }
1396
1397 /* Normal */
1398 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1399 float vn = v3_dot( rv, ct->n ),
1400 lambda = ct->normal_mass * (-vn + ct->bias);
1401
1402 float temp = ct->norm_impulse;
1403 ct->norm_impulse = vg_maxf( temp + lambda, 0.0f );
1404 lambda = ct->norm_impulse - temp;
1405
1406 v3f impulse;
1407 v3_muls( ct->n, lambda, impulse );
1408 rb_linear_impulse( ct->rba, ra, impulse );
1409
1410 v3_muls( ct->n, -lambda, impulse );
1411 rb_linear_impulse( ct->rbb, rb, impulse );
1412 }
1413 }
1414
1415 /*
1416 * -----------------------------------------------------------------------------
1417 * Constraints
1418 * -----------------------------------------------------------------------------
1419 */
1420
1421 static void rb_debug_position_constraints( rb_constr_pos *buffer, int len ){
1422 for( int i=0; i<len; i++ ){
1423 rb_constr_pos *constr = &buffer[i];
1424 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1425
1426 v3f wca, wcb;
1427 m3x3_mulv( rba->to_world, constr->lca, wca );
1428 m3x3_mulv( rbb->to_world, constr->lcb, wcb );
1429
1430 v3f p0, p1;
1431 v3_add( wca, rba->co, p0 );
1432 v3_add( wcb, rbb->co, p1 );
1433 vg_line_point( p0, 0.0025f, 0xff000000 );
1434 vg_line_point( p1, 0.0025f, 0xffffffff );
1435 vg_line2( p0, p1, 0xff000000, 0xffffffff );
1436 }
1437 }
1438
1439 static void rb_presolve_swingtwist_constraints( rb_constr_swingtwist *buf,
1440 int len ){
1441 for( int i=0; i<len; i++ ){
1442 rb_constr_swingtwist *st = &buf[ i ];
1443
1444 v3f vx, vy, va, vxb, axis, center;
1445
1446 m3x3_mulv( st->rba->to_world, st->conevx, vx );
1447 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1448 m3x3_mulv( st->rba->to_world, st->conevy, vy );
1449 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1450 m4x3_mulv( st->rba->to_world, st->view_offset, center );
1451 v3_cross( vy, vx, axis );
1452
1453 /* Constraint violated ? */
1454 float fx = v3_dot( vx, va ), /* projection world */
1455 fy = v3_dot( vy, va ),
1456 fn = v3_dot( va, axis ),
1457
1458 rx = st->conevx[3], /* elipse radii */
1459 ry = st->conevy[3],
1460
1461 lx = fx/rx, /* projection local (fn==lz) */
1462 ly = fy/ry;
1463
1464 st->tangent_violation = ((lx*lx + ly*ly) > fn*fn) || (fn <= 0.0f);
1465 if( st->tangent_violation ){
1466 /* Calculate a good position and the axis to solve on */
1467 v2f closest, tangent,
1468 p = { fx/fabsf(fn), fy/fabsf(fn) };
1469
1470 closest_point_elipse( p, (v2f){rx,ry}, closest );
1471 tangent[0] = -closest[1] / (ry*ry);
1472 tangent[1] = closest[0] / (rx*rx);
1473 v2_normalize( tangent );
1474
1475 v3f v0, v1;
1476 v3_muladds( axis, vx, closest[0], v0 );
1477 v3_muladds( v0, vy, closest[1], v0 );
1478 v3_normalize( v0 );
1479
1480 v3_muls( vx, tangent[0], v1 );
1481 v3_muladds( v1, vy, tangent[1], v1 );
1482
1483 v3_copy( v0, st->tangent_target );
1484 v3_copy( v1, st->tangent_axis );
1485
1486 /* calculate mass */
1487 v3f aIw, bIw;
1488 m3x3_mulv( st->rba->iIw, st->tangent_axis, aIw );
1489 m3x3_mulv( st->rbb->iIw, st->tangent_axis, bIw );
1490 st->tangent_mass = 1.0f / (v3_dot( st->tangent_axis, aIw ) +
1491 v3_dot( st->tangent_axis, bIw ));
1492
1493 float angle = v3_dot( va, st->tangent_target );
1494 }
1495
1496 v3f refaxis;
1497 v3_cross( vy, va, refaxis ); /* our default rotation */
1498 v3_normalize( refaxis );
1499
1500 float angle = v3_dot( refaxis, vxb );
1501 st->axis_violation = fabsf(angle) < st->conet;
1502
1503 if( st->axis_violation ){
1504 v3f dir_test;
1505 v3_cross( refaxis, vxb, dir_test );
1506
1507 if( v3_dot(dir_test, va) < 0.0f )
1508 st->axis_violation = -st->axis_violation;
1509
1510 float newang = (float)st->axis_violation * acosf(st->conet-0.0001f);
1511
1512 v3f refaxis_up;
1513 v3_cross( va, refaxis, refaxis_up );
1514 v3_muls( refaxis_up, sinf(newang), st->axis_target );
1515 v3_muladds( st->axis_target, refaxis, -cosf(newang), st->axis_target );
1516
1517 /* calculate mass */
1518 v3_copy( va, st->axis );
1519 v3f aIw, bIw;
1520 m3x3_mulv( st->rba->iIw, st->axis, aIw );
1521 m3x3_mulv( st->rbb->iIw, st->axis, bIw );
1522 st->axis_mass = 1.0f / (v3_dot( st->axis, aIw ) +
1523 v3_dot( st->axis, bIw ));
1524 }
1525 }
1526 }
1527
1528 static void rb_debug_swingtwist_constraints( rb_constr_swingtwist *buf,
1529 int len ){
1530 float size = 0.12f;
1531
1532 for( int i=0; i<len; i++ ){
1533 rb_constr_swingtwist *st = &buf[ i ];
1534
1535 v3f vx, vxb, vy, va, axis, center;
1536
1537 m3x3_mulv( st->rba->to_world, st->conevx, vx );
1538 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1539 m3x3_mulv( st->rba->to_world, st->conevy, vy );
1540 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1541 m4x3_mulv( st->rba->to_world, st->view_offset, center );
1542 v3_cross( vy, vx, axis );
1543
1544 float rx = st->conevx[3], /* elipse radii */
1545 ry = st->conevy[3];
1546
1547 v3f p0, p1;
1548 v3_muladds( center, va, size, p1 );
1549 vg_line( center, p1, 0xffffffff );
1550 vg_line_point( p1, 0.00025f, 0xffffffff );
1551
1552 if( st->tangent_violation ){
1553 v3_muladds( center, st->tangent_target, size, p0 );
1554
1555 vg_line( center, p0, 0xff00ff00 );
1556 vg_line_point( p0, 0.00025f, 0xff00ff00 );
1557 vg_line( p1, p0, 0xff000000 );
1558 }
1559
1560 for( int x=0; x<32; x++ ){
1561 float t0 = ((float)x * (1.0f/32.0f)) * VG_TAUf,
1562 t1 = (((float)x+1.0f) * (1.0f/32.0f)) * VG_TAUf,
1563 c0 = cosf( t0 ),
1564 s0 = sinf( t0 ),
1565 c1 = cosf( t1 ),
1566 s1 = sinf( t1 );
1567
1568 v3f v0, v1;
1569 v3_muladds( axis, vx, c0*rx, v0 );
1570 v3_muladds( v0, vy, s0*ry, v0 );
1571 v3_muladds( axis, vx, c1*rx, v1 );
1572 v3_muladds( v1, vy, s1*ry, v1 );
1573
1574 v3_normalize( v0 );
1575 v3_normalize( v1 );
1576
1577 v3_muladds( center, v0, size, p0 );
1578 v3_muladds( center, v1, size, p1 );
1579
1580 u32 col0r = fabsf(c0) * 255.0f,
1581 col0g = fabsf(s0) * 255.0f,
1582 col1r = fabsf(c1) * 255.0f,
1583 col1g = fabsf(s1) * 255.0f,
1584 col = st->tangent_violation? 0xff0000ff: 0xff000000,
1585 col0 = col | (col0r<<16) | (col0g << 8),
1586 col1 = col | (col1r<<16) | (col1g << 8);
1587
1588 vg_line2( center, p0, VG__NONE, col0 );
1589 vg_line2( p0, p1, col0, col1 );
1590 }
1591
1592 /* Draw twist */
1593 v3_muladds( center, va, size, p0 );
1594 v3_muladds( p0, vxb, size, p1 );
1595
1596 vg_line( p0, p1, 0xff0000ff );
1597
1598 if( st->axis_violation ){
1599 v3_muladds( p0, st->axis_target, size*1.25f, p1 );
1600 vg_line( p0, p1, 0xffffff00 );
1601 vg_line_point( p1, 0.0025f, 0xffffff80 );
1602 }
1603
1604 v3f refaxis;
1605 v3_cross( vy, va, refaxis ); /* our default rotation */
1606 v3_normalize( refaxis );
1607 v3f refaxis_up;
1608 v3_cross( va, refaxis, refaxis_up );
1609 float newang = acosf(st->conet-0.0001f);
1610
1611 v3_muladds( p0, refaxis_up, sinf(newang)*size, p1 );
1612 v3_muladds( p1, refaxis, -cosf(newang)*size, p1 );
1613 vg_line( p0, p1, 0xff000000 );
1614
1615 v3_muladds( p0, refaxis_up, sinf(-newang)*size, p1 );
1616 v3_muladds( p1, refaxis, -cosf(-newang)*size, p1 );
1617 vg_line( p0, p1, 0xff404040 );
1618 }
1619 }
1620
1621 /*
1622 * Solve a list of positional constraints
1623 */
1624 static void rb_solve_position_constraints( rb_constr_pos *buf, int len ){
1625 for( int i=0; i<len; i++ ){
1626 rb_constr_pos *constr = &buf[i];
1627 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1628
1629 v3f wa, wb;
1630 m3x3_mulv( rba->to_world, constr->lca, wa );
1631 m3x3_mulv( rbb->to_world, constr->lcb, wb );
1632
1633 m3x3f ssra, ssrat, ssrb, ssrbt;
1634
1635 m3x3_skew_symetric( ssrat, wa );
1636 m3x3_skew_symetric( ssrbt, wb );
1637 m3x3_transpose( ssrat, ssra );
1638 m3x3_transpose( ssrbt, ssrb );
1639
1640 v3f b, b_wa, b_wb, b_a, b_b;
1641 m3x3_mulv( ssra, rba->w, b_wa );
1642 m3x3_mulv( ssrb, rbb->w, b_wb );
1643 v3_add( rba->v, b_wa, b );
1644 v3_sub( b, rbb->v, b );
1645 v3_sub( b, b_wb, b );
1646 v3_muls( b, -1.0f, b );
1647
1648 m3x3f invMa, invMb;
1649 m3x3_diagonal( invMa, rba->inv_mass );
1650 m3x3_diagonal( invMb, rbb->inv_mass );
1651
1652 m3x3f ia, ib;
1653 m3x3_mul( ssra, rba->iIw, ia );
1654 m3x3_mul( ia, ssrat, ia );
1655 m3x3_mul( ssrb, rbb->iIw, ib );
1656 m3x3_mul( ib, ssrbt, ib );
1657
1658 m3x3f cma, cmb;
1659 m3x3_add( invMa, ia, cma );
1660 m3x3_add( invMb, ib, cmb );
1661
1662 m3x3f A;
1663 m3x3_add( cma, cmb, A );
1664
1665 /* Solve Ax = b ( A^-1*b = x ) */
1666 v3f impulse;
1667 m3x3f invA;
1668 m3x3_inv( A, invA );
1669 m3x3_mulv( invA, b, impulse );
1670
1671 v3f delta_va, delta_wa, delta_vb, delta_wb;
1672 m3x3f iwa, iwb;
1673 m3x3_mul( rba->iIw, ssrat, iwa );
1674 m3x3_mul( rbb->iIw, ssrbt, iwb );
1675
1676 m3x3_mulv( invMa, impulse, delta_va );
1677 m3x3_mulv( invMb, impulse, delta_vb );
1678 m3x3_mulv( iwa, impulse, delta_wa );
1679 m3x3_mulv( iwb, impulse, delta_wb );
1680
1681 v3_add( rba->v, delta_va, rba->v );
1682 v3_add( rba->w, delta_wa, rba->w );
1683 v3_sub( rbb->v, delta_vb, rbb->v );
1684 v3_sub( rbb->w, delta_wb, rbb->w );
1685 }
1686 }
1687
1688 static void rb_solve_swingtwist_constraints( rb_constr_swingtwist *buf,
1689 int len ){
1690 for( int i=0; i<len; i++ ){
1691 rb_constr_swingtwist *st = &buf[ i ];
1692
1693 if( !st->axis_violation )
1694 continue;
1695
1696 float rv = v3_dot( st->axis, st->rbb->w ) -
1697 v3_dot( st->axis, st->rba->w );
1698
1699 if( rv * (float)st->axis_violation > 0.0f )
1700 continue;
1701
1702 v3f impulse, wa, wb;
1703 v3_muls( st->axis, rv*st->axis_mass, impulse );
1704 m3x3_mulv( st->rba->iIw, impulse, wa );
1705 v3_add( st->rba->w, wa, st->rba->w );
1706
1707 v3_muls( impulse, -1.0f, impulse );
1708 m3x3_mulv( st->rbb->iIw, impulse, wb );
1709 v3_add( st->rbb->w, wb, st->rbb->w );
1710
1711 float rv2 = v3_dot( st->axis, st->rbb->w ) -
1712 v3_dot( st->axis, st->rba->w );
1713 }
1714
1715 for( int i=0; i<len; i++ ){
1716 rb_constr_swingtwist *st = &buf[ i ];
1717
1718 if( !st->tangent_violation )
1719 continue;
1720
1721 float rv = v3_dot( st->tangent_axis, st->rbb->w ) -
1722 v3_dot( st->tangent_axis, st->rba->w );
1723
1724 if( rv > 0.0f )
1725 continue;
1726
1727 v3f impulse, wa, wb;
1728 v3_muls( st->tangent_axis, rv*st->tangent_mass, impulse );
1729 m3x3_mulv( st->rba->iIw, impulse, wa );
1730 v3_add( st->rba->w, wa, st->rba->w );
1731
1732 v3_muls( impulse, -1.0f, impulse );
1733 m3x3_mulv( st->rbb->iIw, impulse, wb );
1734 v3_add( st->rbb->w, wb, st->rbb->w );
1735
1736 float rv2 = v3_dot( st->tangent_axis, st->rbb->w ) -
1737 v3_dot( st->tangent_axis, st->rba->w );
1738 }
1739 }
1740
1741 /* debugging */
1742 static void rb_postsolve_swingtwist_constraints( rb_constr_swingtwist *buf,
1743 u32 len ){
1744 for( int i=0; i<len; i++ ){
1745 rb_constr_swingtwist *st = &buf[ i ];
1746
1747 if( !st->axis_violation ){
1748 st->conv_axis = 0.0f;
1749 continue;
1750 }
1751
1752 f32 rv = v3_dot( st->axis, st->rbb->w ) -
1753 v3_dot( st->axis, st->rba->w );
1754
1755 if( rv * (f32)st->axis_violation > 0.0f )
1756 st->conv_axis = 0.0f;
1757 else
1758 st->conv_axis = rv;
1759 }
1760
1761 for( int i=0; i<len; i++ ){
1762 rb_constr_swingtwist *st = &buf[ i ];
1763
1764 if( !st->tangent_violation ){
1765 st->conv_tangent = 0.0f;
1766 continue;
1767 }
1768
1769 f32 rv = v3_dot( st->tangent_axis, st->rbb->w ) -
1770 v3_dot( st->tangent_axis, st->rba->w );
1771
1772 if( rv > 0.0f )
1773 st->conv_tangent = 0.0f;
1774 else
1775 st->conv_tangent = rv;
1776 }
1777 }
1778
1779 static void rb_solve_constr_angle( rigidbody *rba, rigidbody *rbb,
1780 v3f ra, v3f rb ){
1781 m3x3f ssra, ssrb, ssrat, ssrbt;
1782 m3x3f cma, cmb;
1783
1784 m3x3_skew_symetric( ssrat, ra );
1785 m3x3_skew_symetric( ssrbt, rb );
1786 m3x3_transpose( ssrat, ssra );
1787 m3x3_transpose( ssrbt, ssrb );
1788
1789 m3x3_mul( ssra, rba->iIw, cma );
1790 m3x3_mul( cma, ssrat, cma );
1791 m3x3_mul( ssrb, rbb->iIw, cmb );
1792 m3x3_mul( cmb, ssrbt, cmb );
1793
1794 m3x3f A, invA;
1795 m3x3_add( cma, cmb, A );
1796 m3x3_inv( A, invA );
1797
1798 v3f b_wa, b_wb, b;
1799 m3x3_mulv( ssra, rba->w, b_wa );
1800 m3x3_mulv( ssrb, rbb->w, b_wb );
1801 v3_add( b_wa, b_wb, b );
1802 v3_negate( b, b );
1803
1804 v3f impulse;
1805 m3x3_mulv( invA, b, impulse );
1806
1807 v3f delta_wa, delta_wb;
1808 m3x3f iwa, iwb;
1809 m3x3_mul( rba->iIw, ssrat, iwa );
1810 m3x3_mul( rbb->iIw, ssrbt, iwb );
1811 m3x3_mulv( iwa, impulse, delta_wa );
1812 m3x3_mulv( iwb, impulse, delta_wb );
1813 v3_add( rba->w, delta_wa, rba->w );
1814 v3_sub( rbb->w, delta_wb, rbb->w );
1815 }
1816
1817 /*
1818 * Correct position constraint drift errors
1819 * [ 0.0 <= amt <= 1.0 ]: the correction amount
1820 */
1821 static void rb_correct_position_constraints( rb_constr_pos *buf, int len,
1822 float amt ){
1823 for( int i=0; i<len; i++ ){
1824 rb_constr_pos *constr = &buf[i];
1825 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1826
1827 v3f p0, p1, d;
1828 m3x3_mulv( rba->to_world, constr->lca, p0 );
1829 m3x3_mulv( rbb->to_world, constr->lcb, p1 );
1830 v3_add( rba->co, p0, p0 );
1831 v3_add( rbb->co, p1, p1 );
1832 v3_sub( p1, p0, d );
1833
1834 #if 1
1835 v3_muladds( rbb->co, d, -1.0f * amt, rbb->co );
1836 rb_update_transform( rbb );
1837 #else
1838 f32 mt = 1.0f/(rba->inv_mass+rbb->inv_mass),
1839 a = mt * (k_phys_baumgarte/k_rb_delta);
1840
1841 v3_muladds( rba->v, d, a* rba->inv_mass, rba->v );
1842 v3_muladds( rbb->v, d, a*-rbb->inv_mass, rbb->v );
1843 #endif
1844 }
1845 }
1846
1847 static void rb_correct_swingtwist_constraints( rb_constr_swingtwist *buf,
1848 int len, float amt ){
1849 for( int i=0; i<len; i++ ){
1850 rb_constr_swingtwist *st = &buf[i];
1851
1852 if( !st->tangent_violation )
1853 continue;
1854
1855 v3f va;
1856 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1857
1858 f32 angle = v3_dot( va, st->tangent_target );
1859
1860 if( fabsf(angle) < 0.9999f ){
1861 v3f axis;
1862 v3_cross( va, st->tangent_target, axis );
1863 #if 1
1864 angle = acosf(angle) * amt;
1865 v4f correction;
1866 q_axis_angle( correction, axis, angle );
1867 q_mul( correction, st->rbb->q, st->rbb->q );
1868 rb_update_transform( st->rbb );
1869 #else
1870 f32 mt = 1.0f/(st->rba->inv_mass+st->rbb->inv_mass),
1871 wa = mt * acosf(angle) * (k_phys_baumgarte/k_rb_delta);
1872 //v3_muladds( st->rba->w, axis, wa*-st->rba->inv_mass, st->rba->w );
1873 v3_muladds( st->rbb->w, axis, wa* st->rbb->inv_mass, st->rbb->w );
1874 #endif
1875 }
1876 }
1877
1878 for( int i=0; i<len; i++ ){
1879 rb_constr_swingtwist *st = &buf[i];
1880
1881 if( !st->axis_violation )
1882 continue;
1883
1884 v3f vxb;
1885 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1886
1887 f32 angle = v3_dot( vxb, st->axis_target );
1888
1889 if( fabsf(angle) < 0.9999f ){
1890 v3f axis;
1891 v3_cross( vxb, st->axis_target, axis );
1892
1893 #if 1
1894 angle = acosf(angle) * amt;
1895 v4f correction;
1896 q_axis_angle( correction, axis, angle );
1897 q_mul( correction, st->rbb->q, st->rbb->q );
1898 rb_update_transform( st->rbb );
1899 #else
1900 f32 mt = 1.0f/(st->rba->inv_mass+st->rbb->inv_mass),
1901 wa = mt * acosf(angle) * (k_phys_baumgarte/k_rb_delta);
1902 //v3_muladds( st->rba->w, axis, wa*-0.5f, st->rba->w );
1903 v3_muladds( st->rbb->w, axis, wa* st->rbb->inv_mass, st->rbb->w );
1904 #endif
1905 }
1906 }
1907 }
1908
1909 static void rb_correct_contact_constraints( rb_ct *buf, int len, float amt ){
1910 for( int i=0; i<len; i++ ){
1911 rb_ct *ct = &buf[i];
1912 rigidbody *rba = ct->rba,
1913 *rbb = ct->rbb;
1914
1915 f32 mass_total = 1.0f / (rba->inv_mass + rbb->inv_mass),
1916 d = ct->p*mass_total*amt;
1917
1918 v3_muladds( rba->co, ct->n, -d * rba->inv_mass, rba->co );
1919 v3_muladds( rbb->co, ct->n, d * rbb->inv_mass, rbb->co );
1920 }
1921 }
1922
1923
1924 /*
1925 * Effectors
1926 */
1927
1928 static void rb_effect_simple_bouyency( rigidbody *ra, v4f plane,
1929 float amt, float drag ){
1930 /* float */
1931 float depth = v3_dot( plane, ra->co ) - plane[3],
1932 lambda = vg_clampf( -depth, 0.0f, 1.0f ) * amt;
1933
1934 v3_muladds( ra->v, plane, lambda * k_rb_delta, ra->v );
1935
1936 if( depth < 0.0f )
1937 v3_muls( ra->v, 1.0f-(drag*k_rb_delta), ra->v );
1938 }
1939
1940 /* apply a spring&dampener force to match ra(worldspace) on rigidbody, to
1941 * rt(worldspace)
1942 */
1943 static void rb_effect_spring_target_vector( rigidbody *rba, v3f ra, v3f rt,
1944 float spring, float dampening,
1945 float timestep ){
1946 float d = v3_dot( rt, ra );
1947 float a = acosf( vg_clampf( d, -1.0f, 1.0f ) );
1948
1949 v3f axis;
1950 v3_cross( rt, ra, axis );
1951
1952 float Fs = -a * spring,
1953 Fd = -v3_dot( rba->w, axis ) * dampening;
1954
1955 v3_muladds( rba->w, axis, (Fs+Fd) * timestep, rba->w );
1956 }
1957
1958 #endif /* RIGIDBODY_H */