1 /*
2  * Copyright 2020 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 "tools/viewer/SkRiveSlide.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkStream.h"
12 
13 #if defined(SK_ENABLE_SKRIVE)
14 
SkRiveSlide(const SkString & name,const SkString & path)15 SkRiveSlide::SkRiveSlide(const SkString& name, const SkString& path)
16     : fPath(path) {
17     fName = name;
18 }
19 
20 SkRiveSlide::~SkRiveSlide() = default;
21 
load(SkScalar w,SkScalar h)22 void SkRiveSlide::load(SkScalar w, SkScalar h) {
23     fWinSize    = {w , h};
24     fRive       = skrive::SkRive::Builder().make(SkFILEStream::Make(fPath.c_str()));
25     fRiveBounds = SkRect::MakeEmpty();
26 
27     if (fRive) {
28         SkDebugf("Loaded Rive animation: %zu artboards\n", fRive->artboards().size());
29         for (const auto& ab : fRive->artboards()) {
30             const auto& pos  = ab->getTranslation();
31             const auto& size = ab->getSize();
32 
33             fRiveBounds.join(SkRect::MakeXYWH(pos.x, pos.y, size.x, size.y));
34         }
35     } else {
36         SkDebugf("Failed to load Rive animation: %s\n", fPath.c_str());
37     }
38 }
39 
unload()40 void SkRiveSlide::unload() {
41     fRive.reset();
42 }
43 
resize(SkScalar w,SkScalar h)44 void SkRiveSlide::resize(SkScalar w, SkScalar h) {
45     fWinSize = {w , h};
46 }
47 
getDimensions() const48 SkISize SkRiveSlide::getDimensions() const {
49     // We always scale to fill the window.
50     return fWinSize.toCeil();
51 }
52 
draw(SkCanvas * canvas)53 void SkRiveSlide::draw(SkCanvas* canvas) {
54     if (!fRive) {
55         return;
56     }
57 
58     // Scale the Rive artboards to fill our window.
59     SkAutoCanvasRestore acr(canvas, true);
60     canvas->concat(SkMatrix::RectToRect(fRiveBounds, SkRect::MakeSize(fWinSize),
61                                         SkMatrix::kCenter_ScaleToFit));
62 
63     for (const auto& ab : fRive->artboards()) {
64         ab->render(canvas);
65     }
66 }
67 
68 #endif // defined(SK_ENABLE_SKRIVE)
69