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