blob: 72c2f6cb40e911986ad313928f2ceaf655f6de29 [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"
Brian Osman53136aa2017-07-20 15:43:35 -040024#include "SkEventTracingPriv.h"
Greg Daniel285db442016-10-14 09:12:53 -040025#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050026#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070027#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070028#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070029#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050030#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070031#include "SkRandom.h"
32#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070033#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050034#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050035#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070036#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040037#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070038
Brian Osman79086b92017-02-10 13:36:16 -050039#include "imgui.h"
40
Chris Dalton1a325d22017-07-14 15:17:41 -060041#include "ccpr/GrCoverageCountingPathRenderer.h"
42
csmartdalton578f0642017-02-24 16:04:47 -070043#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070044#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070045
jvanverth34524262016-05-04 13:49:13 -070046using namespace sk_app;
47
csmartdalton61cd31a2017-02-27 17:00:53 -070048using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
49static std::map<GpuPathRenderers, std::string> gPathRendererNames;
50
jvanverth9f372462016-04-06 06:08:59 -070051Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070052 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070053}
54
Christopher Dalton443ec1b2017-02-24 13:22:53 -070055static void on_backend_created_func(void* userData) {
56 Viewer* vv = reinterpret_cast<Viewer*>(userData);
57
58 return vv->onBackendCreated();
59}
60
jvanverth9f372462016-04-06 06:08:59 -070061static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070062 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070063
64 return vv->onPaint(canvas);
65}
66
jvanverth814e38d2016-06-06 08:48:47 -070067static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070068{
69 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
70
71 return viewer->onTouch(owner, state, x, y);
72}
73
liyuqiane5a6cd92016-05-27 08:52:52 -070074static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
75 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
76
77 return viewer->onUIStateChanged(stateName, stateValue);
78}
79
Brian Osman79086b92017-02-10 13:36:16 -050080static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
81 void* userData) {
82 ImGuiIO& io = ImGui::GetIO();
83 io.MousePos.x = static_cast<float>(x);
84 io.MousePos.y = static_cast<float>(y);
85 if (Window::kDown_InputState == state) {
86 io.MouseDown[0] = true;
87 } else if (Window::kUp_InputState == state) {
88 io.MouseDown[0] = false;
89 }
Jim Van Verthe7705782017-05-04 14:00:59 -040090 if (io.WantCaptureMouse) {
91 return true;
92 } else {
93 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
94 return viewer->onMouse(x, y, state, modifiers);
95 }
Brian Osman79086b92017-02-10 13:36:16 -050096}
97
98static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
99 ImGuiIO& io = ImGui::GetIO();
100 io.MouseWheel += delta;
101 return true;
102}
103
104static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
105 void* userData) {
106 ImGuiIO& io = ImGui::GetIO();
107 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
108
109 if (io.WantCaptureKeyboard) {
110 return true;
111 } else {
112 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
113 return viewer->onKey(key, state, modifiers);
114 }
115}
116
117static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
118 ImGuiIO& io = ImGui::GetIO();
119 if (io.WantTextInput) {
120 if (c > 0 && c < 0x10000) {
121 io.AddInputCharacter(c);
122 }
123 return true;
124 } else {
125 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
126 return viewer->onChar(c, modifiers);
127 }
128}
129
Brian Osman2dd96932016-10-18 15:33:53 -0400130static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400131
Brian Osman2dd96932016-10-18 15:33:53 -0400132static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700133 "[~][^]substring[$] [...] of bench name to run.\n"
134 "Multiple matches may be separated by spaces.\n"
135 "~ causes a matching bench to always be skipped\n"
136 "^ requires the start of the bench to match\n"
137 "$ requires the end of the bench to match\n"
138 "^ and $ requires an exact match\n"
139 "If a bench does not match any list entry,\n"
140 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700141
Jim Van Verth6f449692017-02-14 15:16:46 -0500142DEFINE_string(slide, "", "Start on this sample.");
143DEFINE_bool(list, false, "List samples?");
144
bsalomon6c471f72016-07-26 12:56:32 -0700145#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700146# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700147#else
148# define BACKENDS_STR "\"sw\" and \"gl\""
149#endif
150
liyuqian71491dc2016-06-09 12:02:34 -0700151#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400152static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
153static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700154#else
Brian Osman2dd96932016-10-18 15:33:53 -0400155static DEFINE_string(skps, "skps", "Directory to read skps from.");
156static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700157#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700158
Brian Osman2dd96932016-10-18 15:33:53 -0400159static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700160
csmartdalton578f0642017-02-24 16:04:47 -0700161DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700162DEFINE_pathrenderer_flag;
163
Brian Salomon41eac792017-03-08 14:03:56 -0500164DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
Brian Osman53136aa2017-07-20 15:43:35 -0400165DECLARE_int32(threads)
Brian Salomon41eac792017-03-08 14:03:56 -0500166
jvanverthaf236b52016-05-20 06:01:06 -0700167const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700168 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700169#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700170 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700171#endif
csmartdalton578f0642017-02-24 16:04:47 -0700172 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700173};
174
bsalomon6c471f72016-07-26 12:56:32 -0700175static sk_app::Window::BackendType get_backend_type(const char* str) {
176#ifdef SK_VULKAN
177 if (0 == strcmp(str, "vk")) {
178 return sk_app::Window::kVulkan_BackendType;
179 } else
180#endif
181 if (0 == strcmp(str, "gl")) {
182 return sk_app::Window::kNativeGL_BackendType;
183 } else if (0 == strcmp(str, "sw")) {
184 return sk_app::Window::kRaster_BackendType;
185 } else {
186 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
187 return sk_app::Window::kRaster_BackendType;
188 }
189}
190
Brian Osmana109e392017-02-24 09:49:14 -0500191static SkColorSpacePrimaries gSrgbPrimaries = {
192 0.64f, 0.33f,
193 0.30f, 0.60f,
194 0.15f, 0.06f,
195 0.3127f, 0.3290f };
196
197static SkColorSpacePrimaries gAdobePrimaries = {
198 0.64f, 0.33f,
199 0.21f, 0.71f,
200 0.15f, 0.06f,
201 0.3127f, 0.3290f };
202
203static SkColorSpacePrimaries gP3Primaries = {
204 0.680f, 0.320f,
205 0.265f, 0.690f,
206 0.150f, 0.060f,
207 0.3127f, 0.3290f };
208
209static SkColorSpacePrimaries gRec2020Primaries = {
210 0.708f, 0.292f,
211 0.170f, 0.797f,
212 0.131f, 0.046f,
213 0.3127f, 0.3290f };
214
215struct NamedPrimaries {
216 const char* fName;
217 SkColorSpacePrimaries* fPrimaries;
218} gNamedPrimaries[] = {
219 { "sRGB", &gSrgbPrimaries },
220 { "AdobeRGB", &gAdobePrimaries },
221 { "P3", &gP3Primaries },
222 { "Rec. 2020", &gRec2020Primaries },
223};
224
225static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
226 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
227}
228
liyuqiane5a6cd92016-05-27 08:52:52 -0700229const char* kName = "name";
230const char* kValue = "value";
231const char* kOptions = "options";
232const char* kSlideStateName = "Slide";
233const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700234const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700235const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500236const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700237const char* kSoftkeyStateName = "Softkey";
238const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700239const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700240const char* kON = "ON";
241const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700242const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700243
jvanverth34524262016-05-04 13:49:13 -0700244Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700245 : fCurrentMeasurement(0)
246 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700247 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500248 , fShowImGuiDebugWindow(false)
249 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500250 , fShowZoomWindow(false)
251 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700252 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500253 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500254 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700255 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400256 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700257{
Greg Daniel285db442016-10-14 09:12:53 -0400258 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700259
260 static SkOnce initPathRendererNames;
261 initPathRendererNames([]() {
262 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
263 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
264 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400265 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600266 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500267 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700268 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
269 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
270 });
271
Brian Osman1df161a2017-02-09 12:10:20 -0500272 memset(fPaintTimes, 0, sizeof(fPaintTimes));
273 memset(fFlushTimes, 0, sizeof(fFlushTimes));
274 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700275
jvanverth2bb3b6d2016-04-08 07:24:09 -0700276 SkDebugf("Command line arguments: ");
277 for (int i = 1; i < argc; ++i) {
278 SkDebugf("%s ", argv[i]);
279 }
280 SkDebugf("\n");
281
282 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500283#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400284 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500285#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700286
Brian Osmanbc8150f2017-07-24 11:38:01 -0400287 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400288 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400289
bsalomon6c471f72016-07-26 12:56:32 -0700290 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700291 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700292
csmartdalton578f0642017-02-24 16:04:47 -0700293 DisplayParams displayParams;
294 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500295 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700296 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700297 fWindow->setRequestedDisplayParams(displayParams);
298
jvanverth9f372462016-04-06 06:08:59 -0700299 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700300 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700301 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700302 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700303 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700304 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500305 fWindow->registerMouseFunc(on_mouse_handler, this);
306 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
307 fWindow->registerKeyFunc(on_key_handler, this);
308 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700309
brianosman622c8d52016-05-10 06:50:49 -0700310 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500311 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
312 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
313 fWindow->inval();
314 });
315 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
316 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
317 fWindow->inval();
318 });
Brian Osmanf6877092017-02-13 09:39:57 -0500319 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
320 this->fShowZoomWindow = !this->fShowZoomWindow;
321 fWindow->inval();
322 });
brianosman622c8d52016-05-10 06:50:49 -0700323 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
324 this->fDisplayStats = !this->fDisplayStats;
325 fWindow->inval();
326 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500327 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500328 switch (fColorMode) {
329 case ColorMode::kLegacy:
330 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
331 break;
332 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
333 this->setColorMode(ColorMode::kColorManagedSRGB8888);
334 break;
335 case ColorMode::kColorManagedSRGB8888:
336 this->setColorMode(ColorMode::kColorManagedLinearF16);
337 break;
338 case ColorMode::kColorManagedLinearF16:
339 this->setColorMode(ColorMode::kLegacy);
340 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500341 }
brianosman622c8d52016-05-10 06:50:49 -0700342 });
343 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
344 int previousSlide = fCurrentSlide;
345 fCurrentSlide++;
346 if (fCurrentSlide >= fSlides.count()) {
347 fCurrentSlide = 0;
348 }
349 this->setupCurrentSlide(previousSlide);
350 });
351 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
352 int previousSlide = fCurrentSlide;
353 fCurrentSlide--;
354 if (fCurrentSlide < 0) {
355 fCurrentSlide = fSlides.count() - 1;
356 }
357 this->setupCurrentSlide(previousSlide);
358 });
359 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
360 this->changeZoomLevel(1.f / 32.f);
361 fWindow->inval();
362 });
363 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
364 this->changeZoomLevel(-1.f / 32.f);
365 fWindow->inval();
366 });
jvanverthaf236b52016-05-20 06:01:06 -0700367 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Osman621491e2017-02-28 15:45:01 -0500368 sk_app::Window::BackendType newBackend = fBackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500369#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
jvanverthb8794cc2016-07-27 14:29:18 -0700370 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500371 newBackend = sk_app::Window::kNativeGL_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700372#ifdef SK_VULKAN
373 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500374 newBackend = sk_app::Window::kVulkan_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700375#endif
376 } else {
Brian Osman621491e2017-02-28 15:45:01 -0500377 newBackend = sk_app::Window::kRaster_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700378 }
Jim Van Verthd63c1022017-01-05 13:50:49 -0500379#elif defined(SK_BUILD_FOR_UNIX)
380 // Switching to and from Vulkan is problematic on Linux so disabled for now
381 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500382 newBackend = sk_app::Window::kNativeGL_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500383 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500384 newBackend = sk_app::Window::kRaster_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500385 }
386#endif
jvanverthaf236b52016-05-20 06:01:06 -0700387
Brian Osman621491e2017-02-28 15:45:01 -0500388 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700389 });
brianosman622c8d52016-05-10 06:50:49 -0700390
jvanverth2bb3b6d2016-04-08 07:24:09 -0700391 // set up slides
392 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500393 this->setStartupSlide();
394 if (FLAGS_list) {
395 this->listNames();
396 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700397
djsollen12d62a72016-04-21 07:59:44 -0700398 fAnimTimer.run();
399
Brian Osman79086b92017-02-10 13:36:16 -0500400 // ImGui initialization:
401 ImGuiIO& io = ImGui::GetIO();
402 io.DisplaySize.x = static_cast<float>(fWindow->width());
403 io.DisplaySize.y = static_cast<float>(fWindow->height());
404
405 // Keymap...
406 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
407 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
408 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
409 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
410 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
411 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
412 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
413 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
414 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
415 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
416 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
417 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
418 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
419 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
420 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
421 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
422 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
423 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
424 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
425
426 int w, h;
427 unsigned char* pixels;
428 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
429 SkImageInfo info = SkImageInfo::MakeA8(w, h);
430 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500431 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
432 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400433 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500434 fImGuiFontPaint.setShader(fontShader);
435 fImGuiFontPaint.setColor(SK_ColorWHITE);
436 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
437 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500438
Brian Osmana109e392017-02-24 09:49:14 -0500439 auto gamutImage = GetResourceAsImage("gamut.png");
440 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400441 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500442 }
443 fImGuiGamutPaint.setColor(SK_ColorWHITE);
444 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
445
csmartdalton578f0642017-02-24 16:04:47 -0700446 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700447}
448
jvanverth34524262016-05-04 13:49:13 -0700449void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700450 fAllSlideNames = Json::Value(Json::arrayValue);
451
jvanverth2bb3b6d2016-04-08 07:24:09 -0700452 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
453 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400454 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700455
456 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
457 sk_sp<Slide> slide(new GMSlide(gm.release()));
458 fSlides.push_back(slide);
459 }
460
461 gms = gms->next();
462 }
463
464 // reverse array
465 for (int i = 0; i < fSlides.count()/2; ++i) {
466 sk_sp<Slide> temp = fSlides[i];
467 fSlides[i] = fSlides[fSlides.count() - i - 1];
468 fSlides[fSlides.count() - i - 1] = temp;
469 }
470
jvanverthc7027ab2016-06-16 09:52:35 -0700471 // samples
472 const SkViewRegister* reg = SkViewRegister::Head();
473 while (reg) {
474 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700475 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
476 fSlides.push_back(slide);
477 }
jvanverthc7027ab2016-06-16 09:52:35 -0700478 reg = reg->next();
479 }
480
jvanverth2bb3b6d2016-04-08 07:24:09 -0700481 // SKPs
482 for (int i = 0; i < FLAGS_skps.count(); i++) {
483 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700484 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
485 continue;
486 }
487
jvanverth2bb3b6d2016-04-08 07:24:09 -0700488 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700489 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700490 if (slide) {
491 fSlides.push_back(slide);
492 }
493 } else {
494 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700495 SkString skpName;
496 while (it.next(&skpName)) {
497 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
498 continue;
499 }
500
501 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
502 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700503 if (slide) {
504 fSlides.push_back(slide);
505 }
506 }
507 }
508 }
liyuqian6f163d22016-06-13 12:26:45 -0700509
510 // JPGs
511 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
512 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
513 SkString jpgName;
514 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700515 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
516 continue;
517 }
518
liyuqian6f163d22016-06-13 12:26:45 -0700519 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
520 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
521 if (slide) {
522 fSlides.push_back(slide);
523 }
524 }
525 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700526}
527
528
jvanverth34524262016-05-04 13:49:13 -0700529Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700530 fWindow->detach();
531 delete fWindow;
532}
533
brianosman05de2162016-05-06 13:28:57 -0700534void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700535 if (!fWindow) {
536 return;
537 }
538 if (fWindow->sampleCount() < 0) {
539 return; // Surface hasn't been created yet.
540 }
541
jvanverth34524262016-05-04 13:49:13 -0700542 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700543 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700544
Brian Osman92004802017-03-06 11:47:26 -0500545 switch (fColorMode) {
546 case ColorMode::kLegacy:
547 title.append(" Legacy 8888");
548 break;
549 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
550 title.append(" ColorManaged 8888 (Nonlinear blending)");
551 break;
552 case ColorMode::kColorManagedSRGB8888:
553 title.append(" ColorManaged 8888");
554 break;
555 case ColorMode::kColorManagedLinearF16:
556 title.append(" ColorManaged F16");
557 break;
558 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500559
Brian Osman92004802017-03-06 11:47:26 -0500560 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500561 int curPrimaries = -1;
562 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
563 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
564 curPrimaries = i;
565 break;
566 }
567 }
568 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700569 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500570
csmartdalton578f0642017-02-24 16:04:47 -0700571 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700572 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700573 if (int msaa = fWindow->sampleCount()) {
574 title.appendf(" MSAA: %i", msaa);
575 }
576 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700577
578 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
579 if (GpuPathRenderers::kAll != pr) {
580 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
581 }
582
brianosman05de2162016-05-06 13:28:57 -0700583 fWindow->setTitle(title.c_str());
584}
585
Jim Van Verth6f449692017-02-14 15:16:46 -0500586void Viewer::setStartupSlide() {
587
588 if (!FLAGS_slide.isEmpty()) {
589 int count = fSlides.count();
590 for (int i = 0; i < count; i++) {
591 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
592 fCurrentSlide = i;
593 return;
594 }
595 }
596
597 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
598 this->listNames();
599 }
600
601 fCurrentSlide = 0;
602}
603
604void Viewer::listNames() {
605 int count = fSlides.count();
606 SkDebugf("All Slides:\n");
607 for (int i = 0; i < count; i++) {
608 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
609 }
610}
611
brianosman05de2162016-05-06 13:28:57 -0700612void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700613 if (fCurrentSlide == previousSlide) {
614 return; // no change; do nothing
615 }
liyuqian6f163d22016-06-13 12:26:45 -0700616 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700617 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700618
liyuqiane46e4f02016-05-20 07:32:19 -0700619 fGesture.reset();
620 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700621
Brian Osman42bb6ac2017-06-05 08:46:04 -0400622 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
623 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
624 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
625
626 // Start with a matrix that scales the slide to the available screen space
627 if (fWindow->scaleContentToFit()) {
628 if (windowRect.width() > 0 && windowRect.height() > 0) {
629 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700630 }
631 }
632
Brian Osman42bb6ac2017-06-05 08:46:04 -0400633 // Prevent the user from dragging content so far outside the window they can't find it again
634 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700635
brianosman05de2162016-05-06 13:28:57 -0700636 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700637 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700638 if (previousSlide >= 0) {
639 fSlides[previousSlide]->unload();
640 }
jvanverthc265a922016-04-08 12:51:45 -0700641 fWindow->inval();
642}
643
644#define MAX_ZOOM_LEVEL 8
645#define MIN_ZOOM_LEVEL -8
646
jvanverth34524262016-05-04 13:49:13 -0700647void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700648 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400649 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700650}
651
liyuqiand3cdbca2016-05-17 12:44:20 -0700652SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700653 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700654
Brian Osman42bb6ac2017-06-05 08:46:04 -0400655 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
656 : SK_Scalar1 + fZoomLevel;
657 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700658 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400659 m.preConcat(fDefaultMatrix);
660 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700661
liyuqiand3cdbca2016-05-17 12:44:20 -0700662 return m;
jvanverthc265a922016-04-08 12:51:45 -0700663}
664
Brian Osman621491e2017-02-28 15:45:01 -0500665void Viewer::setBackend(sk_app::Window::BackendType backendType) {
666 fBackendType = backendType;
667
668 fWindow->detach();
669
670#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Osman80a82df2017-07-12 15:42:51 -0400671 // Switching from OpenGL to Vulkan (or vice-versa on some systems) in the same window is
672 // problematic at this point on Windows, so we just delete the window and recreate it.
673 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
674 sk_app::Window::kNativeGL_BackendType == fBackendType) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400675 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500676 delete fWindow;
677 fWindow = Window::CreateNativeWindow(nullptr);
678
679 // re-register callbacks
680 fCommands.attach(fWindow);
681 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
682 fWindow->registerPaintFunc(on_paint_handler, this);
683 fWindow->registerTouchFunc(on_touch_handler, this);
684 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
685 fWindow->registerMouseFunc(on_mouse_handler, this);
686 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
687 fWindow->registerKeyFunc(on_key_handler, this);
688 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400689 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
690 // will still include our correct sample count. But the re-created fWindow will lose that
691 // information. On Windows, we need to re-create the window when changing sample count,
692 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
693 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
694 // as if we had never changed windows at all).
695 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500696 }
697#endif
698
699 fWindow->attach(fBackendType);
700}
701
Brian Osman92004802017-03-06 11:47:26 -0500702void Viewer::setColorMode(ColorMode colorMode) {
703 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700704
Brian Osmanf750fbc2017-02-08 10:47:28 -0500705 // 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 -0400706 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700707 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500708 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400709 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
710 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500711 if (wasInLegacy != wantLegacy) {
712 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700713 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500714 }
715
716 this->updateTitle();
717 fWindow->inval();
718}
719
720void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500721 SkAutoCanvasRestore autorestore(canvas, false);
722
Brian Osmanf750fbc2017-02-08 10:47:28 -0500723 // By default, we render directly into the window's surface/canvas
724 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500725 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700726
Brian Osmane0d4fba2017-03-15 10:24:55 -0400727 // If we're in any of the color managed modes, construct the color space we're going to use
728 sk_sp<SkColorSpace> cs = nullptr;
729 if (ColorMode::kLegacy != fColorMode) {
730 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
731 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
732 SkMatrix44 toXYZ;
733 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
734 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
735 }
736
737 // 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 -0500738 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500739 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500740 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500741 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400742 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
743 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
744
Brian Osman92004802017-03-06 11:47:26 -0500745 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
746 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400747 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
748 // with a special canvas (below) that has the color space attached
749 sk_sp<SkColorSpace> offscreenColorSpace =
750 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500751 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400752 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500753 offscreenSurface = canvas->makeSurface(info);
754 slideCanvas = offscreenSurface->getCanvas();
755 }
756
Brian Osmane0d4fba2017-03-15 10:24:55 -0400757 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
758 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
759 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
760 slideCanvas = xformCanvas.get();
761 }
762
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500763 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500764 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500765 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500766 // Time the painting logic of the slide
767 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500768 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500769 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500770 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500771
772 // Force a flush so we can time that, too
773 startTime = SkTime::GetMSecs();
774 slideCanvas->flush();
775 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500776
777 // If we rendered offscreen, snap an image and push the results to the window's canvas
778 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500779 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500780
781 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400782 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500783 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400784 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500785 SkPaint paint;
786 paint.setBlendMode(SkBlendMode::kSrc);
787 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700788 }
liyuqian6f163d22016-06-13 12:26:45 -0700789}
790
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700791void Viewer::onBackendCreated() {
792 this->updateTitle();
793 this->updateUIState();
794 this->setupCurrentSlide(-1);
795 fWindow->show();
796 fWindow->inval();
797}
Jim Van Verth6f449692017-02-14 15:16:46 -0500798
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700799void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500800 // Update ImGui input
801 ImGuiIO& io = ImGui::GetIO();
802 io.DeltaTime = 1.0f / 60.0f;
803 io.DisplaySize.x = static_cast<float>(fWindow->width());
804 io.DisplaySize.y = static_cast<float>(fWindow->height());
805
806 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
807 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
808 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
809
810 ImGui::NewFrame();
811
Brian Osmanf750fbc2017-02-08 10:47:28 -0500812 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700813
Brian Osman1df161a2017-02-09 12:10:20 -0500814 // Advance our timing bookkeeping
815 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
816 SkASSERT(fCurrentMeasurement < kMeasurementCount);
817
818 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700819 if (fDisplayStats) {
820 drawStats(canvas);
821 }
brianosman622c8d52016-05-10 06:50:49 -0700822 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700823
Brian Osman79086b92017-02-10 13:36:16 -0500824 drawImGui(canvas);
825
Brian Osman1df161a2017-02-09 12:10:20 -0500826 // Update the FPS
827 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700828}
829
jvanverth814e38d2016-06-06 08:48:47 -0700830bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400831 if (GestureDevice::kMouse == fGestureDevice) {
832 return false;
833 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700834 void* castedOwner = reinterpret_cast<void*>(owner);
835 switch (state) {
836 case Window::kUp_InputState: {
837 fGesture.touchEnd(castedOwner);
838 break;
839 }
840 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400841 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700842 break;
843 }
844 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400845 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700846 break;
847 }
848 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400849 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700850 fWindow->inval();
851 return true;
852}
853
Jim Van Verthe7705782017-05-04 14:00:59 -0400854bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400855 if (GestureDevice::kTouch == fGestureDevice) {
856 return false;
857 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400858 switch (state) {
859 case Window::kUp_InputState: {
860 fGesture.touchEnd(nullptr);
861 break;
862 }
863 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400864 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400865 break;
866 }
867 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400868 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400869 break;
870 }
871 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400872 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400873 fWindow->inval();
874 return true;
875}
876
jvanverth34524262016-05-04 13:49:13 -0700877void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700878 static const float kPixelPerMS = 2.0f;
879 static const int kDisplayWidth = 130;
880 static const int kDisplayHeight = 100;
881 static const int kDisplayPadding = 10;
882 static const int kGraphPadding = 3;
883 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
884
Mike Reed3661bc92017-02-22 13:21:42 -0500885 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700886 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
887 SkIntToScalar(kDisplayPadding),
888 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
889 SkPaint paint;
890 canvas->save();
891
892 canvas->clipRect(rect);
893 paint.setColor(SK_ColorBLACK);
894 canvas->drawRect(rect, paint);
895 // draw the 16ms line
896 paint.setColor(SK_ColorLTGRAY);
897 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
898 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
899 paint.setColor(SK_ColorRED);
900 paint.setStyle(SkPaint::kStroke_Style);
901 canvas->drawRect(rect, paint);
902
903 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
904 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700905 int i = fCurrentMeasurement;
906 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500907 // Round to nearest values
908 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
909 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
910 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
911 int startY = SkScalarTruncToInt(rect.fBottom);
912 int endY = startY - flushHeight;
913 paint.setColor(SK_ColorRED);
914 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
915 SkIntToScalar(x), SkIntToScalar(endY), paint);
916 startY = endY;
917 endY = startY - paintHeight;
918 paint.setColor(SK_ColorGREEN);
919 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
920 SkIntToScalar(x), SkIntToScalar(endY), paint);
921 startY = endY;
922 endY = startY - animateHeight;
923 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700924 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
925 SkIntToScalar(x), SkIntToScalar(endY), paint);
926 i++;
927 i &= (kMeasurementCount - 1); // fast mod
928 x += xStep;
929 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700930
931 canvas->restore();
932}
933
Brian Osmana109e392017-02-24 09:49:14 -0500934static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
935 const ImVec2& pos, const ImVec2& size) {
936 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
937 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
938
939 // Invisible 10x10 button
940 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
941 ImGui::InvisibleButton(label, ImVec2(10, 10));
942
943 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
944 ImGuiIO& io = ImGui::GetIO();
945 // Normalized mouse position, relative to our gamut box
946 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
947 // Clamp to edge of box, convert back to primary scale
948 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
949 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
950 }
951
952 if (ImGui::IsItemHovered()) {
953 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
954 }
955
956 // Return screen coordinates for the caller. We could just return center here, but we'd have
957 // one frame of lag during drag.
958 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
959}
960
961static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
962 ImDrawList* drawList = ImGui::GetWindowDrawList();
963
964 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
965 // width, and scale the height to maintain aspect ratio.
966 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
967 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
968 ImVec2 pos = ImGui::GetCursorScreenPos();
969
970 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
971 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
972 // Magic numbers are pixel locations of the origin and upper-right corner.
973 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
974 ImVec2(242, 61), ImVec2(1897, 1922));
975 ImVec2 endPos = ImGui::GetCursorPos();
976
977 // Primary markers
978 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
979 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
980 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
981 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
982
983 // Gamut triangle
984 drawList->AddCircle(r, 5.0f, 0xFF000040);
985 drawList->AddCircle(g, 5.0f, 0xFF004000);
986 drawList->AddCircle(b, 5.0f, 0xFF400000);
987 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
988 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
989
990 // Re-position cursor immediate after the diagram for subsequent controls
991 ImGui::SetCursorPos(endPos);
992}
993
Brian Osman79086b92017-02-10 13:36:16 -0500994void Viewer::drawImGui(SkCanvas* canvas) {
995 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
996 if (fShowImGuiTestWindow) {
997 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
998 }
999
1000 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001001 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1002 // always visible, we can end up in a layout feedback loop.
1003 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001004 DisplayParams params = fWindow->getRequestedDisplayParams();
1005 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001006 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1007 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001008 if (ImGui::CollapsingHeader("Backend")) {
1009 int newBackend = static_cast<int>(fBackendType);
1010 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1011 ImGui::SameLine();
1012 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1013#if defined(SK_VULKAN)
1014 ImGui::SameLine();
1015 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1016#endif
1017 if (newBackend != fBackendType) {
1018 fDeferredActions.push_back([=]() {
1019 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1020 });
1021 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001022
Brian Salomon99a33902017-03-07 15:16:34 -05001023 const GrContext* ctx = fWindow->getGrContext();
1024 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1025 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1026 paramsChanged = true;
1027 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001028 bool* wire = &params.fGrContextOptions.fWireframeMode;
1029 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1030 paramsChanged = true;
1031 }
Brian Salomon99a33902017-03-07 15:16:34 -05001032
Brian Osman28b12522017-03-08 17:10:24 -05001033 if (ctx) {
1034 int sampleCount = fWindow->sampleCount();
1035 ImGui::Text("MSAA: "); ImGui::SameLine();
1036 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1037 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1038 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1039 ImGui::RadioButton("16", &sampleCount, 16);
1040
1041 if (sampleCount != params.fMSAASampleCount) {
1042 params.fMSAASampleCount = sampleCount;
1043 paramsChanged = true;
1044 }
1045 }
1046
Brian Osman8a9de3d2017-03-01 14:59:05 -05001047 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001048 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001049 auto prButton = [&](GpuPathRenderers x) {
1050 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001051 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1052 params.fGrContextOptions.fGpuPathRenderers = x;
1053 paramsChanged = true;
1054 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001055 }
1056 };
1057
1058 if (!ctx) {
1059 ImGui::RadioButton("Software", true);
1060 } else if (fWindow->sampleCount()) {
1061 prButton(GpuPathRenderers::kAll);
1062 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1063 prButton(GpuPathRenderers::kStencilAndCover);
1064 }
1065 if (ctx->caps()->sampleShadingSupport()) {
1066 prButton(GpuPathRenderers::kMSAA);
1067 }
1068 prButton(GpuPathRenderers::kTessellating);
1069 prButton(GpuPathRenderers::kDefault);
1070 prButton(GpuPathRenderers::kNone);
1071 } else {
1072 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001073 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1074 prButton(GpuPathRenderers::kCoverageCounting);
1075 }
Jim Van Verth83010462017-03-16 08:45:39 -04001076 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001077 prButton(GpuPathRenderers::kTessellating);
1078 prButton(GpuPathRenderers::kNone);
1079 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001080 ImGui::TreePop();
1081 }
Brian Osman621491e2017-02-28 15:45:01 -05001082 }
1083
Brian Osman79086b92017-02-10 13:36:16 -05001084 if (ImGui::CollapsingHeader("Slide")) {
1085 static ImGuiTextFilter filter;
1086 filter.Draw();
1087 int previousSlide = fCurrentSlide;
1088 fCurrentSlide = 0;
1089 for (auto slide : fSlides) {
1090 if (filter.PassFilter(slide->getName().c_str())) {
1091 ImGui::BulletText("%s", slide->getName().c_str());
1092 if (ImGui::IsItemClicked()) {
1093 setupCurrentSlide(previousSlide);
1094 break;
1095 }
1096 }
1097 ++fCurrentSlide;
1098 }
1099 if (fCurrentSlide >= fSlides.count()) {
1100 fCurrentSlide = previousSlide;
1101 }
1102 }
Brian Osmana109e392017-02-24 09:49:14 -05001103
1104 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001105 ColorMode newMode = fColorMode;
1106 auto cmButton = [&](ColorMode mode, const char* label) {
1107 if (ImGui::RadioButton(label, mode == fColorMode)) {
1108 newMode = mode;
1109 }
1110 };
1111
1112 cmButton(ColorMode::kLegacy, "Legacy 8888");
1113 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1114 "Color Managed 8888 (Nonlinear blending)");
1115 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1116 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1117
1118 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001119 // It isn't safe to switch color mode now (in the middle of painting). We might
1120 // tear down the back-end, etc... Defer this change until the next onIdle.
1121 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001122 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001123 });
Brian Osmana109e392017-02-24 09:49:14 -05001124 }
1125
1126 // Pick from common gamuts:
1127 int primariesIdx = 4; // Default: Custom
1128 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1129 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1130 primariesIdx = i;
1131 break;
1132 }
1133 }
1134
1135 if (ImGui::Combo("Primaries", &primariesIdx,
1136 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1137 if (primariesIdx >= 0 && primariesIdx <= 3) {
1138 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1139 }
1140 }
1141
1142 // Allow direct editing of gamut
1143 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1144 }
Brian Osman79086b92017-02-10 13:36:16 -05001145 }
Brian Salomon99a33902017-03-07 15:16:34 -05001146 if (paramsChanged) {
1147 fDeferredActions.push_back([=]() {
1148 fWindow->setRequestedDisplayParams(params);
1149 fWindow->inval();
1150 this->updateTitle();
1151 });
1152 }
Brian Osman79086b92017-02-10 13:36:16 -05001153 ImGui::End();
1154 }
1155
Brian Osmanf6877092017-02-13 09:39:57 -05001156 SkPaint zoomImagePaint;
1157 if (fShowZoomWindow && fLastImage) {
1158 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1159 static int zoomFactor = 4;
1160 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1161
Mike Reed0acd7952017-04-28 11:12:19 -04001162 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001163 zoomImagePaint.setColor(SK_ColorWHITE);
1164
1165 // Zoom by shrinking the corner UVs towards the mouse cursor
1166 ImVec2 mousePos = ImGui::GetMousePos();
1167 ImVec2 avail = ImGui::GetContentRegionAvail();
1168
1169 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1170 (avail.y * 0.5f) / zoomFactor);
1171 ImGui::Image(&zoomImagePaint, avail,
1172 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1173 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1174 }
1175
1176 ImGui::End();
1177 }
1178
Brian Osman79086b92017-02-10 13:36:16 -05001179 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1180 // (widgets, etc...) that have been issued
1181 ImGui::Render();
1182
1183 // Then we fetch the most recent data, and convert it so we can render with Skia
1184 const ImDrawData* drawData = ImGui::GetDrawData();
1185 SkTDArray<SkPoint> pos;
1186 SkTDArray<SkPoint> uv;
1187 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001188
1189 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1190 const ImDrawList* drawList = drawData->CmdLists[i];
1191
1192 // De-interleave all vertex data (sigh), convert to Skia types
1193 pos.rewind(); uv.rewind(); color.rewind();
1194 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1195 const ImDrawVert& vert = drawList->VtxBuffer[i];
1196 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1197 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1198 color.push(vert.col);
1199 }
1200 // ImGui colors are RGBA
1201 SkSwapRB(color.begin(), color.begin(), color.count());
1202
1203 int indexOffset = 0;
1204
1205 // Draw everything with canvas.drawVertices...
1206 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1207 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1208
1209 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1210 if (drawCmd->UserCallback) {
1211 drawCmd->UserCallback(drawList, drawCmd);
1212 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001213 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1214 SkASSERT(paint);
1215
Brian Osman79086b92017-02-10 13:36:16 -05001216 canvas->save();
1217 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1218 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001219 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1220 drawList->VtxBuffer.size(), pos.begin(),
1221 uv.begin(), color.begin(),
1222 drawCmd->ElemCount,
1223 drawList->IdxBuffer.begin() + indexOffset),
1224 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001225 indexOffset += drawCmd->ElemCount;
1226 canvas->restore();
1227 }
1228 }
1229 }
1230}
1231
liyuqian2edb0f42016-07-06 14:11:32 -07001232void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001233 for (int i = 0; i < fDeferredActions.count(); ++i) {
1234 fDeferredActions[i]();
1235 }
1236 fDeferredActions.reset();
1237
Brian Osman1df161a2017-02-09 12:10:20 -05001238 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001239 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001240 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1241 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1242
Brian Osman79086b92017-02-10 13:36:16 -05001243 ImGuiIO& io = ImGui::GetIO();
1244 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001245 fWindow->inval();
1246 }
jvanverth9f372462016-04-06 06:08:59 -07001247}
liyuqiane5a6cd92016-05-27 08:52:52 -07001248
1249void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001250 if (!fWindow) {
1251 return;
1252 }
1253 if (fWindow->sampleCount() < 0) {
1254 return; // Surface hasn't been created yet.
1255 }
1256
liyuqianb73c24b2016-06-03 08:47:23 -07001257 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001258 Json::Value slideState(Json::objectValue);
1259 slideState[kName] = kSlideStateName;
1260 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001261 if (fAllSlideNames.size() == 0) {
1262 for(auto slide : fSlides) {
1263 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1264 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001265 }
liyuqian1f508fd2016-06-07 06:57:40 -07001266 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001267
liyuqianb73c24b2016-06-03 08:47:23 -07001268 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001269 Json::Value backendState(Json::objectValue);
1270 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001271 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001272 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001273 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001274 backendState[kOptions].append(Json::Value(str));
1275 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001276
csmartdalton578f0642017-02-24 16:04:47 -07001277 // MSAA state
1278 Json::Value msaaState(Json::objectValue);
1279 msaaState[kName] = kMSAAStateName;
1280 msaaState[kValue] = fWindow->sampleCount();
1281 msaaState[kOptions] = Json::Value(Json::arrayValue);
1282 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1283 msaaState[kOptions].append(Json::Value(0));
1284 } else {
1285 for (int msaa : {0, 4, 8, 16}) {
1286 msaaState[kOptions].append(Json::Value(msaa));
1287 }
1288 }
1289
csmartdalton61cd31a2017-02-27 17:00:53 -07001290 // Path renderer state
1291 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1292 Json::Value prState(Json::objectValue);
1293 prState[kName] = kPathRendererStateName;
1294 prState[kValue] = gPathRendererNames[pr];
1295 prState[kOptions] = Json::Value(Json::arrayValue);
1296 const GrContext* ctx = fWindow->getGrContext();
1297 if (!ctx) {
1298 prState[kOptions].append("Software");
1299 } else if (fWindow->sampleCount()) {
1300 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1301 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1302 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1303 }
1304 if (ctx->caps()->sampleShadingSupport()) {
1305 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1306 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001307 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001308 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1309 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1310 } else {
1311 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001312 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1313 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1314 }
Jim Van Verth83010462017-03-16 08:45:39 -04001315 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001316 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001317 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1318 }
1319
Brian Salomon99a33902017-03-07 15:16:34 -05001320 // Instanced rendering state
1321 Json::Value instState(Json::objectValue);
1322 instState[kName] = kInstancedRenderingStateName;
1323 if (ctx) {
1324 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1325 instState[kValue] = kON;
1326 } else {
1327 instState[kValue] = kOFF;
1328 }
1329 instState[kOptions] = Json::Value(Json::arrayValue);
1330 instState[kOptions].append(kOFF);
1331 instState[kOptions].append(kON);
1332 }
1333
liyuqianb73c24b2016-06-03 08:47:23 -07001334 // Softkey state
1335 Json::Value softkeyState(Json::objectValue);
1336 softkeyState[kName] = kSoftkeyStateName;
1337 softkeyState[kValue] = kSoftkeyHint;
1338 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1339 softkeyState[kOptions].append(kSoftkeyHint);
1340 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1341 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1342 }
1343
liyuqian1f508fd2016-06-07 06:57:40 -07001344 // FPS state
1345 Json::Value fpsState(Json::objectValue);
1346 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001347 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1348 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1349 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1350 fAnimateTimes[idx],
1351 fPaintTimes[idx],
1352 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001353 fpsState[kOptions] = Json::Value(Json::arrayValue);
1354
liyuqiane5a6cd92016-05-27 08:52:52 -07001355 Json::Value state(Json::arrayValue);
1356 state.append(slideState);
1357 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001358 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001359 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001360 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001361 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001362 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001363
1364 fWindow->setUIState(state);
1365}
1366
1367void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001368 // For those who will add more features to handle the state change in this function:
1369 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1370 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1371 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001372 if (stateName.equals(kSlideStateName)) {
1373 int previousSlide = fCurrentSlide;
1374 fCurrentSlide = 0;
1375 for(auto slide : fSlides) {
1376 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001377 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001378 break;
1379 }
1380 fCurrentSlide++;
1381 }
1382 if (fCurrentSlide >= fSlides.count()) {
1383 fCurrentSlide = previousSlide;
1384 SkDebugf("Slide not found: %s", stateValue.c_str());
1385 }
liyuqian6cb70252016-06-02 12:16:25 -07001386 } else if (stateName.equals(kBackendStateName)) {
1387 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1388 if (stateValue.equals(kBackendTypeStrings[i])) {
1389 if (fBackendType != i) {
1390 fBackendType = (sk_app::Window::BackendType)i;
1391 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001392 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001393 }
1394 break;
1395 }
1396 }
csmartdalton578f0642017-02-24 16:04:47 -07001397 } else if (stateName.equals(kMSAAStateName)) {
1398 DisplayParams params = fWindow->getRequestedDisplayParams();
1399 int sampleCount = atoi(stateValue.c_str());
1400 if (sampleCount != params.fMSAASampleCount) {
1401 params.fMSAASampleCount = sampleCount;
1402 fWindow->setRequestedDisplayParams(params);
1403 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001404 this->updateTitle();
1405 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001406 }
1407 } else if (stateName.equals(kPathRendererStateName)) {
1408 DisplayParams params = fWindow->getRequestedDisplayParams();
1409 for (const auto& pair : gPathRendererNames) {
1410 if (pair.second == stateValue.c_str()) {
1411 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1412 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1413 fWindow->setRequestedDisplayParams(params);
1414 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001415 this->updateTitle();
1416 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001417 }
1418 break;
1419 }
csmartdalton578f0642017-02-24 16:04:47 -07001420 }
Brian Salomon99a33902017-03-07 15:16:34 -05001421 } else if (stateName.equals(kInstancedRenderingStateName)) {
1422 DisplayParams params = fWindow->getRequestedDisplayParams();
1423 bool value = !strcmp(stateValue.c_str(), kON);
1424 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1425 params.fGrContextOptions.fEnableInstancedRendering = value;
1426 fWindow->setRequestedDisplayParams(params);
1427 fWindow->inval();
1428 this->updateTitle();
1429 this->updateUIState();
1430 }
liyuqianb73c24b2016-06-03 08:47:23 -07001431 } else if (stateName.equals(kSoftkeyStateName)) {
1432 if (!stateValue.equals(kSoftkeyHint)) {
1433 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001434 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001435 }
liyuqian2edb0f42016-07-06 14:11:32 -07001436 } else if (stateName.equals(kRefreshStateName)) {
1437 // This state is actually NOT in the UI state.
1438 // We use this to allow Android to quickly set bool fRefresh.
1439 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001440 } else {
1441 SkDebugf("Unknown stateName: %s", stateName.c_str());
1442 }
1443}
Brian Osman79086b92017-02-10 13:36:16 -05001444
1445bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1446 return fCommands.onKey(key, state, modifiers);
1447}
1448
1449bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001450 if (fSlides[fCurrentSlide]->onChar(c)) {
1451 fWindow->inval();
1452 return true;
1453 }
1454
Brian Osman79086b92017-02-10 13:36:16 -05001455 return fCommands.onChar(c, modifiers);
1456}