bootmanager.cpp 14 KB

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