]> git.tdb.fi Git - libs/gl.git/blob - source/animation/animation.cpp
Add inline data items to the collection
[libs/gl.git] / source / animation / animation.cpp
1 #include <cmath>
2 #include <msp/core/maputils.h>
3 #include <msp/datafile/collection.h>
4 #include <msp/fs/utils.h>
5 #include <msp/interpolate/bezierspline.h>
6 #include <msp/strings/format.h>
7 #include "animation.h"
8 #include "animationeventobserver.h"
9 #include "armature.h"
10 #include "error.h"
11 #include "pose.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace GL {
17
18 Animation::Animation():
19         armature(0),
20         looping(false)
21 { }
22
23 Animation::~Animation()
24 {
25         for(vector<TimedKeyFrame>::iterator i=keyframes.begin(); i!=keyframes.end(); ++i)
26                 if(i->owned)
27                         delete i->keyframe;
28         for(vector<Curve *>::iterator i=curves.begin(); i!=curves.end(); ++i)
29                 delete *i;
30 }
31
32 void Animation::set_armature(const Armature &a)
33 {
34         if(!keyframes.empty() && &a!=armature)
35                 throw invalid_operation("Animation::set_armature");
36         armature = &a;
37 }
38
39 unsigned Animation::get_slot_for_uniform(const string &n) const
40 {
41         for(unsigned i=0; i<uniforms.size(); ++i)
42                 if(uniforms[i].name==n)
43                         return i;
44         throw key_error(n);
45 }
46
47 const string &Animation::get_uniform_name(unsigned i) const
48 {
49         if(i>=uniforms.size())
50                 throw out_of_range("Animation::get_uniform_name");
51         return uniforms[i].name;
52 }
53
54 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf)
55 {
56         add_keyframe(t, &kf, false, false);
57         create_curves();
58 }
59
60 void Animation::add_keyframe_owned(const Time::TimeDelta &t, const KeyFrame *kf)
61 {
62         add_keyframe(t, kf, false, true);
63         create_curves();
64 }
65
66 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf, float slope)
67 {
68         add_keyframe(t, &kf, slope, slope, false);
69         create_curves();
70 }
71
72 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame &kf, float ss, float es)
73 {
74         add_keyframe(t, &kf, ss, es, false);
75         create_curves();
76 }
77
78 void Animation::add_control_keyframe(const KeyFrame &kf)
79 {
80         if(keyframes.empty())
81                 throw invalid_operation("Animation::add_control_keyframe");
82
83         add_keyframe(keyframes.back().time, &kf, true, false);
84 }
85
86 void Animation::add_control_keyframe_owned(const KeyFrame *kf)
87 {
88         if(keyframes.empty())
89                 throw invalid_operation("Animation::add_control_keyframe_owned");
90
91         add_keyframe(keyframes.back().time, kf, true, true);
92 }
93
94 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame *kf, float ss, float es, bool owned)
95 {
96         if(keyframes.empty())
97                 return add_keyframe(t, kf, false, owned);
98
99         if(keyframes.back().control)
100                 throw invalid_operation("Animation::add_keyframe");
101
102         const KeyFrame &last = *keyframes.back().keyframe;
103         const Transform &trn = kf->get_transform();
104         const Transform &last_trn = last.get_transform();
105         const KeyFrame::UniformMap &kf_unis = kf->get_uniforms();
106         const KeyFrame::UniformMap &last_unis = last.get_uniforms();
107         for(unsigned i=1; i<=2; ++i)
108         {
109                 float x = (i==1 ? ss/3 : 1-es/3);
110                 KeyFrame *ckf = new KeyFrame;
111                 Transform ctrn;
112                 ctrn.set_position(last_trn.get_position()*(1-x)+trn.get_position()*x);
113                 const Transform::AngleVector3 &e1 = last_trn.get_euler();
114                 const Transform::AngleVector3 &e2 = trn.get_euler();
115                 ctrn.set_euler(Transform::AngleVector3(e1.x*(1-x)+e2.x*x, e1.y*(1-x)+e2.y*x, e1.z*(1-x)+e2.z*x));
116                 ctrn.set_scale(last_trn.get_scale()*(1-x)+trn.get_scale()*x);
117                 ckf->set_transform(ctrn);
118
119                 for(KeyFrame::UniformMap::const_iterator j=kf_unis.begin(); j!=kf_unis.end(); ++j)
120                 {
121                         KeyFrame::UniformMap::const_iterator k = last_unis.find(j->first);
122                         if(k==last_unis.end())
123                                 continue;
124
125                         KeyFrame::AnimatedUniform uni(j->second.size, 0.0f);
126                         for(unsigned c=0; c<uni.size; ++c)
127                                 uni.values[c] = k->second.values[c]*(1-x)+j->second.values[c]*x;
128
129                         ckf->set_uniform(j->first, uni);
130                 }
131
132                 add_keyframe(t, ckf, true, true);
133         }
134
135         add_keyframe(t, kf, false, owned);
136 }
137
138 void Animation::add_keyframe(const Time::TimeDelta &t, const KeyFrame *kf, bool c, bool owned)
139 {
140         if(c && keyframes.empty())
141                 throw invalid_argument("Animation::add_keyframe");
142         if(keyframes.empty() && t!=Time::zero)
143                 throw invalid_argument("Animation::add_keyframe");
144         if(!keyframes.empty() && t<keyframes.back().time)
145                 throw invalid_argument("Animation::add_keyframe");
146         if(kf->get_pose() && armature && kf->get_pose()->get_armature()!=armature)
147                 throw invalid_argument("Animation::add_keyframe");
148
149         const KeyFrame::UniformMap &kf_uniforms = kf->get_uniforms();
150         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
151         {
152                 KeyFrame::UniformMap::const_iterator j = kf_uniforms.find(i->name);
153                 if(j!=kf_uniforms.end() && j->second.size!=i->size)
154                         throw invalid_argument("Animation::add_keyframe");
155         }
156
157         if(kf->get_pose() && !armature)
158                 armature = kf->get_pose()->get_armature();
159
160         TimedKeyFrame tkf;
161         tkf.time = t;
162         tkf.keyframe = kf;
163         tkf.control = c;
164         tkf.owned = owned;
165
166         keyframes.push_back(tkf);
167
168         for(KeyFrame::UniformMap::const_iterator i=kf_uniforms.begin(); i!=kf_uniforms.end(); ++i)
169         {
170                 bool found = false;
171                 for(vector<UniformInfo>::const_iterator j=uniforms.begin(); (!found && j!=uniforms.end()); ++j)
172                         found = (j->name==i->first);
173
174                 if(!found)
175                         uniforms.push_back(UniformInfo(i->first, i->second.size));
176         }
177 }
178
179 void Animation::create_curves()
180 {
181         for(vector<Curve *>::iterator i=curves.begin(); i!=curves.end(); ++i)
182                 delete *i;
183         curves.clear();
184
185         curves.reserve(6+uniforms.size());
186         create_curve(POSITION, Transform::POSITION, &extract_position);
187         create_curve(EULER, Transform::EULER, &extract_euler);
188         create_curve(SCALE, Transform::SCALE, &extract_scale);
189
190         uniform_curve_offset = curves.size();
191         for(vector<UniformInfo>::const_iterator i=uniforms.begin(); i!=uniforms.end(); ++i)
192         {
193                 if(i->size==1)
194                         create_curve<1>(UNIFORM, -1, ExtractUniform<1>(i->name));
195                 else if(i->size==2)
196                         create_curve<2>(UNIFORM, -1, ExtractUniform<2>(i->name));
197                 else if(i->size==3)
198                         create_curve<3>(UNIFORM, -1, ExtractUniform<3>(i->name));
199                 else if(i->size==4)
200                         create_curve<4>(UNIFORM, -1, ExtractUniform<4>(i->name));
201         }
202 }
203
204 void Animation::create_curve(CurveTarget target, Transform::ComponentMask mask, ExtractComponent::Extract extract)
205 {
206         Transform::ComponentMask all = mask;
207         Transform::ComponentMask any = Transform::NONE;
208         for(vector<TimedKeyFrame>::const_iterator i=keyframes.begin(); i!=keyframes.end(); ++i)
209         {
210                 all = all&i->keyframe->get_transform().get_mask();
211                 any = any|i->keyframe->get_transform().get_mask();
212         }
213
214         if(all==mask)
215                 create_curve<3>(target, -1, extract);
216         else if(any&mask)
217         {
218                 unsigned low_bit = mask&(mask>>2);
219                 for(unsigned i=3; i-->0; )
220                 {
221                         Transform::ComponentMask bit = static_cast<Transform::ComponentMask>(low_bit<<i);
222                         if(any&bit)
223                                 create_curve<1>(target, i, ExtractComponent(extract, i, bit));
224                 }
225         }
226 }
227
228 template<unsigned N, typename T>
229 void Animation::create_curve(CurveTarget target, int component, const T &extract)
230 {
231         typedef typename ValueCurve<N>::Knot Knot;
232
233         vector<Knot> knots;
234         unsigned n_control = 0;
235         for(vector<TimedKeyFrame>::const_iterator i=keyframes.begin(); i!=keyframes.end(); ++i)
236         {
237                 if(i->control && knots.empty())
238                         continue;
239
240                 typename Interpolate::SplineValue<float, N>::Type value;
241                 if(extract(*i->keyframe, value))
242                 {
243                         typename Knot::Value dvalue = value;
244                         float x = i->time/Time::sec;
245                         if(i->control)
246                         {
247                                 ++n_control;
248                                 if(n_control>2)
249                                         throw logic_error("too many control keyframes");
250                         }
251                         else
252                         {
253                                 if(n_control==1)
254                                 {
255                                         typename Knot::Value cv = knots.back().y;
256                                         knots.back().y = (knots[knots.size()-2].y+cv*2.0)/3.0;
257                                         knots.push_back(Knot(x, (dvalue+cv*2.0)/3.0));
258                                 }
259                                 else if(n_control==0 && !knots.empty())
260                                 {
261                                         typename Knot::Value prev = knots.back().y;
262                                         knots.push_back(Knot(knots.back().x, (prev*2.0+dvalue)/3.0));
263                                         knots.push_back(Knot(x, (prev+dvalue*2.0)/3.0));
264                                 }
265                                 n_control = 0;
266                         }
267                         knots.push_back(Knot(x, value));
268                 }
269         }
270         
271         while(n_control--)
272                 knots.pop_back();
273
274         if(knots.size()==1)
275         {
276                 knots.push_back(knots.back());
277                 knots.push_back(knots.back());
278                 knots.back().x += 1;
279                 knots.push_back(knots.back());
280         }
281
282         curves.push_back(new ValueCurve<N>(target, component, knots));
283 }
284
285 bool Animation::extract_position(const KeyFrame &kf, Vector3 &value)
286 {
287         value = kf.get_transform().get_position();
288         return true;
289 }
290
291 bool Animation::extract_euler(const KeyFrame &kf, Vector3 &value)
292 {
293         const Transform::AngleVector3 &euler = kf.get_transform().get_euler();
294         value = Vector3(euler.x.radians(), euler.y.radians(), euler.z.radians());
295         return true;
296 }
297
298 bool Animation::extract_scale(const KeyFrame &kf, Vector3 &value)
299 {
300         value = kf.get_transform().get_scale();
301         return true;
302 }
303
304 void Animation::add_event(const Time::TimeDelta &t, const string &n, const Variant &v)
305 {
306         Event event;
307         event.time = t;
308         event.name = n;
309         event.value = v;
310         events.push_back(event);
311 }
312
313 const Time::TimeDelta &Animation::get_duration() const
314 {
315         if(keyframes.empty())
316                 return Time::zero;
317
318         return keyframes.back().time;
319 }
320
321 void Animation::set_looping(bool l)
322 {
323         looping = l;
324 }
325
326
327 Animation::Curve::Curve(CurveTarget t, int c):
328         target(t),
329         component(c)
330 { }
331
332
333 template<unsigned N>
334 Animation::ValueCurve<N>::ValueCurve(CurveTarget t, int c, const vector<Knot> &k):
335         Curve(t, c),
336         spline(Interpolate::BezierSpline<double, 3, N>(k))
337 { }
338
339 template<unsigned N>
340 void Animation::ValueCurve<N>::apply(float, Matrix &) const
341 {
342         throw invalid_operation("ValueCurve::apply");
343 }
344
345 template<>
346 void Animation::ValueCurve<1>::apply(float x, Matrix &matrix) const
347 {
348         float value = spline(x);
349         if(target==POSITION || target==SCALE)
350         {
351                 if(target==POSITION)
352                 {
353                         Vector3 vec;
354                         vec[component] = value;
355                         matrix.translate(vec);
356                 }
357                 else
358                 {
359                         Vector3 vec(1.0f, 1.0f, 1.0f);
360                         vec[component] = value;
361                         matrix.scale(vec);
362                 }
363         }
364         else if(target==EULER)
365         {
366                 Vector3 vec;
367                 vec[component] = 1.0f;
368                 matrix.rotate(Geometry::Angle<float>::from_radians(value), vec);
369         }
370         else
371                 throw invalid_operation("ValueCurve::apply");
372 }
373
374 template<>
375 void Animation::ValueCurve<3>::apply(float x, Matrix &matrix) const
376 {
377         Vector3 value = spline(x);
378         if(target==POSITION)
379                 matrix.translate(value);
380         else if(target==EULER)
381         {
382                 matrix.rotate(Geometry::Angle<float>::from_radians(value.z), Vector3(0, 0, 1));
383                 matrix.rotate(Geometry::Angle<float>::from_radians(value.y), Vector3(0, 1, 0));
384                 matrix.rotate(Geometry::Angle<float>::from_radians(value.x), Vector3(1, 0, 0));
385         }
386         else if(target==SCALE)
387                 matrix.scale(value);
388         else
389                 throw invalid_operation("ValueCurve::apply");
390 }
391
392 template<unsigned N>
393 void Animation::ValueCurve<N>::apply(float x, KeyFrame::AnimatedUniform &uni) const
394 {
395         uni.size = N;
396         typename Interpolate::Spline<double, 3, N>::Value value = spline(x);
397         for(unsigned i=0; i<N; ++i)
398                 uni.values[i] = Interpolate::SplineValue<double, N>::get(value, i);
399 }
400
401
402 bool Animation::ExtractComponent::operator()(const KeyFrame &kf, float &value) const
403 {
404         Vector3 vec;
405         if(!extract(kf, vec))
406                 return false;
407
408         value = vec[index];
409         return kf.get_transform().get_mask()&mask;
410 }
411
412
413 template<unsigned N>
414 bool Animation::ExtractUniform<N>::operator()(const KeyFrame &kf, typename Interpolate::SplineValue<float, N>::Type &value) const
415 {
416         const KeyFrame::UniformMap &kf_uniforms = kf.get_uniforms();
417         const KeyFrame::UniformMap::const_iterator i = kf_uniforms.find(name);
418         if(i==kf_uniforms.end())
419                 return false;
420
421         value = Interpolate::SplineValue<float, N>::make(i->second.values);
422         return true;
423 }
424
425
426 Animation::UniformInfo::UniformInfo(const string &n, unsigned s):
427         name(n),
428         size(s)
429 { }
430
431
432 Animation::Iterator::Iterator(const Animation &a):
433         animation(&a),
434         event_iter(animation->events.begin()),
435         end(false)
436 {
437 }
438
439 Animation::Iterator &Animation::Iterator::operator+=(const Time::TimeDelta &t)
440 {
441         const Time::TimeDelta &duration = animation->get_duration();
442         if(!duration)
443                 return *this;
444
445         elapsed += t;
446         if(animation->looping)
447         {
448                 while(elapsed>=duration)
449                         elapsed -= duration;
450         }
451         else if(elapsed>=duration)
452         {
453                 end = true;
454                 elapsed = duration;
455         }
456
457         return *this;
458 }
459
460 void Animation::Iterator::dispatch_events(AnimationEventObserver &observer)
461 {
462         for(; (event_iter!=animation->events.end() && event_iter->time<=elapsed); ++event_iter)
463                 observer.animation_event(0, event_iter->name, event_iter->value);
464 }
465
466 Matrix Animation::Iterator::get_matrix() const
467 {
468         Matrix matrix;
469         for(unsigned i=0; i<animation->uniform_curve_offset; ++i)
470                 animation->curves[i]->apply(elapsed/Time::sec, matrix);
471         return matrix;
472 }
473
474 KeyFrame::AnimatedUniform Animation::Iterator::get_uniform(unsigned i) const
475 {
476         if(i>=animation->uniforms.size())
477                 throw out_of_range("Animation::Iterator::get_uniform");
478
479         KeyFrame::AnimatedUniform uni(animation->uniforms[i].size, 0.0f);
480         animation->curves[animation->uniform_curve_offset+i]->apply(elapsed/Time::sec, uni);
481         return uni;
482 }
483
484 Matrix Animation::Iterator::get_pose_matrix(unsigned link) const
485 {
486         if(!animation->armature)
487                 throw invalid_operation("Animation::Iterator::get_pose_matrix");
488         if(link>animation->armature->get_max_link_index())
489                 throw out_of_range("Animation::Iterator::get_pose_matrix");
490
491         throw logic_error("pose animations are currently unimplemented");
492 }
493
494
495 Animation::Loader::Loader(Animation &a):
496         DataFile::CollectionObjectLoader<Animation>(a, 0)
497 {
498         init();
499 }
500
501 Animation::Loader::Loader(Animation &a, Collection &c):
502         DataFile::CollectionObjectLoader<Animation>(a, &c)
503 {
504         init();
505 }
506
507 void Animation::Loader::init()
508 {
509         start_slope = 1;
510         end_slope = 1;
511         slopes_set = 0;
512         add("armature", &Animation::armature);
513         add("control_keyframe", &Loader::control_keyframe);
514         add("control_keyframe", &Loader::control_keyframe_inline);
515         add("event", &Loader::event);
516         add("event", &Loader::event1i);
517         add("event", &Loader::event1f);
518         add("event", &Loader::event2f);
519         add("event", &Loader::event3f);
520         add("event", &Loader::event4f);
521         add("interval", &Loader::interval);
522         add("keyframe", &Loader::keyframe);
523         add("keyframe", &Loader::keyframe_inline);
524         add("looping", &Animation::looping);
525         add("slopes", &Loader::slopes);
526 }
527
528 void Animation::Loader::finish()
529 {
530         obj.create_curves();
531 }
532
533 void Animation::Loader::check_slopes_and_control(bool s, bool c)
534 {
535         if(s && c)
536                 throw logic_error("can't use both slopes and control keyframes in same segment");
537 }
538
539 void Animation::Loader::add_kf(const KeyFrame *kf, bool c, bool owned)
540 {
541         if(slopes_set && !c)
542                 obj.add_keyframe(current_time, kf, start_slope, end_slope, owned);
543         else
544                 obj.add_keyframe(current_time, kf, c, owned);
545
546         start_slope = end_slope;
547         end_slope = 1;
548         slopes_set = (slopes_set<<1)&3;
549 }
550
551 void Animation::Loader::load_kf(const string &n, bool c)
552 {
553         add_kf(&get_collection().get<KeyFrame>(n), c, false);
554 }
555
556 void Animation::Loader::load_kf_inline(bool c)
557 {
558         RefPtr<KeyFrame> kf = new KeyFrame;
559         if(coll)
560         {
561                 KeyFrame::Loader ldr(*kf, get_collection());
562                 ldr.set_inline_base_name(format("%s/%d.kframe", FS::basename(get_source()), obj.keyframes.size()));
563                 load_sub_with(ldr);
564         }
565         else
566                 load_sub(*kf);
567
568         add_kf(kf.get(), c, true);
569         kf.release();
570 }
571
572 void Animation::Loader::control_keyframe(const string &n)
573 {
574         slopes_set &= 1;
575         check_slopes_and_control(slopes_set, true);
576         load_kf(n, true);
577 }
578
579 void Animation::Loader::control_keyframe_inline()
580 {
581         slopes_set &= 1;
582         check_slopes_and_control(slopes_set, true);
583         load_kf_inline(true);
584 }
585
586 void Animation::Loader::event(const string &n)
587 {
588         obj.add_event(current_time, n);
589 }
590
591 void Animation::Loader::event1i(const string &n, int v)
592 {
593         obj.add_event(current_time, n, v);
594 }
595
596 void Animation::Loader::event1f(const string &n, float v)
597 {
598         obj.add_event(current_time, n, v);
599 }
600
601 void Animation::Loader::event2f(const string &n, float v0, float v1)
602 {
603         obj.add_event(current_time, n, LinAl::Vector<float, 2>(v0, v1));
604 }
605
606 void Animation::Loader::event3f(const string &n, float v0, float v1, float v2)
607 {
608         obj.add_event(current_time, n, Vector3(v0, v1, v2));
609 }
610
611 void Animation::Loader::event4f(const string &n, float v0, float v1, float v2, float v3)
612 {
613         obj.add_event(current_time, n, Vector4(v0, v1, v2, v3));
614 }
615
616 void Animation::Loader::interval(float t)
617 {
618         current_time += t*Time::sec;
619 }
620
621 void Animation::Loader::keyframe(const string &n)
622 {
623         load_kf(n, false);
624 }
625
626 void Animation::Loader::keyframe_inline()
627 {
628         load_kf_inline(false);
629 }
630
631 void Animation::Loader::slopes(float s, float e)
632 {
633         check_slopes_and_control(true, (!obj.keyframes.empty() && obj.keyframes.back().control));
634
635         start_slope = s;
636         end_slope = e;
637         slopes_set = 1;
638 }
639
640 } // namespace GL
641 } // namespace Msp