• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 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 "include/core/SkCanvas.h"
9 #include "include/core/SkRRect.h"
10 #include "include/utils/SkRandom.h"
11 #include "samplecode/Sample.h"
12 #include "tools/timer/TimeUtils.h"
13 
14 #include "modules/sksg/include/SkSGDraw.h"
15 #include "modules/sksg/include/SkSGGroup.h"
16 #include "modules/sksg/include/SkSGInvalidationController.h"
17 #include "modules/sksg/include/SkSGPaint.h"
18 #include "modules/sksg/include/SkSGPath.h"
19 #include "modules/sksg/include/SkSGRect.h"
20 #include "modules/sksg/include/SkSGScene.h"
21 #include "modules/sksg/include/SkSGTransform.h"
22 
23 namespace {
24 
25 static const SkRect kBounds     = SkRect::MakeLTRB(0.1f, 0.1f, 0.9f, 0.9f);
26 static const SkSize kPaddleSize = SkSize::Make(0.03f, 0.1f);
27 static const SkScalar kBallSize = 0.04f;
28 static const SkScalar kShadowOpacity       = 0.40f;
29 static const SkScalar kShadowParallax      = 0.04f;
30 static const SkScalar kBackgroundStroke    = 0.01f;
31 static const uint32_t kBackgroundDashCount = 20;
32 
33 static const SkScalar kBallSpeedMax  = 0.0020f;
34 static const SkScalar kBallSpeedMin  = 0.0005f;
35 static const SkScalar kBallSpeedFuzz = 0.0002f;
36 
37 static const SkScalar kTimeScaleMin = 0.0f;
38 static const SkScalar kTimeScaleMax = 5.0f;
39 
40 // Box the value within [min, max), by applying infinite reflection on the interval endpoints.
box_reflect(SkScalar v,SkScalar min,SkScalar max)41 SkScalar box_reflect(SkScalar v, SkScalar min, SkScalar max) {
42     const SkScalar intervalLen = max - min;
43     SkASSERT(intervalLen > 0);
44 
45     // f(v) is periodic in 2 * intervalLen: one normal progression + one reflection
46     const SkScalar P = intervalLen * 2;
47     // relative to P origin
48     const SkScalar vP = v - min;
49     // map to [0, P)
50     const SkScalar vMod = (vP < 0) ? P - SkScalarMod(-vP, P) : SkScalarMod(vP, P);
51     // reflect if needed, to map to [0, intervalLen)
52     const SkScalar vInterval = vMod < intervalLen ? vMod : P - vMod;
53     // finally, reposition relative to min
54     return vInterval + min;
55 }
56 
57 // Compute <t, y> for the trajectory intersection with the next vertical edge.
find_yintercept(const SkPoint & pos,const SkVector & spd,const SkRect & box)58 std::tuple<SkScalar, SkScalar> find_yintercept(const SkPoint& pos, const SkVector& spd,
59                                                const SkRect& box) {
60     const SkScalar edge = spd.fX > 0 ? box.fRight : box.fLeft;
61     const SkScalar    t = (edge - pos.fX) / spd.fX;
62     SkASSERT(t >= 0);
63     const SkScalar   dY = t * spd.fY;
64 
65     return std::make_tuple(t, box_reflect(pos.fY + dY, box.fTop, box.fBottom));
66 }
67 
update_pos(const sk_sp<sksg::RRect> & rr,const SkPoint & pos)68 void update_pos(const sk_sp<sksg::RRect>& rr, const SkPoint& pos) {
69     // TODO: position setters on RRect?
70 
71     const auto r = rr->getRRect().rect();
72     const auto offsetX = pos.x() - r.x(),
73                offsetY = pos.y() - r.y();
74     rr->setRRect(rr->getRRect().makeOffset(offsetX, offsetY));
75 }
76 
77 } // anonymous ns
78 
79 class PongView final : public Sample {
80 public:
81     PongView() = default;
82 
83 protected:
onOnceBeforeDraw()84     void onOnceBeforeDraw() override {
85         const SkRect fieldBounds = kBounds.makeOutset(kBallSize / 2, kBallSize / 2);
86         const SkRRect ball = SkRRect::MakeOval(SkRect::MakeWH(kBallSize, kBallSize));
87         const SkRRect paddle = SkRRect::MakeRectXY(SkRect::MakeWH(kPaddleSize.width(),
88                                                                   kPaddleSize.height()),
89                                                    kPaddleSize.width() / 2,
90                                                    kPaddleSize.width() / 2);
91         fBall.initialize(ball,
92                          SkPoint::Make(kBounds.centerX(), kBounds.centerY()),
93                          SkVector::Make(fRand.nextRangeScalar(kBallSpeedMin, kBallSpeedMax),
94                                         fRand.nextRangeScalar(kBallSpeedMin, kBallSpeedMax)));
95         fPaddle0.initialize(paddle,
96                             SkPoint::Make(fieldBounds.left() - kPaddleSize.width() / 2,
97                                           fieldBounds.centerY()),
98                             SkVector::Make(0, 0));
99         fPaddle1.initialize(paddle,
100                             SkPoint::Make(fieldBounds.right() + kPaddleSize.width() / 2,
101                                           fieldBounds.centerY()),
102                             SkVector::Make(0, 0));
103 
104         // Background decoration.
105         SkPath bgPath;
106         bgPath.moveTo(kBounds.left() , fieldBounds.top());
107         bgPath.lineTo(kBounds.right(), fieldBounds.top());
108         bgPath.moveTo(kBounds.left() , fieldBounds.bottom());
109         bgPath.lineTo(kBounds.right(), fieldBounds.bottom());
110         // TODO: stroke-dash support would come in handy right about now.
111         for (uint32_t i = 0; i < kBackgroundDashCount; ++i) {
112             bgPath.moveTo(kBounds.centerX(),
113                           kBounds.top() + (i + 0.25f) * kBounds.height() / kBackgroundDashCount);
114             bgPath.lineTo(kBounds.centerX(),
115                           kBounds.top() + (i + 0.75f) * kBounds.height() / kBackgroundDashCount);
116         }
117 
118         auto bg_path  = sksg::Path::Make(bgPath);
119         auto bg_paint = sksg::Color::Make(SK_ColorBLACK);
120         bg_paint->setStyle(SkPaint::kStroke_Style);
121         bg_paint->setStrokeWidth(kBackgroundStroke);
122 
123         auto ball_paint    = sksg::Color::Make(SK_ColorGREEN),
124              paddle0_paint = sksg::Color::Make(SK_ColorBLUE),
125              paddle1_paint = sksg::Color::Make(SK_ColorRED),
126              shadow_paint  = sksg::Color::Make(SK_ColorBLACK);
127         ball_paint->setAntiAlias(true);
128         paddle0_paint->setAntiAlias(true);
129         paddle1_paint->setAntiAlias(true);
130         shadow_paint->setAntiAlias(true);
131         shadow_paint->setOpacity(kShadowOpacity);
132 
133         // Build the scene graph.
134         auto group = sksg::Group::Make();
135         group->addChild(sksg::Draw::Make(std::move(bg_path), std::move(bg_paint)));
136         group->addChild(sksg::Draw::Make(fPaddle0.shadowNode, shadow_paint));
137         group->addChild(sksg::Draw::Make(fPaddle1.shadowNode, shadow_paint));
138         group->addChild(sksg::Draw::Make(fBall.shadowNode, shadow_paint));
139         group->addChild(sksg::Draw::Make(fPaddle0.objectNode, paddle0_paint));
140         group->addChild(sksg::Draw::Make(fPaddle1.objectNode, paddle1_paint));
141         group->addChild(sksg::Draw::Make(fBall.objectNode, ball_paint));
142 
143         // Handle everything in a normalized 1x1 space.
144         fContentMatrix = sksg::Matrix<SkMatrix>::Make(
145             SkMatrix::MakeRectToRect(SkRect::MakeWH(1, 1),
146                                      SkRect::MakeIWH(this->width(), this->height()),
147                                      SkMatrix::kFill_ScaleToFit));
148         auto root = sksg::TransformEffect::Make(std::move(group), fContentMatrix);
149         fScene = sksg::Scene::Make(std::move(root), sksg::AnimatorList());
150 
151         // Off we go.
152         this->updatePaddleStrategy();
153     }
154 
name()155     SkString name() override { return SkString("SGPong"); }
156 
onChar(SkUnichar uni)157     bool onChar(SkUnichar uni) override {
158             switch (uni) {
159                 case '[':
160                     fTimeScale = SkTPin(fTimeScale - 0.1f, kTimeScaleMin, kTimeScaleMax);
161                     return true;
162                 case ']':
163                     fTimeScale = SkTPin(fTimeScale + 0.1f, kTimeScaleMin, kTimeScaleMax);
164                     return true;
165                 case 'I':
166                     fShowInval = !fShowInval;
167                     return true;
168                 default:
169                     break;
170             }
171             return false;
172     }
173 
onSizeChange()174     void onSizeChange() override {
175         if (fContentMatrix) {
176             fContentMatrix->setMatrix(SkMatrix::MakeRectToRect(SkRect::MakeWH(1, 1),
177                                                                SkRect::MakeIWH(this->width(),
178                                                                                this->height()),
179                                                                SkMatrix::kFill_ScaleToFit));
180         }
181 
182         this->INHERITED::onSizeChange();
183     }
184 
onDrawContent(SkCanvas * canvas)185     void onDrawContent(SkCanvas* canvas) override {
186         sksg::InvalidationController ic;
187         fScene->animate(0, &ic);
188         fScene->render(canvas);
189 
190         if (fShowInval) {
191             SkPaint fill, stroke;
192             fill.setAntiAlias(true);
193             fill.setColor(0x40ff0000);
194             stroke.setAntiAlias(true);
195             stroke.setColor(0xffff0000);
196             stroke.setStyle(SkPaint::kStroke_Style);
197 
198             for (const auto& r : ic) {
199                 canvas->drawRect(r, fill);
200                 canvas->drawRect(r, stroke);
201             }
202         }
203     }
204 
onAnimate(double nanos)205     bool onAnimate(double nanos) override {
206         // onAnimate may fire before the first draw.
207         if (fScene) {
208             SkScalar dt = (TimeUtils::NanosToMSec(nanos) - fLastTick) * fTimeScale;
209             fLastTick = TimeUtils::NanosToMSec(nanos);
210 
211             fPaddle0.posTick(dt);
212             fPaddle1.posTick(dt);
213             fBall.posTick(dt);
214 
215             this->enforceConstraints();
216 
217             fPaddle0.updateDom();
218             fPaddle1.updateDom();
219             fBall.updateDom();
220         }
221         return true;
222     }
223 
224 private:
225     struct Object {
initializePongView::Object226         void initialize(const SkRRect& rrect, const SkPoint& p, const SkVector& s) {
227             objectNode = sksg::RRect::Make(rrect);
228             shadowNode = sksg::RRect::Make(rrect);
229 
230             pos = p;
231             spd = s;
232             size = SkSize::Make(rrect.width(), rrect.height());
233         }
234 
posTickPongView::Object235         void posTick(SkScalar dt) {
236             pos += spd * dt;
237         }
238 
updateDomPongView::Object239         void updateDom() {
240             const SkPoint corner = pos - SkPoint::Make(size.width() / 2, size.height() / 2);
241             update_pos(objectNode, corner);
242 
243             // Simulate parallax shadow for a centered light source.
244             SkPoint shadowOffset = pos - SkPoint::Make(kBounds.centerX(), kBounds.centerY());
245             shadowOffset.scale(kShadowParallax);
246             const SkPoint shadowCorner = corner + shadowOffset;
247 
248             update_pos(shadowNode, shadowCorner);
249         }
250 
251         sk_sp<sksg::RRect> objectNode,
252                            shadowNode;
253         SkPoint            pos;
254         SkVector           spd;
255         SkSize             size;
256     };
257 
enforceConstraints()258     void enforceConstraints() {
259         // Perfect vertical reflection.
260         if (fBall.pos.fY < kBounds.fTop || fBall.pos.fY >= kBounds.fBottom) {
261             fBall.spd.fY = -fBall.spd.fY;
262             fBall.pos.fY = box_reflect(fBall.pos.fY, kBounds.fTop, kBounds.fBottom);
263         }
264 
265         // Horizontal bounce - introduces a speed fuzz.
266         if (fBall.pos.fX < kBounds.fLeft || fBall.pos.fX >= kBounds.fRight) {
267             fBall.spd.fX = this->fuzzBallSpeed(-fBall.spd.fX);
268             fBall.spd.fY = this->fuzzBallSpeed(fBall.spd.fY);
269             fBall.pos.fX = box_reflect(fBall.pos.fX, kBounds.fLeft, kBounds.fRight);
270             this->updatePaddleStrategy();
271         }
272     }
273 
fuzzBallSpeed(SkScalar spd)274     SkScalar fuzzBallSpeed(SkScalar spd) {
275         // The speed limits are absolute values.
276         const SkScalar   sign = spd >= 0 ? 1.0f : -1.0f;
277         const SkScalar fuzzed = fabs(spd) + fRand.nextRangeScalar(-kBallSpeedFuzz, kBallSpeedFuzz);
278 
279         return sign * SkTPin(fuzzed, kBallSpeedMin, kBallSpeedMax);
280     }
281 
updatePaddleStrategy()282     void updatePaddleStrategy() {
283         Object* pitcher = fBall.spd.fX > 0 ? &fPaddle0 : &fPaddle1;
284         Object* catcher = fBall.spd.fX > 0 ? &fPaddle1 : &fPaddle0;
285 
286         SkScalar t, yIntercept;
287         std::tie(t, yIntercept) = find_yintercept(fBall.pos, fBall.spd, kBounds);
288 
289         // The pitcher aims for a neutral/centered position.
290         pitcher->spd.fY = (kBounds.centerY() - pitcher->pos.fY) / t;
291 
292         // The catcher goes for the ball.  Duh.
293         catcher->spd.fY = (yIntercept - catcher->pos.fY) / t;
294     }
295 
296     std::unique_ptr<sksg::Scene>  fScene;
297     sk_sp<sksg::Matrix<SkMatrix>> fContentMatrix;
298     Object                        fPaddle0, fPaddle1, fBall;
299     SkRandom                      fRand;
300 
301     SkMSec                        fLastTick  = 0;
302     SkScalar                      fTimeScale = 1.0f;
303     bool                          fShowInval = false;
304 
305     typedef Sample INHERITED;
306 };
307 
308 DEF_SAMPLE( return new PongView(); )
309