compiler warnings
[carveJwlIkooP6JGAAIwe30JlM.git] / skeleton.h
1 /*
2 * Copyright (C) 2021-2022 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 */
4
5 #ifndef SKELETON_H
6 #define SKELETON_H
7
8 #include "model.h"
9
10 struct skeleton
11 {
12 struct skeleton_bone
13 {
14 v3f co, end;
15 u32 parent;
16
17 u32 flags;
18 int defer;
19
20 mdl_keyframe kf;
21 mdl_bone *orig_bone;
22
23 u32 collider;
24 boxf hitbox;
25 const char *name;
26 }
27 *bones;
28 u32 bone_count;
29
30 struct skeleton_anim
31 {
32 const char *name;
33 u32 length;
34
35 float rate;
36 mdl_keyframe *anim_data;
37 }
38 *anims;
39 u32 anim_count;
40
41 #if 0
42 m4x3f *final_mtx;
43 #endif
44
45 struct skeleton_ik
46 {
47 u32 lower, upper, target, pole;
48 m3x3f ia, ib;
49 }
50 *ik;
51 u32 ik_count;
52
53 u32
54 collider_count,
55 bindable_count;
56 };
57
58 static u32 skeleton_bone_id( struct skeleton *skele, const char *name )
59 {
60 for( u32 i=1; i<skele->bone_count; i++ ){
61 if( !strcmp( skele->bones[i].name, name ))
62 return i;
63 }
64
65 vg_error( "skeleton_bone_id( *, \"%s\" );\n", name );
66 vg_fatal_error( "Bone does not exist\n" );
67
68 return 0;
69 }
70
71 static void keyframe_copy_pose( mdl_keyframe *kfa, mdl_keyframe *kfb,
72 int num )
73 {
74 for( int i=0; i<num; i++ )
75 kfb[i] = kfa[i];
76 }
77
78
79 /* apply a rotation from the perspective of root */
80 static void keyframe_rotate_around( mdl_keyframe *kf,
81 v3f origin, v3f offset, v4f q )
82 {
83 v3f v0, co;
84 v3_add( kf->co, offset, co );
85 v3_sub( co, origin, v0 );
86 q_mulv( q, v0, v0 );
87 v3_add( v0, origin, co );
88 v3_sub( co, offset, kf->co );
89
90 q_mul( q, kf->q, kf->q );
91 q_normalize( kf->q );
92 }
93
94 /*
95 * Lerp between two sets of keyframes and store in dest. Rotations use Nlerp.
96 */
97 static void keyframe_lerp_pose( mdl_keyframe *kfa, mdl_keyframe *kfb,
98 float t, mdl_keyframe *kfd, int count )
99 {
100 if( t <= 0.0001f ){
101 keyframe_copy_pose( kfa, kfd, count );
102 return;
103 }
104 else if( t >= 0.9999f ){
105 keyframe_copy_pose( kfb, kfd, count );
106 return;
107 }
108
109 for( int i=0; i<count; i++ ){
110 v3_lerp( kfa[i].co, kfb[i].co, t, kfd[i].co );
111 q_nlerp( kfa[i].q, kfb[i].q, t, kfd[i].q );
112 v3_lerp( kfa[i].s, kfb[i].s, t, kfd[i].s );
113 }
114 }
115
116 static
117 void skeleton_lerp_pose( struct skeleton *skele,
118 mdl_keyframe *kfa, mdl_keyframe *kfb, float t,
119 mdl_keyframe *kfd )
120 {
121 keyframe_lerp_pose( kfa, kfb, t, kfd, skele->bone_count-1 );
122 }
123
124 static void skeleton_copy_pose( struct skeleton *skele,
125 mdl_keyframe *kfa, mdl_keyframe *kfd )
126 {
127 keyframe_copy_pose( kfa, kfd, skele->bone_count-1 );
128 }
129
130 /*
131 * Sample animation between 2 closest frames using time value. Output is a
132 * keyframe buffer that is allocated with an appropriate size
133 */
134 static void skeleton_sample_anim( struct skeleton *skele,
135 struct skeleton_anim *anim,
136 float time,
137 mdl_keyframe *output )
138 {
139 f32 animtime = fmodf( time*anim->rate, anim->length ),
140 animframe = floorf( animtime ),
141 t = animtime - animframe;
142
143 u32 frame = (u32)animframe % anim->length,
144 next = (frame+1) % anim->length;
145
146 mdl_keyframe *base = anim->anim_data + (skele->bone_count-1)*frame,
147 *nbase = anim->anim_data + (skele->bone_count-1)*next;
148
149 skeleton_lerp_pose( skele, base, nbase, t, output );
150 }
151
152 static int skeleton_sample_anim_clamped( struct skeleton *skele,
153 struct skeleton_anim *anim,
154 float time,
155 mdl_keyframe *output )
156 {
157 float end = (float)(anim->length-1) / anim->rate;
158 skeleton_sample_anim( skele, anim, vg_minf( end, time ), output );
159
160 if( time > end )
161 return 0;
162 else
163 return 1;
164 }
165
166 typedef enum anim_apply
167 {
168 k_anim_apply_always,
169 k_anim_apply_defer_ik,
170 k_anim_apply_deffered_only,
171 k_anim_apply_absolute
172 }
173 anim_apply;
174
175 static
176 int should_apply_bone( struct skeleton *skele, u32 id, anim_apply type )
177 {
178 struct skeleton_bone *sb = &skele->bones[ id ],
179 *sp = &skele->bones[ sb->parent ];
180
181 if( type == k_anim_apply_defer_ik ){
182 if( ((sp->flags & k_bone_flag_ik) && !(sb->flags & k_bone_flag_ik))
183 || sp->defer )
184 {
185 sb->defer = 1;
186 return 0;
187 }
188 else{
189 sb->defer = 0;
190 return 1;
191 }
192 }
193 else if( type == k_anim_apply_deffered_only ){
194 if( sb->defer )
195 return 1;
196 else
197 return 0;
198 }
199
200 return 1;
201 }
202
203 /*
204 * Apply block of keyframes to skeletons final pose
205 */
206 static void skeleton_apply_pose( struct skeleton *skele, mdl_keyframe *pose,
207 anim_apply passtype, m4x3f *final_mtx ){
208 if( passtype == k_anim_apply_absolute ){
209 for( u32 i=1; i<skele->bone_count; i++ ){
210 mdl_keyframe *kf = &pose[i-1];
211
212 v3f *posemtx = final_mtx[i];
213
214 q_m3x3( kf->q, posemtx );
215 v3_copy( kf->co, posemtx[3] );
216 }
217 return;
218 }
219
220 m4x3_identity( final_mtx[0] );
221 skele->bones[0].defer = 0;
222 skele->bones[0].flags &= ~k_bone_flag_ik;
223
224 for( u32 i=1; i<skele->bone_count; i++ ){
225 struct skeleton_bone *sb = &skele->bones[i],
226 *sp = &skele->bones[sb->parent];
227
228 if( !should_apply_bone( skele, i, passtype ) )
229 continue;
230
231 sb->defer = 0;
232
233 /* process pose */
234 m4x3f posemtx;
235
236 v3f temp_delta;
237 v3_sub( skele->bones[i].co, skele->bones[sb->parent].co, temp_delta );
238
239 /* pose matrix */
240 mdl_keyframe *kf = &pose[i-1];
241 q_m3x3( kf->q, posemtx );
242 v3_copy( kf->co, posemtx[3] );
243 v3_add( temp_delta, posemtx[3], posemtx[3] );
244
245 /* final matrix */
246 m4x3_mul( final_mtx[ sb->parent ], posemtx, final_mtx[i] );
247 }
248 }
249
250 /*
251 * Take the final matrices and decompose it into an absolute positioned anim
252 */
253 static void skeleton_decompose_mtx_absolute( struct skeleton *skele,
254 mdl_keyframe *anim,
255 m4x3f *final_mtx ){
256 for( u32 i=1; i<skele->bone_count; i++ ){
257 struct skeleton_bone *sb = &skele->bones[i];
258 mdl_keyframe *kf = &anim[i-1];
259 m4x3_decompose( final_mtx[i], kf->co, kf->q, kf->s );
260 }
261 }
262
263 /*
264 * creates the reference inverse matrix for an IK bone, as it has an initial
265 * intrisic rotation based on the direction that the IK is setup..
266 */
267 static void skeleton_inverse_for_ik( struct skeleton *skele,
268 v3f ivaxis,
269 u32 id, m3x3f inverse )
270 {
271 v3_copy( ivaxis, inverse[0] );
272 v3_copy( skele->bones[id].end, inverse[1] );
273 v3_normalize( inverse[1] );
274 v3_cross( inverse[0], inverse[1], inverse[2] );
275 m3x3_transpose( inverse, inverse );
276 }
277
278 /*
279 * Creates inverse rotation matrices which the IK system uses.
280 */
281 static void skeleton_create_inverses( struct skeleton *skele )
282 {
283 /* IK: inverse 'plane-bone space' axis '(^axis,^bone,...)[base] */
284 for( u32 i=0; i<skele->ik_count; i++ ){
285 struct skeleton_ik *ik = &skele->ik[i];
286
287 m4x3f inverse;
288 v3f iv0, iv1, ivaxis;
289 v3_sub( skele->bones[ik->target].co, skele->bones[ik->lower].co, iv0 );
290 v3_sub( skele->bones[ik->pole].co, skele->bones[ik->lower].co, iv1 );
291 v3_cross( iv0, iv1, ivaxis );
292 v3_normalize( ivaxis );
293
294 skeleton_inverse_for_ik( skele, ivaxis, ik->lower, ik->ia );
295 skeleton_inverse_for_ik( skele, ivaxis, ik->upper, ik->ib );
296 }
297 }
298
299 /*
300 * Apply a model matrix to all bones, should be done last
301 */
302 static
303 void skeleton_apply_transform( struct skeleton *skele, m4x3f transform,
304 m4x3f *final_mtx )
305 {
306 for( u32 i=0; i<skele->bone_count; i++ ){
307 struct skeleton_bone *sb = &skele->bones[i];
308 m4x3_mul( transform, final_mtx[i], final_mtx[i] );
309 }
310 }
311
312 /*
313 * Apply an inverse matrix to all bones which maps vertices from bind space into
314 * bone relative positions
315 */
316 static void skeleton_apply_inverses( struct skeleton *skele, m4x3f *final_mtx ){
317 for( u32 i=0; i<skele->bone_count; i++ ){
318 struct skeleton_bone *sb = &skele->bones[i];
319 m4x3f inverse;
320 m3x3_identity( inverse );
321 v3_negate( sb->co, inverse[3] );
322
323 m4x3_mul( final_mtx[i], inverse, final_mtx[i] );
324 }
325 }
326
327 /*
328 * Apply all IK modifiers (2 bone ik reference from blender is supported)
329 */
330 static void skeleton_apply_ik_pass( struct skeleton *skele, m4x3f *final_mtx ){
331 for( u32 i=0; i<skele->ik_count; i++ ){
332 struct skeleton_ik *ik = &skele->ik[i];
333
334 v3f v0, /* base -> target */
335 v1, /* base -> pole */
336 vaxis;
337
338 v3f co_base,
339 co_target,
340 co_pole;
341
342 v3_copy( final_mtx[ik->lower][3], co_base );
343 v3_copy( final_mtx[ik->target][3], co_target );
344 v3_copy( final_mtx[ik->pole][3], co_pole );
345
346 v3_sub( co_target, co_base, v0 );
347 v3_sub( co_pole, co_base, v1 );
348 v3_cross( v0, v1, vaxis );
349 v3_normalize( vaxis );
350 v3_normalize( v0 );
351 v3_cross( vaxis, v0, v1 );
352
353 /* localize problem into [x:v0,y:v1] 2d plane */
354 v2f base = { v3_dot( v0, co_base ), v3_dot( v1, co_base ) },
355 end = { v3_dot( v0, co_target ), v3_dot( v1, co_target ) },
356 knee;
357
358 /* Compute angles (basic trig)*/
359 v2f delta;
360 v2_sub( end, base, delta );
361
362 float
363 l1 = v3_length( skele->bones[ik->lower].end ),
364 l2 = v3_length( skele->bones[ik->upper].end ),
365 d = vg_clampf( v2_length(delta), fabsf(l1 - l2), l1+l2-0.00001f ),
366 c = acosf( (l1*l1 + d*d - l2*l2) / (2.0f*l1*d) ),
367 rot = atan2f( delta[1], delta[0] ) + c - VG_PIf/2.0f;
368
369 knee[0] = sinf(-rot) * l1;
370 knee[1] = cosf(-rot) * l1;
371
372 m4x3_identity( final_mtx[ik->lower] );
373 m4x3_identity( final_mtx[ik->upper] );
374
375 /* create rotation matrix */
376 v3f co_knee;
377 v3_muladds( co_base, v0, knee[0], co_knee );
378 v3_muladds( co_knee, v1, knee[1], co_knee );
379 vg_line( co_base, co_knee, 0xff00ff00 );
380
381 m4x3f transform;
382 v3_copy( vaxis, transform[0] );
383 v3_muls( v0, knee[0], transform[1] );
384 v3_muladds( transform[1], v1, knee[1], transform[1] );
385 v3_normalize( transform[1] );
386 v3_cross( transform[0], transform[1], transform[2] );
387 v3_copy( co_base, transform[3] );
388
389 m3x3_mul( transform, ik->ia, transform );
390 m4x3_copy( transform, final_mtx[ik->lower] );
391
392 /* upper/knee bone */
393 v3_copy( vaxis, transform[0] );
394 v3_sub( co_target, co_knee, transform[1] );
395 v3_normalize( transform[1] );
396 v3_cross( transform[0], transform[1], transform[2] );
397 v3_copy( co_knee, transform[3] );
398
399 m3x3_mul( transform, ik->ib, transform );
400 m4x3_copy( transform, final_mtx[ik->upper] );
401 }
402 }
403
404 /*
405 * Applies the typical operations that you want for an IK rig:
406 * Pose, IK, Pose(deferred), Inverses, Transform
407 */
408 static void skeleton_apply_standard( struct skeleton *skele, mdl_keyframe *pose,
409 m4x3f transform, m4x3f *final_mtx ){
410 skeleton_apply_pose( skele, pose, k_anim_apply_defer_ik, final_mtx );
411 skeleton_apply_ik_pass( skele, final_mtx );
412 skeleton_apply_pose( skele, pose, k_anim_apply_deffered_only, final_mtx );
413 skeleton_apply_inverses( skele, final_mtx );
414 skeleton_apply_transform( skele, transform, final_mtx );
415 }
416
417 /*
418 * Get an animation by name
419 */
420 static struct skeleton_anim *skeleton_get_anim( struct skeleton *skele,
421 const char *name ){
422 for( u32 i=0; i<skele->anim_count; i++ ){
423 struct skeleton_anim *anim = &skele->anims[i];
424
425 if( !strcmp( anim->name, name ) )
426 return anim;
427 }
428
429 vg_error( "skeleton_get_anim( *, \"%s\" )\n", name );
430 vg_fatal_error( "Invalid animation name\n" );
431
432 return NULL;
433 }
434
435 static void skeleton_alloc_from( struct skeleton *skele,
436 void *lin_alloc,
437 mdl_context *mdl,
438 mdl_armature *armature ){
439 skele->bone_count = armature->bone_count+1;
440 skele->anim_count = armature->anim_count;
441 skele->ik_count = 0;
442 skele->collider_count = 0;
443
444 for( u32 i=0; i<armature->bone_count; i++ ){
445 mdl_bone *bone = mdl_arritm( &mdl->bones, armature->bone_start+i );
446
447 if( bone->flags & k_bone_flag_ik )
448 skele->ik_count ++;
449
450 if( bone->collider )
451 skele->collider_count ++;
452 }
453
454 u32 bone_size = sizeof(struct skeleton_bone) * skele->bone_count,
455 ik_size = sizeof(struct skeleton_ik) * skele->ik_count,
456 mtx_size = sizeof(m4x3f) * skele->bone_count,
457 anim_size = sizeof(struct skeleton_anim) * skele->anim_count;
458
459 skele->bones = vg_linear_alloc( lin_alloc, bone_size );
460 skele->ik = vg_linear_alloc( lin_alloc, ik_size );
461 //skele->final_mtx = vg_linear_alloc( lin_alloc, mtx_size );
462 skele->anims = vg_linear_alloc( lin_alloc, anim_size );
463
464 memset( skele->bones, 0, bone_size );
465 memset( skele->ik, 0, ik_size );
466 //memset( skele->final_mtx, 0, mtx_size );
467 memset( skele->anims, 0, anim_size );
468 }
469
470 static void skeleton_fatal_err(void){
471 vg_fatal_error( "Skeleton setup failed" );
472 }
473
474 /* Setup an animated skeleton from model. mdl's metadata should stick around */
475 static void skeleton_setup( struct skeleton *skele,
476 void *lin_alloc, mdl_context *mdl ){
477 u32 ik_count = 0, collider_count = 0;
478 skele->bone_count = 0;
479 skele->bones = NULL;
480 //skele->final_mtx = NULL;
481 skele->anims = NULL;
482
483 if( !mdl->armatures.count ){
484 vg_error( "No skeleton in model\n" );
485 skeleton_fatal_err();
486 }
487
488 mdl_armature *armature = mdl_arritm( &mdl->armatures, 0 );
489 skeleton_alloc_from( skele, lin_alloc, mdl, armature );
490
491 for( u32 i=0; i<armature->bone_count; i++ ){
492 mdl_bone *bone = mdl_arritm( &mdl->bones, armature->bone_start+i );
493 struct skeleton_bone *sb = &skele->bones[i+1];
494
495 v3_copy( bone->co, sb->co );
496 v3_copy( bone->end, sb->end );
497
498 sb->parent = bone->parent;
499 sb->name = mdl_pstr( mdl, bone->pstr_name );
500 sb->flags = bone->flags;
501 sb->collider = bone->collider;
502 sb->orig_bone = bone;
503
504 if( sb->flags & k_bone_flag_ik ){
505 skele->bones[ sb->parent ].flags |= k_bone_flag_ik;
506
507 if( ik_count == skele->ik_count ){
508 vg_error( "Too many ik bones, corrupt model file\n" );
509 skeleton_fatal_err();
510 }
511
512 struct skeleton_ik *ik = &skele->ik[ ik_count ++ ];
513 ik->upper = i+1;
514 ik->lower = bone->parent;
515 ik->target = bone->ik_target;
516 ik->pole = bone->ik_pole;
517 }
518
519 box_copy( bone->hitbox, sb->hitbox );
520
521 if( bone->collider ){
522 if( collider_count == skele->collider_count ){
523 vg_error( "Too many collider bones\n" );
524 skeleton_fatal_err();
525 }
526
527 collider_count ++;
528 }
529 }
530
531 /* fill in implicit root bone */
532 v3_zero( skele->bones[0].co );
533 v3_copy( (v3f){0.0f,1.0f,0.0f}, skele->bones[0].end );
534 skele->bones[0].parent = 0xffffffff;
535 skele->bones[0].flags = 0;
536 skele->bones[0].name = "[root]";
537
538 /* process animation quick refs */
539 for( u32 i=0; i<skele->anim_count; i++ ){
540 mdl_animation *anim =
541 mdl_arritm( &mdl->animations, armature->anim_start+i );
542
543 skele->anims[i].rate = anim->rate;
544 skele->anims[i].length = anim->length;
545 skele->anims[i].name = mdl_pstr(mdl, anim->pstr_name);
546 skele->anims[i].anim_data =
547 mdl_arritm( &mdl->keyframes, anim->offset );
548
549 vg_info( "animation[ %f, %u ] '%s'\n", anim->rate,
550 anim->length,
551 skele->anims[i].name );
552 }
553
554 skeleton_create_inverses( skele );
555 vg_success( "Loaded skeleton with %u bones\n", skele->bone_count );
556 vg_success( " %u colliders\n", skele->collider_count );
557 }
558
559 static void skeleton_debug( struct skeleton *skele, m4x3f *final_mtx ){
560 for( u32 i=1; i<skele->bone_count; i ++ ){
561 struct skeleton_bone *sb = &skele->bones[i];
562
563 v3f p0, p1;
564 v3_copy( sb->co, p0 );
565 v3_add( p0, sb->end, p1 );
566
567 m4x3_mulv( final_mtx[i], p0, p0 );
568 m4x3_mulv( final_mtx[i], p1, p1 );
569
570 if( sb->flags & k_bone_flag_deform ){
571 if( sb->flags & k_bone_flag_ik ){
572 vg_line( p0, p1, 0xff0000ff );
573 }
574 else{
575 vg_line( p0, p1, 0xffcccccc );
576 }
577 }
578 else
579 vg_line( p0, p1, 0xff00ffff );
580 }
581 }
582
583 #endif /* SKELETON_H */