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 "include/core/SkCanvas.h"
9 #include "include/core/SkM44.h"
10 #include "include/core/SkPaint.h"
11 #include "include/core/SkRRect.h"
12 #include "include/core/SkVertices.h"
13 #include "include/utils/SkRandom.h"
14 #include "samplecode/Sample.h"
15 #include "tools/Resources.h"
16
17 struct VSphere {
18 SkV2 fCenter;
19 SkScalar fRadius;
20
VSphereVSphere21 VSphere(SkV2 center, SkScalar radius) : fCenter(center), fRadius(radius) {}
22
containsVSphere23 bool contains(SkV2 v) const {
24 return (v - fCenter).length() <= fRadius;
25 }
26
pinLocVSphere27 SkV2 pinLoc(SkV2 p) const {
28 auto v = p - fCenter;
29 if (v.length() > fRadius) {
30 v *= (fRadius / v.length());
31 }
32 return fCenter + v;
33 }
34
computeUnitV3VSphere35 SkV3 computeUnitV3(SkV2 v) const {
36 v = (v - fCenter) * (1 / fRadius);
37 SkScalar len2 = v.lengthSquared();
38 if (len2 > 1) {
39 v = v.normalize();
40 len2 = 1;
41 }
42 SkScalar z = SkScalarSqrt(1 - len2);
43 return {v.x, v.y, z};
44 }
45
46 struct RotateInfo {
47 SkV3 fAxis;
48 SkScalar fAngle;
49 };
50
computeRotationInfoVSphere51 RotateInfo computeRotationInfo(SkV2 a, SkV2 b) const {
52 SkV3 u = this->computeUnitV3(a);
53 SkV3 v = this->computeUnitV3(b);
54 SkV3 axis = u.cross(v);
55 SkScalar length = axis.length();
56
57 if (!SkScalarNearlyZero(length)) {
58 return {axis * (1.0f / length), acos(u.dot(v))};
59 }
60 return {{0, 0, 0}, 0};
61 }
62
computeRotationVSphere63 SkM44 computeRotation(SkV2 a, SkV2 b) const {
64 auto [axis, angle] = this->computeRotationInfo(a, b);
65 return SkM44::Rotate(axis, angle);
66 }
67 };
68
inv(const SkM44 & m)69 static SkM44 inv(const SkM44& m) {
70 SkM44 inverse;
71 SkAssertResult(m.invert(&inverse));
72 return inverse;
73 }
74
75 // Compute the inverse transpose (of the upper-left 3x3) of a matrix, used to transform vectors
normals(SkM44 m)76 static SkM44 normals(SkM44 m) {
77 m.setRow(3, {0, 0, 0, 1});
78 m.setCol(3, {0, 0, 0, 1});
79 SkAssertResult(m.invert(&m));
80 return m.transpose();
81 }
82
83 class Sample3DView : public Sample {
84 protected:
85 float fNear = 0.05f;
86 float fFar = 4;
87 float fAngle = SK_ScalarPI / 12;
88
89 SkV3 fEye { 0, 0, 1.0f/tan(fAngle/2) - 1 };
90 SkV3 fCOA { 0, 0, 0 };
91 SkV3 fUp { 0, 1, 0 };
92
93 public:
concatCamera(SkCanvas * canvas,const SkRect & area,SkScalar zscale)94 void concatCamera(SkCanvas* canvas, const SkRect& area, SkScalar zscale) {
95 SkM44 camera = SkM44::LookAt(fEye, fCOA, fUp),
96 perspective = SkM44::Perspective(fNear, fFar, fAngle),
97 viewport = SkM44::Translate(area.centerX(), area.centerY(), 0) *
98 SkM44::Scale(area.width()*0.5f, area.height()*0.5f, zscale);
99
100 canvas->concat(viewport * perspective * camera * inv(viewport));
101 }
102 };
103
104 struct Face {
105 SkScalar fRx, fRy;
106 SkColor fColor;
107
TFace108 static SkM44 T(SkScalar x, SkScalar y, SkScalar z) {
109 return SkM44::Translate(x, y, z);
110 }
111
RFace112 static SkM44 R(SkV3 axis, SkScalar rad) {
113 return SkM44::Rotate(axis, rad);
114 }
115
asM44Face116 SkM44 asM44(SkScalar scale) const {
117 return R({0,1,0}, fRy) * R({1,0,0}, fRx) * T(0, 0, scale);
118 }
119 };
120
front(const SkM44 & m)121 static bool front(const SkM44& m) {
122 SkM44 m2(SkM44::kUninitialized_Constructor);
123 if (!m.invert(&m2)) {
124 m2.setIdentity();
125 }
126 /*
127 * Classically we want to dot the transpose(inverse(ctm)) with our surface normal.
128 * In this case, the normal is known to be {0, 0, 1}, so we only actually need to look
129 * at the z-scale of the inverse (the transpose doesn't change the main diagonal, so
130 * no need to actually transpose).
131 */
132 return m2.rc(2,2) > 0;
133 }
134
135 const Face faces[] = {
136 { 0, 0, SK_ColorRED }, // front
137 { 0, SK_ScalarPI, SK_ColorGREEN }, // back
138
139 { SK_ScalarPI/2, 0, SK_ColorBLUE }, // top
140 {-SK_ScalarPI/2, 0, SK_ColorCYAN }, // bottom
141
142 { 0, SK_ScalarPI/2, SK_ColorMAGENTA }, // left
143 { 0,-SK_ScalarPI/2, SK_ColorYELLOW }, // right
144 };
145
146 #include "include/effects/SkRuntimeEffect.h"
147
148 struct LightOnSphere {
149 SkV2 fLoc;
150 SkScalar fDistance;
151 SkScalar fRadius;
152
computeWorldPosLightOnSphere153 SkV3 computeWorldPos(const VSphere& s) const {
154 return s.computeUnitV3(fLoc) * fDistance;
155 }
156
drawLightOnSphere157 void draw(SkCanvas* canvas) const {
158 SkPaint paint;
159 paint.setAntiAlias(true);
160 paint.setColor(SK_ColorWHITE);
161 canvas->drawCircle(fLoc.x, fLoc.y, fRadius + 2, paint);
162 paint.setColor(SK_ColorBLACK);
163 canvas->drawCircle(fLoc.x, fLoc.y, fRadius, paint);
164 }
165 };
166
167 #include "include/core/SkTime.h"
168
169 class RotateAnimator {
170 SkV3 fAxis = {0, 0, 0};
171 SkScalar fAngle = 0,
172 fPrevAngle = 1234567;
173 double fNow = 0,
174 fPrevNow = 0;
175
176 SkScalar fAngleSpeed = 0,
177 fAngleSign = 1;
178
179 inline static constexpr double kSlowDown = 4;
180 inline static constexpr SkScalar kMaxSpeed = 16;
181
182 public:
update(SkV3 axis,SkScalar angle)183 void update(SkV3 axis, SkScalar angle) {
184 if (angle != fPrevAngle) {
185 fPrevAngle = fAngle;
186 fAngle = angle;
187
188 fPrevNow = fNow;
189 fNow = SkTime::GetSecs();
190
191 fAxis = axis;
192 }
193 }
194
rotation()195 SkM44 rotation() {
196 if (fAngleSpeed > 0) {
197 double now = SkTime::GetSecs();
198 double dtime = now - fPrevNow;
199 fPrevNow = now;
200 double delta = fAngleSign * fAngleSpeed * dtime;
201 fAngle += delta;
202 fAngleSpeed -= kSlowDown * dtime;
203 if (fAngleSpeed < 0) {
204 fAngleSpeed = 0;
205 }
206 }
207 return SkM44::Rotate(fAxis, fAngle);
208
209 }
210
start()211 void start() {
212 if (fPrevNow != fNow) {
213 fAngleSpeed = (fAngle - fPrevAngle) / (fNow - fPrevNow);
214 fAngleSign = fAngleSpeed < 0 ? -1 : 1;
215 fAngleSpeed = std::min(kMaxSpeed, std::abs(fAngleSpeed));
216 } else {
217 fAngleSpeed = 0;
218 }
219 fPrevNow = SkTime::GetSecs();
220 fAngle = 0;
221 }
222
reset()223 void reset() {
224 fAngleSpeed = 0;
225 fAngle = 0;
226 fPrevAngle = 1234567;
227 }
228
isAnimating() const229 bool isAnimating() const { return fAngleSpeed != 0; }
230 };
231
232 class SampleCubeBase : public Sample3DView {
233 enum {
234 DX = 400,
235 DY = 300
236 };
237
238 SkM44 fRotation; // part of model
239
240 RotateAnimator fRotateAnimator;
241
242 protected:
243 enum Flags {
244 kCanRunOnCPU = 1 << 0,
245 kShowLightDome = 1 << 1,
246 };
247
248 LightOnSphere fLight = {{200 + DX, 200 + DY}, 800, 12};
249
250 VSphere fSphere;
251 Flags fFlags;
252
253 public:
SampleCubeBase(Flags flags)254 SampleCubeBase(Flags flags)
255 : fSphere({200 + DX, 200 + DY}, 400)
256 , fFlags(flags)
257 {}
258
onChar(SkUnichar uni)259 bool onChar(SkUnichar uni) override {
260 switch (uni) {
261 case 'Z': fLight.fDistance += 10; return true;
262 case 'z': fLight.fDistance -= 10; return true;
263 }
264 return this->Sample3DView::onChar(uni);
265 }
266
267 virtual void drawContent(
268 SkCanvas* canvas, SkColor, int index, bool drawFront, const SkM44& localToWorld) = 0;
269
onDrawContent(SkCanvas * canvas)270 void onDrawContent(SkCanvas* canvas) override {
271 if (!canvas->recordingContext() && !(fFlags & kCanRunOnCPU)) {
272 return;
273 }
274
275 canvas->save();
276 canvas->translate(DX, DY);
277
278 this->concatCamera(canvas, {0, 0, 400, 400}, 200);
279
280 for (bool drawFront : {false, true}) {
281 int index = 0;
282 for (auto f : faces) {
283 SkAutoCanvasRestore acr(canvas, true);
284
285 SkM44 trans = SkM44::Translate(200, 200, 0); // center of the rotation
286 SkM44 m = fRotateAnimator.rotation() * fRotation * f.asM44(200);
287
288 canvas->concat(trans);
289
290 // "World" space - content is centered at the origin, in device scale (+-200)
291 SkM44 localToWorld = m * inv(trans);
292
293 canvas->concat(localToWorld);
294 this->drawContent(canvas, f.fColor, index++, drawFront, localToWorld);
295 }
296 }
297
298 canvas->restore(); // camera & center the content in the window
299
300 if (fFlags & kShowLightDome){
301 fLight.draw(canvas);
302
303 SkPaint paint;
304 paint.setAntiAlias(true);
305 paint.setStyle(SkPaint::kStroke_Style);
306 paint.setColor(0x40FF0000);
307 canvas->drawCircle(fSphere.fCenter.x, fSphere.fCenter.y, fSphere.fRadius, paint);
308 canvas->drawLine(fSphere.fCenter.x, fSphere.fCenter.y - fSphere.fRadius,
309 fSphere.fCenter.x, fSphere.fCenter.y + fSphere.fRadius, paint);
310 canvas->drawLine(fSphere.fCenter.x - fSphere.fRadius, fSphere.fCenter.y,
311 fSphere.fCenter.x + fSphere.fRadius, fSphere.fCenter.y, paint);
312 }
313 }
314
onFindClickHandler(SkScalar x,SkScalar y,skui::ModifierKey modi)315 Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey modi) override {
316 SkV2 p = fLight.fLoc - SkV2{x, y};
317 if (p.length() <= fLight.fRadius) {
318 Click* c = new Click();
319 c->fMeta.setS32("type", 0);
320 return c;
321 }
322 if (fSphere.contains({x, y})) {
323 Click* c = new Click();
324 c->fMeta.setS32("type", 1);
325
326 fRotation = fRotateAnimator.rotation() * fRotation;
327 fRotateAnimator.reset();
328 return c;
329 }
330 return nullptr;
331 }
onClick(Click * click)332 bool onClick(Click* click) override {
333 if (click->fMeta.hasS32("type", 0)) {
334 fLight.fLoc = fSphere.pinLoc({click->fCurr.fX, click->fCurr.fY});
335 return true;
336 }
337 if (click->fMeta.hasS32("type", 1)) {
338 if (click->fState == skui::InputState::kUp) {
339 fRotation = fRotateAnimator.rotation() * fRotation;
340 fRotateAnimator.start();
341 } else {
342 auto [axis, angle] = fSphere.computeRotationInfo(
343 {click->fOrig.fX, click->fOrig.fY},
344 {click->fCurr.fX, click->fCurr.fY});
345 fRotateAnimator.update(axis, angle);
346 }
347 return true;
348 }
349 return true;
350 }
351
onAnimate(double nanos)352 bool onAnimate(double nanos) override {
353 return fRotateAnimator.isAnimating();
354 }
355
356 private:
357 using INHERITED = Sample3DView;
358 };
359
360 class SampleBump3D : public SampleCubeBase {
361 sk_sp<SkShader> fBmpShader, fImgShader;
362 sk_sp<SkRuntimeEffect> fEffect;
363 SkRRect fRR;
364
365 public:
SampleBump3D()366 SampleBump3D() : SampleCubeBase(Flags(kCanRunOnCPU | kShowLightDome)) {}
367
name()368 SkString name() override { return SkString("bump3d"); }
369
onOnceBeforeDraw()370 void onOnceBeforeDraw() override {
371 fRR = SkRRect::MakeRectXY({20, 20, 380, 380}, 50, 50);
372 auto img = GetResourceAsImage("images/brickwork-texture.jpg");
373 fImgShader = img->makeShader(SkSamplingOptions(), SkMatrix::Scale(2, 2));
374 img = GetResourceAsImage("images/brickwork_normal-map.jpg");
375 fBmpShader = img->makeShader(SkSamplingOptions(), SkMatrix::Scale(2, 2));
376
377 const char code[] = R"(
378 uniform shader color_map;
379 uniform shader normal_map;
380
381 uniform float4x4 localToWorld;
382 uniform float4x4 localToWorldAdjInv;
383 uniform float3 lightPos;
384
385 float3 convert_normal_sample(half4 c) {
386 float3 n = 2 * c.rgb - 1;
387 n.y = -n.y;
388 return n;
389 }
390
391 half4 main(float2 p) {
392 float3 norm = convert_normal_sample(normal_map.eval(p));
393 float3 plane_norm = normalize(localToWorldAdjInv * norm.xyz0).xyz;
394
395 float3 plane_pos = (localToWorld * p.xy01).xyz;
396 float3 light_dir = normalize(lightPos - plane_pos);
397
398 float ambient = 0.2;
399 float dp = dot(plane_norm, light_dir);
400 float scale = min(ambient + max(dp, 0), 1);
401
402 return color_map.eval(p) * scale.xxx1;
403 }
404 )";
405 auto [effect, error] = SkRuntimeEffect::MakeForShader(SkString(code));
406 if (!effect) {
407 SkDebugf("runtime error %s\n", error.c_str());
408 }
409 fEffect = effect;
410 }
411
drawContent(SkCanvas * canvas,SkColor color,int index,bool drawFront,const SkM44 & localToWorld)412 void drawContent(SkCanvas* canvas,
413 SkColor color,
414 int index,
415 bool drawFront,
416 const SkM44& localToWorld) override {
417 if (!drawFront || !front(canvas->getLocalToDevice())) {
418 return;
419 }
420
421 SkRuntimeShaderBuilder builder(fEffect);
422 builder.uniform("lightPos") = fLight.computeWorldPos(fSphere);
423 builder.uniform("localToWorld") = localToWorld;
424 builder.uniform("localToWorldAdjInv") = normals(localToWorld);
425
426 builder.child("color_map") = fImgShader;
427 builder.child("normal_map") = fBmpShader;
428
429 SkPaint paint;
430 paint.setColor(color);
431 paint.setShader(builder.makeShader(nullptr, true));
432
433 canvas->drawRRect(fRR, paint);
434 }
435 };
436 DEF_SAMPLE( return new SampleBump3D; )
437
438 #include "modules/skottie/include/Skottie.h"
439
440 class SampleSkottieCube : public SampleCubeBase {
441 sk_sp<skottie::Animation> fAnim[6];
442
443 public:
SampleSkottieCube()444 SampleSkottieCube() : SampleCubeBase(kCanRunOnCPU) {}
445
name()446 SkString name() override { return SkString("skottie3d"); }
447
onOnceBeforeDraw()448 void onOnceBeforeDraw() override {
449 const char* files[] = {
450 "skottie/skottie-chained-mattes.json",
451 "skottie/skottie-gradient-ramp.json",
452 "skottie/skottie_sample_2.json",
453 "skottie/skottie-3d-3planes.json",
454 "skottie/skottie-text-animator-4.json",
455 "skottie/skottie-motiontile-effect-phase.json",
456
457 };
458 for (unsigned i = 0; i < SK_ARRAY_COUNT(files); ++i) {
459 if (auto stream = GetResourceAsStream(files[i])) {
460 fAnim[i] = skottie::Animation::Make(stream.get());
461 }
462 }
463 }
464
drawContent(SkCanvas * canvas,SkColor color,int index,bool drawFront,const SkM44 &)465 void drawContent(
466 SkCanvas* canvas, SkColor color, int index, bool drawFront, const SkM44&) override {
467 if (!drawFront || !front(canvas->getLocalToDevice())) {
468 return;
469 }
470
471 SkPaint paint;
472 paint.setColor(color);
473 SkRect r = {0, 0, 400, 400};
474 canvas->drawRect(r, paint);
475 fAnim[index]->render(canvas, &r);
476 }
477
onAnimate(double nanos)478 bool onAnimate(double nanos) override {
479 for (auto& anim : fAnim) {
480 SkScalar dur = anim->duration();
481 SkScalar t = fmod(1e-9 * nanos, dur) / dur;
482 anim->seek(t);
483 }
484 return true;
485 }
486 };
487 DEF_SAMPLE( return new SampleSkottieCube; )
488