blob: aafba4332337ff3e3fdf52cf38c85698320a4d24 [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
jvanverthaf236b52016-05-20 06:01:06 -0700168const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700169 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700170#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700171 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700172#endif
csmartdalton578f0642017-02-24 16:04:47 -0700173 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700174};
175
bsalomon6c471f72016-07-26 12:56:32 -0700176static sk_app::Window::BackendType get_backend_type(const char* str) {
177#ifdef SK_VULKAN
178 if (0 == strcmp(str, "vk")) {
179 return sk_app::Window::kVulkan_BackendType;
180 } else
181#endif
182 if (0 == strcmp(str, "gl")) {
183 return sk_app::Window::kNativeGL_BackendType;
184 } else if (0 == strcmp(str, "sw")) {
185 return sk_app::Window::kRaster_BackendType;
186 } else {
187 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
188 return sk_app::Window::kRaster_BackendType;
189 }
190}
191
Brian Osmana109e392017-02-24 09:49:14 -0500192static SkColorSpacePrimaries gSrgbPrimaries = {
193 0.64f, 0.33f,
194 0.30f, 0.60f,
195 0.15f, 0.06f,
196 0.3127f, 0.3290f };
197
198static SkColorSpacePrimaries gAdobePrimaries = {
199 0.64f, 0.33f,
200 0.21f, 0.71f,
201 0.15f, 0.06f,
202 0.3127f, 0.3290f };
203
204static SkColorSpacePrimaries gP3Primaries = {
205 0.680f, 0.320f,
206 0.265f, 0.690f,
207 0.150f, 0.060f,
208 0.3127f, 0.3290f };
209
210static SkColorSpacePrimaries gRec2020Primaries = {
211 0.708f, 0.292f,
212 0.170f, 0.797f,
213 0.131f, 0.046f,
214 0.3127f, 0.3290f };
215
216struct NamedPrimaries {
217 const char* fName;
218 SkColorSpacePrimaries* fPrimaries;
219} gNamedPrimaries[] = {
220 { "sRGB", &gSrgbPrimaries },
221 { "AdobeRGB", &gAdobePrimaries },
222 { "P3", &gP3Primaries },
223 { "Rec. 2020", &gRec2020Primaries },
224};
225
226static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
227 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
228}
229
liyuqiane5a6cd92016-05-27 08:52:52 -0700230const char* kName = "name";
231const char* kValue = "value";
232const char* kOptions = "options";
233const char* kSlideStateName = "Slide";
234const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700235const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700236const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500237const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700238const char* kSoftkeyStateName = "Softkey";
239const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700240const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700241const char* kON = "ON";
242const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700243const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700244
jvanverth34524262016-05-04 13:49:13 -0700245Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700246 : fCurrentMeasurement(0)
247 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700248 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500249 , fShowImGuiDebugWindow(false)
250 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500251 , fShowZoomWindow(false)
252 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700253 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500254 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500255 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700256 , fZoomLevel(0.0f)
Brian Osmanb53f48c2017-06-07 10:00:30 -0400257 , fGestureDevice(GestureDevice::kNone)
jvanverthc265a922016-04-08 12:51:45 -0700258{
Greg Daniel285db442016-10-14 09:12:53 -0400259 SkGraphics::Init();
csmartdalton61cd31a2017-02-27 17:00:53 -0700260
261 static SkOnce initPathRendererNames;
262 initPathRendererNames([]() {
263 gPathRendererNames[GpuPathRenderers::kAll] = "Default Ganesh Behavior (best path renderer)";
264 gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
265 gPathRendererNames[GpuPathRenderers::kMSAA] = "Sample shading";
Jim Van Verth83010462017-03-16 08:45:39 -0400266 gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
Chris Dalton1a325d22017-07-14 15:17:41 -0600267 gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "Coverage counting";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500268 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700269 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
270 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
271 });
272
Brian Osman1df161a2017-02-09 12:10:20 -0500273 memset(fPaintTimes, 0, sizeof(fPaintTimes));
274 memset(fFlushTimes, 0, sizeof(fFlushTimes));
275 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700276
jvanverth2bb3b6d2016-04-08 07:24:09 -0700277 SkDebugf("Command line arguments: ");
278 for (int i = 1; i < argc; ++i) {
279 SkDebugf("%s ", argv[i]);
280 }
281 SkDebugf("\n");
282
283 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500284#ifdef SK_BUILD_FOR_ANDROID
Brian Salomon96789b32017-05-26 12:06:21 -0400285 SetResourcePath("/data/local/tmp/resources");
Greg Daniel9fcc7432016-11-29 16:35:19 -0500286#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700287
Brian Osmanbc8150f2017-07-24 11:38:01 -0400288 initializeEventTracingForTools();
Brian Osman53136aa2017-07-20 15:43:35 -0400289 static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
Greg Daniel285db442016-10-14 09:12:53 -0400290
bsalomon6c471f72016-07-26 12:56:32 -0700291 fBackendType = get_backend_type(FLAGS_backend[0]);
jvanverth9f372462016-04-06 06:08:59 -0700292 fWindow = Window::CreateNativeWindow(platformData);
jvanverth9f372462016-04-06 06:08:59 -0700293
csmartdalton578f0642017-02-24 16:04:47 -0700294 DisplayParams displayParams;
295 displayParams.fMSAASampleCount = FLAGS_msaa;
Brian Salomon41eac792017-03-08 14:03:56 -0500296 displayParams.fGrContextOptions.fEnableInstancedRendering = FLAGS_instancedRendering;
csmartdalton61cd31a2017-02-27 17:00:53 -0700297 displayParams.fGrContextOptions.fGpuPathRenderers = CollectGpuPathRenderersFromFlags();
csmartdalton578f0642017-02-24 16:04:47 -0700298 fWindow->setRequestedDisplayParams(displayParams);
299
jvanverth9f372462016-04-06 06:08:59 -0700300 // register callbacks
brianosman622c8d52016-05-10 06:50:49 -0700301 fCommands.attach(fWindow);
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700302 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
jvanverth9f372462016-04-06 06:08:59 -0700303 fWindow->registerPaintFunc(on_paint_handler, this);
liyuqiand3cdbca2016-05-17 12:44:20 -0700304 fWindow->registerTouchFunc(on_touch_handler, this);
liyuqiane5a6cd92016-05-27 08:52:52 -0700305 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
Brian Osman79086b92017-02-10 13:36:16 -0500306 fWindow->registerMouseFunc(on_mouse_handler, this);
307 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
308 fWindow->registerKeyFunc(on_key_handler, this);
309 fWindow->registerCharFunc(on_char_handler, this);
jvanverth9f372462016-04-06 06:08:59 -0700310
brianosman622c8d52016-05-10 06:50:49 -0700311 // add key-bindings
Brian Osman79086b92017-02-10 13:36:16 -0500312 fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
313 this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
314 fWindow->inval();
315 });
316 fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
317 this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
318 fWindow->inval();
319 });
Brian Osmanf6877092017-02-13 09:39:57 -0500320 fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
321 this->fShowZoomWindow = !this->fShowZoomWindow;
322 fWindow->inval();
323 });
brianosman622c8d52016-05-10 06:50:49 -0700324 fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
325 this->fDisplayStats = !this->fDisplayStats;
326 fWindow->inval();
327 });
Brian Osmanf750fbc2017-02-08 10:47:28 -0500328 fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
Brian Osman92004802017-03-06 11:47:26 -0500329 switch (fColorMode) {
330 case ColorMode::kLegacy:
331 this->setColorMode(ColorMode::kColorManagedSRGB8888_NonLinearBlending);
332 break;
333 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
334 this->setColorMode(ColorMode::kColorManagedSRGB8888);
335 break;
336 case ColorMode::kColorManagedSRGB8888:
337 this->setColorMode(ColorMode::kColorManagedLinearF16);
338 break;
339 case ColorMode::kColorManagedLinearF16:
340 this->setColorMode(ColorMode::kLegacy);
341 break;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500342 }
brianosman622c8d52016-05-10 06:50:49 -0700343 });
344 fCommands.addCommand(Window::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
345 int previousSlide = fCurrentSlide;
346 fCurrentSlide++;
347 if (fCurrentSlide >= fSlides.count()) {
348 fCurrentSlide = 0;
349 }
350 this->setupCurrentSlide(previousSlide);
351 });
352 fCommands.addCommand(Window::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
353 int previousSlide = fCurrentSlide;
354 fCurrentSlide--;
355 if (fCurrentSlide < 0) {
356 fCurrentSlide = fSlides.count() - 1;
357 }
358 this->setupCurrentSlide(previousSlide);
359 });
360 fCommands.addCommand(Window::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
361 this->changeZoomLevel(1.f / 32.f);
362 fWindow->inval();
363 });
364 fCommands.addCommand(Window::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
365 this->changeZoomLevel(-1.f / 32.f);
366 fWindow->inval();
367 });
jvanverthaf236b52016-05-20 06:01:06 -0700368 fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
Brian Osman621491e2017-02-28 15:45:01 -0500369 sk_app::Window::BackendType newBackend = fBackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500370#if defined(SK_BUILD_FOR_WIN) || defined(SK_BUILD_FOR_MAC)
jvanverthb8794cc2016-07-27 14:29:18 -0700371 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500372 newBackend = sk_app::Window::kNativeGL_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700373#ifdef SK_VULKAN
374 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500375 newBackend = sk_app::Window::kVulkan_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700376#endif
377 } else {
Brian Osman621491e2017-02-28 15:45:01 -0500378 newBackend = sk_app::Window::kRaster_BackendType;
jvanverthb8794cc2016-07-27 14:29:18 -0700379 }
Jim Van Verthd63c1022017-01-05 13:50:49 -0500380#elif defined(SK_BUILD_FOR_UNIX)
381 // Switching to and from Vulkan is problematic on Linux so disabled for now
382 if (sk_app::Window::kRaster_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500383 newBackend = sk_app::Window::kNativeGL_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500384 } else if (sk_app::Window::kNativeGL_BackendType == fBackendType) {
Brian Osman621491e2017-02-28 15:45:01 -0500385 newBackend = sk_app::Window::kRaster_BackendType;
Jim Van Verthd63c1022017-01-05 13:50:49 -0500386 }
387#endif
jvanverthaf236b52016-05-20 06:01:06 -0700388
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;
617 if (GpuPathRenderers::kAll != pr) {
618 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 Osman80a82df2017-07-12 15:42:51 -0400709 // Switching from OpenGL to Vulkan (or vice-versa on some systems) in the same window is
710 // problematic at this point on Windows, so we just delete the window and recreate it.
711 if (sk_app::Window::kVulkan_BackendType == fBackendType ||
712 sk_app::Window::kNativeGL_BackendType == fBackendType) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400713 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500714 delete fWindow;
715 fWindow = Window::CreateNativeWindow(nullptr);
716
717 // re-register callbacks
718 fCommands.attach(fWindow);
719 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
720 fWindow->registerPaintFunc(on_paint_handler, this);
721 fWindow->registerTouchFunc(on_touch_handler, this);
722 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
723 fWindow->registerMouseFunc(on_mouse_handler, this);
724 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
725 fWindow->registerKeyFunc(on_key_handler, this);
726 fWindow->registerCharFunc(on_char_handler, this);
Brian Osman2ac96dc2017-06-23 13:32:29 -0400727 // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
728 // will still include our correct sample count. But the re-created fWindow will lose that
729 // information. On Windows, we need to re-create the window when changing sample count,
730 // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
731 // rendering this tear-down step pointless (and causing the Vulkan window context to fail
732 // as if we had never changed windows at all).
733 fWindow->setRequestedDisplayParams(params, false);
Brian Osman621491e2017-02-28 15:45:01 -0500734 }
735#endif
736
737 fWindow->attach(fBackendType);
738}
739
Brian Osman92004802017-03-06 11:47:26 -0500740void Viewer::setColorMode(ColorMode colorMode) {
741 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700742
Brian Osmanf750fbc2017-02-08 10:47:28 -0500743 // 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 -0400744 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700745 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500746 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400747 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
748 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500749 if (wasInLegacy != wantLegacy) {
750 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700751 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500752 }
753
754 this->updateTitle();
755 fWindow->inval();
756}
757
758void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500759 SkAutoCanvasRestore autorestore(canvas, false);
760
Brian Osmanf750fbc2017-02-08 10:47:28 -0500761 // By default, we render directly into the window's surface/canvas
762 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500763 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700764
Brian Osmane0d4fba2017-03-15 10:24:55 -0400765 // If we're in any of the color managed modes, construct the color space we're going to use
766 sk_sp<SkColorSpace> cs = nullptr;
767 if (ColorMode::kLegacy != fColorMode) {
768 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
769 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
Mike Kleinc722f792017-07-31 11:57:21 -0400770 SkMatrix44 toXYZ(SkMatrix44::kIdentity_Constructor);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400771 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
772 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
773 }
774
775 // 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 -0500776 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500777 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500778 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500779 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400780 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
781 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
782
Brian Osman92004802017-03-06 11:47:26 -0500783 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
784 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400785 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
786 // with a special canvas (below) that has the color space attached
787 sk_sp<SkColorSpace> offscreenColorSpace =
788 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500789 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400790 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500791 offscreenSurface = canvas->makeSurface(info);
792 slideCanvas = offscreenSurface->getCanvas();
793 }
794
Brian Osmane0d4fba2017-03-15 10:24:55 -0400795 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
796 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
797 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
798 slideCanvas = xformCanvas.get();
799 }
800
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500801 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500802 slideCanvas->clear(SK_ColorWHITE);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500803 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500804 // Time the painting logic of the slide
805 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500806 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500807 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500808 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500809
810 // Force a flush so we can time that, too
811 startTime = SkTime::GetMSecs();
812 slideCanvas->flush();
813 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500814
815 // If we rendered offscreen, snap an image and push the results to the window's canvas
816 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500817 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500818
819 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400820 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500821 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400822 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500823 SkPaint paint;
824 paint.setBlendMode(SkBlendMode::kSrc);
825 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700826 }
liyuqian6f163d22016-06-13 12:26:45 -0700827}
828
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700829void Viewer::onBackendCreated() {
830 this->updateTitle();
831 this->updateUIState();
832 this->setupCurrentSlide(-1);
833 fWindow->show();
834 fWindow->inval();
835}
Jim Van Verth6f449692017-02-14 15:16:46 -0500836
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700837void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500838 // Update ImGui input
839 ImGuiIO& io = ImGui::GetIO();
840 io.DeltaTime = 1.0f / 60.0f;
841 io.DisplaySize.x = static_cast<float>(fWindow->width());
842 io.DisplaySize.y = static_cast<float>(fWindow->height());
843
844 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
845 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
846 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
847
848 ImGui::NewFrame();
849
Brian Osmanf750fbc2017-02-08 10:47:28 -0500850 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700851
Brian Osman1df161a2017-02-09 12:10:20 -0500852 // Advance our timing bookkeeping
853 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
854 SkASSERT(fCurrentMeasurement < kMeasurementCount);
855
856 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700857 if (fDisplayStats) {
858 drawStats(canvas);
859 }
brianosman622c8d52016-05-10 06:50:49 -0700860 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700861
Brian Osman79086b92017-02-10 13:36:16 -0500862 drawImGui(canvas);
863
Brian Osman1df161a2017-02-09 12:10:20 -0500864 // Update the FPS
865 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700866}
867
jvanverth814e38d2016-06-06 08:48:47 -0700868bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400869 if (GestureDevice::kMouse == fGestureDevice) {
870 return false;
871 }
liyuqiand3cdbca2016-05-17 12:44:20 -0700872 void* castedOwner = reinterpret_cast<void*>(owner);
873 switch (state) {
874 case Window::kUp_InputState: {
875 fGesture.touchEnd(castedOwner);
876 break;
877 }
878 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400879 fGesture.touchBegin(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700880 break;
881 }
882 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400883 fGesture.touchMoved(castedOwner, x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700884 break;
885 }
886 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400887 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
liyuqiand3cdbca2016-05-17 12:44:20 -0700888 fWindow->inval();
889 return true;
890}
891
Jim Van Verthe7705782017-05-04 14:00:59 -0400892bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
Brian Osmanb53f48c2017-06-07 10:00:30 -0400893 if (GestureDevice::kTouch == fGestureDevice) {
894 return false;
895 }
Jim Van Verthe7705782017-05-04 14:00:59 -0400896 switch (state) {
897 case Window::kUp_InputState: {
898 fGesture.touchEnd(nullptr);
899 break;
900 }
901 case Window::kDown_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400902 fGesture.touchBegin(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400903 break;
904 }
905 case Window::kMove_InputState: {
Brian Osman42bb6ac2017-06-05 08:46:04 -0400906 fGesture.touchMoved(nullptr, x, y);
Jim Van Verthe7705782017-05-04 14:00:59 -0400907 break;
908 }
909 }
Brian Osmanb53f48c2017-06-07 10:00:30 -0400910 fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
Jim Van Verthe7705782017-05-04 14:00:59 -0400911 fWindow->inval();
912 return true;
913}
914
jvanverth34524262016-05-04 13:49:13 -0700915void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700916 static const float kPixelPerMS = 2.0f;
917 static const int kDisplayWidth = 130;
918 static const int kDisplayHeight = 100;
919 static const int kDisplayPadding = 10;
920 static const int kGraphPadding = 3;
921 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
922
Mike Reed3661bc92017-02-22 13:21:42 -0500923 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700924 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
925 SkIntToScalar(kDisplayPadding),
926 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
927 SkPaint paint;
928 canvas->save();
929
930 canvas->clipRect(rect);
931 paint.setColor(SK_ColorBLACK);
932 canvas->drawRect(rect, paint);
933 // draw the 16ms line
934 paint.setColor(SK_ColorLTGRAY);
935 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
936 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
937 paint.setColor(SK_ColorRED);
938 paint.setStyle(SkPaint::kStroke_Style);
939 canvas->drawRect(rect, paint);
940
941 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
942 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700943 int i = fCurrentMeasurement;
944 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500945 // Round to nearest values
946 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
947 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
948 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
949 int startY = SkScalarTruncToInt(rect.fBottom);
950 int endY = startY - flushHeight;
951 paint.setColor(SK_ColorRED);
952 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
953 SkIntToScalar(x), SkIntToScalar(endY), paint);
954 startY = endY;
955 endY = startY - paintHeight;
956 paint.setColor(SK_ColorGREEN);
957 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
958 SkIntToScalar(x), SkIntToScalar(endY), paint);
959 startY = endY;
960 endY = startY - animateHeight;
961 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700962 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
963 SkIntToScalar(x), SkIntToScalar(endY), paint);
964 i++;
965 i &= (kMeasurementCount - 1); // fast mod
966 x += xStep;
967 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700968
969 canvas->restore();
970}
971
Brian Osmana109e392017-02-24 09:49:14 -0500972static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
973 const ImVec2& pos, const ImVec2& size) {
974 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
975 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
976
977 // Invisible 10x10 button
978 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
979 ImGui::InvisibleButton(label, ImVec2(10, 10));
980
981 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
982 ImGuiIO& io = ImGui::GetIO();
983 // Normalized mouse position, relative to our gamut box
984 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
985 // Clamp to edge of box, convert back to primary scale
986 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
987 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
988 }
989
990 if (ImGui::IsItemHovered()) {
991 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
992 }
993
994 // Return screen coordinates for the caller. We could just return center here, but we'd have
995 // one frame of lag during drag.
996 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
997}
998
999static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1000 ImDrawList* drawList = ImGui::GetWindowDrawList();
1001
1002 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
1003 // width, and scale the height to maintain aspect ratio.
1004 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
1005 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
1006 ImVec2 pos = ImGui::GetCursorScreenPos();
1007
1008 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1009 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1010 // Magic numbers are pixel locations of the origin and upper-right corner.
1011 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
1012 ImVec2(242, 61), ImVec2(1897, 1922));
1013 ImVec2 endPos = ImGui::GetCursorPos();
1014
1015 // Primary markers
1016 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1017 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1018 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1019 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1020
1021 // Gamut triangle
1022 drawList->AddCircle(r, 5.0f, 0xFF000040);
1023 drawList->AddCircle(g, 5.0f, 0xFF004000);
1024 drawList->AddCircle(b, 5.0f, 0xFF400000);
1025 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1026 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1027
1028 // Re-position cursor immediate after the diagram for subsequent controls
1029 ImGui::SetCursorPos(endPos);
1030}
1031
Brian Osman79086b92017-02-10 13:36:16 -05001032void Viewer::drawImGui(SkCanvas* canvas) {
1033 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1034 if (fShowImGuiTestWindow) {
1035 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1036 }
1037
1038 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001039 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1040 // always visible, we can end up in a layout feedback loop.
1041 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001042 DisplayParams params = fWindow->getRequestedDisplayParams();
1043 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001044 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1045 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001046 if (ImGui::CollapsingHeader("Backend")) {
1047 int newBackend = static_cast<int>(fBackendType);
1048 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1049 ImGui::SameLine();
1050 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1051#if defined(SK_VULKAN)
1052 ImGui::SameLine();
1053 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1054#endif
1055 if (newBackend != fBackendType) {
1056 fDeferredActions.push_back([=]() {
1057 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1058 });
1059 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001060
Brian Salomon99a33902017-03-07 15:16:34 -05001061 const GrContext* ctx = fWindow->getGrContext();
1062 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1063 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1064 paramsChanged = true;
1065 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001066 bool* wire = &params.fGrContextOptions.fWireframeMode;
1067 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1068 paramsChanged = true;
1069 }
Brian Salomon99a33902017-03-07 15:16:34 -05001070
Brian Osman28b12522017-03-08 17:10:24 -05001071 if (ctx) {
1072 int sampleCount = fWindow->sampleCount();
1073 ImGui::Text("MSAA: "); ImGui::SameLine();
1074 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1075 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1076 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1077 ImGui::RadioButton("16", &sampleCount, 16);
1078
1079 if (sampleCount != params.fMSAASampleCount) {
1080 params.fMSAASampleCount = sampleCount;
1081 paramsChanged = true;
1082 }
1083 }
1084
Brian Osman8a9de3d2017-03-01 14:59:05 -05001085 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001086 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001087 auto prButton = [&](GpuPathRenderers x) {
1088 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001089 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1090 params.fGrContextOptions.fGpuPathRenderers = x;
1091 paramsChanged = true;
1092 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001093 }
1094 };
1095
1096 if (!ctx) {
1097 ImGui::RadioButton("Software", true);
1098 } else if (fWindow->sampleCount()) {
1099 prButton(GpuPathRenderers::kAll);
1100 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1101 prButton(GpuPathRenderers::kStencilAndCover);
1102 }
1103 if (ctx->caps()->sampleShadingSupport()) {
1104 prButton(GpuPathRenderers::kMSAA);
1105 }
1106 prButton(GpuPathRenderers::kTessellating);
1107 prButton(GpuPathRenderers::kDefault);
1108 prButton(GpuPathRenderers::kNone);
1109 } else {
1110 prButton(GpuPathRenderers::kAll);
Chris Dalton1a325d22017-07-14 15:17:41 -06001111 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1112 prButton(GpuPathRenderers::kCoverageCounting);
1113 }
Jim Van Verth83010462017-03-16 08:45:39 -04001114 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001115 prButton(GpuPathRenderers::kTessellating);
1116 prButton(GpuPathRenderers::kNone);
1117 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001118 ImGui::TreePop();
1119 }
Brian Osman621491e2017-02-28 15:45:01 -05001120 }
1121
Brian Osman79086b92017-02-10 13:36:16 -05001122 if (ImGui::CollapsingHeader("Slide")) {
1123 static ImGuiTextFilter filter;
1124 filter.Draw();
1125 int previousSlide = fCurrentSlide;
1126 fCurrentSlide = 0;
1127 for (auto slide : fSlides) {
1128 if (filter.PassFilter(slide->getName().c_str())) {
1129 ImGui::BulletText("%s", slide->getName().c_str());
1130 if (ImGui::IsItemClicked()) {
1131 setupCurrentSlide(previousSlide);
1132 break;
1133 }
1134 }
1135 ++fCurrentSlide;
1136 }
1137 if (fCurrentSlide >= fSlides.count()) {
1138 fCurrentSlide = previousSlide;
1139 }
1140 }
Brian Osmana109e392017-02-24 09:49:14 -05001141
1142 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001143 ColorMode newMode = fColorMode;
1144 auto cmButton = [&](ColorMode mode, const char* label) {
1145 if (ImGui::RadioButton(label, mode == fColorMode)) {
1146 newMode = mode;
1147 }
1148 };
1149
1150 cmButton(ColorMode::kLegacy, "Legacy 8888");
1151 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1152 "Color Managed 8888 (Nonlinear blending)");
1153 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1154 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1155
1156 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001157 // It isn't safe to switch color mode now (in the middle of painting). We might
1158 // tear down the back-end, etc... Defer this change until the next onIdle.
1159 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001160 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001161 });
Brian Osmana109e392017-02-24 09:49:14 -05001162 }
1163
1164 // Pick from common gamuts:
1165 int primariesIdx = 4; // Default: Custom
1166 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1167 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1168 primariesIdx = i;
1169 break;
1170 }
1171 }
1172
1173 if (ImGui::Combo("Primaries", &primariesIdx,
1174 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1175 if (primariesIdx >= 0 && primariesIdx <= 3) {
1176 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1177 }
1178 }
1179
1180 // Allow direct editing of gamut
1181 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1182 }
Brian Osman79086b92017-02-10 13:36:16 -05001183 }
Brian Salomon99a33902017-03-07 15:16:34 -05001184 if (paramsChanged) {
1185 fDeferredActions.push_back([=]() {
1186 fWindow->setRequestedDisplayParams(params);
1187 fWindow->inval();
1188 this->updateTitle();
1189 });
1190 }
Brian Osman79086b92017-02-10 13:36:16 -05001191 ImGui::End();
1192 }
1193
Brian Osmanf6877092017-02-13 09:39:57 -05001194 SkPaint zoomImagePaint;
1195 if (fShowZoomWindow && fLastImage) {
1196 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1197 static int zoomFactor = 4;
1198 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1199
Mike Reed0acd7952017-04-28 11:12:19 -04001200 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001201 zoomImagePaint.setColor(SK_ColorWHITE);
1202
1203 // Zoom by shrinking the corner UVs towards the mouse cursor
1204 ImVec2 mousePos = ImGui::GetMousePos();
1205 ImVec2 avail = ImGui::GetContentRegionAvail();
1206
1207 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1208 (avail.y * 0.5f) / zoomFactor);
1209 ImGui::Image(&zoomImagePaint, avail,
1210 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1211 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1212 }
1213
1214 ImGui::End();
1215 }
1216
Brian Osman79086b92017-02-10 13:36:16 -05001217 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1218 // (widgets, etc...) that have been issued
1219 ImGui::Render();
1220
1221 // Then we fetch the most recent data, and convert it so we can render with Skia
1222 const ImDrawData* drawData = ImGui::GetDrawData();
1223 SkTDArray<SkPoint> pos;
1224 SkTDArray<SkPoint> uv;
1225 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001226
1227 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1228 const ImDrawList* drawList = drawData->CmdLists[i];
1229
1230 // De-interleave all vertex data (sigh), convert to Skia types
1231 pos.rewind(); uv.rewind(); color.rewind();
1232 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1233 const ImDrawVert& vert = drawList->VtxBuffer[i];
1234 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1235 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1236 color.push(vert.col);
1237 }
1238 // ImGui colors are RGBA
1239 SkSwapRB(color.begin(), color.begin(), color.count());
1240
1241 int indexOffset = 0;
1242
1243 // Draw everything with canvas.drawVertices...
1244 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1245 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1246
1247 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1248 if (drawCmd->UserCallback) {
1249 drawCmd->UserCallback(drawList, drawCmd);
1250 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001251 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1252 SkASSERT(paint);
1253
Brian Osman79086b92017-02-10 13:36:16 -05001254 canvas->save();
1255 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1256 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001257 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1258 drawList->VtxBuffer.size(), pos.begin(),
1259 uv.begin(), color.begin(),
1260 drawCmd->ElemCount,
1261 drawList->IdxBuffer.begin() + indexOffset),
1262 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001263 indexOffset += drawCmd->ElemCount;
1264 canvas->restore();
1265 }
1266 }
1267 }
1268}
1269
liyuqian2edb0f42016-07-06 14:11:32 -07001270void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001271 for (int i = 0; i < fDeferredActions.count(); ++i) {
1272 fDeferredActions[i]();
1273 }
1274 fDeferredActions.reset();
1275
Brian Osman1df161a2017-02-09 12:10:20 -05001276 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001277 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001278 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1279 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1280
Brian Osman79086b92017-02-10 13:36:16 -05001281 ImGuiIO& io = ImGui::GetIO();
1282 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001283 fWindow->inval();
1284 }
jvanverth9f372462016-04-06 06:08:59 -07001285}
liyuqiane5a6cd92016-05-27 08:52:52 -07001286
1287void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001288 if (!fWindow) {
1289 return;
1290 }
1291 if (fWindow->sampleCount() < 0) {
1292 return; // Surface hasn't been created yet.
1293 }
1294
liyuqianb73c24b2016-06-03 08:47:23 -07001295 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001296 Json::Value slideState(Json::objectValue);
1297 slideState[kName] = kSlideStateName;
1298 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001299 if (fAllSlideNames.size() == 0) {
1300 for(auto slide : fSlides) {
1301 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1302 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001303 }
liyuqian1f508fd2016-06-07 06:57:40 -07001304 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001305
liyuqianb73c24b2016-06-03 08:47:23 -07001306 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001307 Json::Value backendState(Json::objectValue);
1308 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001309 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001310 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001311 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001312 backendState[kOptions].append(Json::Value(str));
1313 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001314
csmartdalton578f0642017-02-24 16:04:47 -07001315 // MSAA state
1316 Json::Value msaaState(Json::objectValue);
1317 msaaState[kName] = kMSAAStateName;
1318 msaaState[kValue] = fWindow->sampleCount();
1319 msaaState[kOptions] = Json::Value(Json::arrayValue);
1320 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1321 msaaState[kOptions].append(Json::Value(0));
1322 } else {
1323 for (int msaa : {0, 4, 8, 16}) {
1324 msaaState[kOptions].append(Json::Value(msaa));
1325 }
1326 }
1327
csmartdalton61cd31a2017-02-27 17:00:53 -07001328 // Path renderer state
1329 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1330 Json::Value prState(Json::objectValue);
1331 prState[kName] = kPathRendererStateName;
1332 prState[kValue] = gPathRendererNames[pr];
1333 prState[kOptions] = Json::Value(Json::arrayValue);
1334 const GrContext* ctx = fWindow->getGrContext();
1335 if (!ctx) {
1336 prState[kOptions].append("Software");
1337 } else if (fWindow->sampleCount()) {
1338 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1339 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1340 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1341 }
1342 if (ctx->caps()->sampleShadingSupport()) {
1343 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1344 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001345 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001346 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1347 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1348 } else {
1349 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Chris Dalton1a325d22017-07-14 15:17:41 -06001350 if (GrCoverageCountingPathRenderer::IsSupported(*ctx->caps())) {
1351 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kCoverageCounting]);
1352 }
Jim Van Verth83010462017-03-16 08:45:39 -04001353 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001354 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001355 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1356 }
1357
Brian Salomon99a33902017-03-07 15:16:34 -05001358 // Instanced rendering state
1359 Json::Value instState(Json::objectValue);
1360 instState[kName] = kInstancedRenderingStateName;
Yuqian Lid9020422017-07-25 15:01:53 -04001361 instState[kValue] = kOFF;
1362 instState[kOptions] = Json::Value(Json::arrayValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001363 if (ctx) {
1364 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1365 instState[kValue] = kON;
Brian Salomon99a33902017-03-07 15:16:34 -05001366 }
Brian Salomon99a33902017-03-07 15:16:34 -05001367 instState[kOptions].append(kOFF);
1368 instState[kOptions].append(kON);
1369 }
1370
liyuqianb73c24b2016-06-03 08:47:23 -07001371 // Softkey state
1372 Json::Value softkeyState(Json::objectValue);
1373 softkeyState[kName] = kSoftkeyStateName;
1374 softkeyState[kValue] = kSoftkeyHint;
1375 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1376 softkeyState[kOptions].append(kSoftkeyHint);
1377 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1378 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1379 }
1380
liyuqian1f508fd2016-06-07 06:57:40 -07001381 // FPS state
1382 Json::Value fpsState(Json::objectValue);
1383 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001384 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1385 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1386 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1387 fAnimateTimes[idx],
1388 fPaintTimes[idx],
1389 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001390 fpsState[kOptions] = Json::Value(Json::arrayValue);
1391
liyuqiane5a6cd92016-05-27 08:52:52 -07001392 Json::Value state(Json::arrayValue);
1393 state.append(slideState);
1394 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001395 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001396 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001397 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001398 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001399 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001400
1401 fWindow->setUIState(state);
1402}
1403
1404void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001405 // For those who will add more features to handle the state change in this function:
1406 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1407 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1408 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001409 if (stateName.equals(kSlideStateName)) {
1410 int previousSlide = fCurrentSlide;
1411 fCurrentSlide = 0;
1412 for(auto slide : fSlides) {
1413 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001414 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001415 break;
1416 }
1417 fCurrentSlide++;
1418 }
1419 if (fCurrentSlide >= fSlides.count()) {
1420 fCurrentSlide = previousSlide;
1421 SkDebugf("Slide not found: %s", stateValue.c_str());
1422 }
liyuqian6cb70252016-06-02 12:16:25 -07001423 } else if (stateName.equals(kBackendStateName)) {
1424 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1425 if (stateValue.equals(kBackendTypeStrings[i])) {
1426 if (fBackendType != i) {
1427 fBackendType = (sk_app::Window::BackendType)i;
1428 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001429 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001430 }
1431 break;
1432 }
1433 }
csmartdalton578f0642017-02-24 16:04:47 -07001434 } else if (stateName.equals(kMSAAStateName)) {
1435 DisplayParams params = fWindow->getRequestedDisplayParams();
1436 int sampleCount = atoi(stateValue.c_str());
1437 if (sampleCount != params.fMSAASampleCount) {
1438 params.fMSAASampleCount = sampleCount;
1439 fWindow->setRequestedDisplayParams(params);
1440 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001441 this->updateTitle();
1442 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001443 }
1444 } else if (stateName.equals(kPathRendererStateName)) {
1445 DisplayParams params = fWindow->getRequestedDisplayParams();
1446 for (const auto& pair : gPathRendererNames) {
1447 if (pair.second == stateValue.c_str()) {
1448 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1449 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1450 fWindow->setRequestedDisplayParams(params);
1451 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001452 this->updateTitle();
1453 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001454 }
1455 break;
1456 }
csmartdalton578f0642017-02-24 16:04:47 -07001457 }
Brian Salomon99a33902017-03-07 15:16:34 -05001458 } else if (stateName.equals(kInstancedRenderingStateName)) {
1459 DisplayParams params = fWindow->getRequestedDisplayParams();
1460 bool value = !strcmp(stateValue.c_str(), kON);
1461 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1462 params.fGrContextOptions.fEnableInstancedRendering = value;
1463 fWindow->setRequestedDisplayParams(params);
1464 fWindow->inval();
1465 this->updateTitle();
1466 this->updateUIState();
1467 }
liyuqianb73c24b2016-06-03 08:47:23 -07001468 } else if (stateName.equals(kSoftkeyStateName)) {
1469 if (!stateValue.equals(kSoftkeyHint)) {
1470 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001471 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001472 }
liyuqian2edb0f42016-07-06 14:11:32 -07001473 } else if (stateName.equals(kRefreshStateName)) {
1474 // This state is actually NOT in the UI state.
1475 // We use this to allow Android to quickly set bool fRefresh.
1476 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001477 } else {
1478 SkDebugf("Unknown stateName: %s", stateName.c_str());
1479 }
1480}
Brian Osman79086b92017-02-10 13:36:16 -05001481
1482bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1483 return fCommands.onKey(key, state, modifiers);
1484}
1485
1486bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001487 if (fSlides[fCurrentSlide]->onChar(c)) {
1488 fWindow->inval();
1489 return true;
1490 }
1491
Brian Osman79086b92017-02-10 13:36:16 -05001492 return fCommands.onChar(c, modifiers);
1493}