blob: 9bfdc4b60a8fb4edc324a78e2119f435248c9266 [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"
Yuqian Li399b3c22017-08-03 11:08:15 -040032#include "SkScan.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070033#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070034#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050035#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050036#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070037#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040038#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070039
Brian Osman79086b92017-02-10 13:36:16 -050040#include "imgui.h"
41
Chris Dalton1a325d22017-07-14 15:17:41 -060042#include "ccpr/GrCoverageCountingPathRenderer.h"
43
csmartdalton578f0642017-02-24 16:04:47 -070044#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070045#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070046
jvanverth34524262016-05-04 13:49:13 -070047using namespace sk_app;
48
csmartdalton61cd31a2017-02-27 17:00:53 -070049using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
50static 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
Jim Van Verth6f449692017-02-14 15:16:46 -0500143DEFINE_string(slide, "", "Start on this sample.");
144DEFINE_bool(list, false, "List samples?");
145
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
csmartdalton578f0642017-02-24 16:04:47 -0700162DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700163DEFINE_pathrenderer_flag;
164
Brian Salomon41eac792017-03-08 14:03:56 -0500165DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
Brian Osman53136aa2017-07-20 15:43:35 -0400166DECLARE_int32(threads)
Brian Salomon41eac792017-03-08 14:03:56 -0500167
Brian Salomon194db172017-08-17 14:37:06 -0400168const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700169 "OpenGL",
Brian Salomon194db172017-08-17 14:37:06 -0400170#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
171 "ANGLE",
172#endif
jvanverth063ece72016-06-17 09:29:14 -0700173#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700174 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700175#endif
csmartdalton578f0642017-02-24 16:04:47 -0700176 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700177};
178
bsalomon6c471f72016-07-26 12:56:32 -0700179static sk_app::Window::BackendType get_backend_type(const char* str) {
180#ifdef SK_VULKAN
181 if (0 == strcmp(str, "vk")) {
182 return sk_app::Window::kVulkan_BackendType;
183 } else
184#endif
Brian Salomon194db172017-08-17 14:37:06 -0400185#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
186 if (0 == strcmp(str, "angle")) {
187 return sk_app::Window::kANGLE_BackendType;
188 } else
189#endif
bsalomon6c471f72016-07-26 12:56:32 -0700190 if (0 == strcmp(str, "gl")) {
191 return sk_app::Window::kNativeGL_BackendType;
192 } else if (0 == strcmp(str, "sw")) {
193 return sk_app::Window::kRaster_BackendType;
194 } else {
195 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
196 return sk_app::Window::kRaster_BackendType;
197 }
198}
199
Brian Osmana109e392017-02-24 09:49:14 -0500200static SkColorSpacePrimaries gSrgbPrimaries = {
201 0.64f, 0.33f,
202 0.30f, 0.60f,
203 0.15f, 0.06f,
204 0.3127f, 0.3290f };
205
206static SkColorSpacePrimaries gAdobePrimaries = {
207 0.64f, 0.33f,
208 0.21f, 0.71f,
209 0.15f, 0.06f,
210 0.3127f, 0.3290f };
211
212static SkColorSpacePrimaries gP3Primaries = {
213 0.680f, 0.320f,
214 0.265f, 0.690f,
215 0.150f, 0.060f,
216 0.3127f, 0.3290f };
217
218static SkColorSpacePrimaries gRec2020Primaries = {
219 0.708f, 0.292f,
220 0.170f, 0.797f,
221 0.131f, 0.046f,
222 0.3127f, 0.3290f };
223
224struct NamedPrimaries {
225 const char* fName;
226 SkColorSpacePrimaries* fPrimaries;
227} gNamedPrimaries[] = {
228 { "sRGB", &gSrgbPrimaries },
229 { "AdobeRGB", &gAdobePrimaries },
230 { "P3", &gP3Primaries },
231 { "Rec. 2020", &gRec2020Primaries },
232};
233
234static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
235 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
236}
237
liyuqiane5a6cd92016-05-27 08:52:52 -0700238const char* kName = "name";
239const char* kValue = "value";
240const char* kOptions = "options";
241const char* kSlideStateName = "Slide";
242const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700243const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700244const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500245const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700246const char* kSoftkeyStateName = "Softkey";
247const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700248const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700249const char* kON = "ON";
250const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700251const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700252
jvanverth34524262016-05-04 13:49:13 -0700253Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700254 : fCurrentMeasurement(0)
255 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700256 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500257 , fShowImGuiDebugWindow(false)
258 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500259 , fShowZoomWindow(false)
260 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700261 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500262 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500263 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700264 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400265 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700266{
Greg Daniel285db442016-10-14 09:12:53 -0400267 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700268
269 static SkOnce initPathRendererNames;
270 initPathRendererNames([]() {
Brian Osman8b0f2652017-08-29 15:18:34 -0400271 gPathRendererNames[GpuPathRenderers::kAll] = "All Path Renderers";
272 gPathRendererNames[GpuPathRenderers::kDefault] =
273 "Default Ganesh Behavior (best path renderer, not including CCPR)";
csmartdalton61cd31a2017-02-27 17:00:53 -0700274 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
275 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400276 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600277 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500278 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700279 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
280 });
281
Brian Osman1df161a2017-02-09 12:10:20 -0500282 memset(fPaintTimes, 0, sizeof(fPaintTimes));
283 memset(fFlushTimes, 0, sizeof(fFlushTimes));
284 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700285
jvanverth2bb3b6d2016-04-08 07:24:09 -0700286 SkDebugf("Command line arguments: ");
287 for (int i = 1; i < argc; ++i) {
288 SkDebugf("%s ", argv[i]);
289 }
290 SkDebugf("\n");
291
292 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500293#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400294 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500295#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700296
Brian Osmanbc8150f2017-07-24 11:38:01 -0400297 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400298 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400299
bsalomon6c471f72016-07-26 12:56:32 -0700300 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700301 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700302
csmartdalton578f0642017-02-24 16:04:47 -0700303 DisplayParams displayParams;
304 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500305 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700306 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700307 fWindow->setRequestedDisplayParams(displayParams);
308
jvanverth9f372462016-04-06 06:08:59 -0700309 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700310 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700311 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700312 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700313 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700314 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500315 fWindow->registerMouseFunc(on_mouse_handler, this);
316 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
317 fWindow->registerKeyFunc(on_key_handler, this);
318 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700319
brianosman622c8d52016-05-10 06:50:49 -0700320 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500321 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
322 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
323 fWindow->inval();
324 });
325 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
326 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
327 fWindow->inval();
328 });
Brian Osmanf6877092017-02-13 09:39:57 -0500329 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
330 this->fShowZoomWindow = !this->fShowZoomWindow;
331 fWindow->inval();
332 });
brianosman622c8d52016-05-10 06:50:49 -0700333 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
334 this->fDisplayStats = !this->fDisplayStats;
335 fWindow->inval();
336 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500337 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500338 switch (fColorMode) {
339 case ColorMode::kLegacy:
340 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
341 break;
342 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
343 this->setColorMode(ColorMode::kColorManagedSRGB8888);
344 break;
345 case ColorMode::kColorManagedSRGB8888:
346 this->setColorMode(ColorMode::kColorManagedLinearF16);
347 break;
348 case ColorMode::kColorManagedLinearF16:
349 this->setColorMode(ColorMode::kLegacy);
350 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500351 }
brianosman622c8d52016-05-10 06:50:49 -0700352 });
353 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
354 int previousSlide = fCurrentSlide;
355 fCurrentSlide++;
356 if (fCurrentSlide >= fSlides.count()) {
357 fCurrentSlide = 0;
358 }
359 this->setupCurrentSlide(previousSlide);
360 });
361 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
362 int previousSlide = fCurrentSlide;
363 fCurrentSlide--;
364 if (fCurrentSlide < 0) {
365 fCurrentSlide = fSlides.count() - 1;
366 }
367 this->setupCurrentSlide(previousSlide);
368 });
369 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
370 this->changeZoomLevel(1.f / 32.f);
371 fWindow->inval();
372 });
373 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
374 this->changeZoomLevel(-1.f / 32.f);
375 fWindow->inval();
376 });
jvanverthaf236b52016-05-20 06:01:06 -0700377 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Salomon194db172017-08-17 14:37:06 -0400378 sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
379 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
Jim Van Verthd63c1022017-01-05 13:50:49 -0500380 // Switching to and from Vulkan is problematic on Linux so disabled for now
Brian Salomon194db172017-08-17 14:37:06 -0400381#if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
382 if (newBackend == sk_app::Window::kVulkan_BackendType) {
383 newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
384 sk_app::Window::kBackendTypeCount);
385 } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
386 newBackend = sk_app::Window::kVulkan_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500387 }
388#endif
Brian Osman621491e2017-02-28 15:45:01 -0500389 this->setBackend(newBackend);
jvanverthaf236b52016-05-20 06:01:06 -0700390 });
brianosman622c8d52016-05-10 06:50:49 -0700391
Yuqian Li399b3c22017-08-03 11:08:15 -0400392 fCommands.addCommand('A', "AAA", "Toggle analytic AA", [this]() {
393 if (!gSkUseAnalyticAA) {
394 gSkUseAnalyticAA = true;
395 } else if (!gSkForceAnalyticAA) {
396 gSkForceAnalyticAA = true;
397 } else {
398 gSkUseAnalyticAA = gSkForceAnalyticAA = false;
399 }
400 this->updateTitle();
401 fWindow->inval();
402 });
403 fCommands.addCommand('D', "DAA", "Toggle delta AA", [this]() {
404 if (!gSkUseDeltaAA) {
405 gSkUseDeltaAA = true;
406 } else if (!gSkForceDeltaAA) {
407 gSkForceDeltaAA = true;
408 } else {
409 gSkUseDeltaAA = gSkForceDeltaAA = false;
410 }
411 this->updateTitle();
412 fWindow->inval();
413 });
414
jvanverth2bb3b6d2016-04-08 07:24:09 -0700415 // set up slides
416 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500417 this->setStartupSlide();
418 if (FLAGS_list) {
419 this->listNames();
420 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700421
djsollen12d62a72016-04-21 07:59:44 -0700422 fAnimTimer.run();
423
Brian Osman79086b92017-02-10 13:36:16 -0500424 // ImGui initialization:
425 ImGuiIO& io = ImGui::GetIO();
426 io.DisplaySize.x = static_cast<float>(fWindow->width());
427 io.DisplaySize.y = static_cast<float>(fWindow->height());
428
429 // Keymap...
430 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
431 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
432 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
433 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
434 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
435 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
436 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
437 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
438 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
439 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
440 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
441 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
442 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
443 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
444 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
445 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
446 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
447 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
448 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
449
450 int w, h;
451 unsigned char* pixels;
452 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
453 SkImageInfo info = SkImageInfo::MakeA8(w, h);
454 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500455 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
456 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400457 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500458 fImGuiFontPaint.setShader(fontShader);
459 fImGuiFontPaint.setColor(SK_ColorWHITE);
460 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
461 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500462
Brian Osmana109e392017-02-24 09:49:14 -0500463 auto gamutImage = GetResourceAsImage("gamut.png");
464 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400465 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500466 }
467 fImGuiGamutPaint.setColor(SK_ColorWHITE);
468 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
469
csmartdalton578f0642017-02-24 16:04:47 -0700470 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700471}
472
jvanverth34524262016-05-04 13:49:13 -0700473void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700474 fAllSlideNames = Json::Value(Json::arrayValue);
475
jvanverth2bb3b6d2016-04-08 07:24:09 -0700476 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
477 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400478 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700479
480 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
481 sk_sp<Slide> slide(new GMSlide(gm.release()));
482 fSlides.push_back(slide);
483 }
484
485 gms = gms->next();
486 }
487
488 // reverse array
489 for (int i = 0; i < fSlides.count()/2; ++i) {
490 sk_sp<Slide> temp = fSlides[i];
491 fSlides[i] = fSlides[fSlides.count() - i - 1];
492 fSlides[fSlides.count() - i - 1] = temp;
493 }
494
jvanverthc7027ab2016-06-16 09:52:35 -0700495 // samples
496 const SkViewRegister* reg = SkViewRegister::Head();
497 while (reg) {
498 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700499 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
500 fSlides.push_back(slide);
501 }
jvanverthc7027ab2016-06-16 09:52:35 -0700502 reg = reg->next();
503 }
504
jvanverth2bb3b6d2016-04-08 07:24:09 -0700505 // SKPs
506 for (int i = 0; i < FLAGS_skps.count(); i++) {
507 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700508 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
509 continue;
510 }
511
jvanverth2bb3b6d2016-04-08 07:24:09 -0700512 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700513 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700514 if (slide) {
515 fSlides.push_back(slide);
516 }
517 } else {
518 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700519 SkString skpName;
520 while (it.next(&skpName)) {
521 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
522 continue;
523 }
524
525 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
526 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700527 if (slide) {
528 fSlides.push_back(slide);
529 }
530 }
531 }
532 }
liyuqian6f163d22016-06-13 12:26:45 -0700533
534 // JPGs
535 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
536 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
537 SkString jpgName;
538 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700539 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
540 continue;
541 }
542
liyuqian6f163d22016-06-13 12:26:45 -0700543 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
544 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
545 if (slide) {
546 fSlides.push_back(slide);
547 }
548 }
549 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700550}
551
552
jvanverth34524262016-05-04 13:49:13 -0700553Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700554 fWindow->detach();
555 delete fWindow;
556}
557
brianosman05de2162016-05-06 13:28:57 -0700558void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700559 if (!fWindow) {
560 return;
561 }
562 if (fWindow->sampleCount() < 0) {
563 return; // Surface hasn't been created yet.
564 }
565
jvanverth34524262016-05-04 13:49:13 -0700566 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700567 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700568
Yuqian Li399b3c22017-08-03 11:08:15 -0400569 if (gSkUseDeltaAA) {
570 if (gSkForceDeltaAA) {
571 title.append(" <FDAA>");
572 } else {
573 title.append(" <DAA>");
574 }
575 } else if (gSkUseAnalyticAA) {
576 if (gSkForceAnalyticAA) {
577 title.append(" <FAAA>");
578 } else {
579 title.append(" <AAA>");
580 }
581 }
582
Brian Osman92004802017-03-06 11:47:26 -0500583 switch (fColorMode) {
584 case ColorMode::kLegacy:
585 title.append(" Legacy 8888");
586 break;
587 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
588 title.append(" ColorManaged 8888 (Nonlinear blending)");
589 break;
590 case ColorMode::kColorManagedSRGB8888:
591 title.append(" ColorManaged 8888");
592 break;
593 case ColorMode::kColorManagedLinearF16:
594 title.append(" ColorManaged F16");
595 break;
596 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500597
Brian Osman92004802017-03-06 11:47:26 -0500598 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500599 int curPrimaries = -1;
600 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
601 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
602 curPrimaries = i;
603 break;
604 }
605 }
606 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700607 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500608
csmartdalton578f0642017-02-24 16:04:47 -0700609 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700610 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700611 if (int msaa = fWindow->sampleCount()) {
612 title.appendf(" MSAA: %i", msaa);
613 }
614 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700615
616 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
Brian Osman8b0f2652017-08-29 15:18:34 -0400617 if (GpuPathRenderers::kDefault != pr) {
csmartdalton61cd31a2017-02-27 17:00:53 -0700618 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
619 }
620
brianosman05de2162016-05-06 13:28:57 -0700621 fWindow->setTitle(title.c_str());
622}
623
Jim Van Verth6f449692017-02-14 15:16:46 -0500624void Viewer::setStartupSlide() {
625
626 if (!FLAGS_slide.isEmpty()) {
627 int count = fSlides.count();
628 for (int i = 0; i < count; i++) {
629 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
630 fCurrentSlide = i;
631 return;
632 }
633 }
634
635 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
636 this->listNames();
637 }
638
639 fCurrentSlide = 0;
640}
641
642void Viewer::listNames() {
643 int count = fSlides.count();
644 SkDebugf("All Slides:\n");
645 for (int i = 0; i < count; i++) {
646 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
647 }
648}
649
brianosman05de2162016-05-06 13:28:57 -0700650void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700651 if (fCurrentSlide == previousSlide) {
652 return; // no change; do nothing
653 }
liyuqian6f163d22016-06-13 12:26:45 -0700654 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700655 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700656
liyuqiane46e4f02016-05-20 07:32:19 -0700657 fGesture.reset();
658 fDefaultMatrix.reset();
liyuqiane46e4f02016-05-20 07:32:19 -0700659
Brian Osman42bb6ac2017-06-05 08:46:04 -0400660 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
661 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
662 const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
663
664 // Start with a matrix that scales the slide to the available screen space
665 if (fWindow->scaleContentToFit()) {
666 if (windowRect.width() > 0 && windowRect.height() > 0) {
667 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
liyuqiane46e4f02016-05-20 07:32:19 -0700668 }
669 }
670
Brian Osman42bb6ac2017-06-05 08:46:04 -0400671 // Prevent the user from dragging content so far outside the window they can't find it again
672 fGesture.setTransLimit(slideBounds, windowRect, fDefaultMatrix);
liyuqiane46e4f02016-05-20 07:32:19 -0700673
brianosman05de2162016-05-06 13:28:57 -0700674 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700675 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700676 if (previousSlide >= 0) {
677 fSlides[previousSlide]->unload();
678 }
jvanverthc265a922016-04-08 12:51:45 -0700679 fWindow->inval();
680}
681
682#define MAX_ZOOM_LEVEL 8
683#define MIN_ZOOM_LEVEL -8
684
jvanverth34524262016-05-04 13:49:13 -0700685void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700686 fZoomLevel += delta;
Brian Osman42bb6ac2017-06-05 08:46:04 -0400687 fZoomLevel = SkScalarPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
jvanverthc265a922016-04-08 12:51:45 -0700688}
689
liyuqiand3cdbca2016-05-17 12:44:20 -0700690SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700691 SkMatrix m;
jvanverthc265a922016-04-08 12:51:45 -0700692
Brian Osman42bb6ac2017-06-05 08:46:04 -0400693 SkScalar zoomScale = (fZoomLevel < 0) ? SK_Scalar1 / (SK_Scalar1 - fZoomLevel)
694 : SK_Scalar1 + fZoomLevel;
695 m = fGesture.localM();
liyuqiand3cdbca2016-05-17 12:44:20 -0700696 m.preConcat(fGesture.globalM());
Brian Osman42bb6ac2017-06-05 08:46:04 -0400697 m.preConcat(fDefaultMatrix);
698 m.preScale(zoomScale, zoomScale);
jvanverthc265a922016-04-08 12:51:45 -0700699
liyuqiand3cdbca2016-05-17 12:44:20 -0700700 return m;
jvanverthc265a922016-04-08 12:51:45 -0700701}
702
Brian Osman621491e2017-02-28 15:45:01 -0500703void Viewer::setBackend(sk_app::Window::BackendType backendType) {
704 fBackendType = backendType;
705
706 fWindow->detach();
707
708#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
Brian Salomon194db172017-08-17 14:37:06 -0400709 // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
710 // on Windows, so we just delete the window and recreate it.
Brian Osman80a82df2017-07-12 15:42:51 -0400711 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
Brian Salomon194db172017-08-17 14:37:06 -0400712 sk_app::Window::kNativeGL_BackendType == fBackendType
713#if SK_ANGLE
714 || sk_app::Window::kANGLE_BackendType == fBackendType
715#endif
716 ) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400717 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500718 delete fWindow;
719 fWindow = Window::CreateNativeWindow(nullptr);
720
721 // re-register callbacks
722 fCommands.attach(fWindow);
723 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
724 fWindow->registerPaintFunc(on_paint_handler, this);
725 fWindow->registerTouchFunc(on_touch_handler, this);
726 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
727 fWindow->registerMouseFunc(on_mouse_handler, this);
728 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
729 fWindow->registerKeyFunc(on_key_handler, this);
730 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400731 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
732 // will still include our correct sample count. But the re-created fWindow will lose that
733 // information. On Windows, we need to re-create the window when changing sample count,
734 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
735 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
736 // as if we had never changed windows at all).
737 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500738 }
739#endif
740
741 fWindow->attach(fBackendType);
742}
743
Brian Osman92004802017-03-06 11:47:26 -0500744void Viewer::setColorMode(ColorMode colorMode) {
745 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700746
Brian Osmanf750fbc2017-02-08 10:47:28 -0500747 // 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 -0400748 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700749 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500750 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400751 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
752 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500753 if (wasInLegacy != wantLegacy) {
754 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700755 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500756 }
757
758 this->updateTitle();
759 fWindow->inval();
760}
761
762void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500763 SkAutoCanvasRestore autorestore(canvas, false);
764
Brian Osmanf750fbc2017-02-08 10:47:28 -0500765 // By default, we render directly into the window's surface/canvas
766 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500767 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700768
Brian Osmane0d4fba2017-03-15 10:24:55 -0400769 // If we're in any of the color managed modes, construct the color space we're going to use
770 sk_sp<SkColorSpace> cs = nullptr;
771 if (ColorMode::kLegacy != fColorMode) {
772 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
773 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400774 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400775 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
776 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
777 }
778
779 // 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 -0500780 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500781 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500782 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500783 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400784 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
785 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
786
Brian Osman92004802017-03-06 11:47:26 -0500787 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
788 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400789 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
790 // with a special canvas (below) that has the color space attached
791 sk_sp<SkColorSpace> offscreenColorSpace =
792 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500793 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400794 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500795 offscreenSurface = canvas->makeSurface(info);
796 slideCanvas = offscreenSurface->getCanvas();
797 }
798
Brian Osmane0d4fba2017-03-15 10:24:55 -0400799 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
800 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
801 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
802 slideCanvas = xformCanvas.get();
803 }
804
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500805 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500806 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500807 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500808 // Time the painting logic of the slide
809 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500810 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500811 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500812 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500813
814 // Force a flush so we can time that, too
815 startTime = SkTime::GetMSecs();
816 slideCanvas->flush();
817 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500818
819 // If we rendered offscreen, snap an image and push the results to the window's canvas
820 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500821 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500822
823 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400824 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500825 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400826 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500827 SkPaint paint;
828 paint.setBlendMode(SkBlendMode::kSrc);
829 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700830 }
liyuqian6f163d22016-06-13 12:26:45 -0700831}
832
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700833void Viewer::onBackendCreated() {
834 this->updateTitle();
835 this->updateUIState();
836 this->setupCurrentSlide(-1);
837 fWindow->show();
838 fWindow->inval();
839}
Jim Van Verth6f449692017-02-14 15:16:46 -0500840
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700841void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500842 // Update ImGui input
843 ImGuiIO& io = ImGui::GetIO();
844 io.DeltaTime = 1.0f / 60.0f;
845 io.DisplaySize.x = static_cast<float>(fWindow->width());
846 io.DisplaySize.y = static_cast<float>(fWindow->height());
847
848 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
849 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
850 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
851
852 ImGui::NewFrame();
853
Brian Osmanf750fbc2017-02-08 10:47:28 -0500854 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700855
Brian Osman1df161a2017-02-09 12:10:20 -0500856 // Advance our timing bookkeeping
857 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
858 SkASSERT(fCurrentMeasurement < kMeasurementCount);
859
860 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700861 if (fDisplayStats) {
862 drawStats(canvas);
863 }
brianosman622c8d52016-05-10 06:50:49 -0700864 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700865
Brian Osman79086b92017-02-10 13:36:16 -0500866 drawImGui(canvas);
867
Brian Osman1df161a2017-02-09 12:10:20 -0500868 // Update the FPS
869 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700870}
871
jvanverth814e38d2016-06-06 08:48:47 -0700872bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400873 if (GestureDevice::kMouse == fGestureDevice) {
874 return false;
875 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700876 void* castedOwner = reinterpret_cast<void*>(owner);
877 switch (state) {
878 case Window::kUp_InputState: {
879 fGesture.touchEnd(castedOwner);
880 break;
881 }
882 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400883 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700884 break;
885 }
886 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400887 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700888 break;
889 }
890 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400891 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700892 fWindow->inval();
893 return true;
894}
895
Jim Van Verthe7705782017-05-04 14:00:59 -0400896bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400897 if (GestureDevice::kTouch == fGestureDevice) {
898 return false;
899 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400900 switch (state) {
901 case Window::kUp_InputState: {
902 fGesture.touchEnd(nullptr);
903 break;
904 }
905 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400906 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400907 break;
908 }
909 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400910 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400911 break;
912 }
913 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400914 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400915 fWindow->inval();
916 return true;
917}
918
jvanverth34524262016-05-04 13:49:13 -0700919void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700920 static const float kPixelPerMS = 2.0f;
921 static const int kDisplayWidth = 130;
922 static const int kDisplayHeight = 100;
923 static const int kDisplayPadding = 10;
924 static const int kGraphPadding = 3;
925 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
926
Mike Reed3661bc92017-02-22 13:21:42 -0500927 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700928 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
929 SkIntToScalar(kDisplayPadding),
930 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
931 SkPaint paint;
932 canvas->save();
933
934 canvas->clipRect(rect);
935 paint.setColor(SK_ColorBLACK);
936 canvas->drawRect(rect, paint);
937 // draw the 16ms line
938 paint.setColor(SK_ColorLTGRAY);
939 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
940 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
941 paint.setColor(SK_ColorRED);
942 paint.setStyle(SkPaint::kStroke_Style);
943 canvas->drawRect(rect, paint);
944
945 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
946 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700947 int i = fCurrentMeasurement;
948 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500949 // Round to nearest values
950 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
951 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
952 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
953 int startY = SkScalarTruncToInt(rect.fBottom);
954 int endY = startY - flushHeight;
955 paint.setColor(SK_ColorRED);
956 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
957 SkIntToScalar(x), SkIntToScalar(endY), paint);
958 startY = endY;
959 endY = startY - paintHeight;
960 paint.setColor(SK_ColorGREEN);
961 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
962 SkIntToScalar(x), SkIntToScalar(endY), paint);
963 startY = endY;
964 endY = startY - animateHeight;
965 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700966 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
967 SkIntToScalar(x), SkIntToScalar(endY), paint);
968 i++;
969 i &= (kMeasurementCount - 1); // fast mod
970 x += xStep;
971 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700972
973 canvas->restore();
974}
975
Brian Osmana109e392017-02-24 09:49:14 -0500976static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
977 const ImVec2& pos, const ImVec2& size) {
978 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
979 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
980
981 // Invisible 10x10 button
982 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
983 ImGui::InvisibleButton(label, ImVec2(10, 10));
984
985 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
986 ImGuiIO& io = ImGui::GetIO();
987 // Normalized mouse position, relative to our gamut box
988 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
989 // Clamp to edge of box, convert back to primary scale
990 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
991 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
992 }
993
994 if (ImGui::IsItemHovered()) {
995 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
996 }
997
998 // Return screen coordinates for the caller. We could just return center here, but we'd have
999 // one frame of lag during drag.
1000 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
1001}
1002
1003static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1004 ImDrawList* drawList = ImGui::GetWindowDrawList();
1005
1006 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1007 // width, and scale the height to maintain aspect ratio.
1008 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1009 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1010 ImVec2 pos = ImGui::GetCursorScreenPos();
1011
1012 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1013 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1014 // Magic numbers are pixel locations of the origin and upper-right corner.
1015 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1016 ImVec2(242, 61), ImVec2(1897, 1922));
1017 ImVec2 endPos = ImGui::GetCursorPos();
1018
1019 // Primary markers
1020 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1021 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1022 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1023 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1024
1025 // Gamut triangle
1026 drawList->AddCircle(r, 5.0f, 0xFF000040);
1027 drawList->AddCircle(g, 5.0f, 0xFF004000);
1028 drawList->AddCircle(b, 5.0f, 0xFF400000);
1029 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1030 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1031
1032 // Re-position cursor immediate after the diagram for subsequent controls
1033 ImGui::SetCursorPos(endPos);
1034}
1035
Brian Osman79086b92017-02-10 13:36:16 -05001036void Viewer::drawImGui(SkCanvas* canvas) {
1037 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1038 if (fShowImGuiTestWindow) {
1039 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1040 }
1041
1042 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001043 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1044 // always visible, we can end up in a layout feedback loop.
1045 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001046 DisplayParams params = fWindow->getRequestedDisplayParams();
1047 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001048 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1049 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001050 if (ImGui::CollapsingHeader("Backend")) {
1051 int newBackend = static_cast<int>(fBackendType);
1052 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1053 ImGui::SameLine();
1054 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
Brian Salomon194db172017-08-17 14:37:06 -04001055#if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1056 ImGui::SameLine();
1057 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1058#endif
Brian Osman621491e2017-02-28 15:45:01 -05001059#if defined(SK_VULKAN)
1060 ImGui::SameLine();
1061 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1062#endif
1063 if (newBackend != fBackendType) {
1064 fDeferredActions.push_back([=]() {
1065 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1066 });
1067 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001068
Brian Salomon99a33902017-03-07 15:16:34 -05001069 const GrContext* ctx = fWindow->getGrContext();
1070 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1071 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1072 paramsChanged = true;
1073 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001074 bool* wire = &params.fGrContextOptions.fWireframeMode;
1075 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1076 paramsChanged = true;
1077 }
Brian Salomon99a33902017-03-07 15:16:34 -05001078
Brian Osman28b12522017-03-08 17:10:24 -05001079 if (ctx) {
1080 int sampleCount = fWindow->sampleCount();
1081 ImGui::Text("MSAA: "); ImGui::SameLine();
1082 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1083 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1084 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1085 ImGui::RadioButton("16", &sampleCount, 16);
1086
1087 if (sampleCount != params.fMSAASampleCount) {
1088 params.fMSAASampleCount = sampleCount;
1089 paramsChanged = true;
1090 }
1091 }
1092
Brian Osman8a9de3d2017-03-01 14:59:05 -05001093 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001094 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001095 auto prButton = [&](GpuPathRenderers x) {
1096 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001097 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1098 params.fGrContextOptions.fGpuPathRenderers = x;
1099 paramsChanged = true;
1100 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001101 }
1102 };
1103
1104 if (!ctx) {
1105 ImGui::RadioButton("Software", true);
1106 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001107 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001108 prButton(GpuPathRenderers::kAll);
1109 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1110 prButton(GpuPathRenderers::kStencilAndCover);
1111 }
1112 if (ctx->caps()->sampleShadingSupport()) {
1113 prButton(GpuPathRenderers::kMSAA);
1114 }
1115 prButton(GpuPathRenderers::kTessellating);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001116 prButton(GpuPathRenderers::kNone);
1117 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001118 prButton(GpuPathRenderers::kDefault);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001119 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001120 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1121 prButton(GpuPathRenderers::kCoverageCounting);
1122 }
Jim Van Verth83010462017-03-16 08:45:39 -04001123 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001124 prButton(GpuPathRenderers::kTessellating);
1125 prButton(GpuPathRenderers::kNone);
1126 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001127 ImGui::TreePop();
1128 }
Brian Osman621491e2017-02-28 15:45:01 -05001129 }
1130
Brian Osman79086b92017-02-10 13:36:16 -05001131 if (ImGui::CollapsingHeader("Slide")) {
1132 static ImGuiTextFilter filter;
1133 filter.Draw();
1134 int previousSlide = fCurrentSlide;
1135 fCurrentSlide = 0;
1136 for (auto slide : fSlides) {
1137 if (filter.PassFilter(slide->getName().c_str())) {
1138 ImGui::BulletText("%s", slide->getName().c_str());
1139 if (ImGui::IsItemClicked()) {
1140 setupCurrentSlide(previousSlide);
1141 break;
1142 }
1143 }
1144 ++fCurrentSlide;
1145 }
1146 if (fCurrentSlide >= fSlides.count()) {
1147 fCurrentSlide = previousSlide;
1148 }
1149 }
Brian Osmana109e392017-02-24 09:49:14 -05001150
1151 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001152 ColorMode newMode = fColorMode;
1153 auto cmButton = [&](ColorMode mode, const char* label) {
1154 if (ImGui::RadioButton(label, mode == fColorMode)) {
1155 newMode = mode;
1156 }
1157 };
1158
1159 cmButton(ColorMode::kLegacy, "Legacy 8888");
1160 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1161 "Color Managed 8888 (Nonlinear blending)");
1162 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1163 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1164
1165 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001166 // It isn't safe to switch color mode now (in the middle of painting). We might
1167 // tear down the back-end, etc... Defer this change until the next onIdle.
1168 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001169 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001170 });
Brian Osmana109e392017-02-24 09:49:14 -05001171 }
1172
1173 // Pick from common gamuts:
1174 int primariesIdx = 4; // Default: Custom
1175 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1176 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1177 primariesIdx = i;
1178 break;
1179 }
1180 }
1181
1182 if (ImGui::Combo("Primaries", &primariesIdx,
1183 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1184 if (primariesIdx >= 0 && primariesIdx <= 3) {
1185 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1186 }
1187 }
1188
1189 // Allow direct editing of gamut
1190 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1191 }
Brian Osman79086b92017-02-10 13:36:16 -05001192 }
Brian Salomon99a33902017-03-07 15:16:34 -05001193 if (paramsChanged) {
1194 fDeferredActions.push_back([=]() {
1195 fWindow->setRequestedDisplayParams(params);
1196 fWindow->inval();
1197 this->updateTitle();
1198 });
1199 }
Brian Osman79086b92017-02-10 13:36:16 -05001200 ImGui::End();
1201 }
1202
Brian Osmanf6877092017-02-13 09:39:57 -05001203 SkPaint zoomImagePaint;
1204 if (fShowZoomWindow && fLastImage) {
1205 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1206 static int zoomFactor = 4;
1207 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1208
Mike Reed0acd7952017-04-28 11:12:19 -04001209 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001210 zoomImagePaint.setColor(SK_ColorWHITE);
1211
1212 // Zoom by shrinking the corner UVs towards the mouse cursor
1213 ImVec2 mousePos = ImGui::GetMousePos();
1214 ImVec2 avail = ImGui::GetContentRegionAvail();
1215
1216 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1217 (avail.y * 0.5f) / zoomFactor);
1218 ImGui::Image(&zoomImagePaint, avail,
1219 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1220 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1221 }
1222
1223 ImGui::End();
1224 }
1225
Brian Osman79086b92017-02-10 13:36:16 -05001226 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1227 // (widgets, etc...) that have been issued
1228 ImGui::Render();
1229
1230 // Then we fetch the most recent data, and convert it so we can render with Skia
1231 const ImDrawData* drawData = ImGui::GetDrawData();
1232 SkTDArray<SkPoint> pos;
1233 SkTDArray<SkPoint> uv;
1234 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001235
1236 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1237 const ImDrawList* drawList = drawData->CmdLists[i];
1238
1239 // De-interleave all vertex data (sigh), convert to Skia types
1240 pos.rewind(); uv.rewind(); color.rewind();
1241 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1242 const ImDrawVert& vert = drawList->VtxBuffer[i];
1243 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1244 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1245 color.push(vert.col);
1246 }
1247 // ImGui colors are RGBA
1248 SkSwapRB(color.begin(), color.begin(), color.count());
1249
1250 int indexOffset = 0;
1251
1252 // Draw everything with canvas.drawVertices...
1253 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1254 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1255
1256 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1257 if (drawCmd->UserCallback) {
1258 drawCmd->UserCallback(drawList, drawCmd);
1259 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001260 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1261 SkASSERT(paint);
1262
Brian Osman79086b92017-02-10 13:36:16 -05001263 canvas->save();
1264 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1265 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001266 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1267 drawList->VtxBuffer.size(), pos.begin(),
1268 uv.begin(), color.begin(),
1269 drawCmd->ElemCount,
1270 drawList->IdxBuffer.begin() + indexOffset),
1271 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001272 indexOffset += drawCmd->ElemCount;
1273 canvas->restore();
1274 }
1275 }
1276 }
1277}
1278
liyuqian2edb0f42016-07-06 14:11:32 -07001279void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001280 for (int i = 0; i < fDeferredActions.count(); ++i) {
1281 fDeferredActions[i]();
1282 }
1283 fDeferredActions.reset();
1284
Brian Osman1df161a2017-02-09 12:10:20 -05001285 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001286 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001287 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1288 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1289
Brian Osman79086b92017-02-10 13:36:16 -05001290 ImGuiIO& io = ImGui::GetIO();
1291 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001292 fWindow->inval();
1293 }
jvanverth9f372462016-04-06 06:08:59 -07001294}
liyuqiane5a6cd92016-05-27 08:52:52 -07001295
1296void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001297 if (!fWindow) {
1298 return;
1299 }
1300 if (fWindow->sampleCount() < 0) {
1301 return; // Surface hasn't been created yet.
1302 }
1303
liyuqianb73c24b2016-06-03 08:47:23 -07001304 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001305 Json::Value slideState(Json::objectValue);
1306 slideState[kName] = kSlideStateName;
1307 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001308 if (fAllSlideNames.size() == 0) {
1309 for(auto slide : fSlides) {
1310 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1311 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001312 }
liyuqian1f508fd2016-06-07 06:57:40 -07001313 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001314
liyuqianb73c24b2016-06-03 08:47:23 -07001315 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001316 Json::Value backendState(Json::objectValue);
1317 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001318 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001319 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001320 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001321 backendState[kOptions].append(Json::Value(str));
1322 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001323
csmartdalton578f0642017-02-24 16:04:47 -07001324 // MSAA state
1325 Json::Value msaaState(Json::objectValue);
1326 msaaState[kName] = kMSAAStateName;
1327 msaaState[kValue] = fWindow->sampleCount();
1328 msaaState[kOptions] = Json::Value(Json::arrayValue);
1329 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1330 msaaState[kOptions].append(Json::Value(0));
1331 } else {
1332 for (int msaa : {0, 4, 8, 16}) {
1333 msaaState[kOptions].append(Json::Value(msaa));
1334 }
1335 }
1336
csmartdalton61cd31a2017-02-27 17:00:53 -07001337 // Path renderer state
1338 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1339 Json::Value prState(Json::objectValue);
1340 prState[kName] = kPathRendererStateName;
1341 prState[kValue] = gPathRendererNames[pr];
1342 prState[kOptions] = Json::Value(Json::arrayValue);
1343 const GrContext* ctx = fWindow->getGrContext();
1344 if (!ctx) {
1345 prState[kOptions].append("Software");
1346 } else if (fWindow->sampleCount()) {
Brian Osman8b0f2652017-08-29 15:18:34 -04001347 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001348 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1349 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1350 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1351 }
1352 if (ctx->caps()->sampleShadingSupport()) {
1353 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1354 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001355 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001356 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1357 } else {
Brian Osman8b0f2652017-08-29 15:18:34 -04001358 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001359 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001360 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1361 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1362 }
Jim Van Verth83010462017-03-16 08:45:39 -04001363 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001364 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001365 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1366 }
1367
Brian Salomon99a33902017-03-07 15:16:34 -05001368 // Instanced rendering state
1369 Json::Value instState(Json::objectValue);
1370 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001371 instState[kValue] = kOFF;
1372 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001373 if (ctx) {
1374 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1375 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001376 }
Brian Salomon99a33902017-03-07 15:16:34 -05001377 instState[kOptions].append(kOFF);
1378 instState[kOptions].append(kON);
1379 }
1380
liyuqianb73c24b2016-06-03 08:47:23 -07001381 // Softkey state
1382 Json::Value softkeyState(Json::objectValue);
1383 softkeyState[kName] = kSoftkeyStateName;
1384 softkeyState[kValue] = kSoftkeyHint;
1385 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1386 softkeyState[kOptions].append(kSoftkeyHint);
1387 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1388 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1389 }
1390
liyuqian1f508fd2016-06-07 06:57:40 -07001391 // FPS state
1392 Json::Value fpsState(Json::objectValue);
1393 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001394 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1395 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1396 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1397 fAnimateTimes[idx],
1398 fPaintTimes[idx],
1399 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001400 fpsState[kOptions] = Json::Value(Json::arrayValue);
1401
liyuqiane5a6cd92016-05-27 08:52:52 -07001402 Json::Value state(Json::arrayValue);
1403 state.append(slideState);
1404 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001405 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001406 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001407 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001408 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001409 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001410
1411 fWindow->setUIState(state);
1412}
1413
1414void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001415 // For those who will add more features to handle the state change in this function:
1416 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1417 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1418 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001419 if (stateName.equals(kSlideStateName)) {
1420 int previousSlide = fCurrentSlide;
1421 fCurrentSlide = 0;
1422 for(auto slide : fSlides) {
1423 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001424 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001425 break;
1426 }
1427 fCurrentSlide++;
1428 }
1429 if (fCurrentSlide >= fSlides.count()) {
1430 fCurrentSlide = previousSlide;
1431 SkDebugf("Slide not found: %s", stateValue.c_str());
1432 }
liyuqian6cb70252016-06-02 12:16:25 -07001433 } else if (stateName.equals(kBackendStateName)) {
1434 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1435 if (stateValue.equals(kBackendTypeStrings[i])) {
1436 if (fBackendType != i) {
1437 fBackendType = (sk_app::Window::BackendType)i;
1438 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001439 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001440 }
1441 break;
1442 }
1443 }
csmartdalton578f0642017-02-24 16:04:47 -07001444 } else if (stateName.equals(kMSAAStateName)) {
1445 DisplayParams params = fWindow->getRequestedDisplayParams();
1446 int sampleCount = atoi(stateValue.c_str());
1447 if (sampleCount != params.fMSAASampleCount) {
1448 params.fMSAASampleCount = sampleCount;
1449 fWindow->setRequestedDisplayParams(params);
1450 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001451 this->updateTitle();
1452 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001453 }
1454 } else if (stateName.equals(kPathRendererStateName)) {
1455 DisplayParams params = fWindow->getRequestedDisplayParams();
1456 for (const auto& pair : gPathRendererNames) {
1457 if (pair.second == stateValue.c_str()) {
1458 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1459 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1460 fWindow->setRequestedDisplayParams(params);
1461 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001462 this->updateTitle();
1463 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001464 }
1465 break;
1466 }
csmartdalton578f0642017-02-24 16:04:47 -07001467 }
Brian Salomon99a33902017-03-07 15:16:34 -05001468 } else if (stateName.equals(kInstancedRenderingStateName)) {
1469 DisplayParams params = fWindow->getRequestedDisplayParams();
1470 bool value = !strcmp(stateValue.c_str(), kON);
1471 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1472 params.fGrContextOptions.fEnableInstancedRendering = value;
1473 fWindow->setRequestedDisplayParams(params);
1474 fWindow->inval();
1475 this->updateTitle();
1476 this->updateUIState();
1477 }
liyuqianb73c24b2016-06-03 08:47:23 -07001478 } else if (stateName.equals(kSoftkeyStateName)) {
1479 if (!stateValue.equals(kSoftkeyHint)) {
1480 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001481 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001482 }
liyuqian2edb0f42016-07-06 14:11:32 -07001483 } else if (stateName.equals(kRefreshStateName)) {
1484 // This state is actually NOT in the UI state.
1485 // We use this to allow Android to quickly set bool fRefresh.
1486 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001487 } else {
1488 SkDebugf("Unknown stateName: %s", stateName.c_str());
1489 }
1490}
Brian Osman79086b92017-02-10 13:36:16 -05001491
1492bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1493 return fCommands.onKey(key, state, modifiers);
1494}
1495
1496bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001497 if (fSlides[fCurrentSlide]->onChar(c)) {
1498 fWindow->inval();
1499 return true;
1500 }
1501
Brian Osman79086b92017-02-10 13:36:16 -05001502 return fCommands.onChar(c, modifiers);
1503}