-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanimator.rb
More file actions
95 lines (77 loc) · 1.89 KB
/
animator.rb
File metadata and controls
95 lines (77 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Animator
attr_reader :led_string, :led_count, :pattern, :current_frame
DEFAULT_OPTIONS = {
pattern: [[0,0,0]] # this could be improved...
}
def initialize led_string, options={}
options = DEFAULT_OPTIONS.merge options
self.led_string = led_string
self.pattern = options[:pattern]
end
def pattern= pattern
@frame_index = -1
@pattern = pattern
@pattern_is_not_series_of_frames = !(@pattern.first.is_a?(Array) && @pattern.first.first.is_a?(Array))
next_frame
nil
end
def led_string= led_string
@led_string = led_string
end
def next_frame
_next_frame :forward
end
def next_frame!
_next_frame! :forward
end
def previous_frame
_next_frame :backward
end
def previous_frame!
_next_frame! :backward
end
def display!
@led_string.leds = @current_frame
@led_string.sync!
end
def play!(fps=30)
loop(fps) do |_|
_.next_frame!
end
end
def rewind!(fps=30)
loop(fps) do |_|
_.previous_frame!
end
end
def reset!
@frame_index = -1
next_frame!
end
def loop(fps=30) # block
raise Error("Can't loop without block!") unless block_given?
delay = 1.0 / fps
while true
yield(self)
sleep delay
end
end
private
def _next_frame! direction
_next_frame direction
display!
end
def _next_frame direction
if direction == :forward
@frame_index = (@frame_index + 1) % @pattern.length
elsif direction == :backward
@frame_index = @frame_index - 1 < 0 ? @pattern.length - 1 : @frame_index - 1
end
if @pattern_is_not_series_of_frames #in this case we just slide rotate by the frame index and whatever
@current_frame = (@pattern * (@led_string.led_count * 1.0 / @pattern.length).ceil).rotate(@frame_index).first @led_string.led_count
else
@current_frame = @pattern[@frame_index]
end
@current_frame
end
end