Add easing curves to animations.
[kaya.git] / lib / animation_field.rb
blobc3f9247b0f8439653f5e0b9d5438461d4178b26e
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 require 'toolkit'
10 module AnimationBase
11   attr_reader :name
13   def to_s
14     "#<#{self.class.name}:#{name}>"
15   end
16 end
18 class Animation
19   include AnimationBase
21   def initialize(name, &blk)
22     @name = name
23     @anim = blk
24   end
26   def [](t)
27     @anim[t]
28   end
29 end
31 class SimpleAnimation
32   include AnimationBase
34   def initialize(name, length, before, animation, after = nil, opts = { })
35     @name = name
36     @length = length
37     @animation = animation
38     @before = before
39     @after = after
40     @start = nil
41     if opts[:easing]
42       @easing = opts[:easing]
43     else
44       @easing = Qt::EasingCurve.new(Qt::EasingCurve::Linear)
45     end
46   end
48   def [](t)
49     unless @start
50       @start = t
51       @before[] if @before
52     end
54     i = (t - @start).to_f / @length
55     i = @easing.valueForProgress(i)
56     @animation[i]
57     if i >= 1.0
58       @after[] if @after
59       @start = nil
60       return true
61     end
63     return false
64   end
65 end
68 class AnimationField
69   def initialize(interval, timer_class = Qt::Timer)
70     @actions = []
71     @timer = timer_class.every(interval) {|t| tick(t) }
72     @ticks = 0
73   end
75   def tick(t)
76     @ticks += 1
77     @actions.reject! do |action|
78       action[t]
79     end
80   end
82   def run(action)
83     if action
84       @actions << action
85     end
86   end
87 end