blob: 1ec461423d69661fdc29d85f0f56c6ecc10ff397 [file] [log] [blame]
Florin Malita094ccde2017-12-30 12:27:00 -05001/*
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
Florin Malita54f65c42018-01-16 17:04:30 -05008#include "Skottie.h"
Florin Malita094ccde2017-12-30 12:27:00 -05009
10#include "SkCanvas.h"
Florin Malitafc807c82018-01-25 22:35:09 -050011#include "SkJSONCPP.h"
Florin Malita54f65c42018-01-16 17:04:30 -050012#include "SkottieAnimator.h"
Florin Malitacf8ed522018-01-25 15:27:33 -050013#include "SkottieParser.h"
Florin Malita54f65c42018-01-16 17:04:30 -050014#include "SkottieProperties.h"
Florin Malita094ccde2017-12-30 12:27:00 -050015#include "SkData.h"
Florin Malita49328072018-01-08 12:51:12 -050016#include "SkImage.h"
Florin Malita094ccde2017-12-30 12:27:00 -050017#include "SkMakeUnique.h"
Florin Malita49328072018-01-08 12:51:12 -050018#include "SkOSPath.h"
Florin Malita094ccde2017-12-30 12:27:00 -050019#include "SkPaint.h"
Florin Malita0e66fba2018-01-09 17:10:18 -050020#include "SkParse.h"
Florin Malita094ccde2017-12-30 12:27:00 -050021#include "SkPath.h"
22#include "SkPoint.h"
23#include "SkSGColor.h"
24#include "SkSGDraw.h"
Florin Malita16d0ad02018-01-19 15:07:29 -050025#include "SkSGGeometryTransform.h"
Florin Malita6aaee592018-01-12 12:25:09 -050026#include "SkSGGradient.h"
Florin Malita094ccde2017-12-30 12:27:00 -050027#include "SkSGGroup.h"
Florin Malita49328072018-01-08 12:51:12 -050028#include "SkSGImage.h"
29#include "SkSGInvalidationController.h"
Florin Malita5f9102f2018-01-10 13:36:22 -050030#include "SkSGMaskEffect.h"
Florin Malitae6345d92018-01-03 23:37:54 -050031#include "SkSGMerge.h"
Florin Malitac0034172018-01-08 16:42:59 -050032#include "SkSGOpacityEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050033#include "SkSGPath.h"
Florin Malita2e1d7e22018-01-02 10:40:00 -050034#include "SkSGRect.h"
Florin Malita35efaa82018-01-22 12:57:06 -050035#include "SkSGScene.h"
Florin Malita094ccde2017-12-30 12:27:00 -050036#include "SkSGTransform.h"
Florin Malita51b8c892018-01-07 08:54:24 -050037#include "SkSGTrimEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050038#include "SkStream.h"
39#include "SkTArray.h"
40#include "SkTHash.h"
41
42#include <cmath>
Florin Malitae6345d92018-01-03 23:37:54 -050043#include <vector>
44
Florin Malita094ccde2017-12-30 12:27:00 -050045#include "stdlib.h"
46
Florin Malita54f65c42018-01-16 17:04:30 -050047namespace skottie {
Florin Malita094ccde2017-12-30 12:27:00 -050048
Florin Malitacf8ed522018-01-25 15:27:33 -050049#define LOG SkDebugf
50
Florin Malita094ccde2017-12-30 12:27:00 -050051namespace {
52
Florin Malitadd22cf962018-01-29 15:42:01 +000053using AssetMap = SkTHashMap<SkString, const Json::Value*>;
Florin Malita094ccde2017-12-30 12:27:00 -050054
55struct AttachContext {
Florin Malita35efaa82018-01-22 12:57:06 -050056 const ResourceProvider& fResources;
57 const AssetMap& fAssets;
58 sksg::Scene::AnimatorList& fAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -050059};
60
61bool LogFail(const Json::Value& json, const char* msg) {
62 const auto dump = json.toStyledString();
63 LOG("!! %s: %s", msg, dump.c_str());
64 return false;
65}
66
Florin Malita18eafd92018-01-04 21:11:55 -050067sk_sp<sksg::Matrix> AttachMatrix(const Json::Value& t, AttachContext* ctx,
68 sk_sp<sksg::Matrix> parentMatrix) {
69 if (!t.isObject())
70 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -050071
Florin Malita18eafd92018-01-04 21:11:55 -050072 auto matrix = sksg::Matrix::Make(SkMatrix::I(), std::move(parentMatrix));
73 auto composite = sk_make_sp<CompositeTransform>(matrix);
Florin Malitafc807c82018-01-25 22:35:09 -050074 auto anchor_attached = BindProperty<VectorValue>(t["a"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050075 [composite](const VectorValue& a) {
76 composite->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
Florin Malita094ccde2017-12-30 12:27:00 -050077 });
Florin Malitafc807c82018-01-25 22:35:09 -050078 auto position_attached = BindProperty<VectorValue>(t["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050079 [composite](const VectorValue& p) {
80 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malita094ccde2017-12-30 12:27:00 -050081 });
Florin Malitafc807c82018-01-25 22:35:09 -050082 auto scale_attached = BindProperty<VectorValue>(t["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050083 [composite](const VectorValue& s) {
84 composite->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
Florin Malita094ccde2017-12-30 12:27:00 -050085 });
Florin Malita1eb98db2018-01-26 15:03:38 -050086
87 auto* jrotation = &t["r"];
88 if (jrotation->isNull()) {
89 // 3d rotations have separate rx,ry,rz components. While we don't fully support them,
90 // we can still make use of rz.
91 jrotation = &t["rz"];
92 }
93 auto rotation_attached = BindProperty<ScalarValue>(*jrotation, &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050094 [composite](const ScalarValue& r) {
95 composite->setRotation(r);
Florin Malita094ccde2017-12-30 12:27:00 -050096 });
Florin Malitafc807c82018-01-25 22:35:09 -050097 auto skew_attached = BindProperty<ScalarValue>(t["sk"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050098 [composite](const ScalarValue& sk) {
99 composite->setSkew(sk);
Florin Malita094ccde2017-12-30 12:27:00 -0500100 });
Florin Malitafc807c82018-01-25 22:35:09 -0500101 auto skewaxis_attached = BindProperty<ScalarValue>(t["sa"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500102 [composite](const ScalarValue& sa) {
103 composite->setSkewAxis(sa);
Florin Malita094ccde2017-12-30 12:27:00 -0500104 });
105
106 if (!anchor_attached &&
107 !position_attached &&
108 !scale_attached &&
109 !rotation_attached &&
110 !skew_attached &&
111 !skewaxis_attached) {
112 LogFail(t, "Could not parse transform");
Florin Malita18eafd92018-01-04 21:11:55 -0500113 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500114 }
115
Florin Malita18eafd92018-01-04 21:11:55 -0500116 return matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500117}
118
Florin Malitac0034172018-01-08 16:42:59 -0500119sk_sp<sksg::RenderNode> AttachOpacity(const Json::Value& jtransform, AttachContext* ctx,
120 sk_sp<sksg::RenderNode> childNode) {
121 if (!jtransform.isObject() || !childNode)
122 return childNode;
123
124 // This is more peeky than other attachers, because we want to avoid redundant opacity
125 // nodes for the extremely common case of static opaciy == 100.
126 const auto& opacity = jtransform["o"];
127 if (opacity.isObject() &&
Florin Malitacf8ed522018-01-25 15:27:33 -0500128 !ParseDefault(opacity["a"], true) &&
129 ParseDefault(opacity["k"], -1) == 100) {
Florin Malitac0034172018-01-08 16:42:59 -0500130 // Ignoring static full opacity.
131 return childNode;
132 }
133
134 auto opacityNode = sksg::OpacityEffect::Make(childNode);
Florin Malitafc807c82018-01-25 22:35:09 -0500135 BindProperty<ScalarValue>(opacity, &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500136 [opacityNode](const ScalarValue& o) {
Florin Malitac0034172018-01-08 16:42:59 -0500137 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500138 opacityNode->setOpacity(o * 0.01f);
Florin Malitac0034172018-01-08 16:42:59 -0500139 });
140
141 return opacityNode;
142}
143
Florin Malita094ccde2017-12-30 12:27:00 -0500144sk_sp<sksg::RenderNode> AttachComposition(const Json::Value&, AttachContext* ctx);
145
Florin Malita25366fa2018-01-23 13:37:59 -0500146sk_sp<sksg::Path> AttachPath(const Json::Value& jpath, AttachContext* ctx) {
147 auto path_node = sksg::Path::Make();
Florin Malitafc807c82018-01-25 22:35:09 -0500148 return BindProperty<ShapeValue>(jpath, &ctx->fAnimators,
149 [path_node](const ShapeValue& p) { path_node->setPath(p); })
Florin Malita25366fa2018-01-23 13:37:59 -0500150 ? path_node
151 : nullptr;
152}
153
Florin Malita094ccde2017-12-30 12:27:00 -0500154sk_sp<sksg::GeometryNode> AttachPathGeometry(const Json::Value& jpath, AttachContext* ctx) {
155 SkASSERT(jpath.isObject());
156
Florin Malita25366fa2018-01-23 13:37:59 -0500157 return AttachPath(jpath["ks"], ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500158}
159
Florin Malita2e1d7e22018-01-02 10:40:00 -0500160sk_sp<sksg::GeometryNode> AttachRRectGeometry(const Json::Value& jrect, AttachContext* ctx) {
161 SkASSERT(jrect.isObject());
162
163 auto rect_node = sksg::RRect::Make();
164 auto composite = sk_make_sp<CompositeRRect>(rect_node);
165
Florin Malitafc807c82018-01-25 22:35:09 -0500166 auto p_attached = BindProperty<VectorValue>(jrect["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500167 [composite](const VectorValue& p) {
168 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500169 });
Florin Malitafc807c82018-01-25 22:35:09 -0500170 auto s_attached = BindProperty<VectorValue>(jrect["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500171 [composite](const VectorValue& s) {
172 composite->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
Florin Malitaf9590922018-01-09 11:56:09 -0500173 });
Florin Malitafc807c82018-01-25 22:35:09 -0500174 auto r_attached = BindProperty<ScalarValue>(jrect["r"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500175 [composite](const ScalarValue& r) {
176 composite->setRadius(SkSize::Make(r, r));
Florin Malitaf9590922018-01-09 11:56:09 -0500177 });
Florin Malita2e1d7e22018-01-02 10:40:00 -0500178
179 if (!p_attached && !s_attached && !r_attached) {
180 return nullptr;
181 }
182
Florin Malitafbc13f12018-01-04 10:26:35 -0500183 return rect_node;
184}
185
186sk_sp<sksg::GeometryNode> AttachEllipseGeometry(const Json::Value& jellipse, AttachContext* ctx) {
187 SkASSERT(jellipse.isObject());
188
189 auto rect_node = sksg::RRect::Make();
190 auto composite = sk_make_sp<CompositeRRect>(rect_node);
191
Florin Malitafc807c82018-01-25 22:35:09 -0500192 auto p_attached = BindProperty<VectorValue>(jellipse["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500193 [composite](const VectorValue& p) {
194 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500195 });
Florin Malitafc807c82018-01-25 22:35:09 -0500196 auto s_attached = BindProperty<VectorValue>(jellipse["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500197 [composite](const VectorValue& s) {
Florin Malitaf9590922018-01-09 11:56:09 -0500198 const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
Florin Malita2518a0a2018-01-24 18:29:00 -0500199 composite->setSize(sz);
200 composite->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
Florin Malitaf9590922018-01-09 11:56:09 -0500201 });
Florin Malitafbc13f12018-01-04 10:26:35 -0500202
203 if (!p_attached && !s_attached) {
204 return nullptr;
205 }
206
Florin Malita2e1d7e22018-01-02 10:40:00 -0500207 return rect_node;
208}
209
Florin Malita02a32b02018-01-04 11:27:09 -0500210sk_sp<sksg::GeometryNode> AttachPolystarGeometry(const Json::Value& jstar, AttachContext* ctx) {
211 SkASSERT(jstar.isObject());
212
213 static constexpr CompositePolyStar::Type gTypes[] = {
214 CompositePolyStar::Type::kStar, // "sy": 1
215 CompositePolyStar::Type::kPoly, // "sy": 2
216 };
217
Florin Malitacf8ed522018-01-25 15:27:33 -0500218 const auto type = ParseDefault(jstar["sy"], 0) - 1;
Florin Malita02a32b02018-01-04 11:27:09 -0500219 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gTypes))) {
220 LogFail(jstar, "Unknown polystar type");
221 return nullptr;
222 }
223
224 auto path_node = sksg::Path::Make();
225 auto composite = sk_make_sp<CompositePolyStar>(path_node, gTypes[type]);
226
Florin Malitafc807c82018-01-25 22:35:09 -0500227 BindProperty<VectorValue>(jstar["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500228 [composite](const VectorValue& p) {
229 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500230 });
Florin Malitafc807c82018-01-25 22:35:09 -0500231 BindProperty<ScalarValue>(jstar["pt"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500232 [composite](const ScalarValue& pt) {
233 composite->setPointCount(pt);
Florin Malitaf9590922018-01-09 11:56:09 -0500234 });
Florin Malitafc807c82018-01-25 22:35:09 -0500235 BindProperty<ScalarValue>(jstar["ir"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500236 [composite](const ScalarValue& ir) {
237 composite->setInnerRadius(ir);
Florin Malitaf9590922018-01-09 11:56:09 -0500238 });
Florin Malitafc807c82018-01-25 22:35:09 -0500239 BindProperty<ScalarValue>(jstar["or"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500240 [composite](const ScalarValue& otr) {
241 composite->setOuterRadius(otr);
Florin Malita9661b982018-01-06 14:25:49 -0500242 });
Florin Malitafc807c82018-01-25 22:35:09 -0500243 BindProperty<ScalarValue>(jstar["is"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500244 [composite](const ScalarValue& is) {
245 composite->setInnerRoundness(is);
Florin Malita9661b982018-01-06 14:25:49 -0500246 });
Florin Malitafc807c82018-01-25 22:35:09 -0500247 BindProperty<ScalarValue>(jstar["os"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500248 [composite](const ScalarValue& os) {
249 composite->setOuterRoundness(os);
Florin Malita9661b982018-01-06 14:25:49 -0500250 });
Florin Malitafc807c82018-01-25 22:35:09 -0500251 BindProperty<ScalarValue>(jstar["r"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500252 [composite](const ScalarValue& r) {
253 composite->setRotation(r);
Florin Malitaf9590922018-01-09 11:56:09 -0500254 });
Florin Malita02a32b02018-01-04 11:27:09 -0500255
256 return path_node;
257}
258
Florin Malita6aaee592018-01-12 12:25:09 -0500259sk_sp<sksg::Color> AttachColor(const Json::Value& obj, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500260 SkASSERT(obj.isObject());
261
262 auto color_node = sksg::Color::Make(SK_ColorBLACK);
Florin Malitafc807c82018-01-25 22:35:09 -0500263 auto color_attached = BindProperty<VectorValue>(obj["c"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500264 [color_node](const VectorValue& c) {
265 color_node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
Florin Malitaf9590922018-01-09 11:56:09 -0500266 });
Florin Malita094ccde2017-12-30 12:27:00 -0500267
Florin Malita1586d852018-01-12 14:27:39 -0500268 return color_attached ? color_node : nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500269}
270
Florin Malita6aaee592018-01-12 12:25:09 -0500271sk_sp<sksg::Gradient> AttachGradient(const Json::Value& obj, AttachContext* ctx) {
272 SkASSERT(obj.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500273
Florin Malita6aaee592018-01-12 12:25:09 -0500274 const auto& stops = obj["g"];
275 if (!stops.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500276 return nullptr;
277
Florin Malitacf8ed522018-01-25 15:27:33 -0500278 const auto stopCount = ParseDefault(stops["p"], -1);
Florin Malita6aaee592018-01-12 12:25:09 -0500279 if (stopCount < 0)
280 return nullptr;
281
282 sk_sp<sksg::Gradient> gradient_node;
283 sk_sp<CompositeGradient> composite;
284
Florin Malitacf8ed522018-01-25 15:27:33 -0500285 if (ParseDefault(obj["t"], 1) == 1) {
Florin Malita6aaee592018-01-12 12:25:09 -0500286 auto linear_node = sksg::LinearGradient::Make();
287 composite = sk_make_sp<CompositeLinearGradient>(linear_node, stopCount);
288 gradient_node = std::move(linear_node);
289 } else {
290 auto radial_node = sksg::RadialGradient::Make();
291 composite = sk_make_sp<CompositeRadialGradient>(radial_node, stopCount);
292
293 // TODO: highlight, angle
294 gradient_node = std::move(radial_node);
295 }
296
Florin Malitafc807c82018-01-25 22:35:09 -0500297 BindProperty<VectorValue>(stops["k"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500298 [composite](const VectorValue& stops) {
299 composite->setColorStops(stops);
Florin Malita6aaee592018-01-12 12:25:09 -0500300 });
Florin Malitafc807c82018-01-25 22:35:09 -0500301 BindProperty<VectorValue>(obj["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500302 [composite](const VectorValue& s) {
303 composite->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
Florin Malita6aaee592018-01-12 12:25:09 -0500304 });
Florin Malitafc807c82018-01-25 22:35:09 -0500305 BindProperty<VectorValue>(obj["e"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500306 [composite](const VectorValue& e) {
307 composite->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
Florin Malita6aaee592018-01-12 12:25:09 -0500308 });
309
310 return gradient_node;
311}
312
Florin Malita1586d852018-01-12 14:27:39 -0500313sk_sp<sksg::PaintNode> AttachPaint(const Json::Value& jpaint, AttachContext* ctx,
Florin Malita6aaee592018-01-12 12:25:09 -0500314 sk_sp<sksg::PaintNode> paint_node) {
315 if (paint_node) {
316 paint_node->setAntiAlias(true);
317
Florin Malitafc807c82018-01-25 22:35:09 -0500318 BindProperty<ScalarValue>(jpaint["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500319 [paint_node](const ScalarValue& o) {
Florin Malita1586d852018-01-12 14:27:39 -0500320 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500321 paint_node->setOpacity(o * 0.01f);
Florin Malita1586d852018-01-12 14:27:39 -0500322 });
Florin Malita6aaee592018-01-12 12:25:09 -0500323 }
324
325 return paint_node;
326}
327
328sk_sp<sksg::PaintNode> AttachStroke(const Json::Value& jstroke, AttachContext* ctx,
329 sk_sp<sksg::PaintNode> stroke_node) {
330 SkASSERT(jstroke.isObject());
331
332 if (!stroke_node)
333 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500334
335 stroke_node->setStyle(SkPaint::kStroke_Style);
336
Florin Malitafc807c82018-01-25 22:35:09 -0500337 auto width_attached = BindProperty<ScalarValue>(jstroke["w"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500338 [stroke_node](const ScalarValue& w) {
339 stroke_node->setStrokeWidth(w);
Florin Malitaf9590922018-01-09 11:56:09 -0500340 });
Florin Malita094ccde2017-12-30 12:27:00 -0500341 if (!width_attached)
342 return nullptr;
343
Florin Malitacf8ed522018-01-25 15:27:33 -0500344 stroke_node->setStrokeMiter(ParseDefault(jstroke["ml"], 4.0f));
Florin Malita094ccde2017-12-30 12:27:00 -0500345
346 static constexpr SkPaint::Join gJoins[] = {
347 SkPaint::kMiter_Join,
348 SkPaint::kRound_Join,
349 SkPaint::kBevel_Join,
350 };
Florin Malitacf8ed522018-01-25 15:27:33 -0500351 stroke_node->setStrokeJoin(gJoins[SkTPin<int>(ParseDefault(jstroke["lj"], 1) - 1,
Florin Malita094ccde2017-12-30 12:27:00 -0500352 0, SK_ARRAY_COUNT(gJoins) - 1)]);
353
354 static constexpr SkPaint::Cap gCaps[] = {
355 SkPaint::kButt_Cap,
356 SkPaint::kRound_Cap,
357 SkPaint::kSquare_Cap,
358 };
Florin Malitacf8ed522018-01-25 15:27:33 -0500359 stroke_node->setStrokeCap(gCaps[SkTPin<int>(ParseDefault(jstroke["lc"], 1) - 1,
Florin Malita094ccde2017-12-30 12:27:00 -0500360 0, SK_ARRAY_COUNT(gCaps) - 1)]);
361
362 return stroke_node;
363}
364
Florin Malita6aaee592018-01-12 12:25:09 -0500365sk_sp<sksg::PaintNode> AttachColorFill(const Json::Value& jfill, AttachContext* ctx) {
366 SkASSERT(jfill.isObject());
367
368 return AttachPaint(jfill, ctx, AttachColor(jfill, ctx));
369}
370
371sk_sp<sksg::PaintNode> AttachGradientFill(const Json::Value& jfill, AttachContext* ctx) {
372 SkASSERT(jfill.isObject());
373
374 return AttachPaint(jfill, ctx, AttachGradient(jfill, ctx));
375}
376
377sk_sp<sksg::PaintNode> AttachColorStroke(const Json::Value& jstroke, AttachContext* ctx) {
378 SkASSERT(jstroke.isObject());
379
380 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachColor(jstroke, ctx)));
381}
382
383sk_sp<sksg::PaintNode> AttachGradientStroke(const Json::Value& jstroke, AttachContext* ctx) {
384 SkASSERT(jstroke.isObject());
385
386 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachGradient(jstroke, ctx)));
387}
388
Florin Malitae6345d92018-01-03 23:37:54 -0500389std::vector<sk_sp<sksg::GeometryNode>> AttachMergeGeometryEffect(
390 const Json::Value& jmerge, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
391 std::vector<sk_sp<sksg::GeometryNode>> merged;
392
393 static constexpr sksg::Merge::Mode gModes[] = {
394 sksg::Merge::Mode::kMerge, // "mm": 1
395 sksg::Merge::Mode::kUnion, // "mm": 2
396 sksg::Merge::Mode::kDifference, // "mm": 3
397 sksg::Merge::Mode::kIntersect, // "mm": 4
398 sksg::Merge::Mode::kXOR , // "mm": 5
399 };
400
Florin Malitacf8ed522018-01-25 15:27:33 -0500401 const auto mode = gModes[SkTPin<int>(ParseDefault(jmerge["mm"], 1) - 1,
Florin Malita51b8c892018-01-07 08:54:24 -0500402 0, SK_ARRAY_COUNT(gModes) - 1)];
Florin Malitae6345d92018-01-03 23:37:54 -0500403 merged.push_back(sksg::Merge::Make(std::move(geos), mode));
404
Florin Malitae6345d92018-01-03 23:37:54 -0500405 return merged;
406}
407
Florin Malita51b8c892018-01-07 08:54:24 -0500408std::vector<sk_sp<sksg::GeometryNode>> AttachTrimGeometryEffect(
409 const Json::Value& jtrim, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
410
411 enum class Mode {
412 kMerged, // "m": 1
413 kSeparate, // "m": 2
414 } gModes[] = { Mode::kMerged, Mode::kSeparate };
415
Florin Malitacf8ed522018-01-25 15:27:33 -0500416 const auto mode = gModes[SkTPin<int>(ParseDefault(jtrim["m"], 1) - 1,
Florin Malita51b8c892018-01-07 08:54:24 -0500417 0, SK_ARRAY_COUNT(gModes) - 1)];
418
419 std::vector<sk_sp<sksg::GeometryNode>> inputs;
420 if (mode == Mode::kMerged) {
421 inputs.push_back(sksg::Merge::Make(std::move(geos), sksg::Merge::Mode::kMerge));
422 } else {
423 inputs = std::move(geos);
424 }
425
426 std::vector<sk_sp<sksg::GeometryNode>> trimmed;
427 trimmed.reserve(inputs.size());
428 for (const auto& i : inputs) {
429 const auto trim = sksg::TrimEffect::Make(i);
430 trimmed.push_back(trim);
Florin Malitafc807c82018-01-25 22:35:09 -0500431 BindProperty<ScalarValue>(jtrim["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500432 [trim](const ScalarValue& s) {
433 trim->setStart(s * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500434 });
Florin Malitafc807c82018-01-25 22:35:09 -0500435 BindProperty<ScalarValue>(jtrim["e"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500436 [trim](const ScalarValue& e) {
437 trim->setEnd(e * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500438 });
Florin Malitafc807c82018-01-25 22:35:09 -0500439 BindProperty<ScalarValue>(jtrim["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500440 [trim](const ScalarValue& o) {
441 trim->setOffset(o / 360);
Florin Malita51b8c892018-01-07 08:54:24 -0500442 });
443 }
444
445 return trimmed;
446}
447
Florin Malita094ccde2017-12-30 12:27:00 -0500448using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const Json::Value&, AttachContext*);
449static constexpr GeometryAttacherT gGeometryAttachers[] = {
450 AttachPathGeometry,
Florin Malita2e1d7e22018-01-02 10:40:00 -0500451 AttachRRectGeometry,
Florin Malitafbc13f12018-01-04 10:26:35 -0500452 AttachEllipseGeometry,
Florin Malita02a32b02018-01-04 11:27:09 -0500453 AttachPolystarGeometry,
Florin Malita094ccde2017-12-30 12:27:00 -0500454};
455
456using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const Json::Value&, AttachContext*);
457static constexpr PaintAttacherT gPaintAttachers[] = {
Florin Malita6aaee592018-01-12 12:25:09 -0500458 AttachColorFill,
459 AttachColorStroke,
460 AttachGradientFill,
461 AttachGradientStroke,
Florin Malita094ccde2017-12-30 12:27:00 -0500462};
463
Florin Malitae6345d92018-01-03 23:37:54 -0500464using GeometryEffectAttacherT =
465 std::vector<sk_sp<sksg::GeometryNode>> (*)(const Json::Value&,
466 AttachContext*,
467 std::vector<sk_sp<sksg::GeometryNode>>&&);
468static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
469 AttachMergeGeometryEffect,
Florin Malita51b8c892018-01-07 08:54:24 -0500470 AttachTrimGeometryEffect,
Florin Malitae6345d92018-01-03 23:37:54 -0500471};
472
Florin Malita094ccde2017-12-30 12:27:00 -0500473enum class ShapeType {
474 kGeometry,
Florin Malitae6345d92018-01-03 23:37:54 -0500475 kGeometryEffect,
Florin Malita094ccde2017-12-30 12:27:00 -0500476 kPaint,
477 kGroup,
Florin Malitadacc02b2017-12-31 09:12:31 -0500478 kTransform,
Florin Malita094ccde2017-12-30 12:27:00 -0500479};
480
481struct ShapeInfo {
482 const char* fTypeString;
483 ShapeType fShapeType;
484 uint32_t fAttacherIndex; // index into respective attacher tables
485};
486
487const ShapeInfo* FindShapeInfo(const Json::Value& shape) {
488 static constexpr ShapeInfo gShapeInfo[] = {
Florin Malitafbc13f12018-01-04 10:26:35 -0500489 { "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500490 { "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
491 { "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
Florin Malita16d0ad02018-01-19 15:07:29 -0500492 { "gr", ShapeType::kGroup , 0 }, // group -> Inline handler
Florin Malita6aaee592018-01-12 12:25:09 -0500493 { "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
Florin Malitae6345d92018-01-03 23:37:54 -0500494 { "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
Florin Malita02a32b02018-01-04 11:27:09 -0500495 { "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
Florin Malitae6345d92018-01-03 23:37:54 -0500496 { "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
Florin Malita02a32b02018-01-04 11:27:09 -0500497 { "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500498 { "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
Florin Malita51b8c892018-01-07 08:54:24 -0500499 { "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
Florin Malita16d0ad02018-01-19 15:07:29 -0500500 { "tr", ShapeType::kTransform , 0 }, // transform -> Inline handler
Florin Malita094ccde2017-12-30 12:27:00 -0500501 };
502
503 if (!shape.isObject())
504 return nullptr;
505
506 const auto& type = shape["ty"];
507 if (!type.isString())
508 return nullptr;
509
510 const auto* info = bsearch(type.asCString(),
511 gShapeInfo,
512 SK_ARRAY_COUNT(gShapeInfo),
513 sizeof(ShapeInfo),
514 [](const void* key, const void* info) {
515 return strcmp(static_cast<const char*>(key),
516 static_cast<const ShapeInfo*>(info)->fTypeString);
517 });
518
519 return static_cast<const ShapeInfo*>(info);
520}
521
Florin Malita16d0ad02018-01-19 15:07:29 -0500522struct GeometryEffectRec {
523 const Json::Value& fJson;
524 GeometryEffectAttacherT fAttach;
525};
526
Florin Malitaca4439f2018-01-23 10:31:59 -0500527struct AttachShapeContext {
528 AttachShapeContext(AttachContext* ctx,
529 std::vector<sk_sp<sksg::GeometryNode>>* geos,
530 std::vector<GeometryEffectRec>* effects,
531 size_t committedAnimators)
532 : fCtx(ctx)
533 , fGeometryStack(geos)
534 , fGeometryEffectStack(effects)
535 , fCommittedAnimators(committedAnimators) {}
536
537 AttachContext* fCtx;
538 std::vector<sk_sp<sksg::GeometryNode>>* fGeometryStack;
539 std::vector<GeometryEffectRec>* fGeometryEffectStack;
540 size_t fCommittedAnimators;
541};
542
543sk_sp<sksg::RenderNode> AttachShape(const Json::Value& jshape, AttachShapeContext* shapeCtx) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500544 if (!jshape.isArray())
Florin Malita094ccde2017-12-30 12:27:00 -0500545 return nullptr;
546
Florin Malitaca4439f2018-01-23 10:31:59 -0500547 SkDEBUGCODE(const auto initialGeometryEffects = shapeCtx->fGeometryEffectStack->size();)
Florin Malita094ccde2017-12-30 12:27:00 -0500548
Florin Malita16d0ad02018-01-19 15:07:29 -0500549 sk_sp<sksg::Group> shape_group = sksg::Group::Make();
550 sk_sp<sksg::RenderNode> shape_wrapper = shape_group;
551 sk_sp<sksg::Matrix> shape_matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500552
Florin Malita16d0ad02018-01-19 15:07:29 -0500553 struct ShapeRec {
554 const Json::Value& fJson;
555 const ShapeInfo& fInfo;
556 };
557
558 // First pass (bottom->top):
559 //
560 // * pick up the group transform and opacity
561 // * push local geometry effects onto the stack
562 // * store recs for next pass
563 //
564 std::vector<ShapeRec> recs;
565 for (Json::ArrayIndex i = 0; i < jshape.size(); ++i) {
566 const auto& s = jshape[jshape.size() - 1 - i];
Florin Malita094ccde2017-12-30 12:27:00 -0500567 const auto* info = FindShapeInfo(s);
568 if (!info) {
569 LogFail(s.isObject() ? s["ty"] : s, "Unknown shape");
570 continue;
571 }
572
Florin Malita16d0ad02018-01-19 15:07:29 -0500573 recs.push_back({ s, *info });
574
Florin Malita094ccde2017-12-30 12:27:00 -0500575 switch (info->fShapeType) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500576 case ShapeType::kTransform:
Florin Malitaca4439f2018-01-23 10:31:59 -0500577 if ((shape_matrix = AttachMatrix(s, shapeCtx->fCtx, nullptr))) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500578 shape_wrapper = sksg::Transform::Make(std::move(shape_wrapper), shape_matrix);
579 }
Florin Malitaca4439f2018-01-23 10:31:59 -0500580 shape_wrapper = AttachOpacity(s, shapeCtx->fCtx, std::move(shape_wrapper));
Florin Malita16d0ad02018-01-19 15:07:29 -0500581 break;
582 case ShapeType::kGeometryEffect:
583 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500584 shapeCtx->fGeometryEffectStack->push_back(
Florin Malita16d0ad02018-01-19 15:07:29 -0500585 { s, gGeometryEffectAttachers[info->fAttacherIndex] });
586 break;
587 default:
588 break;
589 }
590 }
591
592 // Second pass (top -> bottom, after 2x reverse):
593 //
594 // * track local geometry
595 // * emit local paints
596 //
597 std::vector<sk_sp<sksg::GeometryNode>> geos;
598 std::vector<sk_sp<sksg::RenderNode >> draws;
599 for (auto rec = recs.rbegin(); rec != recs.rend(); ++rec) {
600 switch (rec->fInfo.fShapeType) {
Florin Malita094ccde2017-12-30 12:27:00 -0500601 case ShapeType::kGeometry: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500602 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500603 if (auto geo = gGeometryAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
604 shapeCtx->fCtx)) {
Florin Malita094ccde2017-12-30 12:27:00 -0500605 geos.push_back(std::move(geo));
606 }
607 } break;
Florin Malitae6345d92018-01-03 23:37:54 -0500608 case ShapeType::kGeometryEffect: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500609 // Apply the current effect and pop from the stack.
610 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaee6de4b2018-01-21 11:13:17 -0500611 if (!geos.empty()) {
612 geos = gGeometryEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
Florin Malitaca4439f2018-01-23 10:31:59 -0500613 shapeCtx->fCtx,
Florin Malitaee6de4b2018-01-21 11:13:17 -0500614 std::move(geos));
615 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500616
Florin Malitaca4439f2018-01-23 10:31:59 -0500617 SkASSERT(shapeCtx->fGeometryEffectStack->back().fJson == rec->fJson);
618 SkASSERT(shapeCtx->fGeometryEffectStack->back().fAttach ==
Florin Malita16d0ad02018-01-19 15:07:29 -0500619 gGeometryEffectAttachers[rec->fInfo.fAttacherIndex]);
Florin Malitaca4439f2018-01-23 10:31:59 -0500620 shapeCtx->fGeometryEffectStack->pop_back();
Florin Malita094ccde2017-12-30 12:27:00 -0500621 } break;
622 case ShapeType::kGroup: {
Florin Malitaca4439f2018-01-23 10:31:59 -0500623 AttachShapeContext groupShapeCtx(shapeCtx->fCtx,
624 &geos,
625 shapeCtx->fGeometryEffectStack,
626 shapeCtx->fCommittedAnimators);
627 if (auto subgroup = AttachShape(rec->fJson["it"], &groupShapeCtx)) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500628 draws.push_back(std::move(subgroup));
Florin Malitaca4439f2018-01-23 10:31:59 -0500629 SkASSERT(groupShapeCtx.fCommittedAnimators >= shapeCtx->fCommittedAnimators);
630 shapeCtx->fCommittedAnimators = groupShapeCtx.fCommittedAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -0500631 }
632 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500633 case ShapeType::kPaint: {
634 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500635 auto paint = gPaintAttachers[rec->fInfo.fAttacherIndex](rec->fJson, shapeCtx->fCtx);
Florin Malita16d0ad02018-01-19 15:07:29 -0500636 if (!paint || geos.empty())
637 break;
638
639 auto drawGeos = geos;
640
641 // Apply all pending effects from the stack.
Florin Malitaca4439f2018-01-23 10:31:59 -0500642 for (auto it = shapeCtx->fGeometryEffectStack->rbegin();
643 it != shapeCtx->fGeometryEffectStack->rend(); ++it) {
644 drawGeos = it->fAttach(it->fJson, shapeCtx->fCtx, std::move(drawGeos));
Florin Malita18eafd92018-01-04 21:11:55 -0500645 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500646
647 // If we still have multiple geos, reduce using 'merge'.
648 auto geo = drawGeos.size() > 1
649 ? sksg::Merge::Make(std::move(drawGeos), sksg::Merge::Mode::kMerge)
650 : drawGeos[0];
651
652 SkASSERT(geo);
653 draws.push_back(sksg::Draw::Make(std::move(geo), std::move(paint)));
Florin Malitaca4439f2018-01-23 10:31:59 -0500654 shapeCtx->fCommittedAnimators = shapeCtx->fCtx->fAnimators.size();
Florin Malitadacc02b2017-12-31 09:12:31 -0500655 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500656 default:
657 break;
Florin Malita094ccde2017-12-30 12:27:00 -0500658 }
659 }
660
Florin Malita16d0ad02018-01-19 15:07:29 -0500661 // By now we should have popped all local geometry effects.
Florin Malitaca4439f2018-01-23 10:31:59 -0500662 SkASSERT(shapeCtx->fGeometryEffectStack->size() == initialGeometryEffects);
Florin Malita16d0ad02018-01-19 15:07:29 -0500663
664 // Push transformed local geometries to parent list, for subsequent paints.
665 for (const auto& geo : geos) {
Florin Malitaca4439f2018-01-23 10:31:59 -0500666 shapeCtx->fGeometryStack->push_back(shape_matrix
Florin Malita16d0ad02018-01-19 15:07:29 -0500667 ? sksg::GeometryTransform::Make(std::move(geo), shape_matrix)
668 : std::move(geo));
Florin Malita094ccde2017-12-30 12:27:00 -0500669 }
670
Florin Malita16d0ad02018-01-19 15:07:29 -0500671 // Emit local draws reversed (bottom->top, per spec).
672 for (auto it = draws.rbegin(); it != draws.rend(); ++it) {
673 shape_group->addChild(std::move(*it));
Florin Malita2a8275b2018-01-02 12:52:43 -0500674 }
675
Florin Malita16d0ad02018-01-19 15:07:29 -0500676 return draws.empty() ? nullptr : shape_wrapper;
Florin Malita094ccde2017-12-30 12:27:00 -0500677}
678
Florin Malitadd22cf962018-01-29 15:42:01 +0000679sk_sp<sksg::RenderNode> AttachCompLayer(const Json::Value& layer, AttachContext* ctx) {
680 SkASSERT(layer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500681
Florin Malitacf8ed522018-01-25 15:27:33 -0500682 SkString refId;
Florin Malitadd22cf962018-01-29 15:42:01 +0000683 if (!Parse(layer["refId"], &refId) || refId.isEmpty()) {
684 LOG("!! Comp layer missing refId\n");
Florin Malita094ccde2017-12-30 12:27:00 -0500685 return nullptr;
686 }
687
Florin Malitadd22cf962018-01-29 15:42:01 +0000688 const auto* comp = ctx->fAssets.find(refId);
689 if (!comp) {
690 LOG("!! Pre-comp not found: '%s'\n", refId.c_str());
Florin Malita094ccde2017-12-30 12:27:00 -0500691 return nullptr;
692 }
693
Florin Malitadd22cf962018-01-29 15:42:01 +0000694 // TODO: cycle detection
695 return AttachComposition(**comp, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500696}
697
Florin Malita0e66fba2018-01-09 17:10:18 -0500698sk_sp<sksg::RenderNode> AttachSolidLayer(const Json::Value& jlayer, AttachContext*) {
699 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500700
Florin Malitacf8ed522018-01-25 15:27:33 -0500701 const auto size = SkSize::Make(ParseDefault(jlayer["sw"], 0.0f),
702 ParseDefault(jlayer["sh"], 0.0f));
703 const auto hex = ParseDefault(jlayer["sc"], SkString());
Florin Malita0e66fba2018-01-09 17:10:18 -0500704 uint32_t c;
705 if (size.isEmpty() ||
706 !hex.startsWith("#") ||
707 !SkParse::FindHex(hex.c_str() + 1, &c)) {
708 LogFail(jlayer, "Could not parse solid layer");
709 return nullptr;
710 }
711
712 const SkColor color = 0xff000000 | c;
713
714 return sksg::Draw::Make(sksg::Rect::Make(SkRect::MakeSize(size)),
715 sksg::Color::Make(color));
Florin Malita094ccde2017-12-30 12:27:00 -0500716}
717
Florin Malita49328072018-01-08 12:51:12 -0500718sk_sp<sksg::RenderNode> AttachImageAsset(const Json::Value& jimage, AttachContext* ctx) {
719 SkASSERT(jimage.isObject());
720
Florin Malitacf8ed522018-01-25 15:27:33 -0500721 const auto name = ParseDefault(jimage["p"], SkString()),
722 path = ParseDefault(jimage["u"], SkString());
Florin Malita49328072018-01-08 12:51:12 -0500723 if (name.isEmpty())
724 return nullptr;
725
726 // TODO: plumb resource paths explicitly to ResourceProvider?
727 const auto resName = path.isEmpty() ? name : SkOSPath::Join(path.c_str(), name.c_str());
728 const auto resStream = ctx->fResources.openStream(resName.c_str());
729 if (!resStream || !resStream->hasLength()) {
730 LOG("!! Could not load image resource: %s\n", resName.c_str());
731 return nullptr;
732 }
733
734 // TODO: non-intrisic image sizing
735 return sksg::Image::Make(
736 SkImage::MakeFromEncoded(SkData::MakeFromStream(resStream.get(), resStream->getLength())));
737}
738
Florin Malitadd22cf962018-01-29 15:42:01 +0000739sk_sp<sksg::RenderNode> AttachImageLayer(const Json::Value& layer, AttachContext* ctx) {
740 SkASSERT(layer.isObject());
741
742 SkString refId;
743 if (!Parse(layer["refId"], &refId) || refId.isEmpty()) {
744 LOG("!! Image layer missing refId\n");
745 return nullptr;
746 }
747
748 const auto* jimage = ctx->fAssets.find(refId);
749 if (!jimage) {
750 LOG("!! Image asset not found: '%s'\n", refId.c_str());
751 return nullptr;
752 }
753
754 return AttachImageAsset(**jimage, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500755}
756
757sk_sp<sksg::RenderNode> AttachNullLayer(const Json::Value& layer, AttachContext*) {
758 SkASSERT(layer.isObject());
759
Florin Malita18eafd92018-01-04 21:11:55 -0500760 // Null layers are used solely to drive dependent transforms,
761 // but we use free-floating sksg::Matrices for that purpose.
Florin Malita094ccde2017-12-30 12:27:00 -0500762 return nullptr;
763}
764
765sk_sp<sksg::RenderNode> AttachShapeLayer(const Json::Value& layer, AttachContext* ctx) {
766 SkASSERT(layer.isObject());
767
Florin Malita16d0ad02018-01-19 15:07:29 -0500768 std::vector<sk_sp<sksg::GeometryNode>> geometryStack;
769 std::vector<GeometryEffectRec> geometryEffectStack;
Florin Malitaca4439f2018-01-23 10:31:59 -0500770 AttachShapeContext shapeCtx(ctx, &geometryStack, &geometryEffectStack, ctx->fAnimators.size());
771 auto shapeNode = AttachShape(layer["shapes"], &shapeCtx);
772
773 // Trim uncommitted animators: AttachShape consumes effects on the fly, and greedily attaches
774 // geometries => at the end, we can end up with unused geometries, which are nevertheless alive
775 // due to attached animators. To avoid this, we track committed animators and discard the
776 // orphans here.
777 SkASSERT(shapeCtx.fCommittedAnimators <= ctx->fAnimators.size());
778 ctx->fAnimators.resize(shapeCtx.fCommittedAnimators);
779
780 return shapeNode;
Florin Malita094ccde2017-12-30 12:27:00 -0500781}
782
783sk_sp<sksg::RenderNode> AttachTextLayer(const Json::Value& layer, AttachContext*) {
784 SkASSERT(layer.isObject());
785
786 LOG("?? Text layer stub\n");
787 return nullptr;
788}
789
Florin Malita18eafd92018-01-04 21:11:55 -0500790struct AttachLayerContext {
791 AttachLayerContext(const Json::Value& jlayers, AttachContext* ctx)
792 : fLayerList(jlayers), fCtx(ctx) {}
793
Florin Malita4a490682018-01-28 14:27:51 -0500794 const Json::Value& fLayerList;
795 AttachContext* fCtx;
796 SkTHashMap<int, sk_sp<sksg::Matrix>> fLayerMatrixMap;
797 sk_sp<sksg::RenderNode> fCurrentMatte;
Florin Malita18eafd92018-01-04 21:11:55 -0500798
Florin Malita4a490682018-01-28 14:27:51 -0500799 sk_sp<sksg::Matrix> AttachParentLayerMatrix(const Json::Value& jlayer) {
800 SkASSERT(jlayer.isObject());
Florin Malita18eafd92018-01-04 21:11:55 -0500801 SkASSERT(fLayerList.isArray());
802
Florin Malita4a490682018-01-28 14:27:51 -0500803 const auto parent_index = ParseDefault(jlayer["parent"], -1);
804 if (parent_index < 0)
Florin Malita18eafd92018-01-04 21:11:55 -0500805 return nullptr;
Florin Malita18eafd92018-01-04 21:11:55 -0500806
Florin Malita4a490682018-01-28 14:27:51 -0500807 if (auto* m = fLayerMatrixMap.find(parent_index))
808 return *m;
Florin Malita18eafd92018-01-04 21:11:55 -0500809
810 for (const auto& l : fLayerList) {
811 if (!l.isObject()) {
812 continue;
813 }
814
Florin Malita4a490682018-01-28 14:27:51 -0500815 if (ParseDefault(l["ind"], -1) == parent_index) {
816 return this->AttachLayerMatrix(l);
Florin Malita18eafd92018-01-04 21:11:55 -0500817 }
818 }
819
820 return nullptr;
821 }
822
823 sk_sp<sksg::Matrix> AttachLayerMatrix(const Json::Value& jlayer) {
824 SkASSERT(jlayer.isObject());
825
Florin Malita4a490682018-01-28 14:27:51 -0500826 const auto layer_index = ParseDefault(jlayer["ind"], -1);
827 if (layer_index < 0)
828 return nullptr;
Florin Malita18eafd92018-01-04 21:11:55 -0500829
Florin Malita4a490682018-01-28 14:27:51 -0500830 if (auto* m = fLayerMatrixMap.find(layer_index))
831 return *m;
Florin Malita18eafd92018-01-04 21:11:55 -0500832
Florin Malita4a490682018-01-28 14:27:51 -0500833 // Add a stub entry to break recursion cycles.
834 fLayerMatrixMap.set(layer_index, nullptr);
Florin Malita18eafd92018-01-04 21:11:55 -0500835
Florin Malita4a490682018-01-28 14:27:51 -0500836 auto parent_matrix = this->AttachParentLayerMatrix(jlayer);
Florin Malita18eafd92018-01-04 21:11:55 -0500837
Florin Malita4a490682018-01-28 14:27:51 -0500838 return *fLayerMatrixMap.set(layer_index,
839 AttachMatrix(jlayer["ks"],
840 fCtx,
841 this->AttachParentLayerMatrix(jlayer)));
Florin Malita18eafd92018-01-04 21:11:55 -0500842 }
843};
844
Florin Malita25366fa2018-01-23 13:37:59 -0500845SkBlendMode MaskBlendMode(char mode) {
846 switch (mode) {
847 case 'a': return SkBlendMode::kSrcOver; // Additive
848 case 's': return SkBlendMode::kExclusion; // Subtract
849 case 'i': return SkBlendMode::kDstIn; // Intersect
850 case 'l': return SkBlendMode::kLighten; // Lighten
851 case 'd': return SkBlendMode::kDarken; // Darken
852 case 'f': return SkBlendMode::kDifference; // Difference
853 default: break;
854 }
855
856 return SkBlendMode::kSrcOver;
857}
858
859sk_sp<sksg::RenderNode> AttachMask(const Json::Value& jmask,
860 AttachContext* ctx,
861 sk_sp<sksg::RenderNode> childNode) {
862 if (!jmask.isArray())
863 return childNode;
864
865 auto mask_group = sksg::Group::Make();
866
867 for (const auto& m : jmask) {
868 if (!m.isObject())
869 continue;
870
Florin Malitacf8ed522018-01-25 15:27:33 -0500871 const auto inverted = ParseDefault(m["inv"], false);
Florin Malita25366fa2018-01-23 13:37:59 -0500872 // TODO
873 if (inverted) {
874 LogFail(m, "Unsupported inverse mask");
875 continue;
876 }
877
878 auto mask_path = AttachPath(m["pt"], ctx);
879 if (!mask_path) {
880 LogFail(m, "Could not parse mask path");
881 continue;
882 }
883
Florin Malitacf8ed522018-01-25 15:27:33 -0500884 SkString mode;
885 if (!Parse(m["mode"], &mode) ||
886 mode.size() != 1 ||
887 !strcmp(mode.c_str(), "n")) { // "None" masks have no effect.
Florin Malita25366fa2018-01-23 13:37:59 -0500888 continue;
Florin Malitacf8ed522018-01-25 15:27:33 -0500889 }
Florin Malita25366fa2018-01-23 13:37:59 -0500890
891 auto mask_paint = sksg::Color::Make(SK_ColorBLACK);
892 mask_paint->setBlendMode(MaskBlendMode(mode.c_str()[0]));
Florin Malitafc807c82018-01-25 22:35:09 -0500893 BindProperty<ScalarValue>(m["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500894 [mask_paint](const ScalarValue& o) { mask_paint->setOpacity(o * 0.01f); });
Florin Malita25366fa2018-01-23 13:37:59 -0500895
896 mask_group->addChild(sksg::Draw::Make(std::move(mask_path), std::move(mask_paint)));
897 }
898
899 return mask_group->empty()
900 ? childNode
901 : sksg::MaskEffect::Make(std::move(childNode), std::move(mask_group));
902}
903
Florin Malita18eafd92018-01-04 21:11:55 -0500904sk_sp<sksg::RenderNode> AttachLayer(const Json::Value& jlayer,
905 AttachLayerContext* layerCtx) {
906 if (!jlayer.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500907 return nullptr;
908
909 using LayerAttacher = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*);
910 static constexpr LayerAttacher gLayerAttachers[] = {
911 AttachCompLayer, // 'ty': 0
912 AttachSolidLayer, // 'ty': 1
913 AttachImageLayer, // 'ty': 2
914 AttachNullLayer, // 'ty': 3
915 AttachShapeLayer, // 'ty': 4
916 AttachTextLayer, // 'ty': 5
917 };
918
Florin Malitacf8ed522018-01-25 15:27:33 -0500919 int type = ParseDefault(jlayer["ty"], -1);
Florin Malita094ccde2017-12-30 12:27:00 -0500920 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gLayerAttachers))) {
921 return nullptr;
922 }
923
Florin Malita71cba8f2018-01-09 08:07:14 -0500924 // Layer content.
925 auto layer = gLayerAttachers[type](jlayer, layerCtx->fCtx);
Florin Malita25366fa2018-01-23 13:37:59 -0500926 // Optional layer mask.
927 layer = AttachMask(jlayer["masksProperties"], layerCtx->fCtx, std::move(layer));
928 // Optional layer transform.
Florin Malita71cba8f2018-01-09 08:07:14 -0500929 if (auto layerMatrix = layerCtx->AttachLayerMatrix(jlayer)) {
Florin Malita71cba8f2018-01-09 08:07:14 -0500930 layer = sksg::Transform::Make(std::move(layer), std::move(layerMatrix));
931 }
932 // Optional layer opacity.
933 layer = AttachOpacity(jlayer["ks"], layerCtx->fCtx, std::move(layer));
Florin Malita18eafd92018-01-04 21:11:55 -0500934
Florin Malita71cba8f2018-01-09 08:07:14 -0500935 // TODO: we should also disable related/inactive animators.
Florin Malita35efaa82018-01-22 12:57:06 -0500936 class Activator final : public sksg::Animator {
Florin Malita71cba8f2018-01-09 08:07:14 -0500937 public:
938 Activator(sk_sp<sksg::OpacityEffect> controlNode, float in, float out)
939 : fControlNode(std::move(controlNode))
940 , fIn(in)
941 , fOut(out) {}
942
Florin Malita35efaa82018-01-22 12:57:06 -0500943 void onTick(float t) override {
Florin Malita71cba8f2018-01-09 08:07:14 -0500944 // Keep the layer fully transparent except for its [in..out] lifespan.
945 // (note: opacity == 0 disables rendering, while opacity == 1 is a noop)
946 fControlNode->setOpacity(t >= fIn && t <= fOut ? 1 : 0);
947 }
948
949 private:
950 const sk_sp<sksg::OpacityEffect> fControlNode;
951 const float fIn,
952 fOut;
953 };
954
955 auto layerControl = sksg::OpacityEffect::Make(std::move(layer));
Florin Malitacf8ed522018-01-25 15:27:33 -0500956 const auto in = ParseDefault(jlayer["ip"], 0.0f),
957 out = ParseDefault(jlayer["op"], in);
Florin Malita71cba8f2018-01-09 08:07:14 -0500958
959 if (in >= out || ! layerControl)
960 return nullptr;
961
962 layerCtx->fCtx->fAnimators.push_back(skstd::make_unique<Activator>(layerControl, in, out));
963
Florin Malitacf8ed522018-01-25 15:27:33 -0500964 if (ParseDefault(jlayer["td"], false)) {
Florin Malita5f9102f2018-01-10 13:36:22 -0500965 // This layer is a matte. We apply it as a mask to the next layer.
966 layerCtx->fCurrentMatte = std::move(layerControl);
967 return nullptr;
968 }
969
970 if (layerCtx->fCurrentMatte) {
971 // There is a pending matte. Apply and reset.
972 return sksg::MaskEffect::Make(std::move(layerControl), std::move(layerCtx->fCurrentMatte));
973 }
974
Florin Malita71cba8f2018-01-09 08:07:14 -0500975 return layerControl;
Florin Malita094ccde2017-12-30 12:27:00 -0500976}
977
978sk_sp<sksg::RenderNode> AttachComposition(const Json::Value& comp, AttachContext* ctx) {
979 if (!comp.isObject())
980 return nullptr;
981
Florin Malita18eafd92018-01-04 21:11:55 -0500982 const auto& jlayers = comp["layers"];
983 if (!jlayers.isArray())
984 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500985
Florin Malita18eafd92018-01-04 21:11:55 -0500986 SkSTArray<16, sk_sp<sksg::RenderNode>, true> layers;
987 AttachLayerContext layerCtx(jlayers, ctx);
988
989 for (const auto& l : jlayers) {
990 if (auto layer_fragment = AttachLayer(l, &layerCtx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -0500991 layers.push_back(std::move(layer_fragment));
Florin Malita094ccde2017-12-30 12:27:00 -0500992 }
993 }
994
Florin Malita2a8275b2018-01-02 12:52:43 -0500995 if (layers.empty()) {
996 return nullptr;
997 }
998
999 // Layers are painted in bottom->top order.
1000 auto comp_group = sksg::Group::Make();
1001 for (int i = layers.count() - 1; i >= 0; --i) {
1002 comp_group->addChild(std::move(layers[i]));
1003 }
1004
1005 LOG("** Attached composition '%s': %d layers.\n",
Florin Malitacf8ed522018-01-25 15:27:33 -05001006 ParseDefault(comp["id"], SkString()).c_str(), layers.count());
Florin Malita2a8275b2018-01-02 12:52:43 -05001007
Florin Malita094ccde2017-12-30 12:27:00 -05001008 return comp_group;
1009}
1010
1011} // namespace
1012
Florin Malita49328072018-01-08 12:51:12 -05001013std::unique_ptr<Animation> Animation::Make(SkStream* stream, const ResourceProvider& res) {
Florin Malita094ccde2017-12-30 12:27:00 -05001014 if (!stream->hasLength()) {
1015 // TODO: handle explicit buffering?
1016 LOG("!! cannot parse streaming content\n");
1017 return nullptr;
1018 }
1019
1020 Json::Value json;
1021 {
1022 auto data = SkData::MakeFromStream(stream, stream->getLength());
1023 if (!data) {
1024 LOG("!! could not read stream\n");
1025 return nullptr;
1026 }
1027
1028 Json::Reader reader;
1029
1030 auto dataStart = static_cast<const char*>(data->data());
1031 if (!reader.parse(dataStart, dataStart + data->size(), json, false) || !json.isObject()) {
1032 LOG("!! failed to parse json: %s\n", reader.getFormattedErrorMessages().c_str());
1033 return nullptr;
1034 }
1035 }
1036
Florin Malitacf8ed522018-01-25 15:27:33 -05001037 const auto version = ParseDefault(json["v"], SkString());
1038 const auto size = SkSize::Make(ParseDefault(json["w"], 0.0f),
1039 ParseDefault(json["h"], 0.0f));
1040 const auto fps = ParseDefault(json["fr"], -1.0f);
Florin Malita094ccde2017-12-30 12:27:00 -05001041
1042 if (size.isEmpty() || version.isEmpty() || fps < 0) {
1043 LOG("!! invalid animation params (version: %s, size: [%f %f], frame rate: %f)",
1044 version.c_str(), size.width(), size.height(), fps);
1045 return nullptr;
1046 }
1047
Florin Malita49328072018-01-08 12:51:12 -05001048 return std::unique_ptr<Animation>(new Animation(res, std::move(version), size, fps, json));
Florin Malita094ccde2017-12-30 12:27:00 -05001049}
1050
Florin Malita49328072018-01-08 12:51:12 -05001051std::unique_ptr<Animation> Animation::MakeFromFile(const char path[], const ResourceProvider* res) {
1052 class DirectoryResourceProvider final : public ResourceProvider {
1053 public:
1054 explicit DirectoryResourceProvider(SkString dir) : fDir(std::move(dir)) {}
1055
1056 std::unique_ptr<SkStream> openStream(const char resource[]) const override {
1057 const auto resPath = SkOSPath::Join(fDir.c_str(), resource);
1058 return SkStream::MakeFromFile(resPath.c_str());
1059 }
1060
1061 private:
1062 const SkString fDir;
1063 };
1064
1065 const auto jsonStream = SkStream::MakeFromFile(path);
1066 if (!jsonStream)
1067 return nullptr;
1068
1069 std::unique_ptr<ResourceProvider> defaultProvider;
1070 if (!res) {
1071 defaultProvider = skstd::make_unique<DirectoryResourceProvider>(SkOSPath::Dirname(path));
1072 }
1073
1074 return Make(jsonStream.get(), res ? *res : *defaultProvider);
1075}
1076
1077Animation::Animation(const ResourceProvider& resources,
1078 SkString version, const SkSize& size, SkScalar fps, const Json::Value& json)
Florin Malita094ccde2017-12-30 12:27:00 -05001079 : fVersion(std::move(version))
1080 , fSize(size)
1081 , fFrameRate(fps)
Florin Malitacf8ed522018-01-25 15:27:33 -05001082 , fInPoint(ParseDefault(json["ip"], 0.0f))
1083 , fOutPoint(SkTMax(ParseDefault(json["op"], SK_ScalarMax), fInPoint)) {
Florin Malita094ccde2017-12-30 12:27:00 -05001084
1085 AssetMap assets;
1086 for (const auto& asset : json["assets"]) {
1087 if (!asset.isObject()) {
1088 continue;
1089 }
1090
Florin Malitadd22cf962018-01-29 15:42:01 +00001091 assets.set(ParseDefault(asset["id"], SkString()), &asset);
Florin Malita094ccde2017-12-30 12:27:00 -05001092 }
1093
Florin Malita35efaa82018-01-22 12:57:06 -05001094 sksg::Scene::AnimatorList animators;
1095 AttachContext ctx = { resources, assets, animators };
1096 auto root = AttachComposition(json, &ctx);
1097
1098 LOG("** Attached %d animators\n", animators.size());
1099
1100 fScene = sksg::Scene::Make(std::move(root), std::move(animators));
Florin Malita094ccde2017-12-30 12:27:00 -05001101
Florin Malitadb385732018-01-09 12:19:32 -05001102 // In case the client calls render before the first tick.
1103 this->animationTick(0);
Florin Malita094ccde2017-12-30 12:27:00 -05001104}
1105
1106Animation::~Animation() = default;
1107
Florin Malita35efaa82018-01-22 12:57:06 -05001108void Animation::setShowInval(bool show) {
1109 if (fScene) {
1110 fScene->setShowInval(show);
1111 }
1112}
1113
Mike Reed29859872018-01-08 08:25:27 -05001114void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
Florin Malita35efaa82018-01-22 12:57:06 -05001115 if (!fScene)
Florin Malita094ccde2017-12-30 12:27:00 -05001116 return;
1117
Mike Reed29859872018-01-08 08:25:27 -05001118 SkAutoCanvasRestore restore(canvas, true);
1119 const SkRect srcR = SkRect::MakeSize(this->size());
1120 if (dstR) {
1121 canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
1122 }
1123 canvas->clipRect(srcR);
Florin Malita35efaa82018-01-22 12:57:06 -05001124 fScene->render(canvas);
Florin Malita094ccde2017-12-30 12:27:00 -05001125}
1126
1127void Animation::animationTick(SkMSec ms) {
Florin Malita35efaa82018-01-22 12:57:06 -05001128 if (!fScene)
1129 return;
1130
Florin Malita094ccde2017-12-30 12:27:00 -05001131 // 't' in the BM model really means 'frame #'
1132 auto t = static_cast<float>(ms) * fFrameRate / 1000;
1133
1134 t = fInPoint + std::fmod(t, fOutPoint - fInPoint);
1135
Florin Malita35efaa82018-01-22 12:57:06 -05001136 fScene->animate(t);
Florin Malita094ccde2017-12-30 12:27:00 -05001137}
1138
Florin Malita54f65c42018-01-16 17:04:30 -05001139} // namespace skottie