1 | var lerp = require('lerp-array')
|
2 | var Property = require('./property')
|
3 |
|
4 | function indexOfName(list, name) {
|
5 | for (var i=0; i<list.length; i++)
|
6 | if (list[i].name === name)
|
7 | return i
|
8 | return -1
|
9 | }
|
10 |
|
11 | function TimelineBase(data) {
|
12 | if (!(this instanceof TimelineBase))
|
13 | return new TimelineBase(data)
|
14 |
|
15 | this.properties = []
|
16 |
|
17 | if (data)
|
18 | this.load(data)
|
19 | }
|
20 |
|
21 | TimelineBase.prototype.dispose = function() {
|
22 | this.properties.forEach(function(p) {
|
23 | p.dispose()
|
24 | })
|
25 | this.properties.length = 0
|
26 | }
|
27 |
|
28 | TimelineBase.prototype.addProperty = function(propData) {
|
29 | this.properties.push(new Property(propData))
|
30 | }
|
31 |
|
32 |
|
33 | TimelineBase.prototype.duration = function() {
|
34 | var maxTime = 0
|
35 | for (var j=0; j<this.properties.length; j++) {
|
36 | var prop = this.properties[j]
|
37 | var frames = prop.keyframes.frames
|
38 | for (var i=0; i<frames.length; i++)
|
39 | maxTime = Math.max(frames[i].time, maxTime)
|
40 | }
|
41 | return maxTime
|
42 | }
|
43 |
|
44 |
|
45 | TimelineBase.prototype.property = function(prop) {
|
46 | var idx = typeof prop === 'number' ? prop : indexOfName(this.properties, prop)
|
47 | return idx<0 ? undefined : this.properties[idx]
|
48 | }
|
49 |
|
50 |
|
51 | TimelineBase.prototype.load = function(data) {
|
52 | this.dispose()
|
53 |
|
54 | if (!data)
|
55 | return
|
56 |
|
57 | this.properties = data.map(function(d) {
|
58 | return new Property(d)
|
59 | })
|
60 | }
|
61 |
|
62 | TimelineBase.prototype.export = function() {
|
63 | return this.properties.map(function(p) {
|
64 | return p.export()
|
65 | })
|
66 | }
|
67 |
|
68 |
|
69 | TimelineBase.prototype.ease = function(name, t) {
|
70 | return t
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 | TimelineBase.prototype.interpolate = function(property, frame1, frame2, t) {
|
76 | return lerp(frame1.value, frame2.value, t)
|
77 | }
|
78 |
|
79 |
|
80 | TimelineBase.prototype.valueOf = function(time, property) {
|
81 | var keys = property.keyframes,
|
82 | v = keys.interpolation(time),
|
83 | v0 = v[0],
|
84 | v1 = v[1],
|
85 | t = v[2]
|
86 |
|
87 |
|
88 | if (v0 === -1 || v1 === -1)
|
89 | return property.value
|
90 |
|
91 | var start = keys.frames[v0],
|
92 | end = keys.frames[v1]
|
93 |
|
94 |
|
95 | if (v0 === v1)
|
96 | return start.value
|
97 |
|
98 |
|
99 | else {
|
100 | var easeName = end.ease
|
101 | if (easeName)
|
102 | t = this.ease(easeName, t)
|
103 | return this.interpolate(property, start, end, t)
|
104 | }
|
105 | }
|
106 |
|
107 |
|
108 | TimelineBase.prototype.values = function(time, out) {
|
109 | if (!out)
|
110 | out = {}
|
111 | for (var i=0; i<this.properties.length; i++) {
|
112 | var prop = this.properties[i]
|
113 | out[prop.name] = this.valueOf(time, prop)
|
114 | }
|
115 | return out
|
116 | }
|
117 |
|
118 | module.exports = TimelineBase |
\ | No newline at end of file |