Debian Codegraph @

tools/viewer/MotionMarkSlide.cpp

raw
1 /*
2 * Copyright 2013 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 #include <vector>
8
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkPath.h"
11 #include "include/core/SkPathBuilder.h"
12 #include "include/effects/SkGradient.h"
13 #include "src/base/SkRandom.h"
14 #include "tools/Resources.h"
15 #include "tools/gpu/YUVUtils.h"
16 #include "tools/viewer/Slide.h"
17
18 // Implementation in C++ of some WebKit MotionMark tests
19 // Tests implemented so far:
20 // * Canvas Lines
21 // * Canvas Arcs
22 // * Paths
23 // Based on https://github.com/WebKit/MotionMark/blob/main/MotionMark/
24
25 class MMObject {
26 public:
27 virtual ~MMObject() = default;
28
29 virtual void draw(SkCanvas* canvas) = 0;
30
31 virtual void animate(double /*nanos*/) = 0;
32 };
33
34 class Stage {
35 public:
36 Stage(SkSize size, int startingObjectCount, int objectIncrement)
37 : fSize(size)
38 , fStartingObjectCount(startingObjectCount)
39 , fObjectIncrement(objectIncrement) {}
40 virtual ~Stage() = default;
41
42 // The default impls of draw() and animate() simply iterate over fObjects and call the
43 // MMObject function.
44 virtual void draw(SkCanvas* canvas) {
45 for (size_t i = 0; i < fObjects.size(); ++i) {
46 fObjects[i]->draw(canvas);
47 }
48 }
49
50 virtual bool animate(double nanos) {
51 for (size_t i = 0; i < fObjects.size(); ++i) {
52 fObjects[i]->animate(nanos);
53 }
54 return true;
55 }
56
57 // The default impl handles +/- to add or remove N objects from the scene
58 virtual bool onChar(SkUnichar uni) {
59 bool handled = false;
60 switch (uni) {
61 case '+':
62 case '=':
63 for (int i = 0; i < fObjectIncrement; ++i) {
64 fObjects.push_back(this->createObject());
65 }
66 handled = true;
67 break;
68 case '-':
69 case '_':
70 if (fObjects.size() > (size_t) fObjectIncrement) {
71 fObjects.resize(fObjects.size() - (size_t) fObjectIncrement);
72 }
73 handled = true;
74 break;
75 default:
76 break;
77 }
78
79 return handled;
80 }
81
82 protected:
83 virtual std::unique_ptr<MMObject> createObject() = 0;
84
85 void initializeObjects() {
86 for (int i = 0; i < fStartingObjectCount; ++i) {
87 fObjects.push_back(this->createObject());
88 }
89 }
90
91 [[maybe_unused]] SkSize fSize;
92
93 int fStartingObjectCount;
94 int fObjectIncrement;
95
96 std::vector<std::unique_ptr<MMObject>> fObjects;
97 SkRandom fRandom;
98 };
99
100 class MotionMarkSlide : public Slide {
101 public:
102 MotionMarkSlide() = default;
103
104 bool onChar(SkUnichar uni) override {
105 return fStage->onChar(uni);
106 }
107
108 void draw(SkCanvas* canvas) override {
109 fStage->draw(canvas);
110 }
111
112 bool animate(double nanos) override {
113 return fStage->animate(nanos);
114 }
115
116 protected:
117 std::unique_ptr<Stage> fStage;
118 };
119
120
121 namespace {
122
123 float time_counter_value(double nanos, float factor) {
124 constexpr double kMillisPerNano = 0.0000001;
125 return static_cast<float>(nanos*kMillisPerNano)/factor;
126 }
127
128 float time_fractional_value(double nanos, float cycleLengthMs) {
129 return SkScalarFraction(time_counter_value(nanos, cycleLengthMs));
130 }
131
132 // The following functions match the input processing that Chrome's canvas2d layer performs before
133 // calling into Skia.
134
135 // See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc;drc=572074cb06425797e7e110511db405134cf67e2f;l=299
136 void canonicalize_angle(float* startAngle, float* endAngle) {
137 float newStartAngle = SkScalarMod(*startAngle, 360.f);
138 float delta = newStartAngle - *startAngle;
139 *startAngle = newStartAngle;
140 *endAngle = *endAngle + delta;
141 }
142
143 // See https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/canvas/canvas2d/canvas_path.cc;drc=572074cb06425797e7e110511db405134cf67e2f;l=245
144 float adjust_end_angle(float startAngle, float endAngle, bool ccw) {
145 float newEndAngle = endAngle;
146 if (!ccw && endAngle - startAngle >= 360.f) {
147 newEndAngle = startAngle + 360.f;
148 } else if (ccw && startAngle - endAngle >= 360.f) {
149 newEndAngle = startAngle - 360.f;
150 } else if (!ccw && startAngle > endAngle) {
151 newEndAngle = startAngle + (360.f - SkScalarMod(startAngle - endAngle, 360.f));
152 } else if (ccw && startAngle < endAngle) {
153 newEndAngle = startAngle - (360.f - SkScalarMod(endAngle - startAngle, 360.f));
154 }
155
156 return newEndAngle;
157 }
158
159 } // namespace
160
161 ///////////////////////////////////////////////////////////////////////////////////////////////////
162 // Canvas Lines
163 ///////////////////////////////////////////////////////////////////////////////////////////////////
164 struct LineSegmentParams {
165 float fCircleRadius;
166 SkPoint fCircleCenters[4];
167 float fLineLengthMaximum;
168 float fLineMinimum;
169 };
170
171 class CanvasLineSegment : public MMObject {
172 public:
173 CanvasLineSegment(SkRandom* random, const LineSegmentParams& params) {
174 int circle = random->nextRangeU(0, 3);
175
176 static constexpr SkColor kColors[] = {
177 0xffe01040, 0xff10c030, 0xff744cba, 0xffe05010
178 };
179 fColor = kColors[circle];
180 fLineWidth = std::pow(random->nextF(), 12) * 20 + 3;
181 fOmega = random->nextF() * 3 + 0.2f;
182 float theta = random->nextRangeF(0, 2*SK_ScalarPI);
183 fCosTheta = std::cos(theta);
184 fSinTheta = std::sin(theta);
185 fStart = params.fCircleCenters[circle] + SkPoint::Make(params.fCircleRadius * fCosTheta,
186 params.fCircleRadius * fSinTheta);
187 fLength = params.fLineMinimum;
188 fLength += std::pow(random->nextF(), 8) * params.fLineLengthMaximum;
189 fSegmentDirection = random->nextF() > 0.5 ? -1 : 1;
190 }
191
192 ~CanvasLineSegment() override = default;
193
194 void draw(SkCanvas* canvas) override {
195 SkPaint paint;
196 paint.setAntiAlias(true);
197 paint.setColor(fColor);
198 paint.setStrokeWidth(fLineWidth);
199 paint.setStyle(SkPaint::kStroke_Style);
200
201 SkPoint end = {
202 fStart.fX + fSegmentDirection * fLength * fCosTheta,
203 fStart.fY + fSegmentDirection * fLength * fSinTheta
204 };
205 canvas->drawLine(fStart, end, paint);
206 }
207
208 void animate(double nanos) override {
209 fLength += std::sin(time_counter_value(nanos, 100) * fOmega);
210 }
211
212 private:
213 SkColor fColor;
214 float fLineWidth;
215 float fOmega;
216 float fCosTheta;
217 float fSinTheta;
218 SkPoint fStart;
219 float fLength;
220 float fSegmentDirection;
221 };
222
223 class CanvasLineSegmentStage : public Stage {
224 public:
225 CanvasLineSegmentStage(SkSize size)
226 : Stage(size, /*startingObjectCount=*/5000, /*objectIncrement*/1000) {
227 fParams.fLineMinimum = 20;
228 fParams.fLineLengthMaximum = 40;
229 fParams.fCircleRadius = fSize.fWidth/8 - .4 * (fParams.fLineMinimum +
230 fParams.fLineLengthMaximum);
231 fParams.fCircleCenters[0] = SkPoint::Make(5.5 / 32 * fSize.fWidth, 2.1 / 3*fSize.fHeight);
232 fParams.fCircleCenters[1] = SkPoint::Make(12.5 / 32 * fSize.fWidth, .9 / 3*fSize.fHeight);
233 fParams.fCircleCenters[2] = SkPoint::Make(19.5 / 32 * fSize.fWidth, 2.1 / 3*fSize.fHeight);
234 fParams.fCircleCenters[3] = SkPoint::Make(26.5 / 32 * fSize.fWidth, .9 / 3*fSize.fHeight);
235 fHalfSize = SkSize::Make(fSize.fWidth * 0.5f, fSize.fHeight * 0.5f);
236 fTwoFifthsSizeX = fSize.fWidth * .4;
237
238 this->initializeObjects();
239 }
240
241 ~CanvasLineSegmentStage() override = default;
242
243 void draw(SkCanvas* canvas) override {
244 canvas->clear(SkColors::kWhite);
245
246 float dx = fTwoFifthsSizeX * std::cos(fCurrentAngle);
247 float dy = fTwoFifthsSizeX * std::sin(fCurrentAngle);
248
249 float colorStopStep = SkScalarInterp(-.1f, .1f, fCurrentGradientStep);
250 int brightnessStep = SkScalarRoundToInt(SkScalarInterp(32, 64, fCurrentGradientStep));
251
252 SkColor4f color1Step = SkColor4f::FromColor(SkColorSetARGB(brightnessStep,
253 brightnessStep,
254 (brightnessStep << 1),
255 102)),
256 color2Step = SkColor4f::FromColor(SkColorSetARGB((brightnessStep << 1),
257 (brightnessStep << 1),
258 brightnessStep,
259 102));
260 SkPoint pts[2] = {
261 {fHalfSize.fWidth + dx, fHalfSize.fHeight + dy},
262 {fHalfSize.fWidth - dx, fHalfSize.fHeight - dy}
263 };
264 const SkColor4f colors[] = {
265 color1Step,
266 color1Step,
267 color2Step,
268 color2Step
269 };
270 const float pos[] = {
271 0,
272 0.2f + colorStopStep,
273 0.8f - colorStopStep,
274 1
275 };
276 sk_sp<SkShader> gradientShader = SkShaders::LinearGradient(pts,
277 {{colors, pos, SkTileMode::kClamp}, {}});
278
279 SkPaint paint;
280 paint.setAntiAlias(true);
281 paint.setStrokeWidth(15);
282 for (int i = 0; i < 4; i++) {
283 const SkColor strokeColors[] = {
284 0xffe01040, 0xff10c030, 0xff744cba, 0xffe05010
285 };
286 const SkColor fillColors[] = {
287 0xff70051d, 0xff016112, 0xff2F0C6E, 0xff702701
288 };
289 paint.setColor(strokeColors[i]);
290 paint.setStyle(SkPaint::kStroke_Style);
291 SkRect arcRect = SkRect::MakeXYWH(fParams.fCircleCenters[i].fX - fParams.fCircleRadius,
292 fParams.fCircleCenters[i].fY- fParams.fCircleRadius,
293 2*fParams.fCircleRadius,
294 2*fParams.fCircleRadius);
295 canvas->drawArc(arcRect, 0, 360, false, paint);
296 paint.setColor(fillColors[i]);
297 paint.setStyle(SkPaint::kFill_Style);
298 canvas->drawArc(arcRect, 0, 360, false, paint);
299 paint.setShader(gradientShader);
300 canvas->drawArc(arcRect, 0, 360, false, paint);
301 paint.setShader(nullptr);
302 }
303
304 this->Stage::draw(canvas);
305 }
306
307 bool animate(double nanos) override {
308 fCurrentAngle = time_fractional_value(nanos, 3000) * SK_ScalarPI * 2;
309 fCurrentGradientStep = 0.5f + 0.5f * std::sin(
310 time_fractional_value(nanos, 5000) * SK_ScalarPI * 2);
311
312 this->Stage::animate(nanos);
313 return true;
314 }
315
316 std::unique_ptr<MMObject> createObject() override {
317 return std::make_unique<CanvasLineSegment>(&fRandom,fParams);
318 }
319 private:
320 LineSegmentParams fParams;
321 SkSize fHalfSize;
322 float fTwoFifthsSizeX;
323 float fCurrentAngle = 0;
324 float fCurrentGradientStep = 0.5f;
325 };
326
327 ///////////////////////////////////////////////////////////////////////////////////////////////////
328 // Canvas Arcs
329 ///////////////////////////////////////////////////////////////////////////////////////////////////
330
331 class CanvasArc : public MMObject {
332 public:
333 CanvasArc(SkRandom* random, SkSize size) {
334 constexpr float kMaxX = 6;
335 constexpr float kMaxY = 3;
336
337 const SkColor baseColors[3] = {
338 0xff101010, 0xff808080, 0xffc0c0c0
339 };
340 const SkColor bonusColors[3] = {
341 0xffe01040, 0xff10c030, 0xffe05010
342 };
343 float distanceX = size.fWidth / kMaxX;
344 float distanceY = size.fHeight / (kMaxY + 1);
345 int randY = random->nextRangeU(0, kMaxY);
346 int randX = random->nextRangeU(0, kMaxX - 1 * (randY % 2));
347
348 fPoint = SkPoint::Make(distanceX * (randX + (randY % 2) / 2), distanceY * (randY + 0.5f));
349
350 fRadius = 20 + std::pow(random->nextF(), 5) * (std::min(distanceX, distanceY) / 1.8f);
351 fStartAngle = random->nextRangeF(0, 2*SK_ScalarPI);
352 fEndAngle = random->nextRangeF(0, 2*SK_ScalarPI);
353 fOmega = (random->nextF() - 0.5f) * 0.3f;
354 fCounterclockwise = random->nextBool();
355 // The MotionMark code appends a random element from an array and appends it to the color
356 // array, then randomly picks from that. We'll just pick that random element and use it
357 // if the index is out of bounds for the base color array.
358 SkColor bonusColor = bonusColors[(randX + sk_float_ceil2int(randY * 0.5f)) % 3];
359 int colorIndex = random->nextRangeU(0, 3);
360 fColor = colorIndex == 3 ? bonusColor : baseColors[colorIndex];
361 fLineWidth = 1 + std::pow(random->nextF(), 5) * 30;
362 fDoStroke = random->nextRangeU(0, 3) != 0;
363 }
364
365 ~CanvasArc() override = default;
366
367 void draw(SkCanvas* canvas) override {
368 SkPaint paint;
369 paint.setAntiAlias(true);
370 paint.setColor(fColor);
371 SkRect arcRect = SkRect::MakeXYWH(fPoint.fX - fRadius, fPoint.fY - fRadius,
372 2*fRadius, 2*fRadius);
373
374 float startAngleDeg = fStartAngle * 180.f / SK_ScalarPI;
375 float endAngleDeg = fEndAngle * 180.f / SK_ScalarPI;
376 canonicalize_angle(&startAngleDeg, &endAngleDeg);
377 endAngleDeg = adjust_end_angle(startAngleDeg, endAngleDeg, fCounterclockwise);
378
379 float sweepAngle = startAngleDeg - endAngleDeg;
380
381 if (fDoStroke) {
382 paint.setStrokeWidth(fLineWidth);
383 paint.setStyle(SkPaint::kStroke_Style);
384 canvas->drawArc(arcRect, startAngleDeg, sweepAngle, false, paint);
385 } else {
386 paint.setStyle(SkPaint::kFill_Style);
387 // The MotionMark code creates a path for fills via lineTo(point), arc(), lineTo(point).
388 // For now we'll just use drawArc for both but might need to revisit.
389 canvas->drawArc(arcRect, startAngleDeg, sweepAngle, true, paint);
390 }
391 }
392
393 void animate(double /*nanos*/) override {
394 fStartAngle += fOmega;
395 fEndAngle += fOmega / 2;
396 }
397
398 private:
399 SkPoint fPoint;
400 float fRadius;
401 float fStartAngle; // in radians
402 float fEndAngle; // in radians
403 SkColor fColor;
404 float fOmega; // in radians
405 bool fDoStroke;
406 bool fCounterclockwise;
407 float fLineWidth;
408 };
409
410 class CanvasArcStage : public Stage {
411 public:
412 CanvasArcStage(SkSize size)
413 : Stage(size, /*startingObjectCount=*/1000, /*objectIncrement=*/200) {
414 this->initializeObjects();
415 }
416
417 ~CanvasArcStage() override = default;
418
419 void draw(SkCanvas* canvas) override {
420 canvas->clear(SK_ColorWHITE);
421 this->Stage::draw(canvas);
422 }
423
424 std::unique_ptr<MMObject> createObject() override {
425 return std::make_unique<CanvasArc>(&fRandom, fSize);
426 }
427 };
428
429 ///////////////////////////////////////////////////////////////////////////////////////////////////
430 // Paths
431 ///////////////////////////////////////////////////////////////////////////////////////////////////
432
433 class CanvasLinePoint : public MMObject {
434 protected:
435 void setEndPoint(SkRandom* random, SkSize size, SkPoint* prevCoord) {
436 const SkSize kGridSize = { 80, 40 };
437 const SkPoint kGridCenter = { 40, 20 };
438 const SkPoint kOffsets[4] = {
439 {-4, 0},
440 {2, 0},
441 {1, -2},
442 {1, 2}
443 };
444
445 SkPoint coordinate = prevCoord ? *prevCoord : kGridCenter;
446 if (prevCoord) {
447 SkPoint offset = kOffsets[random->nextRangeU(0, 3)];
448 coordinate += offset;
449 if (coordinate.fX < 0 || coordinate.fX > kGridSize.width())
450 coordinate.fX -= offset.fX * 2;
451 if (coordinate.fY < 0 || coordinate.fY > kGridSize.height())
452 coordinate.fY -= offset.fY * 2;
453 }
454
455 fPoint = SkPoint::Make((coordinate.fX + 0.5f) * size.width() / (kGridSize.width() + 1),
456 (coordinate.fY + 0.5f) * size.height() / (kGridSize.height() + 1));
457 fCoordinate = coordinate;
458 }
459
460 public:
461 CanvasLinePoint(SkRandom* random, SkSize size, SkPoint* prev) {
462 const SkColor kColors[7] = {
463 0xff101010, 0xff808080, 0xffc0c0c0, 0xff101010, 0xff808080, 0xffc0c0c0, 0xffe01040
464 };
465 fColor = kColors[random->nextRangeU(0, 6)];
466
467 fWidth = std::pow(random->nextF(), 5) * 20 + 1;
468 fIsSplit = random->nextBool();
469
470 this->setEndPoint(random, size, prev);
471 }
472
473 ~CanvasLinePoint() override = default;
474
475 virtual void append(SkPathBuilder* path) {
476 path->lineTo(fPoint);
477 }
478
479 // unused, all the work is done by append
480 void draw(SkCanvas*) override {}
481 void animate(double) override {}
482
483 SkColor getColor() { return fColor; }
484 float getWidth() { return fWidth; }
485 SkPoint getPoint() { return fPoint; }
486 SkPoint getCoord() { return fCoordinate; }
487 bool isSplit() { return fIsSplit; }
488 void toggleIsSplit() { fIsSplit = !fIsSplit; }
489
490 private:
491 SkPoint fPoint;
492 SkPoint fCoordinate;
493 SkColor fColor;
494 float fWidth;
495 bool fIsSplit;
496 };
497
498 class CanvasQuadraticSegment : public CanvasLinePoint {
499 public:
500 CanvasQuadraticSegment(SkRandom* random, SkSize size, SkPoint* prev)
501 : CanvasLinePoint(random, size, prev) {
502 // Note: The construction of these points is odd but mirrors the Javascript code.
503
504 // The chosen point from the base constructor is instead the control point.
505 fPoint2 = this->getPoint();
506
507 // Get another random point for the actual end point of the segment.
508 this->setEndPoint(random, size, prev);
509 }
510
511 void append(SkPathBuilder* path) override {
512 path->quadTo(fPoint2, this->getPoint());
513 }
514
515 private:
516 SkPoint fPoint2;
517 };
518
519 class CanvasBezierSegment : public CanvasLinePoint {
520 public:
521 CanvasBezierSegment(SkRandom* random, SkSize size, SkPoint* prev)
522 : CanvasLinePoint(random, size, prev) {
523 // Note: The construction of these points is odd but mirrors the Javascript code.
524
525 // The chosen point from the base constructor is instead the control point.
526 fPoint2 = this->getPoint();
527
528 // Get the second control point.
529 this->setEndPoint(random, size, prev);
530 fPoint3 = this->getPoint();
531
532 // Get third random point for the actual end point of the segment.
533 this->setEndPoint(random, size, prev);
534 }
535
536 void append(SkPathBuilder* path) override {
537 path->cubicTo(fPoint2, fPoint3, this->getPoint());
538 }
539
540 private:
541 SkPoint fPoint2;
542 SkPoint fPoint3;
543 };
544
545
546 std::unique_ptr<CanvasLinePoint> make_line_path(SkRandom* random, SkSize size, SkPoint* prev) {
547 int choice = random->nextRangeU(0, 3);
548 switch (choice) {
549 case 0: return std::make_unique<CanvasQuadraticSegment>(random, size, prev);
550 case 1: return std::make_unique<CanvasBezierSegment>(random, size, prev);
551 case 2: [[fallthrough]];
552 case 3: [[fallthrough]];
553 default: return std::make_unique<CanvasLinePoint>(random, size, prev);
554 }
555 SkUNREACHABLE;
556 }
557
558 class CanvasLinePathStage : public Stage {
559 public:
560 CanvasLinePathStage(SkSize size)
561 : Stage(size, /*startingObjectCount=*/5000, /*objectIncrement=*/1000) {
562 this->initializeObjects();
563 }
564
565 ~CanvasLinePathStage() override = default;
566
567 void draw(SkCanvas* canvas) override {
568 canvas->clear(SK_ColorWHITE);
569
570 SkPathBuilder currentPath;
571 SkPaint paint;
572 paint.setAntiAlias(true);
573 paint.setStyle(SkPaint::kStroke_Style);
574 for (size_t i = 0; i < fObjects.size(); ++i) {
575 CanvasLinePoint* object = reinterpret_cast<CanvasLinePoint*>(fObjects[i].get());
576 if (i == 0) {
577 paint.setStrokeWidth(object->getWidth());
578 paint.setColor(object->getColor());
579 currentPath.moveTo(object->getPoint());
580 } else {
581 object->append(&currentPath);
582
583 if (object->isSplit()) {
584 canvas->drawPath(currentPath.detach(), paint);
585
586 paint.setStrokeWidth(object->getWidth());
587 paint.setColor(object->getColor());
588 currentPath.moveTo(object->getPoint());
589 }
590
591 if (fRandom.nextF() > 0.995) {
592 object->toggleIsSplit();
593 }
594 }
595 }
596 canvas->drawPath(currentPath.detach(), paint);
597 }
598
599 bool animate(double /*nanos*/) override {
600 // Nothing to do, but return true so we redraw.
601 return true;
602 }
603
604 std::unique_ptr<MMObject> createObject() override {
605 if (fObjects.empty()) {
606 return make_line_path(&fRandom, fSize, nullptr);
607 } else {
608 CanvasLinePoint* prevObject = reinterpret_cast<CanvasLinePoint*>(fObjects.back().get());
609 SkPoint coord = prevObject->getCoord();
610 return make_line_path(&fRandom, fSize, &coord);
611 }
612 }
613 };
614
615 ///////////////////////////////////////////////////////////////////////////////////////////////////
616 // Bouncing Particles
617 ///////////////////////////////////////////////////////////////////////////////////////////////////
618
619 SkPoint random_position(SkRandom* random, SkSize maxPosition) {
620 return {(float)random->nextRangeU(0, maxPosition.width()),
621 (float)random->nextRangeU(0, maxPosition.height())};
622 }
623
624 float random_angle(SkRandom* random) {
625 return random->nextRangeF(0, 2*SK_FloatPI);
626 }
627
628 float random_velocity(SkRandom* random, float maxVelocity) {
629 return random->nextRangeF(maxVelocity/8, maxVelocity);
630 }
631
632 class Rotater {
633 public:
634 Rotater(float rotateInterval)
635 : fTimeDelta(0)
636 , fRotateInterval(rotateInterval) {}
637
638 void next(float timeDelta) {
639 fTimeDelta = SkScalarMod(fTimeDelta + timeDelta, fRotateInterval);
640 }
641
642 float degrees() {
643 return (360 * fTimeDelta) / fRotateInterval;
644 }
645
646 private:
647 float fTimeDelta;
648 float fRotateInterval;
649 };
650
651 Rotater random_rotater(SkRandom* random) {
652 return Rotater(random->nextRangeF(10, 100));
653 }
654
655 SkPoint point_on_circle(float angle, float radius) {
656 return {radius * SkScalarCos(angle), radius * SkScalarSin(angle)};
657 }
658
659 class BouncingParticle : public MMObject {
660 public:
661 BouncingParticle(SkRandom* random, SkSize stageSize, SkSize particleSize, float maxVelocity)
662 : fStageSize(stageSize)
663 , fSize(particleSize)
664 , fPosition(random_position(random,
665 {stageSize.fWidth - particleSize.fWidth,
666 stageSize.fHeight - particleSize.fHeight}))
667 , fAngle(random_angle(random))
668 , fVelocity(random_velocity(random, maxVelocity))
669 , fRotater(random_rotater(random)) {
670 }
671
672 void animate(double deltaNanos) override {
673 // TODO: consolidate and pass in millis to the Stages
674 constexpr double kMillisPerNano = 0.0000001;
675 fPosition += point_on_circle(fAngle, fVelocity * (deltaNanos * kMillisPerNano));
676 fRotater.next(deltaNanos * kMillisPerNano);
677
678 // If particle is going to move off right side
679 if (fPosition.fX + fSize.width() > fStageSize.width()) {
680 // If direction is East-South, go West-South.
681 if (fAngle >= 0 && fAngle < SK_FloatPI / 2)
682 fAngle = SK_FloatPI - fAngle;
683 // If angle is East-North, go West-North.
684 else if (fAngle > SK_FloatPI / 2 * 3)
685 fAngle = fAngle - (fAngle - SK_FloatPI / 2 * 3) * 2;
686 // Make sure the particle does not go outside the stage boundaries.
687 fPosition.fX = fStageSize.width() - fSize.width();
688 }
689
690 // If particle is going to move off left side
691 if (fPosition.fX < 0) {
692 // If angle is West-South, go East-South.
693 if (fAngle > SK_FloatPI / 2 && fAngle < SK_FloatPI)
694 fAngle = SK_FloatPI - fAngle;
695 // If angle is West-North, go East-North.
696 else if (fAngle > SK_FloatPI && fAngle < SK_FloatPI / 2 * 3)
697 fAngle = fAngle + (SK_FloatPI / 2 * 3 - fAngle) * 2;
698 // Make sure the particle does not go outside the stage boundaries.
699 fPosition.fX = 0;
700 }
701
702 // If particle is going to move off bottom side
703 if (fPosition.fY + fSize.height() > fStageSize.height()) {
704 // If direction is South, go North.
705 if (fAngle > 0 && fAngle < SK_FloatPI)
706 fAngle = SK_FloatPI * 2 - fAngle;
707 // Make sure the particle does not go outside the stage boundaries.
708 fPosition.fY = fStageSize.height() - fSize.height();
709 }
710
711 // If particle is going to move off top side
712 if (fPosition.fY < 0) {
713 // If direction is North, go South.
714 if (fAngle > SK_FloatPI && fAngle < SK_FloatPI * 2)
715 fAngle = fAngle - (fAngle - SK_FloatPI) * 2;
716 // Make sure the particle does not go outside the stage boundaries.
717 fPosition.fY = 0;
718 }
719 }
720
721 protected:
722 SkSize fStageSize;
723 SkSize fSize;
724 SkPoint fPosition;
725 float fAngle;
726 float fVelocity;
727 Rotater fRotater;
728 };
729
730 class BouncingParticlesStage : public Stage {
731 public:
732 BouncingParticlesStage(SkSize size)
733 : Stage(size, /*startingObjectCount=*/3000, /*objectIncrement=*/500)
734 , fParticleSize({150, 150})
735 , fMaxVelocity(10){
736 }
737
738 bool animate(double nanos) override {
739 // The particles take delta time
740 if (fLastTime < 0) {
741 fLastTime = nanos;
742 }
743 for (size_t i = 0; i < fObjects.size(); ++i) {
744 fObjects[i]->animate(nanos - fLastTime);
745 }
746 fLastTime = nanos;
747 return true;
748 }
749
750 protected:
751 SkSize fParticleSize;
752 float fMaxVelocity;
753 double fLastTime = -1;
754 };
755
756
757 class BouncingTaggedImage : public BouncingParticle {
758 public:
759 BouncingTaggedImage(SkRandom* random, SkSize stageSize, SkSize particleSize, float maxVelocity)
760 : BouncingParticle(random, stageSize, particleSize, maxVelocity) {
761 this->move();
762 fRect = SkRect::MakeSize(fSize);
763 fRect.offset(-fSize.width()/2, -fSize.height()/2);
764 }
765
766 void move() {
767 fTransform = SkMatrix::RotateDeg(std::floor(fRotater.degrees()));
768 fTransform.setTranslateX(fPosition.fX);
769 fTransform.setTranslateY(fPosition.fY);
770 }
771
772 void animate(double deltaNanos) override {
773 BouncingParticle::animate(deltaNanos);
774 this->move();
775 }
776
777 void draw(SkCanvas* canvas) override {
778 // handled by the Stage
779 }
780
781 const SkMatrix& transform() { return fTransform; }
782 SkRect rect() { return fRect; }
783
784 private:
785 SkMatrix fTransform;
786 SkRect fRect;
787 };
788
789
790 class BouncingTaggedImagesStage : public BouncingParticlesStage {
791 public:
792 BouncingTaggedImagesStage(SkSize size) : BouncingParticlesStage(size) {
793
794 this->initializeObjects();
795 }
796
797 ~BouncingTaggedImagesStage() override = default;
798
799 void initImages(SkCanvas* canvas) {
800 const char* kImageSrcs[kImageCount] = {
801 "images/brickwork-texture.jpg",
802 "images/dog.jpg",
803 "images/color_wheel.jpg",
804 "images/mandrill_512_q075.jpg",
805 "images/flutter_logo.jpg",
806 };
807
808 #if defined(SK_GRAPHITE)
809 skgpu::graphite::Recorder* recorder = nullptr;
810 recorder = canvas->recorder();
811 #endif
812 for (int i = 0; i < kImageCount; ++i) {
813 auto lazyYUV = sk_gpu_test::LazyYUVImage::Make(GetResourceAsData(kImageSrcs[i]),
814 skgpu::Mipmapped::kYes);
815 SkASSERT(lazyYUV);
816 #if defined(SK_GRAPHITE)
817 if (recorder) {
818 fImages[i] = lazyYUV->refImage(recorder,
819 sk_gpu_test::LazyYUVImage::Type::kFromPixmaps);
820 }
821 #endif
822 #if defined(SK_GANESH)
823 if (auto rContext = canvas->recordingContext()) {
824 fImages[i] = lazyYUV->refImage(rContext,
825 sk_gpu_test::LazyYUVImage::Type::kFromPixmaps);
826 }
827 #endif
828 }
829 }
830
831 void draw(SkCanvas* canvas) override {
832 if (fNeedToInitImages) {
833 this->initImages(canvas);
834 fNeedToInitImages = false;
835 }
836
837 canvas->clear(SK_ColorWHITE);
838
839 SkPaint paint;
840 SkSamplingOptions sampling(SkFilterMode::kLinear,
841 SkMipmapMode::kNearest);
842 for (size_t i = 0; i < fObjects.size(); ++i) {
843 BouncingTaggedImage* object = reinterpret_cast<BouncingTaggedImage*>(fObjects[i].get());
844
845 canvas->save();
846 canvas->concat(object->transform());
847 canvas->drawImageRect(fImages[i % kImageCount], object->rect(), sampling, nullptr);
848
849 canvas->restore();
850 }
851 }
852
853 std::unique_ptr<MMObject> createObject() override {
854 return std::make_unique<BouncingTaggedImage>(&fRandom, fSize, fParticleSize, fMaxVelocity);
855 }
856
857 void reset() {
858 fNeedToInitImages = true;
859 }
860
861 private:
862 static constexpr int kImageCount = 5;
863
864 bool fNeedToInitImages = true;
865 sk_sp<SkImage> fImages[kImageCount];
866 };
867
868 ///////////////////////////////////////////////////////////////////////////////////////////////////
869
870 class CanvasLinesSlide : public MotionMarkSlide {
871 public:
872 CanvasLinesSlide() {fName = "MotionMarkCanvasLines"; }
873
874 void load(SkScalar w, SkScalar h) override {
875 fStage = std::make_unique<CanvasLineSegmentStage>(SkSize::Make(w, h));
876 }
877 };
878
879 class CanvasArcsSlide : public MotionMarkSlide {
880 public:
881 CanvasArcsSlide() {fName = "MotionMarkCanvasArcs"; }
882
883 void load(SkScalar w, SkScalar h) override {
884 fStage = std::make_unique<CanvasArcStage>(SkSize::Make(w, h));
885 }
886 };
887
888 class PathsSlide : public MotionMarkSlide {
889 public:
890 PathsSlide() {fName = "MotionMarkPaths"; }
891
892 void load(SkScalar w, SkScalar h) override {
893 fStage = std::make_unique<CanvasLinePathStage>(SkSize::Make(w, h));
894 }
895 };
896
897 class BouncingTaggedImagesSlide : public MotionMarkSlide {
898 public:
899 BouncingTaggedImagesSlide() {fName = "MotionMarkBouncingTaggedImages"; }
900
901 void load(SkScalar w, SkScalar h) override {
902 fStage = std::make_unique<BouncingTaggedImagesStage>(SkSize::Make(w, h));
903 }
904
905 void gpuTeardown() override {
906 if (fStage) {
907 reinterpret_cast<BouncingTaggedImagesStage*>(fStage.get())->reset();
908 }
909 }
910 };
911
912 DEF_SLIDE( return new CanvasLinesSlide(); )
913 DEF_SLIDE( return new CanvasArcsSlide(); )
914 DEF_SLIDE( return new PathsSlide(); )
915 DEF_SLIDE( return new BouncingTaggedImagesSlide(); )