bootmanager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <QApplication>
  5. #include <QHBoxLayout>
  6. #include <QKeyEvent>
  7. #include <QOffscreenSurface>
  8. #include <QOpenGLWindow>
  9. #include <QPainter>
  10. #include <QScreen>
  11. #include <QWindow>
  12. #include <fmt/format.h>
  13. #include "common/microprofile.h"
  14. #include "common/scm_rev.h"
  15. #include "core/core.h"
  16. #include "core/frontend/framebuffer_layout.h"
  17. #include "core/settings.h"
  18. #include "input_common/keyboard.h"
  19. #include "input_common/main.h"
  20. #include "input_common/motion_emu.h"
  21. #include "video_core/renderer_base.h"
  22. #include "video_core/video_core.h"
  23. #include "yuzu/bootmanager.h"
  24. #include "yuzu/main.h"
  25. EmuThread::EmuThread(GRenderWindow* render_window) : render_window(render_window) {}
  26. void EmuThread::run() {
  27. render_window->MakeCurrent();
  28. MicroProfileOnThreadCreate("EmuThread");
  29. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  30. Core::System::GetInstance().Renderer().Rasterizer().LoadDiskResources(
  31. stop_run, [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  32. emit LoadProgress(stage, value, total);
  33. });
  34. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  35. if (Settings::values.use_asynchronous_gpu_emulation) {
  36. // Release OpenGL context for the GPU thread
  37. render_window->DoneCurrent();
  38. }
  39. // Holds whether the cpu was running during the last iteration,
  40. // so that the DebugModeLeft signal can be emitted before the
  41. // next execution step
  42. bool was_active = false;
  43. while (!stop_run) {
  44. if (running) {
  45. if (!was_active)
  46. emit DebugModeLeft();
  47. Core::System::ResultStatus result = Core::System::GetInstance().RunLoop();
  48. if (result != Core::System::ResultStatus::Success) {
  49. this->SetRunning(false);
  50. emit ErrorThrown(result, Core::System::GetInstance().GetStatusDetails());
  51. }
  52. was_active = running || exec_step;
  53. if (!was_active && !stop_run)
  54. emit DebugModeEntered();
  55. } else if (exec_step) {
  56. if (!was_active)
  57. emit DebugModeLeft();
  58. exec_step = false;
  59. Core::System::GetInstance().SingleStep();
  60. emit DebugModeEntered();
  61. yieldCurrentThread();
  62. was_active = false;
  63. } else {
  64. std::unique_lock lock{running_mutex};
  65. running_cv.wait(lock, [this] { return IsRunning() || exec_step || stop_run; });
  66. }
  67. }
  68. // Shutdown the core emulation
  69. Core::System::GetInstance().Shutdown();
  70. #if MICROPROFILE_ENABLED
  71. MicroProfileOnThreadExit();
  72. #endif
  73. render_window->moveContext();
  74. }
  75. class GGLContext : public Core::Frontend::GraphicsContext {
  76. public:
  77. explicit GGLContext(QOpenGLContext* shared_context) : shared_context{shared_context} {
  78. context.setFormat(shared_context->format());
  79. context.setShareContext(shared_context);
  80. context.create();
  81. }
  82. void MakeCurrent() override {
  83. context.makeCurrent(shared_context->surface());
  84. }
  85. void DoneCurrent() override {
  86. context.doneCurrent();
  87. }
  88. void SwapBuffers() override {}
  89. private:
  90. QOpenGLContext* shared_context;
  91. QOpenGLContext context;
  92. };
  93. // This class overrides paintEvent and resizeEvent to prevent the GUI thread from stealing GL
  94. // context.
  95. // The corresponding functionality is handled in EmuThread instead
  96. class GGLWidgetInternal : public QOpenGLWindow {
  97. public:
  98. GGLWidgetInternal(GRenderWindow* parent, QOpenGLContext* shared_context)
  99. : QOpenGLWindow(shared_context), parent(parent) {}
  100. void paintEvent(QPaintEvent* ev) override {
  101. if (do_painting) {
  102. QPainter painter(this);
  103. }
  104. }
  105. void resizeEvent(QResizeEvent* ev) override {
  106. parent->OnClientAreaResized(ev->size().width(), ev->size().height());
  107. parent->OnFramebufferSizeChanged();
  108. }
  109. void keyPressEvent(QKeyEvent* event) override {
  110. InputCommon::GetKeyboard()->PressKey(event->key());
  111. }
  112. void keyReleaseEvent(QKeyEvent* event) override {
  113. InputCommon::GetKeyboard()->ReleaseKey(event->key());
  114. }
  115. void mousePressEvent(QMouseEvent* event) override {
  116. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  117. return; // touch input is handled in TouchBeginEvent
  118. const auto pos{event->pos()};
  119. if (event->button() == Qt::LeftButton) {
  120. const auto [x, y] = parent->ScaleTouch(pos);
  121. parent->TouchPressed(x, y);
  122. } else if (event->button() == Qt::RightButton) {
  123. InputCommon::GetMotionEmu()->BeginTilt(pos.x(), pos.y());
  124. }
  125. }
  126. void mouseMoveEvent(QMouseEvent* event) override {
  127. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  128. return; // touch input is handled in TouchUpdateEvent
  129. const auto pos{event->pos()};
  130. const auto [x, y] = parent->ScaleTouch(pos);
  131. parent->TouchMoved(x, y);
  132. InputCommon::GetMotionEmu()->Tilt(pos.x(), pos.y());
  133. }
  134. void mouseReleaseEvent(QMouseEvent* event) override {
  135. if (event->source() == Qt::MouseEventSynthesizedBySystem)
  136. return; // touch input is handled in TouchEndEvent
  137. if (event->button() == Qt::LeftButton)
  138. parent->TouchReleased();
  139. else if (event->button() == Qt::RightButton)
  140. InputCommon::GetMotionEmu()->EndTilt();
  141. }
  142. void DisablePainting() {
  143. do_painting = false;
  144. }
  145. void EnablePainting() {
  146. do_painting = true;
  147. }
  148. private:
  149. GRenderWindow* parent;
  150. bool do_painting;
  151. };
  152. GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread)
  153. : QWidget(parent), emu_thread(emu_thread) {
  154. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  155. .arg(QString::fromUtf8(Common::g_build_name),
  156. QString::fromUtf8(Common::g_scm_branch),
  157. QString::fromUtf8(Common::g_scm_desc)));
  158. setAttribute(Qt::WA_AcceptTouchEvents);
  159. InputCommon::Init();
  160. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
  161. }
  162. GRenderWindow::~GRenderWindow() {
  163. InputCommon::Shutdown();
  164. }
  165. void GRenderWindow::moveContext() {
  166. DoneCurrent();
  167. // If the thread started running, move the GL Context to the new thread. Otherwise, move it
  168. // back.
  169. auto thread = (QThread::currentThread() == qApp->thread() && emu_thread != nullptr)
  170. ? emu_thread
  171. : qApp->thread();
  172. context->moveToThread(thread);
  173. }
  174. void GRenderWindow::SwapBuffers() {
  175. // In our multi-threaded QWidget use case we shouldn't need to call `makeCurrent`,
  176. // since we never call `doneCurrent` in this thread.
  177. // However:
  178. // - The Qt debug runtime prints a bogus warning on the console if `makeCurrent` wasn't called
  179. // since the last time `swapBuffers` was executed;
  180. // - On macOS, if `makeCurrent` isn't called explicitly, resizing the buffer breaks.
  181. context->makeCurrent(child);
  182. context->swapBuffers(child);
  183. if (!first_frame) {
  184. emit FirstFrameDisplayed();
  185. first_frame = true;
  186. }
  187. }
  188. void GRenderWindow::MakeCurrent() {
  189. context->makeCurrent(child);
  190. }
  191. void GRenderWindow::DoneCurrent() {
  192. context->doneCurrent();
  193. }
  194. void GRenderWindow::PollEvents() {}
  195. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  196. //
  197. // Older versions get the window size (density independent pixels),
  198. // and hence, do not support DPI scaling ("retina" displays).
  199. // The result will be a viewport that is smaller than the extent of the window.
  200. void GRenderWindow::OnFramebufferSizeChanged() {
  201. // Screen changes potentially incur a change in screen DPI, hence we should update the
  202. // framebuffer size
  203. qreal pixelRatio = GetWindowPixelRatio();
  204. unsigned width = child->QPaintDevice::width() * pixelRatio;
  205. unsigned height = child->QPaintDevice::height() * pixelRatio;
  206. UpdateCurrentFramebufferLayout(width, height);
  207. }
  208. void GRenderWindow::ForwardKeyPressEvent(QKeyEvent* event) {
  209. if (child) {
  210. child->keyPressEvent(event);
  211. }
  212. }
  213. void GRenderWindow::ForwardKeyReleaseEvent(QKeyEvent* event) {
  214. if (child) {
  215. child->keyReleaseEvent(event);
  216. }
  217. }
  218. void GRenderWindow::BackupGeometry() {
  219. geometry = QWidget::saveGeometry();
  220. }
  221. void GRenderWindow::RestoreGeometry() {
  222. // We don't want to back up the geometry here (obviously)
  223. QWidget::restoreGeometry(geometry);
  224. }
  225. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  226. // Make sure users of this class don't need to deal with backing up the geometry themselves
  227. QWidget::restoreGeometry(geometry);
  228. BackupGeometry();
  229. }
  230. QByteArray GRenderWindow::saveGeometry() {
  231. // If we are a top-level widget, store the current geometry
  232. // otherwise, store the last backup
  233. if (parent() == nullptr) {
  234. return QWidget::saveGeometry();
  235. }
  236. return geometry;
  237. }
  238. qreal GRenderWindow::GetWindowPixelRatio() const {
  239. // windowHandle() might not be accessible until the window is displayed to screen.
  240. return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
  241. }
  242. std::pair<unsigned, unsigned> GRenderWindow::ScaleTouch(const QPointF pos) const {
  243. const qreal pixel_ratio = GetWindowPixelRatio();
  244. return {static_cast<unsigned>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  245. static_cast<unsigned>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  246. }
  247. void GRenderWindow::closeEvent(QCloseEvent* event) {
  248. emit Closed();
  249. QWidget::closeEvent(event);
  250. }
  251. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  252. // TouchBegin always has exactly one touch point, so take the .first()
  253. const auto [x, y] = ScaleTouch(event->touchPoints().first().pos());
  254. this->TouchPressed(x, y);
  255. }
  256. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  257. QPointF pos;
  258. int active_points = 0;
  259. // average all active touch points
  260. for (const auto tp : event->touchPoints()) {
  261. if (tp.state() & (Qt::TouchPointPressed | Qt::TouchPointMoved | Qt::TouchPointStationary)) {
  262. active_points++;
  263. pos += tp.pos();
  264. }
  265. }
  266. pos /= active_points;
  267. const auto [x, y] = ScaleTouch(pos);
  268. this->TouchMoved(x, y);
  269. }
  270. void GRenderWindow::TouchEndEvent() {
  271. this->TouchReleased();
  272. }
  273. bool GRenderWindow::event(QEvent* event) {
  274. if (event->type() == QEvent::TouchBegin) {
  275. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  276. return true;
  277. } else if (event->type() == QEvent::TouchUpdate) {
  278. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  279. return true;
  280. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  281. TouchEndEvent();
  282. return true;
  283. }
  284. return QWidget::event(event);
  285. }
  286. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  287. QWidget::focusOutEvent(event);
  288. InputCommon::GetKeyboard()->ReleaseAllKeys();
  289. }
  290. void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height) {
  291. NotifyClientAreaSizeChanged(std::make_pair(width, height));
  292. }
  293. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  294. return std::make_unique<GGLContext>(context.get());
  295. }
  296. void GRenderWindow::InitRenderTarget() {
  297. shared_context.reset();
  298. context.reset();
  299. delete child;
  300. child = nullptr;
  301. delete container;
  302. container = nullptr;
  303. delete layout();
  304. first_frame = false;
  305. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  306. // WA_DontShowOnScreen, WA_DeleteOnClose
  307. QSurfaceFormat fmt;
  308. fmt.setVersion(4, 3);
  309. if (Settings::values.use_compatibility_profile) {
  310. fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
  311. fmt.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
  312. } else {
  313. fmt.setProfile(QSurfaceFormat::CoreProfile);
  314. }
  315. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  316. fmt.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  317. shared_context = std::make_unique<QOpenGLContext>();
  318. shared_context->setFormat(fmt);
  319. shared_context->create();
  320. context = std::make_unique<QOpenGLContext>();
  321. context->setShareContext(shared_context.get());
  322. context->setFormat(fmt);
  323. context->create();
  324. fmt.setSwapInterval(false);
  325. child = new GGLWidgetInternal(this, shared_context.get());
  326. container = QWidget::createWindowContainer(child, this);
  327. QBoxLayout* layout = new QHBoxLayout(this);
  328. layout->addWidget(container);
  329. layout->setMargin(0);
  330. setLayout(layout);
  331. // Reset minimum size to avoid unwanted resizes when this function is called for a second time.
  332. setMinimumSize(1, 1);
  333. // Show causes the window to actually be created and the OpenGL context as well, but we don't
  334. // want the widget to be shown yet, so immediately hide it.
  335. show();
  336. hide();
  337. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  338. child->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  339. container->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  340. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  341. OnFramebufferSizeChanged();
  342. NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
  343. BackupGeometry();
  344. }
  345. void GRenderWindow::CaptureScreenshot(u16 res_scale, const QString& screenshot_path) {
  346. auto& renderer = Core::System::GetInstance().Renderer();
  347. if (!res_scale)
  348. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  349. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  350. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  351. renderer.RequestScreenshot(screenshot_image.bits(),
  352. [=] {
  353. screenshot_image.mirrored(false, true).save(screenshot_path);
  354. LOG_INFO(Frontend, "The screenshot is saved.");
  355. },
  356. layout);
  357. }
  358. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<unsigned, unsigned> minimal_size) {
  359. setMinimumSize(minimal_size.first, minimal_size.second);
  360. }
  361. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  362. this->emu_thread = emu_thread;
  363. child->DisablePainting();
  364. }
  365. void GRenderWindow::OnEmulationStopping() {
  366. emu_thread = nullptr;
  367. child->EnablePainting();
  368. }
  369. void GRenderWindow::showEvent(QShowEvent* event) {
  370. QWidget::showEvent(event);
  371. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  372. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  373. Qt::UniqueConnection);
  374. }