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 "gm/gm.h"
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkData.h"
11
12 struct Info {
13 float fNear = 0.05f;
14 float fFar = 4;
15 float fAngle = SK_ScalarPI / 4;
16
17 SkV3 fEye { 0, 0, 1.0f/tan(fAngle/2) - 1 };
18 SkV3 fCOA { 0, 0, 0 };
19 SkV3 fUp { 0, 1, 0 };
20 };
21
inv(const SkM44 & m)22 static SkM44 inv(const SkM44& m) {
23 SkM44 inverse(SkM44::kUninitialized_Constructor);
24 if (!m.invert(&inverse)) {
25 inverse.setIdentity();
26 }
27 return inverse;
28 }
29
make_ctm(const Info & info,const SkM44 & model,SkSize size)30 static SkM44 make_ctm(const Info& info, const SkM44& model, SkSize size) {
31 SkM44 camera, perspective, viewport;
32
33 SkScalar w = size.width();
34 SkScalar h = size.height();
35
36 perspective = SkM44::Perspective(info.fNear, info.fFar, info.fAngle);
37 camera = SkM44::LookAt(info.fEye, info.fCOA, info.fUp);
38 viewport.setScale(w*0.5f, h*0.5f, 1);//.postTranslate(r.centerX(), r.centerY(), 0);
39
40 return viewport * perspective * camera * model * inv(viewport);
41 }
42
43 #include "include/core/SkPicture.h"
44 #include "include/core/SkPictureRecorder.h"
45
do_draw(SkCanvas * canvas,SkColor color)46 static void do_draw(SkCanvas* canvas, SkColor color) {
47 SkAutoCanvasRestore acr(canvas, true);
48
49 Info info;
50
51 SkM44 m = SkM44::Rotate({0, 1, 0}, SK_ScalarPI/6);
52
53 canvas->concat(make_ctm(info, m, {300, 300}));
54
55 canvas->translate(150, 150);
56 SkPaint paint;
57 paint.setColor(color);
58 canvas->drawRect({-100, -100, 100, 100}, paint);
59 }
60
61 /*
62 * Test calling drawables w/ translate and matrices
63 */
64 DEF_SIMPLE_GM(sk3d_simple, real_canvas, 300, 300) {
65 do_draw(real_canvas, 0xFFFF0000);
66
67 SkPictureRecorder recorder;
68 SkCanvas* canvas = recorder.beginRecording(300, 300);
69
70 do_draw(canvas, 0x880000FF);
71
72 auto pic = recorder.finishRecordingAsPicture();
73 if (true) {
74 real_canvas->drawPicture(pic);
75 } else {
76 auto data = pic->serialize();
77 auto pic2 = SkPicture::MakeFromData(data.get());
78 real_canvas->drawPicture(pic2);
79 }
80 }
81