bootmanager.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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)
  78. : context{std::make_unique<QOpenGLContext>(shared_context)} {
  79. surface.setFormat(shared_context->format());
  80. surface.create();
  81. }
  82. void MakeCurrent() override {
  83. context->makeCurrent(&surface);
  84. }
  85. void DoneCurrent() override {
  86. context->doneCurrent();
  87. }
  88. void SwapBuffers() override {}
  89. private:
  90. std::unique_ptr<QOpenGLContext> context;
  91. QOffscreenSurface surface;
  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(QWidget* parent, EmuThread* emu_thread)
  153. : QWidget(parent), emu_thread(emu_thread) {
  154. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  155. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  156. setAttribute(Qt::WA_AcceptTouchEvents);
  157. InputCommon::Init();
  158. connect(this, &GRenderWindow::FirstFrameDisplayed, static_cast<GMainWindow*>(parent),
  159. &GMainWindow::OnLoadComplete);
  160. }
  161. GRenderWindow::~GRenderWindow() {
  162. InputCommon::Shutdown();
  163. }
  164. void GRenderWindow::moveContext() {
  165. DoneCurrent();
  166. // If the thread started running, move the GL Context to the new thread. Otherwise, move it
  167. // back.
  168. auto thread = (QThread::currentThread() == qApp->thread() && emu_thread != nullptr)
  169. ? emu_thread
  170. : qApp->thread();
  171. context->moveToThread(thread);
  172. }
  173. void GRenderWindow::SwapBuffers() {
  174. // In our multi-threaded QWidget use case we shouldn't need to call `makeCurrent`,
  175. // since we never call `doneCurrent` in this thread.
  176. // However:
  177. // - The Qt debug runtime prints a bogus warning on the console if `makeCurrent` wasn't called
  178. // since the last time `swapBuffers` was executed;
  179. // - On macOS, if `makeCurrent` isn't called explicitely, resizing the buffer breaks.
  180. context->makeCurrent(child);
  181. context->swapBuffers(child);
  182. if (!first_frame) {
  183. emit FirstFrameDisplayed();
  184. first_frame = true;
  185. }
  186. }
  187. void GRenderWindow::MakeCurrent() {
  188. context->makeCurrent(child);
  189. }
  190. void GRenderWindow::DoneCurrent() {
  191. context->doneCurrent();
  192. }
  193. void GRenderWindow::PollEvents() {}
  194. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  195. //
  196. // Older versions get the window size (density independent pixels),
  197. // and hence, do not support DPI scaling ("retina" displays).
  198. // The result will be a viewport that is smaller than the extent of the window.
  199. void GRenderWindow::OnFramebufferSizeChanged() {
  200. // Screen changes potentially incur a change in screen DPI, hence we should update the
  201. // framebuffer size
  202. qreal pixelRatio = GetWindowPixelRatio();
  203. unsigned width = child->QPaintDevice::width() * pixelRatio;
  204. unsigned height = child->QPaintDevice::height() * pixelRatio;
  205. UpdateCurrentFramebufferLayout(width, height);
  206. }
  207. void GRenderWindow::ForwardKeyPressEvent(QKeyEvent* event) {
  208. if (child) {
  209. child->keyPressEvent(event);
  210. }
  211. }
  212. void GRenderWindow::ForwardKeyReleaseEvent(QKeyEvent* event) {
  213. if (child) {
  214. child->keyReleaseEvent(event);
  215. }
  216. }
  217. void GRenderWindow::BackupGeometry() {
  218. geometry = ((QWidget*)this)->saveGeometry();
  219. }
  220. void GRenderWindow::RestoreGeometry() {
  221. // We don't want to back up the geometry here (obviously)
  222. QWidget::restoreGeometry(geometry);
  223. }
  224. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  225. // Make sure users of this class don't need to deal with backing up the geometry themselves
  226. QWidget::restoreGeometry(geometry);
  227. BackupGeometry();
  228. }
  229. QByteArray GRenderWindow::saveGeometry() {
  230. // If we are a top-level widget, store the current geometry
  231. // otherwise, store the last backup
  232. if (parent() == nullptr)
  233. return ((QWidget*)this)->saveGeometry();
  234. else
  235. return geometry;
  236. }
  237. qreal GRenderWindow::GetWindowPixelRatio() const {
  238. // windowHandle() might not be accessible until the window is displayed to screen.
  239. return windowHandle() ? windowHandle()->screen()->devicePixelRatio() : 1.0f;
  240. }
  241. std::pair<unsigned, unsigned> GRenderWindow::ScaleTouch(const QPointF pos) const {
  242. const qreal pixel_ratio = GetWindowPixelRatio();
  243. return {static_cast<unsigned>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  244. static_cast<unsigned>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  245. }
  246. void GRenderWindow::closeEvent(QCloseEvent* event) {
  247. emit Closed();
  248. QWidget::closeEvent(event);
  249. }
  250. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  251. // TouchBegin always has exactly one touch point, so take the .first()
  252. const auto [x, y] = ScaleTouch(event->touchPoints().first().pos());
  253. this->TouchPressed(x, y);
  254. }
  255. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  256. QPointF pos;
  257. int active_points = 0;
  258. // average all active touch points
  259. for (const auto tp : event->touchPoints()) {
  260. if (tp.state() & (Qt::TouchPointPressed | Qt::TouchPointMoved | Qt::TouchPointStationary)) {
  261. active_points++;
  262. pos += tp.pos();
  263. }
  264. }
  265. pos /= active_points;
  266. const auto [x, y] = ScaleTouch(pos);
  267. this->TouchMoved(x, y);
  268. }
  269. void GRenderWindow::TouchEndEvent() {
  270. this->TouchReleased();
  271. }
  272. bool GRenderWindow::event(QEvent* event) {
  273. if (event->type() == QEvent::TouchBegin) {
  274. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  275. return true;
  276. } else if (event->type() == QEvent::TouchUpdate) {
  277. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  278. return true;
  279. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  280. TouchEndEvent();
  281. return true;
  282. }
  283. return QWidget::event(event);
  284. }
  285. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  286. QWidget::focusOutEvent(event);
  287. InputCommon::GetKeyboard()->ReleaseAllKeys();
  288. }
  289. void GRenderWindow::OnClientAreaResized(unsigned width, unsigned height) {
  290. NotifyClientAreaSizeChanged(std::make_pair(width, height));
  291. }
  292. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  293. return std::make_unique<GGLContext>(shared_context.get());
  294. }
  295. void GRenderWindow::InitRenderTarget() {
  296. shared_context.reset();
  297. context.reset();
  298. delete child;
  299. child = nullptr;
  300. delete container;
  301. container = nullptr;
  302. delete layout();
  303. first_frame = false;
  304. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  305. // WA_DontShowOnScreen, WA_DeleteOnClose
  306. QSurfaceFormat fmt;
  307. fmt.setVersion(4, 3);
  308. if (Settings::values.use_compatibility_profile) {
  309. fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
  310. } else {
  311. fmt.setProfile(QSurfaceFormat::CoreProfile);
  312. }
  313. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  314. fmt.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  315. shared_context = std::make_unique<QOpenGLContext>();
  316. shared_context->setFormat(fmt);
  317. shared_context->create();
  318. context = std::make_unique<QOpenGLContext>();
  319. context->setShareContext(shared_context.get());
  320. context->setFormat(fmt);
  321. context->create();
  322. fmt.setSwapInterval(false);
  323. child = new GGLWidgetInternal(this, shared_context.get());
  324. container = QWidget::createWindowContainer(child, this);
  325. QBoxLayout* layout = new QHBoxLayout(this);
  326. layout->addWidget(container);
  327. layout->setMargin(0);
  328. setLayout(layout);
  329. // Reset minimum size to avoid unwanted resizes when this function is called for a second time.
  330. setMinimumSize(1, 1);
  331. // Show causes the window to actually be created and the OpenGL context as well, but we don't
  332. // want the widget to be shown yet, so immediately hide it.
  333. show();
  334. hide();
  335. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  336. child->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  337. container->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  338. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  339. OnFramebufferSizeChanged();
  340. NotifyClientAreaSizeChanged(std::pair<unsigned, unsigned>(child->width(), child->height()));
  341. BackupGeometry();
  342. }
  343. void GRenderWindow::CaptureScreenshot(u16 res_scale, const QString& screenshot_path) {
  344. auto& renderer = Core::System::GetInstance().Renderer();
  345. if (!res_scale)
  346. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  347. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  348. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  349. renderer.RequestScreenshot(screenshot_image.bits(),
  350. [=] {
  351. screenshot_image.mirrored(false, true).save(screenshot_path);
  352. LOG_INFO(Frontend, "The screenshot is saved.");
  353. },
  354. layout);
  355. }
  356. void GRenderWindow::OnMinimalClientAreaChangeRequest(
  357. const std::pair<unsigned, unsigned>& minimal_size) {
  358. setMinimumSize(minimal_size.first, minimal_size.second);
  359. }
  360. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  361. this->emu_thread = emu_thread;
  362. child->DisablePainting();
  363. }
  364. void GRenderWindow::OnEmulationStopping() {
  365. emu_thread = nullptr;
  366. child->EnablePainting();
  367. }
  368. void GRenderWindow::showEvent(QShowEvent* event) {
  369. QWidget::showEvent(event);
  370. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  371. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  372. Qt::UniqueConnection);
  373. }