blob: 7cf8cd8825bd3ef8f31b49c59be52ad3f46ea8fb [file] [log] [blame]
jvanverth9f372462016-04-06 06:08:59 -07001/*
2* Copyright 2016 Google Inc.
3*
4* Use of this source code is governed by a BSD-style license that can be
5* found in the LICENSE file.
6*/
7
jvanverth34524262016-05-04 13:49:13 -07008#include "Viewer.h"
jvanverth9f372462016-04-06 06:08:59 -07009
jvanverth2bb3b6d2016-04-08 07:24:09 -070010#include "GMSlide.h"
liyuqian6f163d22016-06-13 12:26:45 -070011#include "ImageSlide.h"
Greg Daniel9fcc7432016-11-29 16:35:19 -050012#include "Resources.h"
jvanverthc7027ab2016-06-16 09:52:35 -070013#include "SampleSlide.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070014#include "SKPSlide.h"
jvanverth9f372462016-04-06 06:08:59 -070015
csmartdalton61cd31a2017-02-27 17:00:53 -070016#include "GrContext.h"
Greg Daniel285db442016-10-14 09:12:53 -040017#include "SkATrace.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070018#include "SkCanvas.h"
Brian Osmana109e392017-02-24 09:49:14 -050019#include "SkColorSpace_Base.h"
Brian Osmane0d4fba2017-03-15 10:24:55 -040020#include "SkColorSpaceXformCanvas.h"
Brian Osman2dd96932016-10-18 15:33:53 -040021#include "SkCommandLineFlags.h"
csmartdalton008b9d82017-02-22 12:00:42 -070022#include "SkCommonFlagsPathRenderer.h"
liyuqian74959a12016-06-16 14:10:34 -070023#include "SkDashPathEffect.h"
Greg Daniel285db442016-10-14 09:12:53 -040024#include "SkGraphics.h"
Brian Osmanf750fbc2017-02-08 10:47:28 -050025#include "SkImagePriv.h"
liyuqian6f163d22016-06-13 12:26:45 -070026#include "SkMetaData.h"
csmartdalton61cd31a2017-02-27 17:00:53 -070027#include "SkOnce.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070028#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050029#include "SkOSPath.h"
jvanverth2bb3b6d2016-04-08 07:24:09 -070030#include "SkRandom.h"
31#include "SkStream.h"
liyuqian74959a12016-06-16 14:10:34 -070032#include "SkSurface.h"
Brian Osman79086b92017-02-10 13:36:16 -050033#include "SkSwizzle.h"
csmartdalton29d87152017-02-10 17:05:14 -050034#include "SkTaskGroup.h"
liyuqian2edb0f42016-07-06 14:11:32 -070035#include "SkTime.h"
Mike Reed887cdf12017-04-03 11:11:09 -040036#include "SkVertices.h"
jvanverth9f372462016-04-06 06:08:59 -070037
Brian Osman79086b92017-02-10 13:36:16 -050038#include "imgui.h"
39
csmartdalton578f0642017-02-24 16:04:47 -070040#include <stdlib.h>
csmartdalton61cd31a2017-02-27 17:00:53 -070041#include <map>
csmartdalton578f0642017-02-24 16:04:47 -070042
jvanverth34524262016-05-04 13:49:13 -070043using namespace sk_app;
44
csmartdalton61cd31a2017-02-27 17:00:53 -070045using GpuPathRenderers = GrContextOptions::GpuPathRenderers;
46static std::map<GpuPathRenderers, std::string> gPathRendererNames;
47
jvanverth9f372462016-04-06 06:08:59 -070048Application* Application::Create(int argc, char** argv, void* platformData) {
jvanverth34524262016-05-04 13:49:13 -070049 return new Viewer(argc, argv, platformData);
jvanverth9f372462016-04-06 06:08:59 -070050}
51
Christopher Dalton443ec1b2017-02-24 13:22:53 -070052static void on_backend_created_func(void* userData) {
53 Viewer* vv = reinterpret_cast<Viewer*>(userData);
54
55 return vv->onBackendCreated();
56}
57
jvanverth9f372462016-04-06 06:08:59 -070058static void on_paint_handler(SkCanvas* canvas, void* userData) {
jvanverth34524262016-05-04 13:49:13 -070059 Viewer* vv = reinterpret_cast<Viewer*>(userData);
jvanverth9f372462016-04-06 06:08:59 -070060
61 return vv->onPaint(canvas);
62}
63
jvanverth814e38d2016-06-06 08:48:47 -070064static bool on_touch_handler(intptr_t owner, Window::InputState state, float x, float y, void* userData)
liyuqiand3cdbca2016-05-17 12:44:20 -070065{
66 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
67
68 return viewer->onTouch(owner, state, x, y);
69}
70
liyuqiane5a6cd92016-05-27 08:52:52 -070071static void on_ui_state_changed_handler(const SkString& stateName, const SkString& stateValue, void* userData) {
72 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
73
74 return viewer->onUIStateChanged(stateName, stateValue);
75}
76
Brian Osman79086b92017-02-10 13:36:16 -050077static bool on_mouse_handler(int x, int y, Window::InputState state, uint32_t modifiers,
78 void* userData) {
79 ImGuiIO& io = ImGui::GetIO();
80 io.MousePos.x = static_cast<float>(x);
81 io.MousePos.y = static_cast<float>(y);
82 if (Window::kDown_InputState == state) {
83 io.MouseDown[0] = true;
84 } else if (Window::kUp_InputState == state) {
85 io.MouseDown[0] = false;
86 }
Jim Van Verthe7705782017-05-04 14:00:59 -040087 if (io.WantCaptureMouse) {
88 return true;
89 } else {
90 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
91 return viewer->onMouse(x, y, state, modifiers);
92 }
Brian Osman79086b92017-02-10 13:36:16 -050093}
94
95static bool on_mouse_wheel_handler(float delta, uint32_t modifiers, void* userData) {
96 ImGuiIO& io = ImGui::GetIO();
97 io.MouseWheel += delta;
98 return true;
99}
100
101static bool on_key_handler(Window::Key key, Window::InputState state, uint32_t modifiers,
102 void* userData) {
103 ImGuiIO& io = ImGui::GetIO();
104 io.KeysDown[static_cast<int>(key)] = (Window::kDown_InputState == state);
105
106 if (io.WantCaptureKeyboard) {
107 return true;
108 } else {
109 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
110 return viewer->onKey(key, state, modifiers);
111 }
112}
113
114static bool on_char_handler(SkUnichar c, uint32_t modifiers, void* userData) {
115 ImGuiIO& io = ImGui::GetIO();
116 if (io.WantTextInput) {
117 if (c > 0 && c < 0x10000) {
118 io.AddInputCharacter(c);
119 }
120 return true;
121 } else {
122 Viewer* viewer = reinterpret_cast<Viewer*>(userData);
123 return viewer->onChar(c, modifiers);
124 }
125}
126
Brian Osman2dd96932016-10-18 15:33:53 -0400127static DEFINE_bool2(fullscreen, f, true, "Run fullscreen.");
Brian Osman16adfa32016-10-18 14:42:44 -0400128
Brian Osman2dd96932016-10-18 15:33:53 -0400129static DEFINE_string2(match, m, nullptr,
jvanverth2bb3b6d2016-04-08 07:24:09 -0700130 "[~][^]substring[$] [...] of bench name to run.\n"
131 "Multiple matches may be separated by spaces.\n"
132 "~ causes a matching bench to always be skipped\n"
133 "^ requires the start of the bench to match\n"
134 "$ requires the end of the bench to match\n"
135 "^ and $ requires an exact match\n"
136 "If a bench does not match any list entry,\n"
137 "it is skipped unless some list entry starts with ~");
bsalomon6c471f72016-07-26 12:56:32 -0700138
Jim Van Verth6f449692017-02-14 15:16:46 -0500139DEFINE_string(slide, "", "Start on this sample.");
140DEFINE_bool(list, false, "List samples?");
141
bsalomon6c471f72016-07-26 12:56:32 -0700142#ifdef SK_VULKAN
jvanverthb8794cc2016-07-27 14:29:18 -0700143# define BACKENDS_STR "\"sw\", \"gl\", and \"vk\""
bsalomon6c471f72016-07-26 12:56:32 -0700144#else
145# define BACKENDS_STR "\"sw\" and \"gl\""
146#endif
147
liyuqian71491dc2016-06-09 12:02:34 -0700148#ifdef SK_BUILD_FOR_ANDROID
Brian Osman2dd96932016-10-18 15:33:53 -0400149static DEFINE_string(skps, "/data/local/tmp/skia", "Directory to read skps from.");
150static DEFINE_string(jpgs, "/data/local/tmp/skia", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700151#else
Brian Osman2dd96932016-10-18 15:33:53 -0400152static DEFINE_string(skps, "skps", "Directory to read skps from.");
153static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
liyuqian71491dc2016-06-09 12:02:34 -0700154#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700155
Brian Osman2dd96932016-10-18 15:33:53 -0400156static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
bsalomon6c471f72016-07-26 12:56:32 -0700157
Brian Osman2dd96932016-10-18 15:33:53 -0400158static DEFINE_bool(atrace, false, "Enable support for using ATrace. ATrace is only supported on Android.");
Greg Daniel285db442016-10-14 09:12:53 -0400159
csmartdalton578f0642017-02-24 16:04:47 -0700160DEFINE_int32(msaa, 0, "Number of subpixel samples. 0 for no HW antialiasing.");
csmartdalton008b9d82017-02-22 12:00:42 -0700161DEFINE_pathrenderer_flag;
162
Brian Salomon41eac792017-03-08 14:03:56 -0500163DEFINE_bool(instancedRendering, false, "Enable instanced rendering on GPU backends.");
164
jvanverthaf236b52016-05-20 06:01:06 -0700165const char *kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
csmartdalton578f0642017-02-24 16:04:47 -0700166 "OpenGL",
jvanverth063ece72016-06-17 09:29:14 -0700167#ifdef SK_VULKAN
csmartdalton578f0642017-02-24 16:04:47 -0700168 "Vulkan",
jvanverth063ece72016-06-17 09:29:14 -0700169#endif
csmartdalton578f0642017-02-24 16:04:47 -0700170 "Raster"
jvanverthaf236b52016-05-20 06:01:06 -0700171};
172
bsalomon6c471f72016-07-26 12:56:32 -0700173static sk_app::Window::BackendType get_backend_type(const char* str) {
174#ifdef SK_VULKAN
175 if (0 == strcmp(str, "vk")) {
176 return sk_app::Window::kVulkan_BackendType;
177 } else
178#endif
179 if (0 == strcmp(str, "gl")) {
180 return sk_app::Window::kNativeGL_BackendType;
181 } else if (0 == strcmp(str, "sw")) {
182 return sk_app::Window::kRaster_BackendType;
183 } else {
184 SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
185 return sk_app::Window::kRaster_BackendType;
186 }
187}
188
Brian Osmana109e392017-02-24 09:49:14 -0500189static SkColorSpacePrimaries gSrgbPrimaries = {
190 0.64f, 0.33f,
191 0.30f, 0.60f,
192 0.15f, 0.06f,
193 0.3127f, 0.3290f };
194
195static SkColorSpacePrimaries gAdobePrimaries = {
196 0.64f, 0.33f,
197 0.21f, 0.71f,
198 0.15f, 0.06f,
199 0.3127f, 0.3290f };
200
201static SkColorSpacePrimaries gP3Primaries = {
202 0.680f, 0.320f,
203 0.265f, 0.690f,
204 0.150f, 0.060f,
205 0.3127f, 0.3290f };
206
207static SkColorSpacePrimaries gRec2020Primaries = {
208 0.708f, 0.292f,
209 0.170f, 0.797f,
210 0.131f, 0.046f,
211 0.3127f, 0.3290f };
212
213struct NamedPrimaries {
214 const char* fName;
215 SkColorSpacePrimaries* fPrimaries;
216} gNamedPrimaries[] = {
217 { "sRGB", &gSrgbPrimaries },
218 { "AdobeRGB", &gAdobePrimaries },
219 { "P3", &gP3Primaries },
220 { "Rec. 2020", &gRec2020Primaries },
221};
222
223static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
224 return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
225}
226
liyuqiane5a6cd92016-05-27 08:52:52 -0700227const char* kName = "name";
228const char* kValue = "value";
229const char* kOptions = "options";
230const char* kSlideStateName = "Slide";
231const char* kBackendStateName = "Backend";
csmartdalton578f0642017-02-24 16:04:47 -0700232const char* kMSAAStateName = "MSAA";
csmartdalton61cd31a2017-02-27 17:00:53 -0700233const char* kPathRendererStateName = "Path renderer";
Brian Salomon99a33902017-03-07 15:16:34 -0500234const char* kInstancedRenderingStateName = "Instanced rendering";
liyuqianb73c24b2016-06-03 08:47:23 -0700235const char* kSoftkeyStateName = "Softkey";
236const char* kSoftkeyHint = "Please select a softkey";
liyuqian1f508fd2016-06-07 06:57:40 -0700237const char* kFpsStateName = "FPS";
liyuqian6f163d22016-06-13 12:26:45 -0700238const char* kON = "ON";
239const char* kOFF = "OFF";
liyuqian2edb0f42016-07-06 14:11:32 -0700240const char* kRefreshStateName = "Refresh";
liyuqiane5a6cd92016-05-27 08:52:52 -0700241
jvanverth34524262016-05-04 13:49:13 -0700242Viewer::Viewer(int argc, char** argv, void* platformData)
jvanverthc265a922016-04-08 12:51:45 -0700243 : fCurrentMeasurement(0)
244 , fDisplayStats(false)
liyuqian2edb0f42016-07-06 14:11:32 -0700245 , fRefresh(false)
Brian Osman79086b92017-02-10 13:36:16 -0500246 , fShowImGuiDebugWindow(false)
247 , fShowImGuiTestWindow(false)
Brian Osmanf6877092017-02-13 09:39:57 -0500248 , fShowZoomWindow(false)
249 , fLastImage(nullptr)
jvanverth063ece72016-06-17 09:29:14 -0700250 , fBackendType(sk_app::Window::kNativeGL_BackendType)
Brian Osman92004802017-03-06 11:47:26 -0500251 , fColorMode(ColorMode::kLegacy)
Brian Osmana109e392017-02-24 09:49:14 -0500252 , fColorSpacePrimaries(gSrgbPrimaries)
egdaniel2a0bb0a2016-04-11 08:30:40 -0700253 , fZoomCenterX(0.0f)
254 , fZoomCenterY(0.0f)
255 , fZoomLevel(0.0f)
256 , fZoomScale(SK_Scalar1)
jvanverthc265a922016-04-08 12:51:45 -0700257{
csmartdalton29d87152017-02-10 17:05:14 -0500258 static SkTaskGroup::Enabler kTaskGroupEnabler;
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)";
Brian Osman8a9de3d2017-03-01 14:59:05 -0500267 gPathRendererNames[GpuPathRenderers::kTessellating] = "Tessellating";
csmartdalton61cd31a2017-02-27 17:00:53 -0700268 gPathRendererNames[GpuPathRenderers::kDefault] = "Original Ganesh path renderer";
269 gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
270 });
271
Brian Osman1df161a2017-02-09 12:10:20 -0500272 memset(fPaintTimes, 0, sizeof(fPaintTimes));
273 memset(fFlushTimes, 0, sizeof(fFlushTimes));
274 memset(fAnimateTimes, 0, sizeof(fAnimateTimes));
jvanverth9f372462016-04-06 06:08:59 -0700275
jvanverth2bb3b6d2016-04-08 07:24:09 -0700276 SkDebugf("Command line arguments: ");
277 for (int i = 1; i < argc; ++i) {
278 SkDebugf("%s ", argv[i]);
279 }
280 SkDebugf("\n");
281
282 SkCommandLineFlags::Parse(argc, argv);
Greg Daniel9fcc7432016-11-29 16:35:19 -0500283#ifdef SK_BUILD_FOR_ANDROID
284 SetResourcePath("/data/local/tmp/skia");
285#endif
jvanverth2bb3b6d2016-04-08 07:24:09 -0700286
Greg Daniel285db442016-10-14 09:12:53 -0400287 if (FLAGS_atrace) {
288 SkEventTracer::SetInstance(new SkATrace());
289 }
290
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
jvanverth2bb3b6d2016-04-08 07:24:09 -0700392 // set up slides
393 this->initSlides();
Jim Van Verth6f449692017-02-14 15:16:46 -0500394 this->setStartupSlide();
395 if (FLAGS_list) {
396 this->listNames();
397 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700398
djsollen12d62a72016-04-21 07:59:44 -0700399 fAnimTimer.run();
400
Brian Osman79086b92017-02-10 13:36:16 -0500401 // ImGui initialization:
402 ImGuiIO& io = ImGui::GetIO();
403 io.DisplaySize.x = static_cast<float>(fWindow->width());
404 io.DisplaySize.y = static_cast<float>(fWindow->height());
405
406 // Keymap...
407 io.KeyMap[ImGuiKey_Tab] = (int)Window::Key::kTab;
408 io.KeyMap[ImGuiKey_LeftArrow] = (int)Window::Key::kLeft;
409 io.KeyMap[ImGuiKey_RightArrow] = (int)Window::Key::kRight;
410 io.KeyMap[ImGuiKey_UpArrow] = (int)Window::Key::kUp;
411 io.KeyMap[ImGuiKey_DownArrow] = (int)Window::Key::kDown;
412 io.KeyMap[ImGuiKey_PageUp] = (int)Window::Key::kPageUp;
413 io.KeyMap[ImGuiKey_PageDown] = (int)Window::Key::kPageDown;
414 io.KeyMap[ImGuiKey_Home] = (int)Window::Key::kHome;
415 io.KeyMap[ImGuiKey_End] = (int)Window::Key::kEnd;
416 io.KeyMap[ImGuiKey_Delete] = (int)Window::Key::kDelete;
417 io.KeyMap[ImGuiKey_Backspace] = (int)Window::Key::kBack;
418 io.KeyMap[ImGuiKey_Enter] = (int)Window::Key::kOK;
419 io.KeyMap[ImGuiKey_Escape] = (int)Window::Key::kEscape;
420 io.KeyMap[ImGuiKey_A] = (int)Window::Key::kA;
421 io.KeyMap[ImGuiKey_C] = (int)Window::Key::kC;
422 io.KeyMap[ImGuiKey_V] = (int)Window::Key::kV;
423 io.KeyMap[ImGuiKey_X] = (int)Window::Key::kX;
424 io.KeyMap[ImGuiKey_Y] = (int)Window::Key::kY;
425 io.KeyMap[ImGuiKey_Z] = (int)Window::Key::kZ;
426
427 int w, h;
428 unsigned char* pixels;
429 io.Fonts->GetTexDataAsAlpha8(&pixels, &w, &h);
430 SkImageInfo info = SkImageInfo::MakeA8(w, h);
431 SkPixmap pmap(info, pixels, info.minRowBytes());
Brian Osmanf6877092017-02-13 09:39:57 -0500432 SkMatrix localMatrix = SkMatrix::MakeScale(1.0f / w, 1.0f / h);
433 auto fontImage = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
Mike Reed0acd7952017-04-28 11:12:19 -0400434 auto fontShader = fontImage->makeShader(&localMatrix);
Brian Osmanf6877092017-02-13 09:39:57 -0500435 fImGuiFontPaint.setShader(fontShader);
436 fImGuiFontPaint.setColor(SK_ColorWHITE);
437 fImGuiFontPaint.setFilterQuality(kLow_SkFilterQuality);
438 io.Fonts->TexID = &fImGuiFontPaint;
Brian Osman79086b92017-02-10 13:36:16 -0500439
Brian Osmana109e392017-02-24 09:49:14 -0500440 auto gamutImage = GetResourceAsImage("gamut.png");
441 if (gamutImage) {
Mike Reed0acd7952017-04-28 11:12:19 -0400442 fImGuiGamutPaint.setShader(gamutImage->makeShader());
Brian Osmana109e392017-02-24 09:49:14 -0500443 }
444 fImGuiGamutPaint.setColor(SK_ColorWHITE);
445 fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
446
csmartdalton578f0642017-02-24 16:04:47 -0700447 fWindow->attach(fBackendType);
jvanverth9f372462016-04-06 06:08:59 -0700448}
449
jvanverth34524262016-05-04 13:49:13 -0700450void Viewer::initSlides() {
liyuqian1f508fd2016-06-07 06:57:40 -0700451 fAllSlideNames = Json::Value(Json::arrayValue);
452
jvanverth2bb3b6d2016-04-08 07:24:09 -0700453 const skiagm::GMRegistry* gms(skiagm::GMRegistry::Head());
454 while (gms) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400455 std::unique_ptr<skiagm::GM> gm(gms->factory()(nullptr));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700456
457 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
458 sk_sp<Slide> slide(new GMSlide(gm.release()));
459 fSlides.push_back(slide);
460 }
461
462 gms = gms->next();
463 }
464
465 // reverse array
466 for (int i = 0; i < fSlides.count()/2; ++i) {
467 sk_sp<Slide> temp = fSlides[i];
468 fSlides[i] = fSlides[fSlides.count() - i - 1];
469 fSlides[fSlides.count() - i - 1] = temp;
470 }
471
jvanverthc7027ab2016-06-16 09:52:35 -0700472 // samples
473 const SkViewRegister* reg = SkViewRegister::Head();
474 while (reg) {
475 sk_sp<Slide> slide(new SampleSlide(reg->factory()));
brianosmane1d20072016-07-12 09:07:33 -0700476 if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
477 fSlides.push_back(slide);
478 }
jvanverthc7027ab2016-06-16 09:52:35 -0700479 reg = reg->next();
480 }
481
jvanverth2bb3b6d2016-04-08 07:24:09 -0700482 // SKPs
483 for (int i = 0; i < FLAGS_skps.count(); i++) {
484 if (SkStrEndsWith(FLAGS_skps[i], ".skp")) {
jvanverthc265a922016-04-08 12:51:45 -0700485 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, FLAGS_skps[i])) {
486 continue;
487 }
488
jvanverth2bb3b6d2016-04-08 07:24:09 -0700489 SkString path(FLAGS_skps[i]);
jvanverthc265a922016-04-08 12:51:45 -0700490 sk_sp<SKPSlide> slide(new SKPSlide(SkOSPath::Basename(path.c_str()), path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700491 if (slide) {
492 fSlides.push_back(slide);
493 }
494 } else {
495 SkOSFile::Iter it(FLAGS_skps[i], ".skp");
jvanverthc265a922016-04-08 12:51:45 -0700496 SkString skpName;
497 while (it.next(&skpName)) {
498 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, skpName.c_str())) {
499 continue;
500 }
501
502 SkString path = SkOSPath::Join(FLAGS_skps[i], skpName.c_str());
503 sk_sp<SKPSlide> slide(new SKPSlide(skpName, path));
jvanverth2bb3b6d2016-04-08 07:24:09 -0700504 if (slide) {
505 fSlides.push_back(slide);
506 }
507 }
508 }
509 }
liyuqian6f163d22016-06-13 12:26:45 -0700510
511 // JPGs
512 for (int i = 0; i < FLAGS_jpgs.count(); i++) {
513 SkOSFile::Iter it(FLAGS_jpgs[i], ".jpg");
514 SkString jpgName;
515 while (it.next(&jpgName)) {
brianosmane1d20072016-07-12 09:07:33 -0700516 if (SkCommandLineFlags::ShouldSkip(FLAGS_match, jpgName.c_str())) {
517 continue;
518 }
519
liyuqian6f163d22016-06-13 12:26:45 -0700520 SkString path = SkOSPath::Join(FLAGS_jpgs[i], jpgName.c_str());
521 sk_sp<ImageSlide> slide(new ImageSlide(jpgName, path));
522 if (slide) {
523 fSlides.push_back(slide);
524 }
525 }
526 }
jvanverth2bb3b6d2016-04-08 07:24:09 -0700527}
528
529
jvanverth34524262016-05-04 13:49:13 -0700530Viewer::~Viewer() {
jvanverth9f372462016-04-06 06:08:59 -0700531 fWindow->detach();
532 delete fWindow;
533}
534
brianosman05de2162016-05-06 13:28:57 -0700535void Viewer::updateTitle() {
csmartdalton578f0642017-02-24 16:04:47 -0700536 if (!fWindow) {
537 return;
538 }
539 if (fWindow->sampleCount() < 0) {
540 return; // Surface hasn't been created yet.
541 }
542
jvanverth34524262016-05-04 13:49:13 -0700543 SkString title("Viewer: ");
jvanverthc265a922016-04-08 12:51:45 -0700544 title.append(fSlides[fCurrentSlide]->getName());
brianosmanb109b8c2016-06-16 13:03:24 -0700545
Brian Osman92004802017-03-06 11:47:26 -0500546 switch (fColorMode) {
547 case ColorMode::kLegacy:
548 title.append(" Legacy 8888");
549 break;
550 case ColorMode::kColorManagedSRGB8888_NonLinearBlending:
551 title.append(" ColorManaged 8888 (Nonlinear blending)");
552 break;
553 case ColorMode::kColorManagedSRGB8888:
554 title.append(" ColorManaged 8888");
555 break;
556 case ColorMode::kColorManagedLinearF16:
557 title.append(" ColorManaged F16");
558 break;
559 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500560
Brian Osman92004802017-03-06 11:47:26 -0500561 if (ColorMode::kLegacy != fColorMode) {
Brian Osmana109e392017-02-24 09:49:14 -0500562 int curPrimaries = -1;
563 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
564 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
565 curPrimaries = i;
566 break;
567 }
568 }
569 title.appendf(" %s", curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom");
brianosman05de2162016-05-06 13:28:57 -0700570 }
Brian Osmanf750fbc2017-02-08 10:47:28 -0500571
csmartdalton578f0642017-02-24 16:04:47 -0700572 title.append(" [");
jvanverthaf236b52016-05-20 06:01:06 -0700573 title.append(kBackendTypeStrings[fBackendType]);
csmartdalton578f0642017-02-24 16:04:47 -0700574 if (int msaa = fWindow->sampleCount()) {
575 title.appendf(" MSAA: %i", msaa);
576 }
577 title.append("]");
csmartdalton61cd31a2017-02-27 17:00:53 -0700578
579 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
580 if (GpuPathRenderers::kAll != pr) {
581 title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
582 }
583
brianosman05de2162016-05-06 13:28:57 -0700584 fWindow->setTitle(title.c_str());
585}
586
Jim Van Verth6f449692017-02-14 15:16:46 -0500587void Viewer::setStartupSlide() {
588
589 if (!FLAGS_slide.isEmpty()) {
590 int count = fSlides.count();
591 for (int i = 0; i < count; i++) {
592 if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
593 fCurrentSlide = i;
594 return;
595 }
596 }
597
598 fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
599 this->listNames();
600 }
601
602 fCurrentSlide = 0;
603}
604
605void Viewer::listNames() {
606 int count = fSlides.count();
607 SkDebugf("All Slides:\n");
608 for (int i = 0; i < count; i++) {
609 SkDebugf(" %s\n", fSlides[i]->getName().c_str());
610 }
611}
612
brianosman05de2162016-05-06 13:28:57 -0700613void Viewer::setupCurrentSlide(int previousSlide) {
liyuqiane5a6cd92016-05-27 08:52:52 -0700614 if (fCurrentSlide == previousSlide) {
615 return; // no change; do nothing
616 }
liyuqian6f163d22016-06-13 12:26:45 -0700617 // prepare dimensions for image slides
jvanverthc7027ab2016-06-16 09:52:35 -0700618 fSlides[fCurrentSlide]->load(SkIntToScalar(fWindow->width()), SkIntToScalar(fWindow->height()));
liyuqian6f163d22016-06-13 12:26:45 -0700619
liyuqiane46e4f02016-05-20 07:32:19 -0700620 fGesture.reset();
621 fDefaultMatrix.reset();
622 fDefaultMatrixInv.reset();
623
624 if (fWindow->supportsContentRect() && fWindow->scaleContentToFit()) {
625 const SkRect contentRect = fWindow->getContentRect();
626 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
627 const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
628 if (contentRect.width() > 0 && contentRect.height() > 0) {
629 fDefaultMatrix.setRectToRect(slideBounds, contentRect, SkMatrix::kStart_ScaleToFit);
liyuqianbeb1c672016-05-20 11:41:01 -0700630 SkAssertResult(fDefaultMatrix.invert(&fDefaultMatrixInv));
liyuqiane46e4f02016-05-20 07:32:19 -0700631 }
632 }
633
634 if (fWindow->supportsContentRect()) {
635 const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
636 SkRect windowRect = fWindow->getContentRect();
637 fDefaultMatrixInv.mapRect(&windowRect);
jvanverth1e305ba2016-06-01 09:39:15 -0700638 fGesture.setTransLimit(SkRect::MakeWH(SkIntToScalar(slideSize.width()),
639 SkIntToScalar(slideSize.height())),
640 windowRect);
liyuqiane46e4f02016-05-20 07:32:19 -0700641 }
642
brianosman05de2162016-05-06 13:28:57 -0700643 this->updateTitle();
liyuqiane5a6cd92016-05-27 08:52:52 -0700644 this->updateUIState();
jvanverthc265a922016-04-08 12:51:45 -0700645 if (previousSlide >= 0) {
646 fSlides[previousSlide]->unload();
647 }
jvanverthc265a922016-04-08 12:51:45 -0700648 fWindow->inval();
649}
650
651#define MAX_ZOOM_LEVEL 8
652#define MIN_ZOOM_LEVEL -8
653
jvanverth34524262016-05-04 13:49:13 -0700654void Viewer::changeZoomLevel(float delta) {
jvanverthc265a922016-04-08 12:51:45 -0700655 fZoomLevel += delta;
656 if (fZoomLevel > 0) {
657 fZoomLevel = SkMinScalar(fZoomLevel, MAX_ZOOM_LEVEL);
658 fZoomScale = fZoomLevel + SK_Scalar1;
659 } else if (fZoomLevel < 0) {
660 fZoomLevel = SkMaxScalar(fZoomLevel, MIN_ZOOM_LEVEL);
661 fZoomScale = SK_Scalar1 / (SK_Scalar1 - fZoomLevel);
662 } else {
663 fZoomScale = SK_Scalar1;
664 }
jvanverthc265a922016-04-08 12:51:45 -0700665}
666
liyuqiand3cdbca2016-05-17 12:44:20 -0700667SkMatrix Viewer::computeMatrix() {
jvanverthc265a922016-04-08 12:51:45 -0700668 SkMatrix m;
669 m.reset();
670
671 if (fZoomLevel) {
672 SkPoint center;
673 //m = this->getLocalMatrix();//.invert(&m);
674 m.mapXY(fZoomCenterX, fZoomCenterY, &center);
675 SkScalar cx = center.fX;
676 SkScalar cy = center.fY;
677
678 m.setTranslate(-cx, -cy);
679 m.postScale(fZoomScale, fZoomScale);
680 m.postTranslate(cx, cy);
681 }
682
liyuqiand3cdbca2016-05-17 12:44:20 -0700683 m.preConcat(fGesture.localM());
684 m.preConcat(fGesture.globalM());
jvanverthc265a922016-04-08 12:51:45 -0700685
liyuqiand3cdbca2016-05-17 12:44:20 -0700686 return m;
jvanverthc265a922016-04-08 12:51:45 -0700687}
688
Brian Osman621491e2017-02-28 15:45:01 -0500689void Viewer::setBackend(sk_app::Window::BackendType backendType) {
690 fBackendType = backendType;
691
692 fWindow->detach();
693
694#if defined(SK_BUILD_FOR_WIN) && defined(SK_VULKAN)
695 // Switching from OpenGL to Vulkan in the same window is problematic at this point on
696 // Windows, so we just delete the window and recreate it.
697 if (sk_app::Window::kVulkan_BackendType == fBackendType) {
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400698 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman621491e2017-02-28 15:45:01 -0500699 delete fWindow;
700 fWindow = Window::CreateNativeWindow(nullptr);
701
702 // re-register callbacks
703 fCommands.attach(fWindow);
704 fWindow->registerBackendCreatedFunc(on_backend_created_func, this);
705 fWindow->registerPaintFunc(on_paint_handler, this);
706 fWindow->registerTouchFunc(on_touch_handler, this);
707 fWindow->registerUIStateChangedFunc(on_ui_state_changed_handler, this);
708 fWindow->registerMouseFunc(on_mouse_handler, this);
709 fWindow->registerMouseWheelFunc(on_mouse_wheel_handler, this);
710 fWindow->registerKeyFunc(on_key_handler, this);
711 fWindow->registerCharFunc(on_char_handler, this);
Jim Van Verthfbdc0802017-05-02 16:15:53 -0400712 fWindow->setRequestedDisplayParams(params);
Brian Osman621491e2017-02-28 15:45:01 -0500713 }
714#endif
715
716 fWindow->attach(fBackendType);
717}
718
Brian Osman92004802017-03-06 11:47:26 -0500719void Viewer::setColorMode(ColorMode colorMode) {
720 fColorMode = colorMode;
liyuqian6f163d22016-06-13 12:26:45 -0700721
Brian Osmanf750fbc2017-02-08 10:47:28 -0500722 // 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 -0400723 // or out of legacy/nonlinear mode, we need to update our window configuration.
csmartdalton578f0642017-02-24 16:04:47 -0700724 DisplayParams params = fWindow->getRequestedDisplayParams();
Brian Osman92004802017-03-06 11:47:26 -0500725 bool wasInLegacy = !SkToBool(params.fColorSpace);
Brian Osmane0d4fba2017-03-15 10:24:55 -0400726 bool wantLegacy = (ColorMode::kLegacy == fColorMode) ||
727 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode);
Brian Osman92004802017-03-06 11:47:26 -0500728 if (wasInLegacy != wantLegacy) {
729 params.fColorSpace = wantLegacy ? nullptr : SkColorSpace::MakeSRGB();
csmartdalton578f0642017-02-24 16:04:47 -0700730 fWindow->setRequestedDisplayParams(params);
Brian Osmanf750fbc2017-02-08 10:47:28 -0500731 }
732
733 this->updateTitle();
734 fWindow->inval();
735}
736
737void Viewer::drawSlide(SkCanvas* canvas) {
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500738 SkAutoCanvasRestore autorestore(canvas, false);
739
djsollen12d62a72016-04-21 07:59:44 -0700740 if (fWindow->supportsContentRect()) {
741 SkRect contentRect = fWindow->getContentRect();
742 canvas->clipRect(contentRect);
743 canvas->translate(contentRect.fLeft, contentRect.fTop);
744 }
745
Brian Osmanf750fbc2017-02-08 10:47:28 -0500746 // By default, we render directly into the window's surface/canvas
747 SkCanvas* slideCanvas = canvas;
Brian Osmanf6877092017-02-13 09:39:57 -0500748 fLastImage.reset();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700749
Brian Osmane0d4fba2017-03-15 10:24:55 -0400750 // If we're in any of the color managed modes, construct the color space we're going to use
751 sk_sp<SkColorSpace> cs = nullptr;
752 if (ColorMode::kLegacy != fColorMode) {
753 auto transferFn = (ColorMode::kColorManagedLinearF16 == fColorMode)
754 ? SkColorSpace::kLinear_RenderTargetGamma : SkColorSpace::kSRGB_RenderTargetGamma;
755 SkMatrix44 toXYZ;
756 SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
757 cs = SkColorSpace::MakeRGB(transferFn, toXYZ);
758 }
759
760 // 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 -0500761 // we need to render offscreen
Brian Osmanf750fbc2017-02-08 10:47:28 -0500762 sk_sp<SkSurface> offscreenSurface = nullptr;
Brian Osman92004802017-03-06 11:47:26 -0500763 if (ColorMode::kColorManagedLinearF16 == fColorMode ||
Brian Osman92004802017-03-06 11:47:26 -0500764 fShowZoomWindow ||
Brian Osmane0d4fba2017-03-15 10:24:55 -0400765 (ColorMode::kColorManagedSRGB8888 == fColorMode &&
766 !primaries_equal(fColorSpacePrimaries, gSrgbPrimaries))) {
767
Brian Osman92004802017-03-06 11:47:26 -0500768 SkColorType colorType = (ColorMode::kColorManagedLinearF16 == fColorMode)
769 ? kRGBA_F16_SkColorType : kN32_SkColorType;
Brian Osmane0d4fba2017-03-15 10:24:55 -0400770 // In nonlinear blending mode, we actually use a legacy off-screen canvas, and wrap it
771 // with a special canvas (below) that has the color space attached
772 sk_sp<SkColorSpace> offscreenColorSpace =
773 (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) ? nullptr : cs;
Brian Osman92004802017-03-06 11:47:26 -0500774 SkImageInfo info = SkImageInfo::Make(fWindow->width(), fWindow->height(), colorType,
Brian Osmane0d4fba2017-03-15 10:24:55 -0400775 kPremul_SkAlphaType, std::move(offscreenColorSpace));
Brian Osmanf750fbc2017-02-08 10:47:28 -0500776 offscreenSurface = canvas->makeSurface(info);
777 slideCanvas = offscreenSurface->getCanvas();
778 }
779
Brian Osmane0d4fba2017-03-15 10:24:55 -0400780 std::unique_ptr<SkCanvas> xformCanvas = nullptr;
781 if (ColorMode::kColorManagedSRGB8888_NonLinearBlending == fColorMode) {
782 xformCanvas = SkCreateColorSpaceXformCanvas(slideCanvas, cs);
783 slideCanvas = xformCanvas.get();
784 }
785
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500786 int count = slideCanvas->save();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500787 slideCanvas->clear(SK_ColorWHITE);
788 slideCanvas->concat(fDefaultMatrix);
789 slideCanvas->concat(computeMatrix());
Brian Osman1df161a2017-02-09 12:10:20 -0500790 // Time the painting logic of the slide
791 double startTime = SkTime::GetMSecs();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500792 fSlides[fCurrentSlide]->draw(slideCanvas);
Brian Osman1df161a2017-02-09 12:10:20 -0500793 fPaintTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500794 slideCanvas->restoreToCount(count);
Brian Osman1df161a2017-02-09 12:10:20 -0500795
796 // Force a flush so we can time that, too
797 startTime = SkTime::GetMSecs();
798 slideCanvas->flush();
799 fFlushTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
Brian Osmanf750fbc2017-02-08 10:47:28 -0500800
801 // If we rendered offscreen, snap an image and push the results to the window's canvas
802 if (offscreenSurface) {
Brian Osmanf6877092017-02-13 09:39:57 -0500803 fLastImage = offscreenSurface->makeImageSnapshot();
Brian Osmanf750fbc2017-02-08 10:47:28 -0500804
805 // Tag the image with the sRGB gamut, so no further color space conversion happens
Brian Osmane0d4fba2017-03-15 10:24:55 -0400806 sk_sp<SkColorSpace> srgb = (ColorMode::kColorManagedLinearF16 == fColorMode)
Brian Osmanf750fbc2017-02-08 10:47:28 -0500807 ? SkColorSpace::MakeSRGBLinear() : SkColorSpace::MakeSRGB();
Brian Osmane0d4fba2017-03-15 10:24:55 -0400808 auto retaggedImage = SkImageMakeRasterCopyAndAssignColorSpace(fLastImage.get(), srgb.get());
Brian Salomonbf52e3d2017-02-22 15:21:11 -0500809 SkPaint paint;
810 paint.setBlendMode(SkBlendMode::kSrc);
811 canvas->drawImage(retaggedImage, 0, 0, &paint);
liyuqian74959a12016-06-16 14:10:34 -0700812 }
liyuqian6f163d22016-06-13 12:26:45 -0700813}
814
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700815void Viewer::onBackendCreated() {
816 this->updateTitle();
817 this->updateUIState();
818 this->setupCurrentSlide(-1);
819 fWindow->show();
820 fWindow->inval();
821}
Jim Van Verth6f449692017-02-14 15:16:46 -0500822
Christopher Dalton443ec1b2017-02-24 13:22:53 -0700823void Viewer::onPaint(SkCanvas* canvas) {
Brian Osman79086b92017-02-10 13:36:16 -0500824 // Update ImGui input
825 ImGuiIO& io = ImGui::GetIO();
826 io.DeltaTime = 1.0f / 60.0f;
827 io.DisplaySize.x = static_cast<float>(fWindow->width());
828 io.DisplaySize.y = static_cast<float>(fWindow->height());
829
830 io.KeyAlt = io.KeysDown[static_cast<int>(Window::Key::kOption)];
831 io.KeyCtrl = io.KeysDown[static_cast<int>(Window::Key::kCtrl)];
832 io.KeyShift = io.KeysDown[static_cast<int>(Window::Key::kShift)];
833
834 ImGui::NewFrame();
835
Brian Osmanf750fbc2017-02-08 10:47:28 -0500836 drawSlide(canvas);
jvanverthc265a922016-04-08 12:51:45 -0700837
Brian Osman1df161a2017-02-09 12:10:20 -0500838 // Advance our timing bookkeeping
839 fCurrentMeasurement = (fCurrentMeasurement + 1) & (kMeasurementCount - 1);
840 SkASSERT(fCurrentMeasurement < kMeasurementCount);
841
842 // Draw any overlays or UI that we don't want timed
jvanverthc265a922016-04-08 12:51:45 -0700843 if (fDisplayStats) {
844 drawStats(canvas);
845 }
brianosman622c8d52016-05-10 06:50:49 -0700846 fCommands.drawHelp(canvas);
liyuqian2edb0f42016-07-06 14:11:32 -0700847
Brian Osman79086b92017-02-10 13:36:16 -0500848 drawImGui(canvas);
849
Brian Osman1df161a2017-02-09 12:10:20 -0500850 // Update the FPS
851 updateUIState();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700852}
853
jvanverth814e38d2016-06-06 08:48:47 -0700854bool Viewer::onTouch(intptr_t owner, Window::InputState state, float x, float y) {
liyuqiand3cdbca2016-05-17 12:44:20 -0700855 void* castedOwner = reinterpret_cast<void*>(owner);
liyuqiane46e4f02016-05-20 07:32:19 -0700856 SkPoint touchPoint = fDefaultMatrixInv.mapXY(x, y);
liyuqiand3cdbca2016-05-17 12:44:20 -0700857 switch (state) {
858 case Window::kUp_InputState: {
859 fGesture.touchEnd(castedOwner);
860 break;
861 }
862 case Window::kDown_InputState: {
liyuqiane46e4f02016-05-20 07:32:19 -0700863 fGesture.touchBegin(castedOwner, touchPoint.fX, touchPoint.fY);
liyuqiand3cdbca2016-05-17 12:44:20 -0700864 break;
865 }
866 case Window::kMove_InputState: {
liyuqiane46e4f02016-05-20 07:32:19 -0700867 fGesture.touchMoved(castedOwner, touchPoint.fX, touchPoint.fY);
liyuqiand3cdbca2016-05-17 12:44:20 -0700868 break;
869 }
870 }
871 fWindow->inval();
872 return true;
873}
874
Jim Van Verthe7705782017-05-04 14:00:59 -0400875bool Viewer::onMouse(float x, float y, Window::InputState state, uint32_t modifiers) {
876
877 SkPoint touchPoint = fDefaultMatrixInv.mapXY(x, y);
878 switch (state) {
879 case Window::kUp_InputState: {
880 fGesture.touchEnd(nullptr);
881 break;
882 }
883 case Window::kDown_InputState: {
884 fGesture.touchBegin(nullptr, touchPoint.fX, touchPoint.fY);
885 break;
886 }
887 case Window::kMove_InputState: {
888 fGesture.touchMoved(nullptr, touchPoint.fX, touchPoint.fY);
889 break;
890 }
891 }
892 fWindow->inval();
893 return true;
894}
895
jvanverth34524262016-05-04 13:49:13 -0700896void Viewer::drawStats(SkCanvas* canvas) {
jvanverth3d6ed3a2016-04-07 11:09:51 -0700897 static const float kPixelPerMS = 2.0f;
898 static const int kDisplayWidth = 130;
899 static const int kDisplayHeight = 100;
900 static const int kDisplayPadding = 10;
901 static const int kGraphPadding = 3;
902 static const SkScalar kBaseMS = 1000.f / 60.f; // ms/frame to hit 60 fps
903
Mike Reed3661bc92017-02-22 13:21:42 -0500904 SkISize canvasSize = canvas->getBaseLayerSize();
jvanverth3d6ed3a2016-04-07 11:09:51 -0700905 SkRect rect = SkRect::MakeXYWH(SkIntToScalar(canvasSize.fWidth-kDisplayWidth-kDisplayPadding),
906 SkIntToScalar(kDisplayPadding),
907 SkIntToScalar(kDisplayWidth), SkIntToScalar(kDisplayHeight));
908 SkPaint paint;
909 canvas->save();
910
djsollen12d62a72016-04-21 07:59:44 -0700911 if (fWindow->supportsContentRect()) {
912 SkRect contentRect = fWindow->getContentRect();
913 canvas->clipRect(contentRect);
914 canvas->translate(contentRect.fLeft, contentRect.fTop);
915 }
916
jvanverth3d6ed3a2016-04-07 11:09:51 -0700917 canvas->clipRect(rect);
918 paint.setColor(SK_ColorBLACK);
919 canvas->drawRect(rect, paint);
920 // draw the 16ms line
921 paint.setColor(SK_ColorLTGRAY);
922 canvas->drawLine(rect.fLeft, rect.fBottom - kBaseMS*kPixelPerMS,
923 rect.fRight, rect.fBottom - kBaseMS*kPixelPerMS, paint);
924 paint.setColor(SK_ColorRED);
925 paint.setStyle(SkPaint::kStroke_Style);
926 canvas->drawRect(rect, paint);
927
928 int x = SkScalarTruncToInt(rect.fLeft) + kGraphPadding;
929 const int xStep = 2;
jvanverth3d6ed3a2016-04-07 11:09:51 -0700930 int i = fCurrentMeasurement;
931 do {
Brian Osman1df161a2017-02-09 12:10:20 -0500932 // Round to nearest values
933 int animateHeight = (int)(fAnimateTimes[i] * kPixelPerMS + 0.5);
934 int paintHeight = (int)(fPaintTimes[i] * kPixelPerMS + 0.5);
935 int flushHeight = (int)(fFlushTimes[i] * kPixelPerMS + 0.5);
936 int startY = SkScalarTruncToInt(rect.fBottom);
937 int endY = startY - flushHeight;
938 paint.setColor(SK_ColorRED);
939 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
940 SkIntToScalar(x), SkIntToScalar(endY), paint);
941 startY = endY;
942 endY = startY - paintHeight;
943 paint.setColor(SK_ColorGREEN);
944 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
945 SkIntToScalar(x), SkIntToScalar(endY), paint);
946 startY = endY;
947 endY = startY - animateHeight;
948 paint.setColor(SK_ColorMAGENTA);
jvanverth3d6ed3a2016-04-07 11:09:51 -0700949 canvas->drawLine(SkIntToScalar(x), SkIntToScalar(startY),
950 SkIntToScalar(x), SkIntToScalar(endY), paint);
951 i++;
952 i &= (kMeasurementCount - 1); // fast mod
953 x += xStep;
954 } while (i != fCurrentMeasurement);
jvanverth9f372462016-04-06 06:08:59 -0700955
956 canvas->restore();
957}
958
Brian Osmana109e392017-02-24 09:49:14 -0500959static ImVec2 ImGui_DragPrimary(const char* label, float* x, float* y,
960 const ImVec2& pos, const ImVec2& size) {
961 // Transform primaries ([0, 0] - [0.8, 0.9]) to screen coords (including Y-flip)
962 ImVec2 center(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
963
964 // Invisible 10x10 button
965 ImGui::SetCursorScreenPos(ImVec2(center.x - 5, center.y - 5));
966 ImGui::InvisibleButton(label, ImVec2(10, 10));
967
968 if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) {
969 ImGuiIO& io = ImGui::GetIO();
970 // Normalized mouse position, relative to our gamut box
971 ImVec2 mousePosXY((io.MousePos.x - pos.x) / size.x, (io.MousePos.y - pos.y) / size.y);
972 // Clamp to edge of box, convert back to primary scale
973 *x = SkTPin(mousePosXY.x, 0.0f, 1.0f) * 0.8f;
974 *y = SkTPin(1 - mousePosXY.y, 0.0f, 1.0f) * 0.9f;
975 }
976
977 if (ImGui::IsItemHovered()) {
978 ImGui::SetTooltip("x: %.3f\ny: %.3f", *x, *y);
979 }
980
981 // Return screen coordinates for the caller. We could just return center here, but we'd have
982 // one frame of lag during drag.
983 return ImVec2(pos.x + (*x / 0.8f) * size.x, pos.y + (1.0f - (*y / 0.9f)) * size.y);
984}
985
986static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
987 ImDrawList* drawList = ImGui::GetWindowDrawList();
988
989 // The gamut image covers a (0.8 x 0.9) shaped region, so fit our image/canvas to the available
990 // width, and scale the height to maintain aspect ratio.
991 float canvasWidth = SkTMax(ImGui::GetContentRegionAvailWidth(), 50.0f);
992 ImVec2 size = ImVec2(canvasWidth, canvasWidth * (0.9f / 0.8f));
993 ImVec2 pos = ImGui::GetCursorScreenPos();
994
995 // Background image. Only draw a subset of the image, to avoid the regions less than zero.
996 // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
997 // Magic numbers are pixel locations of the origin and upper-right corner.
998 drawList->AddImage(gamutPaint, pos, ImVec2(pos.x + size.x, pos.y + size.y),
999 ImVec2(242, 61), ImVec2(1897, 1922));
1000 ImVec2 endPos = ImGui::GetCursorPos();
1001
1002 // Primary markers
1003 ImVec2 r = ImGui_DragPrimary("R", &primaries->fRX, &primaries->fRY, pos, size);
1004 ImVec2 g = ImGui_DragPrimary("G", &primaries->fGX, &primaries->fGY, pos, size);
1005 ImVec2 b = ImGui_DragPrimary("B", &primaries->fBX, &primaries->fBY, pos, size);
1006 ImVec2 w = ImGui_DragPrimary("W", &primaries->fWX, &primaries->fWY, pos, size);
1007
1008 // Gamut triangle
1009 drawList->AddCircle(r, 5.0f, 0xFF000040);
1010 drawList->AddCircle(g, 5.0f, 0xFF004000);
1011 drawList->AddCircle(b, 5.0f, 0xFF400000);
1012 drawList->AddCircle(w, 5.0f, 0xFFFFFFFF);
1013 drawList->AddTriangle(r, g, b, 0xFFFFFFFF);
1014
1015 // Re-position cursor immediate after the diagram for subsequent controls
1016 ImGui::SetCursorPos(endPos);
1017}
1018
Brian Osman79086b92017-02-10 13:36:16 -05001019void Viewer::drawImGui(SkCanvas* canvas) {
1020 // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1021 if (fShowImGuiTestWindow) {
1022 ImGui::ShowTestWindow(&fShowImGuiTestWindow);
1023 }
1024
1025 if (fShowImGuiDebugWindow) {
Brian Osmana109e392017-02-24 09:49:14 -05001026 // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1027 // always visible, we can end up in a layout feedback loop.
1028 ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiSetCond_FirstUseEver);
Brian Salomon99a33902017-03-07 15:16:34 -05001029 DisplayParams params = fWindow->getRequestedDisplayParams();
1030 bool paramsChanged = false;
Brian Osmana109e392017-02-24 09:49:14 -05001031 if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1032 ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
Brian Osman621491e2017-02-28 15:45:01 -05001033 if (ImGui::CollapsingHeader("Backend")) {
1034 int newBackend = static_cast<int>(fBackendType);
1035 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1036 ImGui::SameLine();
1037 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1038#if defined(SK_VULKAN)
1039 ImGui::SameLine();
1040 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1041#endif
1042 if (newBackend != fBackendType) {
1043 fDeferredActions.push_back([=]() {
1044 this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1045 });
1046 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001047
Brian Salomon99a33902017-03-07 15:16:34 -05001048 const GrContext* ctx = fWindow->getGrContext();
1049 bool* inst = &params.fGrContextOptions.fEnableInstancedRendering;
1050 if (ctx && ImGui::Checkbox("Instanced Rendering", inst)) {
1051 paramsChanged = true;
1052 }
Jim Van Verthfbdc0802017-05-02 16:15:53 -04001053 bool* wire = &params.fGrContextOptions.fWireframeMode;
1054 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1055 paramsChanged = true;
1056 }
Brian Salomon99a33902017-03-07 15:16:34 -05001057
Brian Osman28b12522017-03-08 17:10:24 -05001058 if (ctx) {
1059 int sampleCount = fWindow->sampleCount();
1060 ImGui::Text("MSAA: "); ImGui::SameLine();
1061 ImGui::RadioButton("0", &sampleCount, 0); ImGui::SameLine();
1062 ImGui::RadioButton("4", &sampleCount, 4); ImGui::SameLine();
1063 ImGui::RadioButton("8", &sampleCount, 8); ImGui::SameLine();
1064 ImGui::RadioButton("16", &sampleCount, 16);
1065
1066 if (sampleCount != params.fMSAASampleCount) {
1067 params.fMSAASampleCount = sampleCount;
1068 paramsChanged = true;
1069 }
1070 }
1071
Brian Osman8a9de3d2017-03-01 14:59:05 -05001072 if (ImGui::TreeNode("Path Renderers")) {
Brian Osman8a9de3d2017-03-01 14:59:05 -05001073 GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
Brian Osman8a9de3d2017-03-01 14:59:05 -05001074 auto prButton = [&](GpuPathRenderers x) {
1075 if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001076 if (x != params.fGrContextOptions.fGpuPathRenderers) {
1077 params.fGrContextOptions.fGpuPathRenderers = x;
1078 paramsChanged = true;
1079 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001080 }
1081 };
1082
1083 if (!ctx) {
1084 ImGui::RadioButton("Software", true);
1085 } else if (fWindow->sampleCount()) {
1086 prButton(GpuPathRenderers::kAll);
1087 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1088 prButton(GpuPathRenderers::kStencilAndCover);
1089 }
1090 if (ctx->caps()->sampleShadingSupport()) {
1091 prButton(GpuPathRenderers::kMSAA);
1092 }
1093 prButton(GpuPathRenderers::kTessellating);
1094 prButton(GpuPathRenderers::kDefault);
1095 prButton(GpuPathRenderers::kNone);
1096 } else {
1097 prButton(GpuPathRenderers::kAll);
Jim Van Verth83010462017-03-16 08:45:39 -04001098 prButton(GpuPathRenderers::kSmall);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001099 prButton(GpuPathRenderers::kTessellating);
1100 prButton(GpuPathRenderers::kNone);
1101 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001102 ImGui::TreePop();
1103 }
Brian Osman621491e2017-02-28 15:45:01 -05001104 }
1105
Brian Osman79086b92017-02-10 13:36:16 -05001106 if (ImGui::CollapsingHeader("Slide")) {
1107 static ImGuiTextFilter filter;
1108 filter.Draw();
1109 int previousSlide = fCurrentSlide;
1110 fCurrentSlide = 0;
1111 for (auto slide : fSlides) {
1112 if (filter.PassFilter(slide->getName().c_str())) {
1113 ImGui::BulletText("%s", slide->getName().c_str());
1114 if (ImGui::IsItemClicked()) {
1115 setupCurrentSlide(previousSlide);
1116 break;
1117 }
1118 }
1119 ++fCurrentSlide;
1120 }
1121 if (fCurrentSlide >= fSlides.count()) {
1122 fCurrentSlide = previousSlide;
1123 }
1124 }
Brian Osmana109e392017-02-24 09:49:14 -05001125
1126 if (ImGui::CollapsingHeader("Color Mode")) {
Brian Osman92004802017-03-06 11:47:26 -05001127 ColorMode newMode = fColorMode;
1128 auto cmButton = [&](ColorMode mode, const char* label) {
1129 if (ImGui::RadioButton(label, mode == fColorMode)) {
1130 newMode = mode;
1131 }
1132 };
1133
1134 cmButton(ColorMode::kLegacy, "Legacy 8888");
1135 cmButton(ColorMode::kColorManagedSRGB8888_NonLinearBlending,
1136 "Color Managed 8888 (Nonlinear blending)");
1137 cmButton(ColorMode::kColorManagedSRGB8888, "Color Managed 8888");
1138 cmButton(ColorMode::kColorManagedLinearF16, "Color Managed F16");
1139
1140 if (newMode != fColorMode) {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001141 // It isn't safe to switch color mode now (in the middle of painting). We might
1142 // tear down the back-end, etc... Defer this change until the next onIdle.
1143 fDeferredActions.push_back([=]() {
Brian Osman92004802017-03-06 11:47:26 -05001144 this->setColorMode(newMode);
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001145 });
Brian Osmana109e392017-02-24 09:49:14 -05001146 }
1147
1148 // Pick from common gamuts:
1149 int primariesIdx = 4; // Default: Custom
1150 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1151 if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1152 primariesIdx = i;
1153 break;
1154 }
1155 }
1156
1157 if (ImGui::Combo("Primaries", &primariesIdx,
1158 "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
1159 if (primariesIdx >= 0 && primariesIdx <= 3) {
1160 fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
1161 }
1162 }
1163
1164 // Allow direct editing of gamut
1165 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
1166 }
Brian Osman79086b92017-02-10 13:36:16 -05001167 }
Brian Salomon99a33902017-03-07 15:16:34 -05001168 if (paramsChanged) {
1169 fDeferredActions.push_back([=]() {
1170 fWindow->setRequestedDisplayParams(params);
1171 fWindow->inval();
1172 this->updateTitle();
1173 });
1174 }
Brian Osman79086b92017-02-10 13:36:16 -05001175 ImGui::End();
1176 }
1177
Brian Osmanf6877092017-02-13 09:39:57 -05001178 SkPaint zoomImagePaint;
1179 if (fShowZoomWindow && fLastImage) {
1180 if (ImGui::Begin("Zoom", &fShowZoomWindow, ImVec2(200, 200))) {
1181 static int zoomFactor = 4;
1182 ImGui::SliderInt("Scale", &zoomFactor, 1, 16);
1183
Mike Reed0acd7952017-04-28 11:12:19 -04001184 zoomImagePaint.setShader(fLastImage->makeShader());
Brian Osmanf6877092017-02-13 09:39:57 -05001185 zoomImagePaint.setColor(SK_ColorWHITE);
1186
1187 // Zoom by shrinking the corner UVs towards the mouse cursor
1188 ImVec2 mousePos = ImGui::GetMousePos();
1189 ImVec2 avail = ImGui::GetContentRegionAvail();
1190
1191 ImVec2 zoomHalfExtents = ImVec2((avail.x * 0.5f) / zoomFactor,
1192 (avail.y * 0.5f) / zoomFactor);
1193 ImGui::Image(&zoomImagePaint, avail,
1194 ImVec2(mousePos.x - zoomHalfExtents.x, mousePos.y - zoomHalfExtents.y),
1195 ImVec2(mousePos.x + zoomHalfExtents.x, mousePos.y + zoomHalfExtents.y));
1196 }
1197
1198 ImGui::End();
1199 }
1200
Brian Osman79086b92017-02-10 13:36:16 -05001201 // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
1202 // (widgets, etc...) that have been issued
1203 ImGui::Render();
1204
1205 // Then we fetch the most recent data, and convert it so we can render with Skia
1206 const ImDrawData* drawData = ImGui::GetDrawData();
1207 SkTDArray<SkPoint> pos;
1208 SkTDArray<SkPoint> uv;
1209 SkTDArray<SkColor> color;
Brian Osman79086b92017-02-10 13:36:16 -05001210
1211 for (int i = 0; i < drawData->CmdListsCount; ++i) {
1212 const ImDrawList* drawList = drawData->CmdLists[i];
1213
1214 // De-interleave all vertex data (sigh), convert to Skia types
1215 pos.rewind(); uv.rewind(); color.rewind();
1216 for (int i = 0; i < drawList->VtxBuffer.size(); ++i) {
1217 const ImDrawVert& vert = drawList->VtxBuffer[i];
1218 pos.push(SkPoint::Make(vert.pos.x, vert.pos.y));
1219 uv.push(SkPoint::Make(vert.uv.x, vert.uv.y));
1220 color.push(vert.col);
1221 }
1222 // ImGui colors are RGBA
1223 SkSwapRB(color.begin(), color.begin(), color.count());
1224
1225 int indexOffset = 0;
1226
1227 // Draw everything with canvas.drawVertices...
1228 for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
1229 const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
1230
1231 // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
1232 if (drawCmd->UserCallback) {
1233 drawCmd->UserCallback(drawList, drawCmd);
1234 } else {
Brian Osmanf6877092017-02-13 09:39:57 -05001235 SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
1236 SkASSERT(paint);
1237
Brian Osman79086b92017-02-10 13:36:16 -05001238 canvas->save();
1239 canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
1240 drawCmd->ClipRect.z, drawCmd->ClipRect.w));
Mike Reed887cdf12017-04-03 11:11:09 -04001241 canvas->drawVertices(SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
1242 drawList->VtxBuffer.size(), pos.begin(),
1243 uv.begin(), color.begin(),
1244 drawCmd->ElemCount,
1245 drawList->IdxBuffer.begin() + indexOffset),
1246 SkBlendMode::kModulate, *paint);
Brian Osman79086b92017-02-10 13:36:16 -05001247 indexOffset += drawCmd->ElemCount;
1248 canvas->restore();
1249 }
1250 }
1251 }
1252}
1253
liyuqian2edb0f42016-07-06 14:11:32 -07001254void Viewer::onIdle() {
Brian Osmanfd8f4d52017-02-24 11:57:23 -05001255 for (int i = 0; i < fDeferredActions.count(); ++i) {
1256 fDeferredActions[i]();
1257 }
1258 fDeferredActions.reset();
1259
Brian Osman1df161a2017-02-09 12:10:20 -05001260 double startTime = SkTime::GetMSecs();
jvanverthc265a922016-04-08 12:51:45 -07001261 fAnimTimer.updateTime();
Brian Osman1df161a2017-02-09 12:10:20 -05001262 bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer);
1263 fAnimateTimes[fCurrentMeasurement] = SkTime::GetMSecs() - startTime;
1264
Brian Osman79086b92017-02-10 13:36:16 -05001265 ImGuiIO& io = ImGui::GetIO();
1266 if (animateWantsInval || fDisplayStats || fRefresh || io.MetricsActiveWindows) {
jvanverthc265a922016-04-08 12:51:45 -07001267 fWindow->inval();
1268 }
jvanverth9f372462016-04-06 06:08:59 -07001269}
liyuqiane5a6cd92016-05-27 08:52:52 -07001270
1271void Viewer::updateUIState() {
csmartdalton578f0642017-02-24 16:04:47 -07001272 if (!fWindow) {
1273 return;
1274 }
1275 if (fWindow->sampleCount() < 0) {
1276 return; // Surface hasn't been created yet.
1277 }
1278
liyuqianb73c24b2016-06-03 08:47:23 -07001279 // Slide state
liyuqiane5a6cd92016-05-27 08:52:52 -07001280 Json::Value slideState(Json::objectValue);
1281 slideState[kName] = kSlideStateName;
1282 slideState[kValue] = fSlides[fCurrentSlide]->getName().c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001283 if (fAllSlideNames.size() == 0) {
1284 for(auto slide : fSlides) {
1285 fAllSlideNames.append(Json::Value(slide->getName().c_str()));
1286 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001287 }
liyuqian1f508fd2016-06-07 06:57:40 -07001288 slideState[kOptions] = fAllSlideNames;
liyuqiane5a6cd92016-05-27 08:52:52 -07001289
liyuqianb73c24b2016-06-03 08:47:23 -07001290 // Backend state
liyuqiane5a6cd92016-05-27 08:52:52 -07001291 Json::Value backendState(Json::objectValue);
1292 backendState[kName] = kBackendStateName;
liyuqian6cb70252016-06-02 12:16:25 -07001293 backendState[kValue] = kBackendTypeStrings[fBackendType];
liyuqiane5a6cd92016-05-27 08:52:52 -07001294 backendState[kOptions] = Json::Value(Json::arrayValue);
liyuqianb73c24b2016-06-03 08:47:23 -07001295 for (auto str : kBackendTypeStrings) {
liyuqian6cb70252016-06-02 12:16:25 -07001296 backendState[kOptions].append(Json::Value(str));
1297 }
liyuqiane5a6cd92016-05-27 08:52:52 -07001298
csmartdalton578f0642017-02-24 16:04:47 -07001299 // MSAA state
1300 Json::Value msaaState(Json::objectValue);
1301 msaaState[kName] = kMSAAStateName;
1302 msaaState[kValue] = fWindow->sampleCount();
1303 msaaState[kOptions] = Json::Value(Json::arrayValue);
1304 if (sk_app::Window::kRaster_BackendType == fBackendType) {
1305 msaaState[kOptions].append(Json::Value(0));
1306 } else {
1307 for (int msaa : {0, 4, 8, 16}) {
1308 msaaState[kOptions].append(Json::Value(msaa));
1309 }
1310 }
1311
csmartdalton61cd31a2017-02-27 17:00:53 -07001312 // Path renderer state
1313 GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1314 Json::Value prState(Json::objectValue);
1315 prState[kName] = kPathRendererStateName;
1316 prState[kValue] = gPathRendererNames[pr];
1317 prState[kOptions] = Json::Value(Json::arrayValue);
1318 const GrContext* ctx = fWindow->getGrContext();
1319 if (!ctx) {
1320 prState[kOptions].append("Software");
1321 } else if (fWindow->sampleCount()) {
1322 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
1323 if (ctx->caps()->shaderCaps()->pathRenderingSupport()) {
1324 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kStencilAndCover]);
1325 }
1326 if (ctx->caps()->sampleShadingSupport()) {
1327 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kMSAA]);
1328 }
Brian Osman8a9de3d2017-03-01 14:59:05 -05001329 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001330 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kDefault]);
1331 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1332 } else {
1333 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kAll]);
Jim Van Verth83010462017-03-16 08:45:39 -04001334 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kSmall]);
Brian Osman8a9de3d2017-03-01 14:59:05 -05001335 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kTessellating]);
csmartdalton61cd31a2017-02-27 17:00:53 -07001336 prState[kOptions].append(gPathRendererNames[GpuPathRenderers::kNone]);
1337 }
1338
Brian Salomon99a33902017-03-07 15:16:34 -05001339 // Instanced rendering state
1340 Json::Value instState(Json::objectValue);
1341 instState[kName] = kInstancedRenderingStateName;
1342 if (ctx) {
1343 if (fWindow->getRequestedDisplayParams().fGrContextOptions.fEnableInstancedRendering) {
1344 instState[kValue] = kON;
1345 } else {
1346 instState[kValue] = kOFF;
1347 }
1348 instState[kOptions] = Json::Value(Json::arrayValue);
1349 instState[kOptions].append(kOFF);
1350 instState[kOptions].append(kON);
1351 }
1352
liyuqianb73c24b2016-06-03 08:47:23 -07001353 // Softkey state
1354 Json::Value softkeyState(Json::objectValue);
1355 softkeyState[kName] = kSoftkeyStateName;
1356 softkeyState[kValue] = kSoftkeyHint;
1357 softkeyState[kOptions] = Json::Value(Json::arrayValue);
1358 softkeyState[kOptions].append(kSoftkeyHint);
1359 for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
1360 softkeyState[kOptions].append(Json::Value(softkey.c_str()));
1361 }
1362
liyuqian1f508fd2016-06-07 06:57:40 -07001363 // FPS state
1364 Json::Value fpsState(Json::objectValue);
1365 fpsState[kName] = kFpsStateName;
Brian Osman1df161a2017-02-09 12:10:20 -05001366 int idx = (fCurrentMeasurement + (kMeasurementCount - 1)) & (kMeasurementCount - 1);
1367 fpsState[kValue] = SkStringPrintf("%8.3lf ms\n\nA %8.3lf\nP %8.3lf\nF%8.3lf",
1368 fAnimateTimes[idx] + fPaintTimes[idx] + fFlushTimes[idx],
1369 fAnimateTimes[idx],
1370 fPaintTimes[idx],
1371 fFlushTimes[idx]).c_str();
liyuqian1f508fd2016-06-07 06:57:40 -07001372 fpsState[kOptions] = Json::Value(Json::arrayValue);
1373
liyuqiane5a6cd92016-05-27 08:52:52 -07001374 Json::Value state(Json::arrayValue);
1375 state.append(slideState);
1376 state.append(backendState);
csmartdalton578f0642017-02-24 16:04:47 -07001377 state.append(msaaState);
csmartdalton61cd31a2017-02-27 17:00:53 -07001378 state.append(prState);
Brian Salomon99a33902017-03-07 15:16:34 -05001379 state.append(instState);
liyuqianb73c24b2016-06-03 08:47:23 -07001380 state.append(softkeyState);
liyuqian1f508fd2016-06-07 06:57:40 -07001381 state.append(fpsState);
liyuqiane5a6cd92016-05-27 08:52:52 -07001382
1383 fWindow->setUIState(state);
1384}
1385
1386void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
liyuqian6cb70252016-06-02 12:16:25 -07001387 // For those who will add more features to handle the state change in this function:
1388 // After the change, please call updateUIState no notify the frontend (e.g., Android app).
1389 // For example, after slide change, updateUIState is called inside setupCurrentSlide;
1390 // after backend change, updateUIState is called in this function.
liyuqiane5a6cd92016-05-27 08:52:52 -07001391 if (stateName.equals(kSlideStateName)) {
1392 int previousSlide = fCurrentSlide;
1393 fCurrentSlide = 0;
1394 for(auto slide : fSlides) {
1395 if (slide->getName().equals(stateValue)) {
Brian Salomon99a33902017-03-07 15:16:34 -05001396 this->setupCurrentSlide(previousSlide);
liyuqiane5a6cd92016-05-27 08:52:52 -07001397 break;
1398 }
1399 fCurrentSlide++;
1400 }
1401 if (fCurrentSlide >= fSlides.count()) {
1402 fCurrentSlide = previousSlide;
1403 SkDebugf("Slide not found: %s", stateValue.c_str());
1404 }
liyuqian6cb70252016-06-02 12:16:25 -07001405 } else if (stateName.equals(kBackendStateName)) {
1406 for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
1407 if (stateValue.equals(kBackendTypeStrings[i])) {
1408 if (fBackendType != i) {
1409 fBackendType = (sk_app::Window::BackendType)i;
1410 fWindow->detach();
csmartdalton578f0642017-02-24 16:04:47 -07001411 fWindow->attach(fBackendType);
liyuqian6cb70252016-06-02 12:16:25 -07001412 }
1413 break;
1414 }
1415 }
csmartdalton578f0642017-02-24 16:04:47 -07001416 } else if (stateName.equals(kMSAAStateName)) {
1417 DisplayParams params = fWindow->getRequestedDisplayParams();
1418 int sampleCount = atoi(stateValue.c_str());
1419 if (sampleCount != params.fMSAASampleCount) {
1420 params.fMSAASampleCount = sampleCount;
1421 fWindow->setRequestedDisplayParams(params);
1422 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001423 this->updateTitle();
1424 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001425 }
1426 } else if (stateName.equals(kPathRendererStateName)) {
1427 DisplayParams params = fWindow->getRequestedDisplayParams();
1428 for (const auto& pair : gPathRendererNames) {
1429 if (pair.second == stateValue.c_str()) {
1430 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
1431 params.fGrContextOptions.fGpuPathRenderers = pair.first;
1432 fWindow->setRequestedDisplayParams(params);
1433 fWindow->inval();
Brian Salomon99a33902017-03-07 15:16:34 -05001434 this->updateTitle();
1435 this->updateUIState();
csmartdalton61cd31a2017-02-27 17:00:53 -07001436 }
1437 break;
1438 }
csmartdalton578f0642017-02-24 16:04:47 -07001439 }
Brian Salomon99a33902017-03-07 15:16:34 -05001440 } else if (stateName.equals(kInstancedRenderingStateName)) {
1441 DisplayParams params = fWindow->getRequestedDisplayParams();
1442 bool value = !strcmp(stateValue.c_str(), kON);
1443 if (params.fGrContextOptions.fEnableInstancedRendering != value) {
1444 params.fGrContextOptions.fEnableInstancedRendering = value;
1445 fWindow->setRequestedDisplayParams(params);
1446 fWindow->inval();
1447 this->updateTitle();
1448 this->updateUIState();
1449 }
liyuqianb73c24b2016-06-03 08:47:23 -07001450 } else if (stateName.equals(kSoftkeyStateName)) {
1451 if (!stateValue.equals(kSoftkeyHint)) {
1452 fCommands.onSoftkey(stateValue);
Brian Salomon99a33902017-03-07 15:16:34 -05001453 this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
liyuqianb73c24b2016-06-03 08:47:23 -07001454 }
liyuqian2edb0f42016-07-06 14:11:32 -07001455 } else if (stateName.equals(kRefreshStateName)) {
1456 // This state is actually NOT in the UI state.
1457 // We use this to allow Android to quickly set bool fRefresh.
1458 fRefresh = stateValue.equals(kON);
liyuqiane5a6cd92016-05-27 08:52:52 -07001459 } else {
1460 SkDebugf("Unknown stateName: %s", stateName.c_str());
1461 }
1462}
Brian Osman79086b92017-02-10 13:36:16 -05001463
1464bool Viewer::onKey(sk_app::Window::Key key, sk_app::Window::InputState state, uint32_t modifiers) {
1465 return fCommands.onKey(key, state, modifiers);
1466}
1467
1468bool Viewer::onChar(SkUnichar c, uint32_t modifiers) {
Jim Van Verth6f449692017-02-14 15:16:46 -05001469 if (fSlides[fCurrentSlide]->onChar(c)) {
1470 fWindow->inval();
1471 return true;
1472 }
1473
Brian Osman79086b92017-02-10 13:36:16 -05001474 return fCommands.onChar(c, modifiers);
1475}