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