blob: 31b0a7d8b9262b1a778128b7ef7b1d1fff34f940 [file] [log] [blame]
csmartdaltoned4984b2017-02-13 14:57:28 -07001/*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SampleCode.h"
9#include "SkAnimTimer.h"
10#include "SkCanvas.h"
11#include "SkGlyphCache.h"
12#include "SkPaint.h"
13#include "SkPath.h"
14#include "SkRandom.h"
15#include "SkTaskGroup.h"
Chris Dalton7c02cc72017-11-06 14:10:54 -070016#include "sk_tool_utils.h"
csmartdaltoned4984b2017-02-13 14:57:28 -070017
18////////////////////////////////////////////////////////////////////////////////////////////////////
19// Static text from paths.
20class PathText : public SampleView {
21public:
22 constexpr static int kNumPaths = 1500;
23 virtual const char* getName() const { return "PathText"; }
24
Chris Dalton7c02cc72017-11-06 14:10:54 -070025 PathText() {
csmartdaltoned4984b2017-02-13 14:57:28 -070026 SkPaint defaultPaint;
27 SkAutoGlyphCache agc(defaultPaint, nullptr, &SkMatrix::I());
28 SkGlyphCache* cache = agc.getCache();
29 SkPath glyphPaths[52];
30 for (int i = 0; i < 52; ++i) {
31 // I and l are rects on OS X ...
32 char c = "aQCDEFGH7JKLMNOPBRZTUVWXYSAbcdefghijk1mnopqrstuvwxyz"[i];
33 SkGlyphID id = cache->unicharToGlyph(c);
34 cache->getScalerContext()->getPath(SkPackedGlyphID(id), &glyphPaths[i]);
35 }
36
37 for (int i = 0; i < kNumPaths; ++i) {
38 const SkPath& p = glyphPaths[i % 52];
39 fGlyphs[i].init(fRand, p);
40 }
41 }
42
43 virtual void reset() {
44 for (Glyph& glyph : fGlyphs) {
45 glyph.reset(fRand, this->width(), this->height());
46 }
47 }
48
49 void onOnceBeforeDraw() final { this->INHERITED::onOnceBeforeDraw(); this->reset(); }
50 void onSizeChange() final { this->INHERITED::onSizeChange(); this->reset(); }
51
52 bool onQuery(SkEvent* evt) final {
53 if (SampleCode::TitleQ(*evt)) {
54 SampleCode::TitleR(evt, this->getName());
55 return true;
56 }
Chris Dalton7c02cc72017-11-06 14:10:54 -070057 SkUnichar unichar;
58 if (SampleCode::CharQ(*evt, &unichar)) {
59 if (unichar == 'X') {
60 fDoClip = !fDoClip;
Chris Dalton7c02cc72017-11-06 14:10:54 -070061 return true;
62 }
63 }
csmartdaltoned4984b2017-02-13 14:57:28 -070064 return this->INHERITED::onQuery(evt);
65 }
66
67 void onDrawContent(SkCanvas* canvas) override {
Chris Dalton7c02cc72017-11-06 14:10:54 -070068 if (fDoClip) {
69 SkMatrix oldMatrix = canvas->getTotalMatrix();
70 canvas->setMatrix(SkMatrix::MakeScale(this->width(), this->height()));
71 canvas->save();
72 canvas->clipPath(fClipPath, SkClipOp::kDifference, true);
73 canvas->clear(SK_ColorBLACK);
74 canvas->restore();
75 canvas->clipPath(fClipPath, SkClipOp::kIntersect, true);
76 canvas->setMatrix(oldMatrix);
77 }
78 this->drawGlyphs(canvas);
79 }
80
81 virtual void drawGlyphs(SkCanvas* canvas) {
csmartdaltoned4984b2017-02-13 14:57:28 -070082 for (Glyph& glyph : fGlyphs) {
83 SkAutoCanvasRestore acr(canvas, true);
84 canvas->translate(glyph.fPosition.x(), glyph.fPosition.y());
85 canvas->scale(glyph.fZoom, glyph.fZoom);
86 canvas->rotate(glyph.fSpin);
87 canvas->translate(-glyph.fMidpt.x(), -glyph.fMidpt.y());
88 canvas->drawPath(glyph.fPath, glyph.fPaint);
89 }
90 }
91
92protected:
93 struct Glyph {
94 void init(SkRandom& rand, const SkPath& path);
95 void reset(SkRandom& rand, int w, int h);
96
97 SkPath fPath;
98 SkPaint fPaint;
99 SkPoint fPosition;
100 SkScalar fZoom;
101 SkScalar fSpin;
102 SkPoint fMidpt;
103 };
104
105 Glyph fGlyphs[kNumPaths];
Chris Dalton7c02cc72017-11-06 14:10:54 -0700106 SkRandom fRand{25};
107 SkPath fClipPath = sk_tool_utils::make_star(SkRect{0,0,1,1}, 11, 3);
108 bool fDoClip = false;
csmartdaltoned4984b2017-02-13 14:57:28 -0700109
110 typedef SampleView INHERITED;
111};
112
113void PathText::Glyph::init(SkRandom& rand, const SkPath& path) {
114 fPath = path;
115 fPaint.setAntiAlias(true);
116 fPaint.setColor(rand.nextU() | 0x80808080);
117}
118
119void PathText::Glyph::reset(SkRandom& rand, int w, int h) {
120 int screensize = SkTMax(w, h);
121 const SkRect& bounds = fPath.getBounds();
122 SkScalar t;
123
124 fPosition = {rand.nextF() * w, rand.nextF() * h};
125 t = pow(rand.nextF(), 100);
126 fZoom = ((1 - t) * screensize / 50 + t * screensize / 3) /
127 SkTMax(bounds.width(), bounds.height());
128 fSpin = rand.nextF() * 360;
129 fMidpt = {bounds.centerX(), bounds.centerY()};
130}
131
132////////////////////////////////////////////////////////////////////////////////////////////////////
133// Text from paths with animated transformation matrices.
134class MovingPathText : public PathText {
135public:
136 const char* getName() const override { return "MovingPathText"; }
137
138 MovingPathText()
139 : fFrontMatrices(kNumPaths)
140 , fBackMatrices(kNumPaths) {
141 }
142
Brian Salomond3b65972017-03-22 12:05:03 -0400143 ~MovingPathText() override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700144 fBackgroundAnimationTask.wait();
145 }
146
147 void reset() override {
148 const SkScalar screensize = static_cast<SkScalar>(SkTMax(this->width(), this->height()));
149 this->INHERITED::reset();
150
151 for (auto& v : fVelocities) {
152 for (SkScalar* d : {&v.fDx, &v.fDy}) {
153 SkScalar t = pow(fRand.nextF(), 3);
154 *d = ((1 - t) / 60 + t / 10) * (fRand.nextBool() ? screensize : -screensize);
155 }
156
157 SkScalar t = pow(fRand.nextF(), 25);
158 v.fDSpin = ((1 - t) * 360 / 7.5 + t * 360 / 1.5) * (fRand.nextBool() ? 1 : -1);
159 }
160
161 // Get valid front data.
162 fBackgroundAnimationTask.wait();
163 this->runAnimationTask(0, 0, this->width(), this->height());
164 memcpy(fFrontMatrices, fBackMatrices, kNumPaths * sizeof(SkMatrix));
165 fLastTick = 0;
166 }
167
168 bool onAnimate(const SkAnimTimer& timer) final {
169 fBackgroundAnimationTask.wait();
170 this->swapAnimationBuffers();
171
172 const double tsec = timer.secs();
173 const double dt = fLastTick ? (timer.secs() - fLastTick) : 0;
174 fBackgroundAnimationTask.add(std::bind(&MovingPathText::runAnimationTask, this, tsec,
175 dt, this->width(), this->height()));
176 fLastTick = timer.secs();
177 return true;
178 }
179
180 /**
181 * Called on a background thread. Here we can only modify fBackMatrices.
182 */
183 virtual void runAnimationTask(double t, double dt, int w, int h) {
184 for (int idx = 0; idx < kNumPaths; ++idx) {
185 Velocity* v = &fVelocities[idx];
186 Glyph* glyph = &fGlyphs[idx];
187 SkMatrix* backMatrix = &fBackMatrices[idx];
188
189 glyph->fPosition.fX += v->fDx * dt;
190 if (glyph->fPosition.x() < 0) {
191 glyph->fPosition.fX -= 2 * glyph->fPosition.x();
192 v->fDx = -v->fDx;
193 } else if (glyph->fPosition.x() > w) {
194 glyph->fPosition.fX -= 2 * (glyph->fPosition.x() - w);
195 v->fDx = -v->fDx;
196 }
197
198 glyph->fPosition.fY += v->fDy * dt;
199 if (glyph->fPosition.y() < 0) {
200 glyph->fPosition.fY -= 2 * glyph->fPosition.y();
201 v->fDy = -v->fDy;
202 } else if (glyph->fPosition.y() > h) {
203 glyph->fPosition.fY -= 2 * (glyph->fPosition.y() - h);
204 v->fDy = -v->fDy;
205 }
206
207 glyph->fSpin += v->fDSpin * dt;
208
209 backMatrix->setTranslate(glyph->fPosition.x(), glyph->fPosition.y());
210 backMatrix->preScale(glyph->fZoom, glyph->fZoom);
211 backMatrix->preRotate(glyph->fSpin);
212 backMatrix->preTranslate(-glyph->fMidpt.x(), -glyph->fMidpt.y());
213 }
214 }
215
216 virtual void swapAnimationBuffers() {
217 std::swap(fFrontMatrices, fBackMatrices);
218 }
219
Chris Dalton7c02cc72017-11-06 14:10:54 -0700220 void drawGlyphs(SkCanvas* canvas) override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700221 for (int i = 0; i < kNumPaths; ++i) {
222 SkAutoCanvasRestore acr(canvas, true);
223 canvas->concat(fFrontMatrices[i]);
224 canvas->drawPath(fGlyphs[i].fPath, fGlyphs[i].fPaint);
225 }
226 }
227
228protected:
229 struct Velocity {
230 SkScalar fDx, fDy;
231 SkScalar fDSpin;
232 };
233
234 Velocity fVelocities[kNumPaths];
235 SkAutoTMalloc<SkMatrix> fFrontMatrices;
236 SkAutoTMalloc<SkMatrix> fBackMatrices;
237 SkTaskGroup fBackgroundAnimationTask;
238 double fLastTick;
239
240 typedef PathText INHERITED;
241};
242
243
244////////////////////////////////////////////////////////////////////////////////////////////////////
245// Text from paths with animated control points.
246class WavyPathText : public MovingPathText {
247public:
248 const char* getName() const override { return "WavyPathText"; }
249
250 WavyPathText()
251 : fFrontPaths(kNumPaths)
252 , fBackPaths(kNumPaths) {}
253
Brian Salomond3b65972017-03-22 12:05:03 -0400254 ~WavyPathText() override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700255 fBackgroundAnimationTask.wait();
256 }
257
258 void reset() override {
259 fWaves.reset(fRand, this->width(), this->height());
260 this->INHERITED::reset();
261 std::copy(fBackPaths.get(), fBackPaths.get() + kNumPaths, fFrontPaths.get());
262 }
263
264 /**
265 * Called on a background thread. Here we can only modify fBackPaths.
266 */
267 void runAnimationTask(double t, double dt, int w, int h) override {
268 const float tsec = static_cast<float>(t);
269 this->INHERITED::runAnimationTask(t, 0.5 * dt, w, h);
270
271 for (int i = 0; i < kNumPaths; ++i) {
272 const Glyph& glyph = fGlyphs[i];
273 const SkMatrix& backMatrix = fBackMatrices[i];
274
275 const Sk2f matrix[3] = {
276 Sk2f(backMatrix.getScaleX(), backMatrix.getSkewY()),
277 Sk2f(backMatrix.getSkewX(), backMatrix.getScaleY()),
278 Sk2f(backMatrix.getTranslateX(), backMatrix.getTranslateY())
279 };
280
281 SkPath* backpath = &fBackPaths[i];
282 backpath->reset();
283 backpath->setFillType(SkPath::kEvenOdd_FillType);
284
285 SkPath::RawIter iter(glyph.fPath);
286 SkPath::Verb verb;
287 SkPoint pts[4];
288
289 while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
290 switch (verb) {
291 case SkPath::kMove_Verb: {
292 SkPoint pt = fWaves.apply(tsec, matrix, pts[0]);
293 backpath->moveTo(pt.x(), pt.y());
294 break;
295 }
296 case SkPath::kLine_Verb: {
297 SkPoint endpt = fWaves.apply(tsec, matrix, pts[1]);
298 backpath->lineTo(endpt.x(), endpt.y());
299 break;
300 }
301 case SkPath::kQuad_Verb: {
302 SkPoint controlPt = fWaves.apply(tsec, matrix, pts[1]);
303 SkPoint endpt = fWaves.apply(tsec, matrix, pts[2]);
304 backpath->quadTo(controlPt.x(), controlPt.y(), endpt.x(), endpt.y());
305 break;
306 }
307 case SkPath::kClose_Verb: {
308 backpath->close();
309 break;
310 }
311 case SkPath::kCubic_Verb:
312 case SkPath::kConic_Verb:
313 case SkPath::kDone_Verb:
Ben Wagnerb4aab9a2017-08-16 10:53:04 -0400314 SK_ABORT("Unexpected path verb");
csmartdaltoned4984b2017-02-13 14:57:28 -0700315 break;
316 }
317 }
318 }
319 }
320
321 void swapAnimationBuffers() override {
322 this->INHERITED::swapAnimationBuffers();
323 fFrontPaths.swap(fBackPaths);
324 }
325
Chris Dalton7c02cc72017-11-06 14:10:54 -0700326 void drawGlyphs(SkCanvas* canvas) override {
csmartdaltoned4984b2017-02-13 14:57:28 -0700327 for (int i = 0; i < kNumPaths; ++i) {
328 canvas->drawPath(fFrontPaths[i], fGlyphs[i].fPaint);
329 }
330 }
331
332private:
333 /**
334 * Describes 4 stacked sine waves that can offset a point as a function of wall time.
335 */
336 class Waves {
337 public:
338 void reset(SkRandom& rand, int w, int h);
339 SkPoint apply(float tsec, const Sk2f matrix[3], const SkPoint& pt) const;
340
341 private:
342 constexpr static double kAverageAngle = SK_ScalarPI / 8.0;
343 constexpr static double kMaxOffsetAngle = SK_ScalarPI / 3.0;
344
345 float fAmplitudes[4];
346 float fFrequencies[4];
347 float fDirsX[4];
348 float fDirsY[4];
349 float fSpeeds[4];
350 float fOffsets[4];
351 };
352
353 SkAutoTArray<SkPath> fFrontPaths;
354 SkAutoTArray<SkPath> fBackPaths;
355 Waves fWaves;
356
357 typedef MovingPathText INHERITED;
358};
359
360void WavyPathText::Waves::reset(SkRandom& rand, int w, int h) {
361 const double pixelsPerMeter = 0.06 * SkTMax(w, h);
362 const double medianWavelength = 8 * pixelsPerMeter;
363 const double medianWaveAmplitude = 0.05 * 4 * pixelsPerMeter;
364 const double gravity = 9.8 * pixelsPerMeter;
365
366 for (int i = 0; i < 4; ++i) {
367 const double offsetAngle = (rand.nextF() * 2 - 1) * kMaxOffsetAngle;
368 const double intensity = pow(2, rand.nextF() * 2 - 1);
369 const double wavelength = intensity * medianWavelength;
370
371 fAmplitudes[i] = intensity * medianWaveAmplitude;
372 fFrequencies[i] = 2 * SK_ScalarPI / wavelength;
373 fDirsX[i] = cosf(kAverageAngle + offsetAngle);
374 fDirsY[i] = sinf(kAverageAngle + offsetAngle);
375 fSpeeds[i] = -sqrt(gravity * 2 * SK_ScalarPI / wavelength);
376 fOffsets[i] = rand.nextF() * 2 * SK_ScalarPI;
377 }
378}
379
380SkPoint WavyPathText::Waves::apply(float tsec, const Sk2f matrix[3], const SkPoint& pt) const {
Chris Dalton95cf1662017-06-20 16:32:59 -0700381 constexpr static int kTablePeriod = 1 << 12;
382 static float sin2table[kTablePeriod + 1];
csmartdaltoned4984b2017-02-13 14:57:28 -0700383 static SkOnce initTable;
384 initTable([]() {
Chris Dalton95cf1662017-06-20 16:32:59 -0700385 for (int i = 0; i <= kTablePeriod; ++i) {
386 const double sintheta = sin(i * (SK_ScalarPI / kTablePeriod));
csmartdaltoned4984b2017-02-13 14:57:28 -0700387 sin2table[i] = static_cast<float>(sintheta * sintheta - 0.5);
388 }
389 });
390
391 const Sk4f amplitudes = Sk4f::Load(fAmplitudes);
392 const Sk4f frequencies = Sk4f::Load(fFrequencies);
393 const Sk4f dirsX = Sk4f::Load(fDirsX);
394 const Sk4f dirsY = Sk4f::Load(fDirsY);
395 const Sk4f speeds = Sk4f::Load(fSpeeds);
396 const Sk4f offsets = Sk4f::Load(fOffsets);
397
398 float devicePt[2];
399 (matrix[0] * pt.x() + matrix[1] * pt.y() + matrix[2]).store(devicePt);
400
401 const Sk4f t = (frequencies * (dirsX * devicePt[0] + dirsY * devicePt[1]) +
402 speeds * tsec +
Chris Dalton95cf1662017-06-20 16:32:59 -0700403 offsets).abs() * (float(kTablePeriod) / float(SK_ScalarPI));
csmartdaltoned4984b2017-02-13 14:57:28 -0700404
405 const Sk4i ipart = SkNx_cast<int>(t);
406 const Sk4f fpart = t - SkNx_cast<float>(ipart);
407
408 int32_t indices[4];
Chris Dalton95cf1662017-06-20 16:32:59 -0700409 (ipart & (kTablePeriod-1)).store(indices);
csmartdaltoned4984b2017-02-13 14:57:28 -0700410
411 const Sk4f left(sin2table[indices[0]], sin2table[indices[1]],
412 sin2table[indices[2]], sin2table[indices[3]]);
413 const Sk4f right(sin2table[indices[0] + 1], sin2table[indices[1] + 1],
414 sin2table[indices[2] + 1], sin2table[indices[3] + 1]);
415 const Sk4f height = amplitudes * (left * (1.f - fpart) + right * fpart);
416
417 Sk4f dy = height * dirsY;
418 Sk4f dx = height * dirsX;
419
420 float offsetY[4], offsetX[4];
421 (dy + SkNx_shuffle<2,3,0,1>(dy)).store(offsetY); // accumulate.
422 (dx + SkNx_shuffle<2,3,0,1>(dx)).store(offsetX);;
423
424 return {devicePt[0] + offsetY[0] + offsetY[1], devicePt[1] - offsetX[0] - offsetX[1]};
425}
426
427////////////////////////////////////////////////////////////////////////////////////////////////////
428
429DEF_SAMPLE( return new WavyPathText; )
430DEF_SAMPLE( return new MovingPathText; )
431DEF_SAMPLE( return new PathText; )