1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "SkottieValue.h"
9 
10 #include "SkColor.h"
11 #include "SkottieJson.h"
12 #include "SkottiePriv.h"
13 #include "SkNx.h"
14 #include "SkPoint.h"
15 #include "SkSize.h"
16 
17 namespace  skottie {
18 
19 template <>
FromJSON(const skjson::Value & jv,const internal::AnimationBuilder *,ScalarValue * v)20 bool ValueTraits<ScalarValue>::FromJSON(const skjson::Value& jv, const internal::AnimationBuilder*,
21                                         ScalarValue* v) {
22     return Parse(jv, v);
23 }
24 
25 template <>
CanLerp(const ScalarValue &,const ScalarValue &)26 bool ValueTraits<ScalarValue>::CanLerp(const ScalarValue&, const ScalarValue&) {
27     return true;
28 }
29 
30 template <>
Lerp(const ScalarValue & v0,const ScalarValue & v1,float t,ScalarValue * result)31 void ValueTraits<ScalarValue>::Lerp(const ScalarValue& v0, const ScalarValue& v1, float t,
32                                     ScalarValue* result) {
33     SkASSERT(t >= 0 && t <= 1);
34     *result = v0 + (v1 - v0) * t;
35 }
36 
37 template <>
38 template <>
As(const ScalarValue & v)39 SkScalar ValueTraits<ScalarValue>::As<SkScalar>(const ScalarValue& v) {
40     return v;
41 }
42 
43 template <>
FromJSON(const skjson::Value & jv,const internal::AnimationBuilder *,VectorValue * v)44 bool ValueTraits<VectorValue>::FromJSON(const skjson::Value& jv, const internal::AnimationBuilder*,
45                                         VectorValue* v) {
46     return Parse(jv, v);
47 }
48 
49 template <>
CanLerp(const VectorValue & v1,const VectorValue & v2)50 bool ValueTraits<VectorValue>::CanLerp(const VectorValue& v1, const VectorValue& v2) {
51     return v1.size() == v2.size();
52 }
53 
54 template <>
Lerp(const VectorValue & v0,const VectorValue & v1,float t,VectorValue * result)55 void ValueTraits<VectorValue>::Lerp(const VectorValue& v0, const VectorValue& v1, float t,
56                                     VectorValue* result) {
57     SkASSERT(v0.size() == v1.size());
58 
59     result->resize(v0.size());
60 
61     for (size_t i = 0; i < v0.size(); ++i) {
62         ValueTraits<ScalarValue>::Lerp(v0[i], v1[i], t, &(*result)[i]);
63     }
64 }
65 
66 template <>
67 template <>
As(const VectorValue & v)68 SkColor ValueTraits<VectorValue>::As<SkColor>(const VectorValue& v) {
69     // best effort to turn this into a color
70     const auto r = v.size() > 0 ? v[0] : 0,
71                g = v.size() > 1 ? v[1] : 0,
72                b = v.size() > 2 ? v[2] : 0,
73                a = v.size() > 3 ? v[3] : 1;
74 
75     return SkColorSetARGB(SkScalarRoundToInt(SkTPin(a, 0.0f, 1.0f) * 255),
76                           SkScalarRoundToInt(SkTPin(r, 0.0f, 1.0f) * 255),
77                           SkScalarRoundToInt(SkTPin(g, 0.0f, 1.0f) * 255),
78                           SkScalarRoundToInt(SkTPin(b, 0.0f, 1.0f) * 255));
79 }
80 
81 template <>
82 template <>
As(const VectorValue & vec)83 SkPoint ValueTraits<VectorValue>::As<SkPoint>(const VectorValue& vec) {
84     // best effort to turn this into a point
85     const auto x = vec.size() > 0 ? vec[0] : 0,
86                y = vec.size() > 1 ? vec[1] : 0;
87     return SkPoint::Make(x, y);
88 }
89 
90 template <>
91 template <>
As(const VectorValue & vec)92 SkSize ValueTraits<VectorValue>::As<SkSize>(const VectorValue& vec) {
93     const auto pt = ValueTraits::As<SkPoint>(vec);
94     return SkSize::Make(pt.x(), pt.y());
95 }
96 
97 namespace {
98 
ParsePointVec(const skjson::Value & jv,std::vector<SkPoint> * pts)99 bool ParsePointVec(const skjson::Value& jv, std::vector<SkPoint>* pts) {
100     if (!jv.is<skjson::ArrayValue>())
101         return false;
102     const auto& av = jv.as<skjson::ArrayValue>();
103 
104     pts->clear();
105     pts->reserve(av.size());
106 
107     std::vector<float> vec;
108     for (size_t i = 0; i < av.size(); ++i) {
109         if (!Parse(av[i], &vec) || vec.size() != 2)
110             return false;
111         pts->push_back(SkPoint::Make(vec[0], vec[1]));
112     }
113 
114     return true;
115 }
116 
117 } // namespace
118 
119 template <>
FromJSON(const skjson::Value & jv,const internal::AnimationBuilder * abuilder,ShapeValue * v)120 bool ValueTraits<ShapeValue>::FromJSON(const skjson::Value& jv,
121                                        const internal::AnimationBuilder* abuilder,
122                                        ShapeValue* v) {
123     SkASSERT(v->fVertices.empty());
124 
125     // Some versions wrap values as single-element arrays.
126     if (const skjson::ArrayValue* av = jv) {
127         if (av->size() == 1) {
128             return FromJSON((*av)[0], abuilder, v);
129         }
130     }
131 
132     if (!jv.is<skjson::ObjectValue>())
133         return false;
134     const auto& ov = jv.as<skjson::ObjectValue>();
135 
136     std::vector<SkPoint> verts,  // Cubic Bezier vertices.
137                          inPts,  // Cubic Bezier "in" control points, relative to vertices.
138                          outPts; // Cubic Bezier "out" control points, relative to vertices.
139 
140     if (!ParsePointVec(ov["v"], &verts)) {
141         // Vertices are required.
142         return false;
143     }
144 
145     // In/out points are optional.
146     ParsePointVec(ov["i"], &inPts);
147     if (!inPts.empty() && inPts.size() != verts.size()) {
148         return false;
149     }
150     inPts.resize(verts.size(), { 0, 0 });
151 
152     ParsePointVec(ov["o"], &outPts);
153     if (!outPts.empty() && outPts.size() != verts.size()) {
154         return false;
155     }
156     outPts.resize(verts.size(), { 0, 0 });
157 
158     v->fVertices.reserve(inPts.size());
159     for (size_t i = 0; i < inPts.size(); ++i) {
160         v->fVertices.push_back(BezierVertex({inPts[i], outPts[i], verts[i]}));
161     }
162     v->fClosed = ParseDefault<bool>(ov["c"], false);
163 
164     return true;
165 }
166 
167 template <>
CanLerp(const ShapeValue & v1,const ShapeValue & v2)168 bool ValueTraits<ShapeValue>::CanLerp(const ShapeValue& v1, const ShapeValue& v2) {
169     return v1.fVertices.size() == v2.fVertices.size()
170         && v1.fClosed == v2.fClosed;
171 }
172 
lerp_point(const SkPoint & v0,const SkPoint & v1,const Sk2f & t)173 static SkPoint lerp_point(const SkPoint& v0, const SkPoint& v1, const Sk2f& t) {
174     const auto v2f0 = Sk2f::Load(&v0),
175                v2f1 = Sk2f::Load(&v1);
176 
177     SkPoint v;
178     (v2f0 + (v2f1 - v2f0) * t).store(&v);
179 
180     return v;
181 }
182 
183 template <>
Lerp(const ShapeValue & v0,const ShapeValue & v1,float t,ShapeValue * result)184 void ValueTraits<ShapeValue>::Lerp(const ShapeValue& v0, const ShapeValue& v1, float t,
185                                    ShapeValue* result) {
186     SkASSERT(t >= 0 && t <= 1);
187     SkASSERT(v0.fVertices.size() == v1.fVertices.size());
188     SkASSERT(v0.fClosed == v1.fClosed);
189 
190     result->fClosed = v0.fClosed;
191     result->fVolatile = true; // interpolated values are volatile
192 
193     const auto t2f = Sk2f(t);
194     result->fVertices.resize(v0.fVertices.size());
195 
196     for (size_t i = 0; i < v0.fVertices.size(); ++i) {
197         result->fVertices[i] = BezierVertex({
198             lerp_point(v0.fVertices[i].fInPoint , v1.fVertices[i].fInPoint , t2f),
199             lerp_point(v0.fVertices[i].fOutPoint, v1.fVertices[i].fOutPoint, t2f),
200             lerp_point(v0.fVertices[i].fVertex  , v1.fVertices[i].fVertex  , t2f)
201         });
202     }
203 }
204 
205 template <>
206 template <>
As(const ShapeValue & shape)207 SkPath ValueTraits<ShapeValue>::As<SkPath>(const ShapeValue& shape) {
208     SkPath path;
209 
210     if (!shape.fVertices.empty()) {
211         // conservatively assume all cubics
212         path.incReserve(1 + SkToU32(shape.fVertices.size() * 3));
213 
214         path.moveTo(shape.fVertices.front().fVertex);
215     }
216 
217     const auto& addCubic = [&](size_t from, size_t to) {
218         const auto c0 = shape.fVertices[from].fVertex + shape.fVertices[from].fOutPoint,
219                    c1 = shape.fVertices[to].fVertex   + shape.fVertices[to].fInPoint;
220 
221         if (c0 == shape.fVertices[from].fVertex &&
222             c1 == shape.fVertices[to].fVertex) {
223             // If the control points are coincident, we can power-reduce to a straight line.
224             // TODO: we could also do that when the controls are on the same line as the
225             //       vertices, but it's unclear how common that case is.
226             path.lineTo(shape.fVertices[to].fVertex);
227         } else {
228             path.cubicTo(c0, c1, shape.fVertices[to].fVertex);
229         }
230     };
231 
232     for (size_t i = 1; i < shape.fVertices.size(); ++i) {
233         addCubic(i - 1, i);
234     }
235 
236     if (!shape.fVertices.empty() && shape.fClosed) {
237         addCubic(shape.fVertices.size() - 1, 0);
238         path.close();
239     }
240 
241     path.setIsVolatile(shape.fVolatile);
242     path.shrinkToFit();
243 
244     return path;
245 }
246 
247 template <>
FromJSON(const skjson::Value & jv,const internal::AnimationBuilder * abuilder,TextValue * v)248 bool ValueTraits<TextValue>::FromJSON(const skjson::Value& jv,
249                                        const internal::AnimationBuilder* abuilder,
250                                        TextValue* v) {
251     const skjson::ObjectValue* jtxt = jv;
252     if (!jtxt) {
253         return false;
254     }
255 
256     const skjson::StringValue* font_name = (*jtxt)["f"];
257     const skjson::StringValue* text      = (*jtxt)["t"];
258     const skjson::NumberValue* text_size = (*jtxt)["s"];
259     if (!font_name || !text || !text_size ||
260         !(v->fTypeface = abuilder->findFont(SkString(font_name->begin(), font_name->size())))) {
261         return false;
262     }
263     v->fText.set(text->begin(), text->size());
264     v->fTextSize = **text_size;
265 
266     static constexpr SkTextUtils::Align gAlignMap[] = {
267         SkTextUtils::kLeft_Align,  // 'j': 0
268         SkTextUtils::kRight_Align, // 'j': 1
269         SkTextUtils::kCenter_Align // 'j': 2
270     };
271     v->fAlign = gAlignMap[SkTMin<size_t>(ParseDefault<size_t>((*jtxt)["j"], 0),
272                                          SK_ARRAY_COUNT(gAlignMap))];
273 
274     const auto& parse_color = [] (const skjson::ArrayValue* jcolor,
275                                   const internal::AnimationBuilder* abuilder,
276                                   SkColor* c) {
277         if (!jcolor) {
278             return false;
279         }
280 
281         VectorValue color_vec;
282         if (!ValueTraits<VectorValue>::FromJSON(*jcolor, abuilder, &color_vec)) {
283             return false;
284         }
285 
286         *c = ValueTraits<VectorValue>::As<SkColor>(color_vec);
287         return true;
288     };
289 
290     v->fHasFill   = parse_color((*jtxt)["fc"], abuilder, &v->fFillColor);
291     v->fHasStroke = parse_color((*jtxt)["sc"], abuilder, &v->fStrokeColor);
292 
293     if (v->fHasStroke) {
294         v->fStrokeWidth = ParseDefault((*jtxt)["s"], 0.0f);
295     }
296 
297     return true;
298 }
299 
300 template <>
CanLerp(const TextValue &,const TextValue &)301 bool ValueTraits<TextValue>::CanLerp(const TextValue&, const TextValue&) {
302     // Text values are never interpolated, but we pretend that they could be.
303     return true;
304 }
305 
306 template <>
Lerp(const TextValue & v0,const TextValue &,float,TextValue * result)307 void ValueTraits<TextValue>::Lerp(const TextValue& v0, const TextValue&, float, TextValue* result) {
308     // Text value keyframes are treated as selectors, not as interpolated values.
309     *result = v0;
310 }
311 
312 } // namespace skottie
313