blob: f13136931e1dbc8cb92765a306b0c11674939a31 [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"
Brian Osmanf9810662017-08-30 10:02:10 -040022#include "SkCommonFlagsGpuThreads.h"
csmartdalton008b9d82017-02-22 12:00:42 -070023#include "SkCommonFlagsPathRenderer.h"
liyuqian74959a12016-06-16 14:10:34 -070024#include "SkDashPathEffect.h"
Brian Osman53136aa2017-07-20 15:43:35 -040025#include "SkEventTracingPriv.h"
Greg Daniel285db442016-10-14 09:12:53 -040026#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050027#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070028#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070029#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070030#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050031#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070032#include "SkRandom.h"
Yuqian Li399b3c22017-08-03 11:08:15 -040033#include "SkScan.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070034#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070035#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050036#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050037#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070038#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040039#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070040
Brian Osman79086b92017-02-10 13:36:16 -050041#include "imgui.h"
42
Chris Dalton1a325d22017-07-14 15:17:41 -060043#include "ccpr/GrCoverageCountingPathRenderer.h"
44
csmartdalton578f0642017-02-24 16:04:47 -070045#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070046#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070047
jvanverth34524262016-05-04 13:49:13 -070048using namespace sk_app;
49
csmartdalton61cd31a2017-02-27 17:00:53 -070050static std::map<GpuPathRenderers, std::string> gPathRendererNames;
51
jvanverth9f372462016-04-06 06:08:59 -070052Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070053 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070054}
55
Christopher Dalton443ec1b2017-02-24 13:22:53 -070056static void on_backend_created_func(void* userData) {
57 Viewer* vv = reinterpret_cast<Viewer*>(userData);
58
59 return vv->onBackendCreated();
60}
61
jvanverth9f372462016-04-06 06:08:59 -070062static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070063 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070064
65 return vv->onPaint(canvas);
66}
67
jvanverth814e38d2016-06-06 08:48:47 -070068static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070069{
70 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
71
72 return viewer->onTouch(owner, state, x, y);
73}
74
liyuqiane5a6cd92016-05-27 08:52:52 -070075static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
76 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
77
78 return viewer->onUIStateChanged(stateName, stateValue);
79}
80
Brian Osman79086b92017-02-10 13:36:16 -050081static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
82 void* userData) {
83 ImGuiIO& io = ImGui::GetIO();
84 io.MousePos.x = static_cast<float>(x);
85 io.MousePos.y = static_cast<float>(y);
86 if (Window::kDown_InputState == state) {
87 io.MouseDown[0] = true;
88 } else if (Window::kUp_InputState == state) {
89 io.MouseDown[0] = false;
90 }
Jim Van Verthe7705782017-05-04 14:00:59 -040091 if (io.WantCaptureMouse) {
92 return true;
93 } else {
94 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
95 return viewer->onMouse(x, y, state, modifiers);
96 }
Brian Osman79086b92017-02-10 13:36:16 -050097}
98
99static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
100 ImGuiIO& io = ImGui::GetIO();
101 io.MouseWheel += delta;
102 return true;
103}
104
105static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
106 void* userData) {
107 ImGuiIO& io = ImGui::GetIO();
108 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
109
110 if (io.WantCaptureKeyboard) {
111 return true;
112 } else {
113 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
114 return viewer->onKey(key, state, modifiers);
115 }
116}
117
118static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
119 ImGuiIO& io = ImGui::GetIO();
120 if (io.WantTextInput) {
121 if (c > 0 && c < 0x10000) {
122 io.AddInputCharacter(c);
123 }
124 return true;
125 } else {
126 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
127 return viewer->onChar(c, modifiers);
128 }
129}
130
Brian Osman2dd96932016-10-18 15:33:53 -0400131static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400132
Brian Osman2dd96932016-10-18 15:33:53 -0400133static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700134 "[~][^]substring[$] [...] of bench name to run.\n"
135 "Multiple matches may be separated by spaces.\n"
136 "~ causes a matching bench to always be skipped\n"
137 "^ requires the start of the bench to match\n"
138 "$ requires the end of the bench to match\n"
139 "^ and $ requires an exact match\n"
140 "If a bench does not match any list entry,\n"
141 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700142
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600143static DEFINE_string(slide, "", "Start on this sample.");
144static DEFINE_bool(list, false, "List samples?");
Jim Van Verth6f449692017-02-14 15:16:46 -0500145
bsalomon6c471f72016-07-26 12:56:32 -0700146#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700147# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700148#else
149# define BACKENDS_STR "\"sw\" and \"gl\""
150#endif
151
liyuqian71491dc2016-06-09 12:02:34 -0700152#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400153static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
154static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700155#else
Brian Osman2dd96932016-10-18 15:33:53 -0400156static DEFINE_string(skps, "skps", "Directory to read skps from.");
157static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700158#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700159
Brian Osman2dd96932016-10-18 15:33:53 -0400160static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700161
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600162static DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
163static DEFINE_bool(cachePathMasks, true, "Allows path mask textures to be cached in GPU configs.");
csmartdalton008b9d82017-02-22 12:00:42 -0700164DEFINE_pathrenderer_flag;
165
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600166static DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
Brian Osman53136aa2017-07-20 15:43:35 -0400167DECLARE_int32(threads)
Brian Salomon41eac792017-03-08 14:03:56 -0500168
Brian Salomon194db172017-08-17 14:37:06 -0400169const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700170 "OpenGL",
Brian Salomon194db172017-08-17 14:37:06 -0400171#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
172 "ANGLE",
173#endif
jvanverth063ece72016-06-17 09:29:14 -0700174#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700175 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700176#endif
csmartdalton578f0642017-02-24 16:04:47 -0700177 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700178};
179
bsalomon6c471f72016-07-26 12:56:32 -0700180static sk_app::Window::BackendType get_backend_type(const char* str) {
181#ifdef SK_VULKAN
182 if (0 == strcmp(str, "vk")) {
183 return sk_app::Window::kVulkan_BackendType;
184 } else
185#endif
Brian Salomon194db172017-08-17 14:37:06 -0400186#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
187 if (0 == strcmp(str, "angle")) {
188 return sk_app::Window::kANGLE_BackendType;
189 } else
190#endif
bsalomon6c471f72016-07-26 12:56:32 -0700191 if (0 == strcmp(str, "gl")) {
192 return sk_app::Window::kNativeGL_BackendType;
193 } else if (0 == strcmp(str, "sw")) {
194 return sk_app::Window::kRaster_BackendType;
195 } else {
196 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
197 return sk_app::Window::kRaster_BackendType;
198 }
199}
200
Brian Osmana109e392017-02-24 09:49:14 -0500201static SkColorSpacePrimaries gSrgbPrimaries = {
202 0.64f, 0.33f,
203 0.30f, 0.60f,
204 0.15f, 0.06f,
205 0.3127f, 0.3290f };
206
207static SkColorSpacePrimaries gAdobePrimaries = {
208 0.64f, 0.33f,
209 0.21f, 0.71f,
210 0.15f, 0.06f,
211 0.3127f, 0.3290f };
212
213static SkColorSpacePrimaries gP3Primaries = {
214 0.680f, 0.320f,
215 0.265f, 0.690f,
216 0.150f, 0.060f,
217 0.3127f, 0.3290f };
218
219static SkColorSpacePrimaries gRec2020Primaries = {
220 0.708f, 0.292f,
221 0.170f, 0.797f,
222 0.131f, 0.046f,
223 0.3127f, 0.3290f };
224
225struct NamedPrimaries {
226 const char* fName;
227 SkColorSpacePrimaries* fPrimaries;
228} gNamedPrimaries[] = {
229 { "sRGB", &gSrgbPrimaries },
230 { "AdobeRGB", &gAdobePrimaries },
231 { "P3", &gP3Primaries },
232 { "Rec. 2020", &gRec2020Primaries },
233};
234
235static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
236 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
237}
238
liyuqiane5a6cd92016-05-27 08:52:52 -0700239const char* kName = "name";
240const char* kValue = "value";
241const char* kOptions = "options";
242const char* kSlideStateName = "Slide";
243const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700244const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700245const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500246const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700247const char* kSoftkeyStateName = "Softkey";
248const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700249const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700250const char* kON = "ON";
251const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700252const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700253
jvanverth34524262016-05-04 13:49:13 -0700254Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700255 : fCurrentMeasurement(0)
Jim Van Verth90dcce52017-11-03 13:36:07 -0400256 , fCumulativeMeasurementTime(0)
257 , fCumulativeMeasurementCount(0)
jvanverthc265a922016-04-08 12:51:45 -0700258 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700259 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500260 , fShowImGuiDebugWindow(false)
261 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500262 , fShowZoomWindow(false)
263 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700264 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500265 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500266 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700267 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400268 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700269{
Greg Daniel285db442016-10-14 09:12:53 -0400270 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700271
272 static SkOnce initPathRendererNames;
273 initPathRendererNames([]() {
Brian Osman8b0f2652017-08-29 15:18:34 -0400274 gPathRendererNames[GpuPathRenderers::kAll] = "All Path Renderers";
275 gPathRendererNames[GpuPathRenderers::kDefault] =
276 "Default Ganesh Behavior (best path renderer, not including CCPR)";
csmartdalton61cd31a2017-02-27 17:00:53 -0700277 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
278 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400279 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600280 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500281 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700282 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
283 });
284
Brian Osman1df161a2017-02-09 12:10:20 -0500285 memset(fPaintTimes, 0, sizeof(fPaintTimes));
286 memset(fFlushTimes, 0, sizeof(fFlushTimes));
287 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700288
jvanverth2bb3b6d2016-04-08 07:24:09 -0700289 SkDebugf("Command line arguments: ");
290 for (int i = 1; i < argc; ++i) {
291 SkDebugf("%s ", argv[i]);
292 }
293 SkDebugf("\n");
294
295 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500296#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400297 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500298#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700299
Brian Osmanbc8150f2017-07-24 11:38:01 -0400300 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400301 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400302
bsalomon6c471f72016-07-26 12:56:32 -0700303 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700304 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700305
csmartdalton578f0642017-02-24 16:04:47 -0700306 DisplayParams displayParams;
307 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500308 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700309 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
Chris Dalton7a0ebfc2017-10-13 12:35:50 -0600310 displayParams.fGrContextOptions.fAllowPathMaskCaching = FLAGS_cachePathMasks;
Brian Osmanf9810662017-08-30 10:02:10 -0400311 displayParams.fGrContextOptions.fExecutor = GpuExecutorForTools();
csmartdalton578f0642017-02-24 16:04:47 -0700312 fWindow->setRequestedDisplayParams(displayParams);
313
jvanverth9f372462016-04-06 06:08:59 -0700314 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700315 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700316 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700317 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700318 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700319 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500320 fWindow->registerMouseFunc(on_mouse_handler, this);
321 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
322 fWindow->registerKeyFunc(on_key_handler, this);
323 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700324
brianosman622c8d52016-05-10 06:50:49 -0700325 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500326 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
327 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
328 fWindow->inval();
329 });
330 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
331 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
332 fWindow->inval();
333 });
Brian Osmanf6877092017-02-13 09:39:57 -0500334 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
335 this->fShowZoomWindow = !this->fShowZoomWindow;
336 fWindow->inval();
337 });
brianosman622c8d52016-05-10 06:50:49 -0700338 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
339 this->fDisplayStats = !this->fDisplayStats;
340 fWindow->inval();
341 });
Jim Van Verth90dcce52017-11-03 13:36:07 -0400342 fCommands.addCommand('0', "Overlays", "Reset stats", [this]() {
343 this->resetMeasurements();
344 this->updateTitle();
345 fWindow->inval();
346 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500347 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500348 switch (fColorMode) {
349 case ColorMode::kLegacy:
350 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
351 break;
352 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
353 this->setColorMode(ColorMode::kColorManagedSRGB8888);
354 break;
355 case ColorMode::kColorManagedSRGB8888:
356 this->setColorMode(ColorMode::kColorManagedLinearF16);
357 break;
358 case ColorMode::kColorManagedLinearF16:
359 this->setColorMode(ColorMode::kLegacy);
360 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500361 }
brianosman622c8d52016-05-10 06:50:49 -0700362 });
363 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
364 int previousSlide = fCurrentSlide;
365 fCurrentSlide++;
366 if (fCurrentSlide >= fSlides.count()) {
367 fCurrentSlide = 0;
368 }
369 this->setupCurrentSlide(previousSlide);
370 });
371 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
372 int previousSlide = fCurrentSlide;
373 fCurrentSlide--;
374 if (fCurrentSlide < 0) {
375 fCurrentSlide = fSlides.count() - 1;
376 }
377 this->setupCurrentSlide(previousSlide);
378 });
379 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
380 this->changeZoomLevel(1.f / 32.f);
381 fWindow->inval();
382 });
383 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
384 this->changeZoomLevel(-1.f / 32.f);
385 fWindow->inval();
386 });
jvanverthaf236b52016-05-20 06:01:06 -0700387 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400388 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
389 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500390 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400391#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
392 if (newBackend == sk_app::Window::kVulkan_BackendType) {
393 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
394 sk_app::Window::kBackendTypeCount);
395 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
396 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500397 }
398#endif
Brian Osman621491e2017-02-28 15:45:01 -0500399 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700400 });
brianosman622c8d52016-05-10 06:50:49 -0700401
Yuqian Li399b3c22017-08-03 11:08:15 -0400402 fCommands.addCommand('A', "AAA", "Toggle analytic AA", [this]() {
403 if (!gSkUseAnalyticAA) {
404 gSkUseAnalyticAA = true;
405 } else if (!gSkForceAnalyticAA) {
406 gSkForceAnalyticAA = true;
407 } else {
408 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
409 }
410 this->updateTitle();
411 fWindow->inval();
412 });
413 fCommands.addCommand('D', "DAA", "Toggle delta AA", [this]() {
414 if (!gSkUseDeltaAA) {
415 gSkUseDeltaAA = true;
416 } else if (!gSkForceDeltaAA) {
417 gSkForceDeltaAA = true;
418 } else {
419 gSkUseDeltaAA = gSkForceDeltaAA = false;
420 }
421 this->updateTitle();
422 fWindow->inval();
423 });
424
jvanverth2bb3b6d2016-04-08 07:24:09 -0700425 // set up slides
426 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500427 this->setStartupSlide();
428 if (FLAGS_list) {
429 this->listNames();
430 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700431
djsollen12d62a72016-04-21 07:59:44 -0700432 fAnimTimer.run();
433
Brian Osman79086b92017-02-10 13:36:16 -0500434 // ImGui initialization:
435 ImGuiIO& io = ImGui::GetIO();
436 io.DisplaySize.x = static_cast<float>(fWindow->width());
437 io.DisplaySize.y = static_cast<float>(fWindow->height());
438
439 // Keymap...
440 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
441 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
442 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
443 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
444 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
445 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
446 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
447 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
448 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
449 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
450 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
451 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
452 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
453 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
454 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
455 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
456 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
457 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
458 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
459
460 int w, h;
461 unsigned char* pixels;
462 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
463 SkImageInfo info = SkImageInfo::MakeA8(w, h);
464 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500465 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
466 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400467 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500468 fImGuiFontPaint.setShader(fontShader);
469 fImGuiFontPaint.setColor(SK_ColorWHITE);
470 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
471 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500472
Brian Osmana109e392017-02-24 09:49:14 -0500473 auto gamutImage = GetResourceAsImage("gamut.png");
474 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400475 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500476 }
477 fImGuiGamutPaint.setColor(SK_ColorWHITE);
478 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
479
csmartdalton578f0642017-02-24 16:04:47 -0700480 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700481}
482
jvanverth34524262016-05-04 13:49:13 -0700483void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700484 fAllSlideNames = Json::Value(Json::arrayValue);
485
jvanverth2bb3b6d2016-04-08 07:24:09 -0700486 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
487 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400488 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700489
490 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
491 sk_sp<Slide> slide(new GMSlide(gm.release()));
492 fSlides.push_back(slide);
493 }
494
495 gms = gms->next();
496 }
497
498 // reverse array
499 for (int i = 0; i < fSlides.count()/2; ++i) {
500 sk_sp<Slide> temp = fSlides[i];
501 fSlides[i] = fSlides[fSlides.count() - i - 1];
502 fSlides[fSlides.count() - i - 1] = temp;
503 }
504
jvanverthc7027ab2016-06-16 09:52:35 -0700505 // samples
506 const SkViewRegister* reg = SkViewRegister::Head();
507 while (reg) {
508 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700509 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
510 fSlides.push_back(slide);
511 }
jvanverthc7027ab2016-06-16 09:52:35 -0700512 reg = reg->next();
513 }
514
jvanverth2bb3b6d2016-04-08 07:24:09 -0700515 // SKPs
516 for (int i = 0; i < FLAGS_skps.count(); i++) {
517 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700518 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
519 continue;
520 }
521
jvanverth2bb3b6d2016-04-08 07:24:09 -0700522 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700523 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700524 if (slide) {
525 fSlides.push_back(slide);
526 }
527 } else {
528 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700529 SkString skpName;
530 while (it.next(&skpName)) {
531 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
532 continue;
533 }
534
535 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
536 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700537 if (slide) {
538 fSlides.push_back(slide);
539 }
540 }
541 }
542 }
liyuqian6f163d22016-06-13 12:26:45 -0700543
544 // JPGs
545 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
546 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
547 SkString jpgName;
548 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700549 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
550 continue;
551 }
552
liyuqian6f163d22016-06-13 12:26:45 -0700553 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
554 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
555 if (slide) {
556 fSlides.push_back(slide);
557 }
558 }
559 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700560}
561
562
jvanverth34524262016-05-04 13:49:13 -0700563Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700564 fWindow->detach();
565 delete fWindow;
566}
567
brianosman05de2162016-05-06 13:28:57 -0700568void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700569 if (!fWindow) {
570 return;
571 }
572 if (fWindow->sampleCount() < 0) {
573 return; // Surface hasn't been created yet.
574 }
575
jvanverth34524262016-05-04 13:49:13 -0700576 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700577 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700578
Yuqian Li399b3c22017-08-03 11:08:15 -0400579 if (gSkUseDeltaAA) {
580 if (gSkForceDeltaAA) {
581 title.append(" <FDAA>");
582 } else {
583 title.append(" <DAA>");
584 }
585 } else if (gSkUseAnalyticAA) {
586 if (gSkForceAnalyticAA) {
587 title.append(" <FAAA>");
588 } else {
589 title.append(" <AAA>");
590 }
591 }
592
Brian Osman92004802017-03-06 11:47:26 -0500593 switch (fColorMode) {
594 case ColorMode::kLegacy:
595 title.append(" Legacy 8888");
596 break;
597 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
598 title.append(" ColorManaged 8888 (Nonlinear blending)");
599 break;
600 case ColorMode::kColorManagedSRGB8888:
601 title.append(" ColorManaged 8888");
602 break;
603 case ColorMode::kColorManagedLinearF16:
604 title.append(" ColorManaged F16");
605 break;
606 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500607
Brian Osman92004802017-03-06 11:47:26 -0500608 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500609 int curPrimaries = -1;
610 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
611 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
612 curPrimaries = i;
613 break;
614 }
615 }
616 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700617 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500618
Jim Van Verth90dcce52017-11-03 13:36:07 -0400619 if (fDisplayStats) {
620 double ms = 0;
621 int count = 0;
622 int i = (fCurrentMeasurement + kMeasurementCount - 1) & (kMeasurementCount - 1);
623 do {
624 double inc = fAnimateTimes[i] + fPaintTimes[i] + fFlushTimes[i];
625 if (inc <= 0) {
626 break;
627 }
628 ms += inc;
629 ++count;
630 i = (i + kMeasurementCount - 1) & (kMeasurementCount - 1);
631 } while (i != fCurrentMeasurement);
632
633 title.appendf(" %8.4f ms -> %4.4f ms", ms / SkTMax(1, count),
634 fCumulativeMeasurementTime / SkTMax(1, fCumulativeMeasurementCount));
635 }
636
csmartdalton578f0642017-02-24 16:04:47 -0700637 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700638 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700639 if (int msaa = fWindow->sampleCount()) {
640 title.appendf(" MSAA: %i", msaa);
641 }
642 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700643
644 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Brian Osman8b0f2652017-08-29 15:18:34 -0400645 if (GpuPathRenderers::kDefault != pr) {
csmartdalton61cd31a2017-02-27 17:00:53 -0700646 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
647 }
648
brianosman05de2162016-05-06 13:28:57 -0700649 fWindow->setTitle(title.c_str());
650}
651
Jim Van Verth6f449692017-02-14 15:16:46 -0500652void Viewer::setStartupSlide() {
653
654 if (!FLAGS_slide.isEmpty()) {
655 int count = fSlides.count();
656 for (int i = 0; i < count; i++) {
657 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
658 fCurrentSlide = i;
659 return;
660 }
661 }
662
663 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
664 this->listNames();
665 }
666
667 fCurrentSlide = 0;
668}
669
670void Viewer::listNames() {
671 int count = fSlides.count();
672 SkDebugf("All Slides:\n");
673 for (int i = 0; i < count; i++) {
674 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
675 }
676}
677
Jim Van Verth90dcce52017-11-03 13:36:07 -0400678void Viewer::resetMeasurements() {
679 memset(fPaintTimes, 0, sizeof(fPaintTimes));
680 memset(fFlushTimes, 0, sizeof(fFlushTimes));
681 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
682 fCurrentMeasurement = 0;
683 fCumulativeMeasurementTime = 0;
684 fCumulativeMeasurementCount = 0;
685}
686
brianosman05de2162016-05-06 13:28:57 -0700687void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700688 if (fCurrentSlide == previousSlide) {
689 return; // no change; do nothing
690 }
liyuqian6f163d22016-06-13 12:26:45 -0700691 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700692 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700693
liyuqiane46e4f02016-05-20 07:32:19 -0700694 fGesture.reset();
695 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700696
Brian Osman42bb6ac2017-06-05 08:46:04 -0400697 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
698 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
699 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
700
701 // Start with a matrix that scales the slide to the available screen space
702 if (fWindow->scaleContentToFit()) {
703 if (windowRect.width() > 0 && windowRect.height() > 0) {
704 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700705 }
706 }
707
Brian Osman42bb6ac2017-06-05 08:46:04 -0400708 // Prevent the user from dragging content so far outside the window they can't find it again
709 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700710
brianosman05de2162016-05-06 13:28:57 -0700711 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700712 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700713 if (previousSlide >= 0) {
714 fSlides[previousSlide]->unload();
715 }
Jim Van Verth90dcce52017-11-03 13:36:07 -0400716
717 this->resetMeasurements();
718
jvanverthc265a922016-04-08 12:51:45 -0700719 fWindow->inval();
720}
721
722#define MAX_ZOOM_LEVEL 8
723#define MIN_ZOOM_LEVEL -8
724
jvanverth34524262016-05-04 13:49:13 -0700725void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700726 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400727 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700728}
729
liyuqiand3cdbca2016-05-17 12:44:20 -0700730SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700731 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700732
Brian Osman42bb6ac2017-06-05 08:46:04 -0400733 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
734 : SK_Scalar1 + fZoomLevel;
735 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700736 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400737 m.preConcat(fDefaultMatrix);
738 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700739
liyuqiand3cdbca2016-05-17 12:44:20 -0700740 return m;
jvanverthc265a922016-04-08 12:51:45 -0700741}
742
Brian Osman621491e2017-02-28 15:45:01 -0500743void Viewer::setBackend(sk_app::Window::BackendType backendType) {
744 fBackendType = backendType;
745
746 fWindow->detach();
747
748#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Salomon194db172017-08-17 14:37:06 -0400749 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
750 // on Windows, so we just delete the window and recreate it.
Brian Osman80a82df2017-07-12 15:42:51 -0400751 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
Brian Salomon194db172017-08-17 14:37:06 -0400752 sk_app::Window::kNativeGL_BackendType == fBackendType
753#if SK_ANGLE
754 || sk_app::Window::kANGLE_BackendType == fBackendType
755#endif
756 ) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400757 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500758 delete fWindow;
759 fWindow = Window::CreateNativeWindow(nullptr);
760
761 // re-register callbacks
762 fCommands.attach(fWindow);
763 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
764 fWindow->registerPaintFunc(on_paint_handler, this);
765 fWindow->registerTouchFunc(on_touch_handler, this);
766 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
767 fWindow->registerMouseFunc(on_mouse_handler, this);
768 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
769 fWindow->registerKeyFunc(on_key_handler, this);
770 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400771 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
772 // will still include our correct sample count. But the re-created fWindow will lose that
773 // information. On Windows, we need to re-create the window when changing sample count,
774 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
775 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
776 // as if we had never changed windows at all).
777 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500778 }
779#endif
780
781 fWindow->attach(fBackendType);
782}
783
Brian Osman92004802017-03-06 11:47:26 -0500784void Viewer::setColorMode(ColorMode colorMode) {
785 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700786
Brian Osmanf750fbc2017-02-08 10:47:28 -0500787 // 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 -0400788 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700789 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500790 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400791 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
792 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500793 if (wasInLegacy != wantLegacy) {
794 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700795 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500796 }
797
798 this->updateTitle();
799 fWindow->inval();
800}
801
802void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500803 SkAutoCanvasRestore autorestore(canvas, false);
804
Brian Osmanf750fbc2017-02-08 10:47:28 -0500805 // By default, we render directly into the window's surface/canvas
806 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500807 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700808
Brian Osmane0d4fba2017-03-15 10:24:55 -0400809 // If we're in any of the color managed modes, construct the color space we're going to use
810 sk_sp<SkColorSpace> cs = nullptr;
811 if (ColorMode::kLegacy != fColorMode) {
812 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
813 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400814 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400815 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
816 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
817 }
818
819 // 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 -0500820 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500821 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500822 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500823 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400824 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
825 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
826
Brian Osman92004802017-03-06 11:47:26 -0500827 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
828 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400829 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
830 // with a special canvas (below) that has the color space attached
831 sk_sp<SkColorSpace> offscreenColorSpace =
832 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500833 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400834 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500835 offscreenSurface = canvas->makeSurface(info);
836 slideCanvas = offscreenSurface->getCanvas();
837 }
838
Brian Osmane0d4fba2017-03-15 10:24:55 -0400839 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
840 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
841 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
842 slideCanvas = xformCanvas.get();
843 }
844
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500845 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500846 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500847 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500848 // Time the painting logic of the slide
849 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500850 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500851 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500852 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500853
854 // Force a flush so we can time that, too
855 startTime = SkTime::GetMSecs();
856 slideCanvas->flush();
857 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500858
859 // If we rendered offscreen, snap an image and push the results to the window's canvas
860 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500861 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500862
863 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400864 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500865 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400866 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500867 SkPaint paint;
868 paint.setBlendMode(SkBlendMode::kSrc);
869 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700870 }
liyuqian6f163d22016-06-13 12:26:45 -0700871}
872
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700873void Viewer::onBackendCreated() {
874 this->updateTitle();
875 this->updateUIState();
876 this->setupCurrentSlide(-1);
Jim Van Verth90dcce52017-11-03 13:36:07 -0400877 this->resetMeasurements();
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700878 fWindow->show();
879 fWindow->inval();
880}
Jim Van Verth6f449692017-02-14 15:16:46 -0500881
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700882void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500883 // Update ImGui input
884 ImGuiIO& io = ImGui::GetIO();
885 io.DeltaTime = 1.0f / 60.0f;
886 io.DisplaySize.x = static_cast<float>(fWindow->width());
887 io.DisplaySize.y = static_cast<float>(fWindow->height());
888
889 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
890 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
891 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
892
893 ImGui::NewFrame();
894
Jim Van Verth90dcce52017-11-03 13:36:07 -0400895 this->drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700896
Brian Osman1df161a2017-02-09 12:10:20 -0500897 // Advance our timing bookkeeping
Jim Van Verth90dcce52017-11-03 13:36:07 -0400898 fCumulativeMeasurementTime += fAnimateTimes[fCurrentMeasurement] +
899 fPaintTimes[fCurrentMeasurement] +
900 fFlushTimes[fCurrentMeasurement];
901 fCumulativeMeasurementCount++;
Brian Osman1df161a2017-02-09 12:10:20 -0500902 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
903 SkASSERT(fCurrentMeasurement < kMeasurementCount);
904
905 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700906 if (fDisplayStats) {
907 drawStats(canvas);
Jim Van Verth90dcce52017-11-03 13:36:07 -0400908 this->updateTitle();
jvanverthc265a922016-04-08 12:51:45 -0700909 }
brianosman622c8d52016-05-10 06:50:49 -0700910 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700911
Jim Van Verth90dcce52017-11-03 13:36:07 -0400912 this->drawImGui(canvas);
Brian Osman79086b92017-02-10 13:36:16 -0500913
Brian Osman1df161a2017-02-09 12:10:20 -0500914 // Update the FPS
Jim Van Verth90dcce52017-11-03 13:36:07 -0400915 this->updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700916}
917
jvanverth814e38d2016-06-06 08:48:47 -0700918bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400919 if (GestureDevice::kMouse == fGestureDevice) {
920 return false;
921 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700922 void* castedOwner = reinterpret_cast<void*>(owner);
923 switch (state) {
924 case Window::kUp_InputState: {
925 fGesture.touchEnd(castedOwner);
926 break;
927 }
928 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400929 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700930 break;
931 }
932 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400933 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700934 break;
935 }
936 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400937 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700938 fWindow->inval();
939 return true;
940}
941
Jim Van Verthe7705782017-05-04 14:00:59 -0400942bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Jim Van Verthc9e7f9c2017-11-02 09:46:49 -0400943 if (!fSlides[fCurrentSlide]->onMouse(x, y, state, modifiers)) {
944 if (GestureDevice::kTouch == fGestureDevice) {
945 return false;
946 }
947 switch (state) {
948 case Window::kUp_InputState: {
949 fGesture.touchEnd(nullptr);
950 break;
951 }
952 case Window::kDown_InputState: {
953 fGesture.touchBegin(nullptr, x, y);
954 break;
955 }
956 case Window::kMove_InputState: {
957 fGesture.touchMoved(nullptr, x, y);
958 break;
959 }
960 }
961 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Brian Osmanb53f48c2017-06-07 10:00:30 -0400962 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400963 fWindow->inval();
964 return true;
965}
966
jvanverth34524262016-05-04 13:49:13 -0700967void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700968 static const float kPixelPerMS = 2.0f;
969 static const int kDisplayWidth = 130;
970 static const int kDisplayHeight = 100;
971 static const int kDisplayPadding = 10;
972 static const int kGraphPadding = 3;
973 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
974
Mike Reed3661bc92017-02-22 13:21:42 -0500975 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700976 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
977 SkIntToScalar(kDisplayPadding),
978 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
979 SkPaint paint;
980 canvas->save();
981
982 canvas->clipRect(rect);
983 paint.setColor(SK_ColorBLACK);
984 canvas->drawRect(rect, paint);
985 // draw the 16ms line
986 paint.setColor(SK_ColorLTGRAY);
987 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
988 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
989 paint.setColor(SK_ColorRED);
990 paint.setStyle(SkPaint::kStroke_Style);
991 canvas->drawRect(rect, paint);
992
993 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
994 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700995 int i = fCurrentMeasurement;
996 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500997 // Round to nearest values
998 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
999 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
1000 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
1001 int startY = SkScalarTruncToInt(rect.fBottom);
1002 int endY = startY - flushHeight;
1003 paint.setColor(SK_ColorRED);
1004 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
1005 SkIntToScalar(x), SkIntToScalar(endY), paint);
1006 startY = endY;
1007 endY = startY - paintHeight;
1008 paint.setColor(SK_ColorGREEN);
1009 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
1010 SkIntToScalar(x), SkIntToScalar(endY), paint);
1011 startY = endY;
1012 endY = startY - animateHeight;
1013 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -07001014 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
1015 SkIntToScalar(x), SkIntToScalar(endY), paint);
1016 i++;
1017 i &= (kMeasurementCount - 1); // fast mod
1018 x += xStep;
1019 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -07001020
1021 canvas->restore();
1022}
1023
Brian Osmana109e392017-02-24 09:49:14 -05001024static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
1025 const ImVec2& pos, const ImVec2& size) {
1026 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
1027 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1028
1029 // Invisible 10x10 button
1030 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
1031 ImGui::InvisibleButton(label, ImVec2(10, 10));
1032
1033 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
1034 ImGuiIO& io = ImGui::GetIO();
1035 // Normalized mouse position, relative to our gamut box
1036 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
1037 // Clamp to edge of box, convert back to primary scale
1038 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
1039 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
1040 }
1041
1042 if (ImGui::IsItemHovered()) {
1043 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
1044 }
1045
1046 // Return screen coordinates for the caller. We could just return center here, but we'd have
1047 // one frame of lag during drag.
1048 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1049}
1050
1051static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1052 ImDrawList* drawList = ImGui::GetWindowDrawList();
1053
1054 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1055 // width, and scale the height to maintain aspect ratio.
1056 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1057 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1058 ImVec2 pos = ImGui::GetCursorScreenPos();
1059
1060 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1061 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1062 // Magic numbers are pixel locations of the origin and upper-right corner.
1063 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1064 ImVec2(242, 61), ImVec2(1897, 1922));
1065 ImVec2 endPos = ImGui::GetCursorPos();
1066
1067 // Primary markers
1068 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1069 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1070 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1071 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1072
1073 // Gamut triangle
1074 drawList->AddCircle(r, 5.0f, 0xFF000040);
1075 drawList->AddCircle(g, 5.0f, 0xFF004000);
1076 drawList->AddCircle(b, 5.0f, 0xFF400000);
1077 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1078 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1079
1080 // Re-position cursor immediate after the diagram for subsequent controls
1081 ImGui::SetCursorPos(endPos);
1082}
1083
Brian Osman79086b92017-02-10 13:36:16 -05001084void Viewer::drawImGui(SkCanvas* canvas) {
1085 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1086 if (fShowImGuiTestWindow) {
1087 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1088 }
1089
1090 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001091 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1092 // always visible, we can end up in a layout feedback loop.
1093 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001094 DisplayParams params = fWindow->getRequestedDisplayParams();
1095 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001096 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1097 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001098 if (ImGui::CollapsingHeader("Backend")) {
1099 int newBackend = static_cast<int>(fBackendType);
1100 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1101 ImGui::SameLine();
1102 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001103#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1104 ImGui::SameLine();
1105 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1106#endif
Brian Osman621491e2017-02-28 15:45:01 -05001107#if defined(SK_VULKAN)
1108 ImGui::SameLine();
1109 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1110#endif
1111 if (newBackend != fBackendType) {
1112 fDeferredActions.push_back([=]() {
1113 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1114 });
1115 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001116
Brian Salomon99a33902017-03-07 15:16:34 -05001117 const GrContext* ctx = fWindow->getGrContext();
1118 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1119 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1120 paramsChanged = true;
1121 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001122 bool* wire = &params.fGrContextOptions.fWireframeMode;
1123 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1124 paramsChanged = true;
1125 }
Brian Salomon99a33902017-03-07 15:16:34 -05001126
Brian Osman28b12522017-03-08 17:10:24 -05001127 if (ctx) {
1128 int sampleCount = fWindow->sampleCount();
1129 ImGui::Text("MSAA: "); ImGui::SameLine();
1130 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1131 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1132 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1133 ImGui::RadioButton("16", &sampleCount, 16);
1134
1135 if (sampleCount != params.fMSAASampleCount) {
1136 params.fMSAASampleCount = sampleCount;
1137 paramsChanged = true;
1138 }
1139 }
1140
Brian Osman8a9de3d2017-03-01 14:59:05 -05001141 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001142 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001143 auto prButton = [&](GpuPathRenderers x) {
1144 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001145 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1146 params.fGrContextOptions.fGpuPathRenderers = x;
1147 paramsChanged = true;
1148 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001149 }
1150 };
1151
1152 if (!ctx) {
1153 ImGui::RadioButton("Software", true);
1154 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001155 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001156 prButton(GpuPathRenderers::kAll);
1157 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1158 prButton(GpuPathRenderers::kStencilAndCover);
1159 }
1160 if (ctx->caps()->sampleShadingSupport()) {
1161 prButton(GpuPathRenderers::kMSAA);
1162 }
1163 prButton(GpuPathRenderers::kTessellating);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001164 prButton(GpuPathRenderers::kNone);
1165 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001166 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001167 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001168 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1169 prButton(GpuPathRenderers::kCoverageCounting);
1170 }
Jim Van Verth83010462017-03-16 08:45:39 -04001171 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001172 prButton(GpuPathRenderers::kTessellating);
1173 prButton(GpuPathRenderers::kNone);
1174 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001175 ImGui::TreePop();
1176 }
Brian Osman621491e2017-02-28 15:45:01 -05001177 }
1178
Brian Osman79086b92017-02-10 13:36:16 -05001179 if (ImGui::CollapsingHeader("Slide")) {
1180 static ImGuiTextFilter filter;
1181 filter.Draw();
1182 int previousSlide = fCurrentSlide;
1183 fCurrentSlide = 0;
1184 for (auto slide : fSlides) {
1185 if (filter.PassFilter(slide->getName().c_str())) {
1186 ImGui::BulletText("%s", slide->getName().c_str());
1187 if (ImGui::IsItemClicked()) {
1188 setupCurrentSlide(previousSlide);
1189 break;
1190 }
1191 }
1192 ++fCurrentSlide;
1193 }
1194 if (fCurrentSlide >= fSlides.count()) {
1195 fCurrentSlide = previousSlide;
1196 }
1197 }
Brian Osmana109e392017-02-24 09:49:14 -05001198
1199 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001200 ColorMode newMode = fColorMode;
1201 auto cmButton = [&](ColorMode mode, const char* label) {
1202 if (ImGui::RadioButton(label, mode == fColorMode)) {
1203 newMode = mode;
1204 }
1205 };
1206
1207 cmButton(ColorMode::kLegacy, "Legacy 8888");
1208 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1209 "Color Managed 8888 (Nonlinear blending)");
1210 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1211 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1212
1213 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001214 // It isn't safe to switch color mode now (in the middle of painting). We might
1215 // tear down the back-end, etc... Defer this change until the next onIdle.
1216 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001217 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001218 });
Brian Osmana109e392017-02-24 09:49:14 -05001219 }
1220
1221 // Pick from common gamuts:
1222 int primariesIdx = 4; // Default: Custom
1223 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1224 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1225 primariesIdx = i;
1226 break;
1227 }
1228 }
1229
1230 if (ImGui::Combo("Primaries", &primariesIdx,
1231 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1232 if (primariesIdx >= 0 && primariesIdx <= 3) {
1233 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1234 }
1235 }
1236
1237 // Allow direct editing of gamut
1238 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1239 }
Brian Osman79086b92017-02-10 13:36:16 -05001240 }
Brian Salomon99a33902017-03-07 15:16:34 -05001241 if (paramsChanged) {
1242 fDeferredActions.push_back([=]() {
1243 fWindow->setRequestedDisplayParams(params);
1244 fWindow->inval();
1245 this->updateTitle();
1246 });
1247 }
Brian Osman79086b92017-02-10 13:36:16 -05001248 ImGui::End();
1249 }
1250
Brian Osmanf6877092017-02-13 09:39:57 -05001251 SkPaint zoomImagePaint;
1252 if (fShowZoomWindow && fLastImage) {
1253 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1254 static int zoomFactor = 4;
1255 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1256
Mike Reed0acd7952017-04-28 11:12:19 -04001257 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001258 zoomImagePaint.setColor(SK_ColorWHITE);
1259
1260 // Zoom by shrinking the corner UVs towards the mouse cursor
1261 ImVec2 mousePos = ImGui::GetMousePos();
1262 ImVec2 avail = ImGui::GetContentRegionAvail();
1263
1264 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1265 (avail.y * 0.5f) / zoomFactor);
1266 ImGui::Image(&zoomImagePaint, avail,
1267 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1268 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1269 }
1270
1271 ImGui::End();
1272 }
1273
Brian Osman79086b92017-02-10 13:36:16 -05001274 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1275 // (widgets, etc...) that have been issued
1276 ImGui::Render();
1277
1278 // Then we fetch the most recent data, and convert it so we can render with Skia
1279 const ImDrawData* drawData = ImGui::GetDrawData();
1280 SkTDArray<SkPoint> pos;
1281 SkTDArray<SkPoint> uv;
1282 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001283
1284 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1285 const ImDrawList* drawList = drawData->CmdLists[i];
1286
1287 // De-interleave all vertex data (sigh), convert to Skia types
1288 pos.rewind(); uv.rewind(); color.rewind();
1289 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1290 const ImDrawVert& vert = drawList->VtxBuffer[i];
1291 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1292 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1293 color.push(vert.col);
1294 }
1295 // ImGui colors are RGBA
1296 SkSwapRB(color.begin(), color.begin(), color.count());
1297
1298 int indexOffset = 0;
1299
1300 // Draw everything with canvas.drawVertices...
1301 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1302 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1303
1304 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1305 if (drawCmd->UserCallback) {
1306 drawCmd->UserCallback(drawList, drawCmd);
1307 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001308 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1309 SkASSERT(paint);
1310
Brian Osman79086b92017-02-10 13:36:16 -05001311 canvas->save();
1312 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1313 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001314 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1315 drawList->VtxBuffer.size(), pos.begin(),
1316 uv.begin(), color.begin(),
1317 drawCmd->ElemCount,
1318 drawList->IdxBuffer.begin() + indexOffset),
1319 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001320 indexOffset += drawCmd->ElemCount;
1321 canvas->restore();
1322 }
1323 }
1324 }
1325}
1326
liyuqian2edb0f42016-07-06 14:11:32 -07001327void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001328 for (int i = 0; i < fDeferredActions.count(); ++i) {
1329 fDeferredActions[i]();
1330 }
1331 fDeferredActions.reset();
1332
Brian Osman1df161a2017-02-09 12:10:20 -05001333 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001334 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001335 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1336 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1337
Brian Osman79086b92017-02-10 13:36:16 -05001338 ImGuiIO& io = ImGui::GetIO();
1339 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001340 fWindow->inval();
1341 }
jvanverth9f372462016-04-06 06:08:59 -07001342}
liyuqiane5a6cd92016-05-27 08:52:52 -07001343
1344void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001345 if (!fWindow) {
1346 return;
1347 }
1348 if (fWindow->sampleCount() < 0) {
1349 return; // Surface hasn't been created yet.
1350 }
1351
liyuqianb73c24b2016-06-03 08:47:23 -07001352 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001353 Json::Value slideState(Json::objectValue);
1354 slideState[kName] = kSlideStateName;
1355 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001356 if (fAllSlideNames.size() == 0) {
1357 for(auto slide : fSlides) {
1358 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1359 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001360 }
liyuqian1f508fd2016-06-07 06:57:40 -07001361 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001362
liyuqianb73c24b2016-06-03 08:47:23 -07001363 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001364 Json::Value backendState(Json::objectValue);
1365 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001366 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001367 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001368 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001369 backendState[kOptions].append(Json::Value(str));
1370 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001371
csmartdalton578f0642017-02-24 16:04:47 -07001372 // MSAA state
1373 Json::Value msaaState(Json::objectValue);
1374 msaaState[kName] = kMSAAStateName;
1375 msaaState[kValue] = fWindow->sampleCount();
1376 msaaState[kOptions] = Json::Value(Json::arrayValue);
1377 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1378 msaaState[kOptions].append(Json::Value(0));
1379 } else {
1380 for (int msaa : {0, 4, 8, 16}) {
1381 msaaState[kOptions].append(Json::Value(msaa));
1382 }
1383 }
1384
csmartdalton61cd31a2017-02-27 17:00:53 -07001385 // Path renderer state
1386 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1387 Json::Value prState(Json::objectValue);
1388 prState[kName] = kPathRendererStateName;
1389 prState[kValue] = gPathRendererNames[pr];
1390 prState[kOptions] = Json::Value(Json::arrayValue);
1391 const GrContext* ctx = fWindow->getGrContext();
1392 if (!ctx) {
1393 prState[kOptions].append("Software");
1394 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001395 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001396 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1397 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1398 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1399 }
1400 if (ctx->caps()->sampleShadingSupport()) {
1401 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1402 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001403 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001404 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1405 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001406 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001407 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001408 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1409 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1410 }
Jim Van Verth83010462017-03-16 08:45:39 -04001411 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001412 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001413 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1414 }
1415
Brian Salomon99a33902017-03-07 15:16:34 -05001416 // Instanced rendering state
1417 Json::Value instState(Json::objectValue);
1418 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001419 instState[kValue] = kOFF;
1420 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001421 if (ctx) {
1422 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1423 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001424 }
Brian Salomon99a33902017-03-07 15:16:34 -05001425 instState[kOptions].append(kOFF);
1426 instState[kOptions].append(kON);
1427 }
1428
liyuqianb73c24b2016-06-03 08:47:23 -07001429 // Softkey state
1430 Json::Value softkeyState(Json::objectValue);
1431 softkeyState[kName] = kSoftkeyStateName;
1432 softkeyState[kValue] = kSoftkeyHint;
1433 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1434 softkeyState[kOptions].append(kSoftkeyHint);
1435 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1436 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1437 }
1438
liyuqian1f508fd2016-06-07 06:57:40 -07001439 // FPS state
1440 Json::Value fpsState(Json::objectValue);
1441 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001442 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1443 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1444 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1445 fAnimateTimes[idx],
1446 fPaintTimes[idx],
1447 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001448 fpsState[kOptions] = Json::Value(Json::arrayValue);
1449
liyuqiane5a6cd92016-05-27 08:52:52 -07001450 Json::Value state(Json::arrayValue);
1451 state.append(slideState);
1452 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001453 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001454 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001455 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001456 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001457 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001458
1459 fWindow->setUIState(state);
1460}
1461
1462void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001463 // For those who will add more features to handle the state change in this function:
1464 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1465 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1466 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001467 if (stateName.equals(kSlideStateName)) {
1468 int previousSlide = fCurrentSlide;
1469 fCurrentSlide = 0;
1470 for(auto slide : fSlides) {
1471 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001472 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001473 break;
1474 }
1475 fCurrentSlide++;
1476 }
1477 if (fCurrentSlide >= fSlides.count()) {
1478 fCurrentSlide = previousSlide;
1479 SkDebugf("Slide not found: %s", stateValue.c_str());
1480 }
liyuqian6cb70252016-06-02 12:16:25 -07001481 } else if (stateName.equals(kBackendStateName)) {
1482 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1483 if (stateValue.equals(kBackendTypeStrings[i])) {
1484 if (fBackendType != i) {
1485 fBackendType = (sk_app::Window::BackendType)i;
1486 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001487 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001488 }
1489 break;
1490 }
1491 }
csmartdalton578f0642017-02-24 16:04:47 -07001492 } else if (stateName.equals(kMSAAStateName)) {
1493 DisplayParams params = fWindow->getRequestedDisplayParams();
1494 int sampleCount = atoi(stateValue.c_str());
1495 if (sampleCount != params.fMSAASampleCount) {
1496 params.fMSAASampleCount = sampleCount;
1497 fWindow->setRequestedDisplayParams(params);
1498 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001499 this->updateTitle();
1500 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001501 }
1502 } else if (stateName.equals(kPathRendererStateName)) {
1503 DisplayParams params = fWindow->getRequestedDisplayParams();
1504 for (const auto& pair : gPathRendererNames) {
1505 if (pair.second == stateValue.c_str()) {
1506 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1507 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1508 fWindow->setRequestedDisplayParams(params);
1509 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001510 this->updateTitle();
1511 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001512 }
1513 break;
1514 }
csmartdalton578f0642017-02-24 16:04:47 -07001515 }
Brian Salomon99a33902017-03-07 15:16:34 -05001516 } else if (stateName.equals(kInstancedRenderingStateName)) {
1517 DisplayParams params = fWindow->getRequestedDisplayParams();
1518 bool value = !strcmp(stateValue.c_str(), kON);
1519 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1520 params.fGrContextOptions.fEnableInstancedRendering = value;
1521 fWindow->setRequestedDisplayParams(params);
1522 fWindow->inval();
1523 this->updateTitle();
1524 this->updateUIState();
1525 }
liyuqianb73c24b2016-06-03 08:47:23 -07001526 } else if (stateName.equals(kSoftkeyStateName)) {
1527 if (!stateValue.equals(kSoftkeyHint)) {
1528 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001529 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001530 }
liyuqian2edb0f42016-07-06 14:11:32 -07001531 } else if (stateName.equals(kRefreshStateName)) {
1532 // This state is actually NOT in the UI state.
1533 // We use this to allow Android to quickly set bool fRefresh.
1534 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001535 } else {
1536 SkDebugf("Unknown stateName: %s", stateName.c_str());
1537 }
1538}
Brian Osman79086b92017-02-10 13:36:16 -05001539
1540bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1541 return fCommands.onKey(key, state, modifiers);
1542}
1543
1544bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001545 if (fSlides[fCurrentSlide]->onChar(c)) {
1546 fWindow->inval();
1547 return true;
1548 }
1549
Brian Osman79086b92017-02-10 13:36:16 -05001550 return fCommands.onChar(c, modifiers);
1551}