blob: e8e37346d8691b326c8c2df23dfd05afb27c842d [file] [log] [blame]
jvanverth9f372462016-04-06 06:08:59 -07001/*
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
jvanverth34524262016-05-04 13:49:13 -07008#include "Viewer.h"
jvanverth9f372462016-04-06 06:08:59 -07009
jvanverth2bb3b6d2016-04-08 07:24:09 -070010#include "GMSlide.h"
liyuqian6f163d22016-06-13 12:26:45 -070011#include "ImageSlide.h"
Greg Daniel9fcc7432016-11-29 16:35:19 -050012#include "Resources.h"
jvanverthc7027ab2016-06-16 09:52:35 -070013#include "SampleSlide.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070014#include "SKPSlide.h"
jvanverth9f372462016-04-06 06:08:59 -070015
csmartdalton61cd31a2017-02-27 17:00:53 -070016#include "GrContext.h"
Greg Daniel285db442016-10-14 09:12:53 -040017#include "SkATrace.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070018#include "SkCanvas.h"
Brian Osmana109e392017-02-24 09:49:14 -050019#include "SkColorSpace_Base.h"
Brian Osmane0d4fba2017-03-15 10:24:55 -040020#include "SkColorSpaceXformCanvas.h"
Brian Osman2dd96932016-10-18 15:33:53 -040021#include "SkCommandLineFlags.h"
csmartdalton008b9d82017-02-22 12:00:42 -070022#include "SkCommonFlagsPathRenderer.h"
liyuqian74959a12016-06-16 14:10:34 -070023#include "SkDashPathEffect.h"
Greg Daniel285db442016-10-14 09:12:53 -040024#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050025#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070026#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070027#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070028#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050029#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070030#include "SkRandom.h"
31#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070032#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050033#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050034#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070035#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040036#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070037
Brian Osman79086b92017-02-10 13:36:16 -050038#include "imgui.h"
39
csmartdalton578f0642017-02-24 16:04:47 -070040#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070041#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070042
jvanverth34524262016-05-04 13:49:13 -070043using namespace sk_app;
44
csmartdalton61cd31a2017-02-27 17:00:53 -070045using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
46static std::map<GpuPathRenderers, std::string> gPathRendererNames;
47
jvanverth9f372462016-04-06 06:08:59 -070048Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070049 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070050}
51
Christopher Dalton443ec1b2017-02-24 13:22:53 -070052static void on_backend_created_func(void* userData) {
53 Viewer* vv = reinterpret_cast<Viewer*>(userData);
54
55 return vv->onBackendCreated();
56}
57
jvanverth9f372462016-04-06 06:08:59 -070058static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070059 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070060
61 return vv->onPaint(canvas);
62}
63
jvanverth814e38d2016-06-06 08:48:47 -070064static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070065{
66 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
67
68 return viewer->onTouch(owner, state, x, y);
69}
70
liyuqiane5a6cd92016-05-27 08:52:52 -070071static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
72 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
73
74 return viewer->onUIStateChanged(stateName, stateValue);
75}
76
Brian Osman79086b92017-02-10 13:36:16 -050077static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
78 void* userData) {
79 ImGuiIO& io = ImGui::GetIO();
80 io.MousePos.x = static_cast<float>(x);
81 io.MousePos.y = static_cast<float>(y);
82 if (Window::kDown_InputState == state) {
83 io.MouseDown[0] = true;
84 } else if (Window::kUp_InputState == state) {
85 io.MouseDown[0] = false;
86 }
Jim Van Verthe7705782017-05-04 14:00:59 -040087 if (io.WantCaptureMouse) {
88 return true;
89 } else {
90 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
91 return viewer->onMouse(x, y, state, modifiers);
92 }
Brian Osman79086b92017-02-10 13:36:16 -050093}
94
95static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
96 ImGuiIO& io = ImGui::GetIO();
97 io.MouseWheel += delta;
98 return true;
99}
100
101static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
102 void* userData) {
103 ImGuiIO& io = ImGui::GetIO();
104 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
105
106 if (io.WantCaptureKeyboard) {
107 return true;
108 } else {
109 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
110 return viewer->onKey(key, state, modifiers);
111 }
112}
113
114static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
115 ImGuiIO& io = ImGui::GetIO();
116 if (io.WantTextInput) {
117 if (c > 0 && c < 0x10000) {
118 io.AddInputCharacter(c);
119 }
120 return true;
121 } else {
122 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
123 return viewer->onChar(c, modifiers);
124 }
125}
126
Brian Osman2dd96932016-10-18 15:33:53 -0400127static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400128
Brian Osman2dd96932016-10-18 15:33:53 -0400129static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700130 "[~][^]substring[$] [...] of bench name to run.\n"
131 "Multiple matches may be separated by spaces.\n"
132 "~ causes a matching bench to always be skipped\n"
133 "^ requires the start of the bench to match\n"
134 "$ requires the end of the bench to match\n"
135 "^ and $ requires an exact match\n"
136 "If a bench does not match any list entry,\n"
137 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700138
Jim Van Verth6f449692017-02-14 15:16:46 -0500139DEFINE_string(slide, "", "Start on this sample.");
140DEFINE_bool(list, false, "List samples?");
141
bsalomon6c471f72016-07-26 12:56:32 -0700142#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700143# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700144#else
145# define BACKENDS_STR "\"sw\" and \"gl\""
146#endif
147
liyuqian71491dc2016-06-09 12:02:34 -0700148#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400149static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
150static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700151#else
Brian Osman2dd96932016-10-18 15:33:53 -0400152static DEFINE_string(skps, "skps", "Directory to read skps from.");
153static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700154#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700155
Brian Osman2dd96932016-10-18 15:33:53 -0400156static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700157
Brian Osman2dd96932016-10-18 15:33:53 -0400158static DEFINE_bool(atrace, false, "Enable support for using ATrace. ATrace is only supported on Android.");
Greg Daniel285db442016-10-14 09:12:53 -0400159
csmartdalton578f0642017-02-24 16:04:47 -0700160DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700161DEFINE_pathrenderer_flag;
162
Brian Salomon41eac792017-03-08 14:03:56 -0500163DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
164
jvanverthaf236b52016-05-20 06:01:06 -0700165const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700166 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700167#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700168 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700169#endif
csmartdalton578f0642017-02-24 16:04:47 -0700170 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700171};
172
bsalomon6c471f72016-07-26 12:56:32 -0700173static sk_app::Window::BackendType get_backend_type(const char* str) {
174#ifdef SK_VULKAN
175 if (0 == strcmp(str, "vk")) {
176 return sk_app::Window::kVulkan_BackendType;
177 } else
178#endif
179 if (0 == strcmp(str, "gl")) {
180 return sk_app::Window::kNativeGL_BackendType;
181 } else if (0 == strcmp(str, "sw")) {
182 return sk_app::Window::kRaster_BackendType;
183 } else {
184 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
185 return sk_app::Window::kRaster_BackendType;
186 }
187}
188
Brian Osmana109e392017-02-24 09:49:14 -0500189static SkColorSpacePrimaries gSrgbPrimaries = {
190 0.64f, 0.33f,
191 0.30f, 0.60f,
192 0.15f, 0.06f,
193 0.3127f, 0.3290f };
194
195static SkColorSpacePrimaries gAdobePrimaries = {
196 0.64f, 0.33f,
197 0.21f, 0.71f,
198 0.15f, 0.06f,
199 0.3127f, 0.3290f };
200
201static SkColorSpacePrimaries gP3Primaries = {
202 0.680f, 0.320f,
203 0.265f, 0.690f,
204 0.150f, 0.060f,
205 0.3127f, 0.3290f };
206
207static SkColorSpacePrimaries gRec2020Primaries = {
208 0.708f, 0.292f,
209 0.170f, 0.797f,
210 0.131f, 0.046f,
211 0.3127f, 0.3290f };
212
213struct NamedPrimaries {
214 const char* fName;
215 SkColorSpacePrimaries* fPrimaries;
216} gNamedPrimaries[] = {
217 { "sRGB", &gSrgbPrimaries },
218 { "AdobeRGB", &gAdobePrimaries },
219 { "P3", &gP3Primaries },
220 { "Rec. 2020", &gRec2020Primaries },
221};
222
223static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
224 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
225}
226
liyuqiane5a6cd92016-05-27 08:52:52 -0700227const char* kName = "name";
228const char* kValue = "value";
229const char* kOptions = "options";
230const char* kSlideStateName = "Slide";
231const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700232const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700233const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500234const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700235const char* kSoftkeyStateName = "Softkey";
236const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700237const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700238const char* kON = "ON";
239const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700240const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700241
jvanverth34524262016-05-04 13:49:13 -0700242Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700243 : fCurrentMeasurement(0)
244 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700245 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500246 , fShowImGuiDebugWindow(false)
247 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500248 , fShowZoomWindow(false)
249 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700250 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500251 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500252 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700253 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400254 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700255{
csmartdalton29d87152017-02-10 17:05:14 -0500256 static SkTaskGroup::Enabler kTaskGroupEnabler;
Greg Daniel285db442016-10-14 09:12:53 -0400257 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700258
259 static SkOnce initPathRendererNames;
260 initPathRendererNames([]() {
261 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
262 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
263 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400264 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500265 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700266 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
267 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
268 });
269
Brian Osman1df161a2017-02-09 12:10:20 -0500270 memset(fPaintTimes, 0, sizeof(fPaintTimes));
271 memset(fFlushTimes, 0, sizeof(fFlushTimes));
272 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700273
jvanverth2bb3b6d2016-04-08 07:24:09 -0700274 SkDebugf("Command line arguments: ");
275 for (int i = 1; i < argc; ++i) {
276 SkDebugf("%s ", argv[i]);
277 }
278 SkDebugf("\n");
279
280 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500281#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400282 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500283#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700284
Greg Daniel285db442016-10-14 09:12:53 -0400285 if (FLAGS_atrace) {
Brian Salomon175f5882017-05-12 12:02:50 -0400286 SkAssertResult(SkEventTracer::SetInstance(new SkATrace()));
Greg Daniel285db442016-10-14 09:12:53 -0400287 }
288
bsalomon6c471f72016-07-26 12:56:32 -0700289 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700290 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700291
csmartdalton578f0642017-02-24 16:04:47 -0700292 DisplayParams displayParams;
293 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500294 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700295 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700296 fWindow->setRequestedDisplayParams(displayParams);
297
jvanverth9f372462016-04-06 06:08:59 -0700298 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700299 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700300 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700301 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700302 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700303 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500304 fWindow->registerMouseFunc(on_mouse_handler, this);
305 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
306 fWindow->registerKeyFunc(on_key_handler, this);
307 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700308
brianosman622c8d52016-05-10 06:50:49 -0700309 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500310 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
311 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
312 fWindow->inval();
313 });
314 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
315 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
316 fWindow->inval();
317 });
Brian Osmanf6877092017-02-13 09:39:57 -0500318 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
319 this->fShowZoomWindow = !this->fShowZoomWindow;
320 fWindow->inval();
321 });
brianosman622c8d52016-05-10 06:50:49 -0700322 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
323 this->fDisplayStats = !this->fDisplayStats;
324 fWindow->inval();
325 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500326 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500327 switch (fColorMode) {
328 case ColorMode::kLegacy:
329 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
330 break;
331 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
332 this->setColorMode(ColorMode::kColorManagedSRGB8888);
333 break;
334 case ColorMode::kColorManagedSRGB8888:
335 this->setColorMode(ColorMode::kColorManagedLinearF16);
336 break;
337 case ColorMode::kColorManagedLinearF16:
338 this->setColorMode(ColorMode::kLegacy);
339 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500340 }
brianosman622c8d52016-05-10 06:50:49 -0700341 });
342 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
343 int previousSlide = fCurrentSlide;
344 fCurrentSlide++;
345 if (fCurrentSlide >= fSlides.count()) {
346 fCurrentSlide = 0;
347 }
348 this->setupCurrentSlide(previousSlide);
349 });
350 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
351 int previousSlide = fCurrentSlide;
352 fCurrentSlide--;
353 if (fCurrentSlide < 0) {
354 fCurrentSlide = fSlides.count() - 1;
355 }
356 this->setupCurrentSlide(previousSlide);
357 });
358 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
359 this->changeZoomLevel(1.f / 32.f);
360 fWindow->inval();
361 });
362 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
363 this->changeZoomLevel(-1.f / 32.f);
364 fWindow->inval();
365 });
jvanverthaf236b52016-05-20 06:01:06 -0700366 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Osman621491e2017-02-28 15:45:01 -0500367 sk_app::Window::BackendType newBackend = fBackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500368#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
jvanverthb8794cc2016-07-27 14:29:18 -0700369 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500370 newBackend = sk_app::Window::kNativeGL_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700371#ifdef SK_VULKAN
372 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500373 newBackend = sk_app::Window::kVulkan_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700374#endif
375 } else {
Brian Osman621491e2017-02-28 15:45:01 -0500376 newBackend = sk_app::Window::kRaster_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700377 }
Jim Van Verthd63c1022017-01-05 13:50:49 -0500378#elif defined(SK_BUILD_FOR_UNIX)
379 // Switching to and from Vulkan is problematic on Linux so disabled for now
380 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500381 newBackend = sk_app::Window::kNativeGL_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500382 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500383 newBackend = sk_app::Window::kRaster_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500384 }
385#endif
jvanverthaf236b52016-05-20 06:01:06 -0700386
Brian Osman621491e2017-02-28 15:45:01 -0500387 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700388 });
brianosman622c8d52016-05-10 06:50:49 -0700389
jvanverth2bb3b6d2016-04-08 07:24:09 -0700390 // set up slides
391 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500392 this->setStartupSlide();
393 if (FLAGS_list) {
394 this->listNames();
395 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700396
djsollen12d62a72016-04-21 07:59:44 -0700397 fAnimTimer.run();
398
Brian Osman79086b92017-02-10 13:36:16 -0500399 // ImGui initialization:
400 ImGuiIO& io = ImGui::GetIO();
401 io.DisplaySize.x = static_cast<float>(fWindow->width());
402 io.DisplaySize.y = static_cast<float>(fWindow->height());
403
404 // Keymap...
405 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
406 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
407 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
408 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
409 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
410 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
411 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
412 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
413 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
414 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
415 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
416 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
417 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
418 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
419 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
420 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
421 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
422 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
423 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
424
425 int w, h;
426 unsigned char* pixels;
427 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
428 SkImageInfo info = SkImageInfo::MakeA8(w, h);
429 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500430 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
431 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400432 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500433 fImGuiFontPaint.setShader(fontShader);
434 fImGuiFontPaint.setColor(SK_ColorWHITE);
435 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
436 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500437
Brian Osmana109e392017-02-24 09:49:14 -0500438 auto gamutImage = GetResourceAsImage("gamut.png");
439 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400440 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500441 }
442 fImGuiGamutPaint.setColor(SK_ColorWHITE);
443 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
444
csmartdalton578f0642017-02-24 16:04:47 -0700445 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700446}
447
jvanverth34524262016-05-04 13:49:13 -0700448void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700449 fAllSlideNames = Json::Value(Json::arrayValue);
450
jvanverth2bb3b6d2016-04-08 07:24:09 -0700451 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
452 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400453 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700454
455 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
456 sk_sp<Slide> slide(new GMSlide(gm.release()));
457 fSlides.push_back(slide);
458 }
459
460 gms = gms->next();
461 }
462
463 // reverse array
464 for (int i = 0; i < fSlides.count()/2; ++i) {
465 sk_sp<Slide> temp = fSlides[i];
466 fSlides[i] = fSlides[fSlides.count() - i - 1];
467 fSlides[fSlides.count() - i - 1] = temp;
468 }
469
jvanverthc7027ab2016-06-16 09:52:35 -0700470 // samples
471 const SkViewRegister* reg = SkViewRegister::Head();
472 while (reg) {
473 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700474 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
475 fSlides.push_back(slide);
476 }
jvanverthc7027ab2016-06-16 09:52:35 -0700477 reg = reg->next();
478 }
479
jvanverth2bb3b6d2016-04-08 07:24:09 -0700480 // SKPs
481 for (int i = 0; i < FLAGS_skps.count(); i++) {
482 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700483 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
484 continue;
485 }
486
jvanverth2bb3b6d2016-04-08 07:24:09 -0700487 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700488 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700489 if (slide) {
490 fSlides.push_back(slide);
491 }
492 } else {
493 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700494 SkString skpName;
495 while (it.next(&skpName)) {
496 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
497 continue;
498 }
499
500 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
501 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700502 if (slide) {
503 fSlides.push_back(slide);
504 }
505 }
506 }
507 }
liyuqian6f163d22016-06-13 12:26:45 -0700508
509 // JPGs
510 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
511 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
512 SkString jpgName;
513 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700514 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
515 continue;
516 }
517
liyuqian6f163d22016-06-13 12:26:45 -0700518 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
519 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
520 if (slide) {
521 fSlides.push_back(slide);
522 }
523 }
524 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700525}
526
527
jvanverth34524262016-05-04 13:49:13 -0700528Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700529 fWindow->detach();
530 delete fWindow;
531}
532
brianosman05de2162016-05-06 13:28:57 -0700533void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700534 if (!fWindow) {
535 return;
536 }
537 if (fWindow->sampleCount() < 0) {
538 return; // Surface hasn't been created yet.
539 }
540
jvanverth34524262016-05-04 13:49:13 -0700541 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700542 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700543
Brian Osman92004802017-03-06 11:47:26 -0500544 switch (fColorMode) {
545 case ColorMode::kLegacy:
546 title.append(" Legacy 8888");
547 break;
548 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
549 title.append(" ColorManaged 8888 (Nonlinear blending)");
550 break;
551 case ColorMode::kColorManagedSRGB8888:
552 title.append(" ColorManaged 8888");
553 break;
554 case ColorMode::kColorManagedLinearF16:
555 title.append(" ColorManaged F16");
556 break;
557 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500558
Brian Osman92004802017-03-06 11:47:26 -0500559 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500560 int curPrimaries = -1;
561 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
562 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
563 curPrimaries = i;
564 break;
565 }
566 }
567 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700568 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500569
csmartdalton578f0642017-02-24 16:04:47 -0700570 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700571 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700572 if (int msaa = fWindow->sampleCount()) {
573 title.appendf(" MSAA: %i", msaa);
574 }
575 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700576
577 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
578 if (GpuPathRenderers::kAll != pr) {
579 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
580 }
581
brianosman05de2162016-05-06 13:28:57 -0700582 fWindow->setTitle(title.c_str());
583}
584
Jim Van Verth6f449692017-02-14 15:16:46 -0500585void Viewer::setStartupSlide() {
586
587 if (!FLAGS_slide.isEmpty()) {
588 int count = fSlides.count();
589 for (int i = 0; i < count; i++) {
590 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
591 fCurrentSlide = i;
592 return;
593 }
594 }
595
596 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
597 this->listNames();
598 }
599
600 fCurrentSlide = 0;
601}
602
603void Viewer::listNames() {
604 int count = fSlides.count();
605 SkDebugf("All Slides:\n");
606 for (int i = 0; i < count; i++) {
607 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
608 }
609}
610
brianosman05de2162016-05-06 13:28:57 -0700611void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700612 if (fCurrentSlide == previousSlide) {
613 return; // no change; do nothing
614 }
liyuqian6f163d22016-06-13 12:26:45 -0700615 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700616 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700617
liyuqiane46e4f02016-05-20 07:32:19 -0700618 fGesture.reset();
619 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700620
Brian Osman42bb6ac2017-06-05 08:46:04 -0400621 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
622 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
623 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
624
625 // Start with a matrix that scales the slide to the available screen space
626 if (fWindow->scaleContentToFit()) {
627 if (windowRect.width() > 0 && windowRect.height() > 0) {
628 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700629 }
630 }
631
Brian Osman42bb6ac2017-06-05 08:46:04 -0400632 // Prevent the user from dragging content so far outside the window they can't find it again
633 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700634
brianosman05de2162016-05-06 13:28:57 -0700635 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700636 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700637 if (previousSlide >= 0) {
638 fSlides[previousSlide]->unload();
639 }
jvanverthc265a922016-04-08 12:51:45 -0700640 fWindow->inval();
641}
642
643#define MAX_ZOOM_LEVEL 8
644#define MIN_ZOOM_LEVEL -8
645
jvanverth34524262016-05-04 13:49:13 -0700646void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700647 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400648 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700649}
650
liyuqiand3cdbca2016-05-17 12:44:20 -0700651SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700652 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700653
Brian Osman42bb6ac2017-06-05 08:46:04 -0400654 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
655 : SK_Scalar1 + fZoomLevel;
656 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700657 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400658 m.preConcat(fDefaultMatrix);
659 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700660
liyuqiand3cdbca2016-05-17 12:44:20 -0700661 return m;
jvanverthc265a922016-04-08 12:51:45 -0700662}
663
Brian Osman621491e2017-02-28 15:45:01 -0500664void Viewer::setBackend(sk_app::Window::BackendType backendType) {
665 fBackendType = backendType;
666
667 fWindow->detach();
668
669#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
670 // Switching from OpenGL to Vulkan in the same window is problematic at this point on
671 // Windows, so we just delete the window and recreate it.
672 if (sk_app::Window::kVulkan_BackendType == fBackendType) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400673 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500674 delete fWindow;
675 fWindow = Window::CreateNativeWindow(nullptr);
676
677 // re-register callbacks
678 fCommands.attach(fWindow);
679 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
680 fWindow->registerPaintFunc(on_paint_handler, this);
681 fWindow->registerTouchFunc(on_touch_handler, this);
682 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
683 fWindow->registerMouseFunc(on_mouse_handler, this);
684 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
685 fWindow->registerKeyFunc(on_key_handler, this);
686 fWindow->registerCharFunc(on_char_handler, this);
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400687 fWindow->setRequestedDisplayParams(params);
Brian Osman621491e2017-02-28 15:45:01 -0500688 }
689#endif
690
691 fWindow->attach(fBackendType);
692}
693
Brian Osman92004802017-03-06 11:47:26 -0500694void Viewer::setColorMode(ColorMode colorMode) {
695 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700696
Brian Osmanf750fbc2017-02-08 10:47:28 -0500697 // When we're in color managed mode, we tag our window surface as sRGB. If we've switched into
Brian Osmane0d4fba2017-03-15 10:24:55 -0400698 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700699 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500700 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400701 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
702 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500703 if (wasInLegacy != wantLegacy) {
704 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700705 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500706 }
707
708 this->updateTitle();
709 fWindow->inval();
710}
711
712void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500713 SkAutoCanvasRestore autorestore(canvas, false);
714
Brian Osmanf750fbc2017-02-08 10:47:28 -0500715 // By default, we render directly into the window's surface/canvas
716 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500717 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700718
Brian Osmane0d4fba2017-03-15 10:24:55 -0400719 // If we're in any of the color managed modes, construct the color space we're going to use
720 sk_sp<SkColorSpace> cs = nullptr;
721 if (ColorMode::kLegacy != fColorMode) {
722 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
723 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
724 SkMatrix44 toXYZ;
725 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
726 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
727 }
728
729 // If we're in F16, or we're zooming, or we're in color correct 8888 and the gamut isn't sRGB,
Brian Osman92004802017-03-06 11:47:26 -0500730 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500731 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500732 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500733 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400734 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
735 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
736
Brian Osman92004802017-03-06 11:47:26 -0500737 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
738 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400739 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
740 // with a special canvas (below) that has the color space attached
741 sk_sp<SkColorSpace> offscreenColorSpace =
742 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500743 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400744 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500745 offscreenSurface = canvas->makeSurface(info);
746 slideCanvas = offscreenSurface->getCanvas();
747 }
748
Brian Osmane0d4fba2017-03-15 10:24:55 -0400749 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
750 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
751 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
752 slideCanvas = xformCanvas.get();
753 }
754
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500755 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500756 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500757 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500758 // Time the painting logic of the slide
759 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500760 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500761 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500762 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500763
764 // Force a flush so we can time that, too
765 startTime = SkTime::GetMSecs();
766 slideCanvas->flush();
767 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500768
769 // If we rendered offscreen, snap an image and push the results to the window's canvas
770 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500771 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500772
773 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400774 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500775 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400776 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500777 SkPaint paint;
778 paint.setBlendMode(SkBlendMode::kSrc);
779 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700780 }
liyuqian6f163d22016-06-13 12:26:45 -0700781}
782
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700783void Viewer::onBackendCreated() {
784 this->updateTitle();
785 this->updateUIState();
786 this->setupCurrentSlide(-1);
787 fWindow->show();
788 fWindow->inval();
789}
Jim Van Verth6f449692017-02-14 15:16:46 -0500790
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700791void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500792 // Update ImGui input
793 ImGuiIO& io = ImGui::GetIO();
794 io.DeltaTime = 1.0f / 60.0f;
795 io.DisplaySize.x = static_cast<float>(fWindow->width());
796 io.DisplaySize.y = static_cast<float>(fWindow->height());
797
798 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
799 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
800 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
801
802 ImGui::NewFrame();
803
Brian Osmanf750fbc2017-02-08 10:47:28 -0500804 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700805
Brian Osman1df161a2017-02-09 12:10:20 -0500806 // Advance our timing bookkeeping
807 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
808 SkASSERT(fCurrentMeasurement < kMeasurementCount);
809
810 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700811 if (fDisplayStats) {
812 drawStats(canvas);
813 }
brianosman622c8d52016-05-10 06:50:49 -0700814 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700815
Brian Osman79086b92017-02-10 13:36:16 -0500816 drawImGui(canvas);
817
Brian Osman1df161a2017-02-09 12:10:20 -0500818 // Update the FPS
819 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700820}
821
jvanverth814e38d2016-06-06 08:48:47 -0700822bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400823 if (GestureDevice::kMouse == fGestureDevice) {
824 return false;
825 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700826 void* castedOwner = reinterpret_cast<void*>(owner);
827 switch (state) {
828 case Window::kUp_InputState: {
829 fGesture.touchEnd(castedOwner);
830 break;
831 }
832 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400833 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700834 break;
835 }
836 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400837 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700838 break;
839 }
840 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400841 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700842 fWindow->inval();
843 return true;
844}
845
Jim Van Verthe7705782017-05-04 14:00:59 -0400846bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400847 if (GestureDevice::kTouch == fGestureDevice) {
848 return false;
849 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400850 switch (state) {
851 case Window::kUp_InputState: {
852 fGesture.touchEnd(nullptr);
853 break;
854 }
855 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400856 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400857 break;
858 }
859 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400860 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400861 break;
862 }
863 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400864 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400865 fWindow->inval();
866 return true;
867}
868
jvanverth34524262016-05-04 13:49:13 -0700869void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700870 static const float kPixelPerMS = 2.0f;
871 static const int kDisplayWidth = 130;
872 static const int kDisplayHeight = 100;
873 static const int kDisplayPadding = 10;
874 static const int kGraphPadding = 3;
875 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
876
Mike Reed3661bc92017-02-22 13:21:42 -0500877 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700878 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
879 SkIntToScalar(kDisplayPadding),
880 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
881 SkPaint paint;
882 canvas->save();
883
884 canvas->clipRect(rect);
885 paint.setColor(SK_ColorBLACK);
886 canvas->drawRect(rect, paint);
887 // draw the 16ms line
888 paint.setColor(SK_ColorLTGRAY);
889 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
890 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
891 paint.setColor(SK_ColorRED);
892 paint.setStyle(SkPaint::kStroke_Style);
893 canvas->drawRect(rect, paint);
894
895 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
896 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700897 int i = fCurrentMeasurement;
898 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500899 // Round to nearest values
900 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
901 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
902 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
903 int startY = SkScalarTruncToInt(rect.fBottom);
904 int endY = startY - flushHeight;
905 paint.setColor(SK_ColorRED);
906 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
907 SkIntToScalar(x), SkIntToScalar(endY), paint);
908 startY = endY;
909 endY = startY - paintHeight;
910 paint.setColor(SK_ColorGREEN);
911 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
912 SkIntToScalar(x), SkIntToScalar(endY), paint);
913 startY = endY;
914 endY = startY - animateHeight;
915 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700916 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
917 SkIntToScalar(x), SkIntToScalar(endY), paint);
918 i++;
919 i &= (kMeasurementCount - 1); // fast mod
920 x += xStep;
921 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700922
923 canvas->restore();
924}
925
Brian Osmana109e392017-02-24 09:49:14 -0500926static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
927 const ImVec2& pos, const ImVec2& size) {
928 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
929 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
930
931 // Invisible 10x10 button
932 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
933 ImGui::InvisibleButton(label, ImVec2(10, 10));
934
935 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
936 ImGuiIO& io = ImGui::GetIO();
937 // Normalized mouse position, relative to our gamut box
938 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
939 // Clamp to edge of box, convert back to primary scale
940 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
941 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
942 }
943
944 if (ImGui::IsItemHovered()) {
945 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
946 }
947
948 // Return screen coordinates for the caller. We could just return center here, but we'd have
949 // one frame of lag during drag.
950 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
951}
952
953static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
954 ImDrawList* drawList = ImGui::GetWindowDrawList();
955
956 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
957 // width, and scale the height to maintain aspect ratio.
958 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
959 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
960 ImVec2 pos = ImGui::GetCursorScreenPos();
961
962 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
963 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
964 // Magic numbers are pixel locations of the origin and upper-right corner.
965 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
966 ImVec2(242, 61), ImVec2(1897, 1922));
967 ImVec2 endPos = ImGui::GetCursorPos();
968
969 // Primary markers
970 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
971 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
972 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
973 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
974
975 // Gamut triangle
976 drawList->AddCircle(r, 5.0f, 0xFF000040);
977 drawList->AddCircle(g, 5.0f, 0xFF004000);
978 drawList->AddCircle(b, 5.0f, 0xFF400000);
979 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
980 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
981
982 // Re-position cursor immediate after the diagram for subsequent controls
983 ImGui::SetCursorPos(endPos);
984}
985
Brian Osman79086b92017-02-10 13:36:16 -0500986void Viewer::drawImGui(SkCanvas* canvas) {
987 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
988 if (fShowImGuiTestWindow) {
989 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
990 }
991
992 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -0500993 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
994 // always visible, we can end up in a layout feedback loop.
995 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -0500996 DisplayParams params = fWindow->getRequestedDisplayParams();
997 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -0500998 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
999 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001000 if (ImGui::CollapsingHeader("Backend")) {
1001 int newBackend = static_cast<int>(fBackendType);
1002 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1003 ImGui::SameLine();
1004 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1005#if defined(SK_VULKAN)
1006 ImGui::SameLine();
1007 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1008#endif
1009 if (newBackend != fBackendType) {
1010 fDeferredActions.push_back([=]() {
1011 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1012 });
1013 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001014
Brian Salomon99a33902017-03-07 15:16:34 -05001015 const GrContext* ctx = fWindow->getGrContext();
1016 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1017 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1018 paramsChanged = true;
1019 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001020 bool* wire = &params.fGrContextOptions.fWireframeMode;
1021 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1022 paramsChanged = true;
1023 }
Brian Salomon99a33902017-03-07 15:16:34 -05001024
Brian Osman28b12522017-03-08 17:10:24 -05001025 if (ctx) {
1026 int sampleCount = fWindow->sampleCount();
1027 ImGui::Text("MSAA: "); ImGui::SameLine();
1028 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1029 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1030 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1031 ImGui::RadioButton("16", &sampleCount, 16);
1032
1033 if (sampleCount != params.fMSAASampleCount) {
1034 params.fMSAASampleCount = sampleCount;
1035 paramsChanged = true;
1036 }
1037 }
1038
Brian Osman8a9de3d2017-03-01 14:59:05 -05001039 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001040 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001041 auto prButton = [&](GpuPathRenderers x) {
1042 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001043 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1044 params.fGrContextOptions.fGpuPathRenderers = x;
1045 paramsChanged = true;
1046 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001047 }
1048 };
1049
1050 if (!ctx) {
1051 ImGui::RadioButton("Software", true);
1052 } else if (fWindow->sampleCount()) {
1053 prButton(GpuPathRenderers::kAll);
1054 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1055 prButton(GpuPathRenderers::kStencilAndCover);
1056 }
1057 if (ctx->caps()->sampleShadingSupport()) {
1058 prButton(GpuPathRenderers::kMSAA);
1059 }
1060 prButton(GpuPathRenderers::kTessellating);
1061 prButton(GpuPathRenderers::kDefault);
1062 prButton(GpuPathRenderers::kNone);
1063 } else {
1064 prButton(GpuPathRenderers::kAll);
Jim Van Verth83010462017-03-16 08:45:39 -04001065 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001066 prButton(GpuPathRenderers::kTessellating);
1067 prButton(GpuPathRenderers::kNone);
1068 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001069 ImGui::TreePop();
1070 }
Brian Osman621491e2017-02-28 15:45:01 -05001071 }
1072
Brian Osman79086b92017-02-10 13:36:16 -05001073 if (ImGui::CollapsingHeader("Slide")) {
1074 static ImGuiTextFilter filter;
1075 filter.Draw();
1076 int previousSlide = fCurrentSlide;
1077 fCurrentSlide = 0;
1078 for (auto slide : fSlides) {
1079 if (filter.PassFilter(slide->getName().c_str())) {
1080 ImGui::BulletText("%s", slide->getName().c_str());
1081 if (ImGui::IsItemClicked()) {
1082 setupCurrentSlide(previousSlide);
1083 break;
1084 }
1085 }
1086 ++fCurrentSlide;
1087 }
1088 if (fCurrentSlide >= fSlides.count()) {
1089 fCurrentSlide = previousSlide;
1090 }
1091 }
Brian Osmana109e392017-02-24 09:49:14 -05001092
1093 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001094 ColorMode newMode = fColorMode;
1095 auto cmButton = [&](ColorMode mode, const char* label) {
1096 if (ImGui::RadioButton(label, mode == fColorMode)) {
1097 newMode = mode;
1098 }
1099 };
1100
1101 cmButton(ColorMode::kLegacy, "Legacy 8888");
1102 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1103 "Color Managed 8888 (Nonlinear blending)");
1104 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1105 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1106
1107 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001108 // It isn't safe to switch color mode now (in the middle of painting). We might
1109 // tear down the back-end, etc... Defer this change until the next onIdle.
1110 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001111 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001112 });
Brian Osmana109e392017-02-24 09:49:14 -05001113 }
1114
1115 // Pick from common gamuts:
1116 int primariesIdx = 4; // Default: Custom
1117 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1118 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1119 primariesIdx = i;
1120 break;
1121 }
1122 }
1123
1124 if (ImGui::Combo("Primaries", &primariesIdx,
1125 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1126 if (primariesIdx >= 0 && primariesIdx <= 3) {
1127 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1128 }
1129 }
1130
1131 // Allow direct editing of gamut
1132 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1133 }
Brian Osman79086b92017-02-10 13:36:16 -05001134 }
Brian Salomon99a33902017-03-07 15:16:34 -05001135 if (paramsChanged) {
1136 fDeferredActions.push_back([=]() {
1137 fWindow->setRequestedDisplayParams(params);
1138 fWindow->inval();
1139 this->updateTitle();
1140 });
1141 }
Brian Osman79086b92017-02-10 13:36:16 -05001142 ImGui::End();
1143 }
1144
Brian Osmanf6877092017-02-13 09:39:57 -05001145 SkPaint zoomImagePaint;
1146 if (fShowZoomWindow && fLastImage) {
1147 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1148 static int zoomFactor = 4;
1149 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1150
Mike Reed0acd7952017-04-28 11:12:19 -04001151 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001152 zoomImagePaint.setColor(SK_ColorWHITE);
1153
1154 // Zoom by shrinking the corner UVs towards the mouse cursor
1155 ImVec2 mousePos = ImGui::GetMousePos();
1156 ImVec2 avail = ImGui::GetContentRegionAvail();
1157
1158 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1159 (avail.y * 0.5f) / zoomFactor);
1160 ImGui::Image(&zoomImagePaint, avail,
1161 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1162 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1163 }
1164
1165 ImGui::End();
1166 }
1167
Brian Osman79086b92017-02-10 13:36:16 -05001168 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1169 // (widgets, etc...) that have been issued
1170 ImGui::Render();
1171
1172 // Then we fetch the most recent data, and convert it so we can render with Skia
1173 const ImDrawData* drawData = ImGui::GetDrawData();
1174 SkTDArray<SkPoint> pos;
1175 SkTDArray<SkPoint> uv;
1176 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001177
1178 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1179 const ImDrawList* drawList = drawData->CmdLists[i];
1180
1181 // De-interleave all vertex data (sigh), convert to Skia types
1182 pos.rewind(); uv.rewind(); color.rewind();
1183 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1184 const ImDrawVert& vert = drawList->VtxBuffer[i];
1185 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1186 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1187 color.push(vert.col);
1188 }
1189 // ImGui colors are RGBA
1190 SkSwapRB(color.begin(), color.begin(), color.count());
1191
1192 int indexOffset = 0;
1193
1194 // Draw everything with canvas.drawVertices...
1195 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1196 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1197
1198 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1199 if (drawCmd->UserCallback) {
1200 drawCmd->UserCallback(drawList, drawCmd);
1201 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001202 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1203 SkASSERT(paint);
1204
Brian Osman79086b92017-02-10 13:36:16 -05001205 canvas->save();
1206 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1207 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001208 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1209 drawList->VtxBuffer.size(), pos.begin(),
1210 uv.begin(), color.begin(),
1211 drawCmd->ElemCount,
1212 drawList->IdxBuffer.begin() + indexOffset),
1213 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001214 indexOffset += drawCmd->ElemCount;
1215 canvas->restore();
1216 }
1217 }
1218 }
1219}
1220
liyuqian2edb0f42016-07-06 14:11:32 -07001221void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001222 for (int i = 0; i < fDeferredActions.count(); ++i) {
1223 fDeferredActions[i]();
1224 }
1225 fDeferredActions.reset();
1226
Brian Osman1df161a2017-02-09 12:10:20 -05001227 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001228 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001229 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1230 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1231
Brian Osman79086b92017-02-10 13:36:16 -05001232 ImGuiIO& io = ImGui::GetIO();
1233 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001234 fWindow->inval();
1235 }
jvanverth9f372462016-04-06 06:08:59 -07001236}
liyuqiane5a6cd92016-05-27 08:52:52 -07001237
1238void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001239 if (!fWindow) {
1240 return;
1241 }
1242 if (fWindow->sampleCount() < 0) {
1243 return; // Surface hasn't been created yet.
1244 }
1245
liyuqianb73c24b2016-06-03 08:47:23 -07001246 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001247 Json::Value slideState(Json::objectValue);
1248 slideState[kName] = kSlideStateName;
1249 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001250 if (fAllSlideNames.size() == 0) {
1251 for(auto slide : fSlides) {
1252 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1253 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001254 }
liyuqian1f508fd2016-06-07 06:57:40 -07001255 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001256
liyuqianb73c24b2016-06-03 08:47:23 -07001257 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001258 Json::Value backendState(Json::objectValue);
1259 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001260 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001261 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001262 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001263 backendState[kOptions].append(Json::Value(str));
1264 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001265
csmartdalton578f0642017-02-24 16:04:47 -07001266 // MSAA state
1267 Json::Value msaaState(Json::objectValue);
1268 msaaState[kName] = kMSAAStateName;
1269 msaaState[kValue] = fWindow->sampleCount();
1270 msaaState[kOptions] = Json::Value(Json::arrayValue);
1271 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1272 msaaState[kOptions].append(Json::Value(0));
1273 } else {
1274 for (int msaa : {0, 4, 8, 16}) {
1275 msaaState[kOptions].append(Json::Value(msaa));
1276 }
1277 }
1278
csmartdalton61cd31a2017-02-27 17:00:53 -07001279 // Path renderer state
1280 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1281 Json::Value prState(Json::objectValue);
1282 prState[kName] = kPathRendererStateName;
1283 prState[kValue] = gPathRendererNames[pr];
1284 prState[kOptions] = Json::Value(Json::arrayValue);
1285 const GrContext* ctx = fWindow->getGrContext();
1286 if (!ctx) {
1287 prState[kOptions].append("Software");
1288 } else if (fWindow->sampleCount()) {
1289 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1290 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1291 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1292 }
1293 if (ctx->caps()->sampleShadingSupport()) {
1294 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1295 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001296 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001297 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1298 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1299 } else {
1300 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Jim Van Verth83010462017-03-16 08:45:39 -04001301 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001302 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001303 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1304 }
1305
Brian Salomon99a33902017-03-07 15:16:34 -05001306 // Instanced rendering state
1307 Json::Value instState(Json::objectValue);
1308 instState[kName] = kInstancedRenderingStateName;
1309 if (ctx) {
1310 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1311 instState[kValue] = kON;
1312 } else {
1313 instState[kValue] = kOFF;
1314 }
1315 instState[kOptions] = Json::Value(Json::arrayValue);
1316 instState[kOptions].append(kOFF);
1317 instState[kOptions].append(kON);
1318 }
1319
liyuqianb73c24b2016-06-03 08:47:23 -07001320 // Softkey state
1321 Json::Value softkeyState(Json::objectValue);
1322 softkeyState[kName] = kSoftkeyStateName;
1323 softkeyState[kValue] = kSoftkeyHint;
1324 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1325 softkeyState[kOptions].append(kSoftkeyHint);
1326 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1327 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1328 }
1329
liyuqian1f508fd2016-06-07 06:57:40 -07001330 // FPS state
1331 Json::Value fpsState(Json::objectValue);
1332 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001333 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1334 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1335 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1336 fAnimateTimes[idx],
1337 fPaintTimes[idx],
1338 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001339 fpsState[kOptions] = Json::Value(Json::arrayValue);
1340
liyuqiane5a6cd92016-05-27 08:52:52 -07001341 Json::Value state(Json::arrayValue);
1342 state.append(slideState);
1343 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001344 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001345 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001346 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001347 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001348 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001349
1350 fWindow->setUIState(state);
1351}
1352
1353void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001354 // For those who will add more features to handle the state change in this function:
1355 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1356 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1357 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001358 if (stateName.equals(kSlideStateName)) {
1359 int previousSlide = fCurrentSlide;
1360 fCurrentSlide = 0;
1361 for(auto slide : fSlides) {
1362 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001363 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001364 break;
1365 }
1366 fCurrentSlide++;
1367 }
1368 if (fCurrentSlide >= fSlides.count()) {
1369 fCurrentSlide = previousSlide;
1370 SkDebugf("Slide not found: %s", stateValue.c_str());
1371 }
liyuqian6cb70252016-06-02 12:16:25 -07001372 } else if (stateName.equals(kBackendStateName)) {
1373 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1374 if (stateValue.equals(kBackendTypeStrings[i])) {
1375 if (fBackendType != i) {
1376 fBackendType = (sk_app::Window::BackendType)i;
1377 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001378 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001379 }
1380 break;
1381 }
1382 }
csmartdalton578f0642017-02-24 16:04:47 -07001383 } else if (stateName.equals(kMSAAStateName)) {
1384 DisplayParams params = fWindow->getRequestedDisplayParams();
1385 int sampleCount = atoi(stateValue.c_str());
1386 if (sampleCount != params.fMSAASampleCount) {
1387 params.fMSAASampleCount = sampleCount;
1388 fWindow->setRequestedDisplayParams(params);
1389 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001390 this->updateTitle();
1391 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001392 }
1393 } else if (stateName.equals(kPathRendererStateName)) {
1394 DisplayParams params = fWindow->getRequestedDisplayParams();
1395 for (const auto& pair : gPathRendererNames) {
1396 if (pair.second == stateValue.c_str()) {
1397 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1398 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1399 fWindow->setRequestedDisplayParams(params);
1400 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001401 this->updateTitle();
1402 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001403 }
1404 break;
1405 }
csmartdalton578f0642017-02-24 16:04:47 -07001406 }
Brian Salomon99a33902017-03-07 15:16:34 -05001407 } else if (stateName.equals(kInstancedRenderingStateName)) {
1408 DisplayParams params = fWindow->getRequestedDisplayParams();
1409 bool value = !strcmp(stateValue.c_str(), kON);
1410 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1411 params.fGrContextOptions.fEnableInstancedRendering = value;
1412 fWindow->setRequestedDisplayParams(params);
1413 fWindow->inval();
1414 this->updateTitle();
1415 this->updateUIState();
1416 }
liyuqianb73c24b2016-06-03 08:47:23 -07001417 } else if (stateName.equals(kSoftkeyStateName)) {
1418 if (!stateValue.equals(kSoftkeyHint)) {
1419 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001420 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001421 }
liyuqian2edb0f42016-07-06 14:11:32 -07001422 } else if (stateName.equals(kRefreshStateName)) {
1423 // This state is actually NOT in the UI state.
1424 // We use this to allow Android to quickly set bool fRefresh.
1425 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001426 } else {
1427 SkDebugf("Unknown stateName: %s", stateName.c_str());
1428 }
1429}
Brian Osman79086b92017-02-10 13:36:16 -05001430
1431bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1432 return fCommands.onKey(key, state, modifiers);
1433}
1434
1435bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001436 if (fSlides[fCurrentSlide]->onChar(c)) {
1437 fWindow->inval();
1438 return true;
1439 }
1440
Brian Osman79086b92017-02-10 13:36:16 -05001441 return fCommands.onChar(c, modifiers);
1442}