bootmanager.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <glad/glad.h>
  5. #include <QApplication>
  6. #include <QHBoxLayout>
  7. #include <QKeyEvent>
  8. #include <QMessageBox>
  9. #include <QPainter>
  10. #include <QScreen>
  11. #include <QString>
  12. #include <QStringList>
  13. #include <QWindow>
  14. #ifdef HAS_OPENGL
  15. #include <QOffscreenSurface>
  16. #include <QOpenGLContext>
  17. #endif
  18. #if !defined(WIN32)
  19. #include <qpa/qplatformnativeinterface.h>
  20. #endif
  21. #include <fmt/format.h>
  22. #include "common/assert.h"
  23. #include "common/microprofile.h"
  24. #include "common/scm_rev.h"
  25. #include "common/scope_exit.h"
  26. #include "common/settings.h"
  27. #include "core/core.h"
  28. #include "core/frontend/framebuffer_layout.h"
  29. #include "core/hle/kernel/k_process.h"
  30. #include "input_common/keyboard.h"
  31. #include "input_common/main.h"
  32. #include "input_common/mouse/mouse_input.h"
  33. #include "input_common/tas/tas_input.h"
  34. #include "video_core/renderer_base.h"
  35. #include "video_core/video_core.h"
  36. #include "yuzu/bootmanager.h"
  37. #include "yuzu/main.h"
  38. EmuThread::EmuThread(Core::System& system_) : system{system_} {}
  39. EmuThread::~EmuThread() = default;
  40. void EmuThread::run() {
  41. std::string name = "yuzu:EmuControlThread";
  42. MicroProfileOnThreadCreate(name.c_str());
  43. Common::SetCurrentThreadName(name.c_str());
  44. auto& gpu = system.GPU();
  45. auto stop_token = stop_source.get_token();
  46. system.RegisterHostThread();
  47. // Main process has been loaded. Make the context current to this thread and begin GPU and CPU
  48. // execution.
  49. gpu.Start();
  50. gpu.ObtainContext();
  51. emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0);
  52. if (Settings::values.use_disk_shader_cache.GetValue()) {
  53. system.Renderer().ReadRasterizer()->LoadDiskResources(
  54. system.CurrentProcess()->GetTitleID(), stop_token,
  55. [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) {
  56. emit LoadProgress(stage, value, total);
  57. });
  58. }
  59. emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0);
  60. gpu.ReleaseContext();
  61. // Holds whether the cpu was running during the last iteration,
  62. // so that the DebugModeLeft signal can be emitted before the
  63. // next execution step
  64. bool was_active = false;
  65. while (!stop_token.stop_requested()) {
  66. if (running) {
  67. if (was_active) {
  68. emit DebugModeLeft();
  69. }
  70. running_guard = true;
  71. Core::System::ResultStatus result = system.Run();
  72. if (result != Core::System::ResultStatus::Success) {
  73. running_guard = false;
  74. this->SetRunning(false);
  75. emit ErrorThrown(result, system.GetStatusDetails());
  76. }
  77. running_wait.Wait();
  78. result = system.Pause();
  79. if (result != Core::System::ResultStatus::Success) {
  80. running_guard = false;
  81. this->SetRunning(false);
  82. emit ErrorThrown(result, system.GetStatusDetails());
  83. }
  84. running_guard = false;
  85. if (!stop_token.stop_requested()) {
  86. was_active = true;
  87. emit DebugModeEntered();
  88. }
  89. } else if (exec_step) {
  90. UNIMPLEMENTED();
  91. } else {
  92. std::unique_lock lock{running_mutex};
  93. running_cv.wait(lock, stop_token, [this] { return IsRunning() || exec_step; });
  94. }
  95. }
  96. // Shutdown the core emulation
  97. system.Shutdown();
  98. #if MICROPROFILE_ENABLED
  99. MicroProfileOnThreadExit();
  100. #endif
  101. }
  102. #ifdef HAS_OPENGL
  103. class OpenGLSharedContext : public Core::Frontend::GraphicsContext {
  104. public:
  105. /// Create the original context that should be shared from
  106. explicit OpenGLSharedContext(QSurface* surface) : surface(surface) {
  107. QSurfaceFormat format;
  108. format.setVersion(4, 6);
  109. format.setProfile(QSurfaceFormat::CompatibilityProfile);
  110. format.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions);
  111. if (Settings::values.renderer_debug) {
  112. format.setOption(QSurfaceFormat::FormatOption::DebugContext);
  113. }
  114. // TODO: expose a setting for buffer value (ie default/single/double/triple)
  115. format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
  116. format.setSwapInterval(0);
  117. context = std::make_unique<QOpenGLContext>();
  118. context->setFormat(format);
  119. if (!context->create()) {
  120. LOG_ERROR(Frontend, "Unable to create main openGL context");
  121. }
  122. }
  123. /// Create the shared contexts for rendering and presentation
  124. explicit OpenGLSharedContext(QOpenGLContext* share_context, QSurface* main_surface = nullptr) {
  125. // disable vsync for any shared contexts
  126. auto format = share_context->format();
  127. format.setSwapInterval(main_surface ? Settings::values.use_vsync.GetValue() : 0);
  128. context = std::make_unique<QOpenGLContext>();
  129. context->setShareContext(share_context);
  130. context->setFormat(format);
  131. if (!context->create()) {
  132. LOG_ERROR(Frontend, "Unable to create shared openGL context");
  133. }
  134. if (!main_surface) {
  135. offscreen_surface = std::make_unique<QOffscreenSurface>(nullptr);
  136. offscreen_surface->setFormat(format);
  137. offscreen_surface->create();
  138. surface = offscreen_surface.get();
  139. } else {
  140. surface = main_surface;
  141. }
  142. }
  143. ~OpenGLSharedContext() {
  144. DoneCurrent();
  145. }
  146. void SwapBuffers() override {
  147. context->swapBuffers(surface);
  148. }
  149. void MakeCurrent() override {
  150. // We can't track the current state of the underlying context in this wrapper class because
  151. // Qt may make the underlying context not current for one reason or another. In particular,
  152. // the WebBrowser uses GL, so it seems to conflict if we aren't careful.
  153. // Instead of always just making the context current (which does not have any caching to
  154. // check if the underlying context is already current) we can check for the current context
  155. // in the thread local data by calling `currentContext()` and checking if its ours.
  156. if (QOpenGLContext::currentContext() != context.get()) {
  157. context->makeCurrent(surface);
  158. }
  159. }
  160. void DoneCurrent() override {
  161. context->doneCurrent();
  162. }
  163. QOpenGLContext* GetShareContext() {
  164. return context.get();
  165. }
  166. const QOpenGLContext* GetShareContext() const {
  167. return context.get();
  168. }
  169. private:
  170. // Avoid using Qt parent system here since we might move the QObjects to new threads
  171. // As a note, this means we should avoid using slots/signals with the objects too
  172. std::unique_ptr<QOpenGLContext> context;
  173. std::unique_ptr<QOffscreenSurface> offscreen_surface{};
  174. QSurface* surface;
  175. };
  176. #endif
  177. class DummyContext : public Core::Frontend::GraphicsContext {};
  178. class RenderWidget : public QWidget {
  179. public:
  180. explicit RenderWidget(GRenderWindow* parent) : QWidget(parent), render_window(parent) {
  181. setAttribute(Qt::WA_NativeWindow);
  182. setAttribute(Qt::WA_PaintOnScreen);
  183. }
  184. virtual ~RenderWidget() = default;
  185. QPaintEngine* paintEngine() const override {
  186. return nullptr;
  187. }
  188. private:
  189. GRenderWindow* render_window;
  190. };
  191. class OpenGLRenderWidget : public RenderWidget {
  192. public:
  193. explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  194. windowHandle()->setSurfaceType(QWindow::OpenGLSurface);
  195. }
  196. void SetContext(std::unique_ptr<Core::Frontend::GraphicsContext>&& context_) {
  197. context = std::move(context_);
  198. }
  199. private:
  200. std::unique_ptr<Core::Frontend::GraphicsContext> context;
  201. };
  202. class VulkanRenderWidget : public RenderWidget {
  203. public:
  204. explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {
  205. windowHandle()->setSurfaceType(QWindow::VulkanSurface);
  206. }
  207. };
  208. static Core::Frontend::WindowSystemType GetWindowSystemType() {
  209. // Determine WSI type based on Qt platform.
  210. QString platform_name = QGuiApplication::platformName();
  211. if (platform_name == QStringLiteral("windows"))
  212. return Core::Frontend::WindowSystemType::Windows;
  213. else if (platform_name == QStringLiteral("xcb"))
  214. return Core::Frontend::WindowSystemType::X11;
  215. else if (platform_name == QStringLiteral("wayland"))
  216. return Core::Frontend::WindowSystemType::Wayland;
  217. LOG_CRITICAL(Frontend, "Unknown Qt platform!");
  218. return Core::Frontend::WindowSystemType::Windows;
  219. }
  220. static Core::Frontend::EmuWindow::WindowSystemInfo GetWindowSystemInfo(QWindow* window) {
  221. Core::Frontend::EmuWindow::WindowSystemInfo wsi;
  222. wsi.type = GetWindowSystemType();
  223. // Our Win32 Qt external doesn't have the private API.
  224. #if defined(WIN32) || defined(__APPLE__)
  225. wsi.render_surface = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
  226. #else
  227. QPlatformNativeInterface* pni = QGuiApplication::platformNativeInterface();
  228. wsi.display_connection = pni->nativeResourceForWindow("display", window);
  229. if (wsi.type == Core::Frontend::WindowSystemType::Wayland)
  230. wsi.render_surface = window ? pni->nativeResourceForWindow("surface", window) : nullptr;
  231. else
  232. wsi.render_surface = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
  233. #endif
  234. wsi.render_surface_scale = window ? static_cast<float>(window->devicePixelRatio()) : 1.0f;
  235. return wsi;
  236. }
  237. GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_,
  238. std::shared_ptr<InputCommon::InputSubsystem> input_subsystem_,
  239. Core::System& system_)
  240. : QWidget(parent),
  241. emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)}, system{system_} {
  242. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  243. .arg(QString::fromUtf8(Common::g_build_name),
  244. QString::fromUtf8(Common::g_scm_branch),
  245. QString::fromUtf8(Common::g_scm_desc)));
  246. setAttribute(Qt::WA_AcceptTouchEvents);
  247. auto* layout = new QHBoxLayout(this);
  248. layout->setContentsMargins(0, 0, 0, 0);
  249. setLayout(layout);
  250. input_subsystem->Initialize();
  251. this->setMouseTracking(true);
  252. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
  253. connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram,
  254. Qt::QueuedConnection);
  255. connect(this, &GRenderWindow::ExitSignal, parent, &GMainWindow::OnExit, Qt::QueuedConnection);
  256. }
  257. void GRenderWindow::ExecuteProgram(std::size_t program_index) {
  258. emit ExecuteProgramSignal(program_index);
  259. }
  260. void GRenderWindow::Exit() {
  261. emit ExitSignal();
  262. }
  263. GRenderWindow::~GRenderWindow() {
  264. input_subsystem->Shutdown();
  265. }
  266. void GRenderWindow::OnFrameDisplayed() {
  267. input_subsystem->GetTas()->UpdateThread();
  268. if (!first_frame) {
  269. first_frame = true;
  270. emit FirstFrameDisplayed();
  271. }
  272. }
  273. bool GRenderWindow::IsShown() const {
  274. return !isMinimized();
  275. }
  276. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  277. //
  278. // Older versions get the window size (density independent pixels),
  279. // and hence, do not support DPI scaling ("retina" displays).
  280. // The result will be a viewport that is smaller than the extent of the window.
  281. void GRenderWindow::OnFramebufferSizeChanged() {
  282. // Screen changes potentially incur a change in screen DPI, hence we should update the
  283. // framebuffer size
  284. const qreal pixel_ratio = windowPixelRatio();
  285. const u32 width = this->width() * pixel_ratio;
  286. const u32 height = this->height() * pixel_ratio;
  287. UpdateCurrentFramebufferLayout(width, height);
  288. }
  289. void GRenderWindow::BackupGeometry() {
  290. geometry = QWidget::saveGeometry();
  291. }
  292. void GRenderWindow::RestoreGeometry() {
  293. // We don't want to back up the geometry here (obviously)
  294. QWidget::restoreGeometry(geometry);
  295. }
  296. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  297. // Make sure users of this class don't need to deal with backing up the geometry themselves
  298. QWidget::restoreGeometry(geometry);
  299. BackupGeometry();
  300. }
  301. QByteArray GRenderWindow::saveGeometry() {
  302. // If we are a top-level widget, store the current geometry
  303. // otherwise, store the last backup
  304. if (parent() == nullptr) {
  305. return QWidget::saveGeometry();
  306. }
  307. return geometry;
  308. }
  309. qreal GRenderWindow::windowPixelRatio() const {
  310. return devicePixelRatioF();
  311. }
  312. std::pair<u32, u32> GRenderWindow::ScaleTouch(const QPointF& pos) const {
  313. const qreal pixel_ratio = windowPixelRatio();
  314. return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  315. static_cast<u32>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  316. }
  317. void GRenderWindow::closeEvent(QCloseEvent* event) {
  318. emit Closed();
  319. QWidget::closeEvent(event);
  320. }
  321. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  322. if (!event->isAutoRepeat()) {
  323. input_subsystem->GetKeyboard()->PressKey(event->key());
  324. }
  325. }
  326. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  327. if (!event->isAutoRepeat()) {
  328. input_subsystem->GetKeyboard()->ReleaseKey(event->key());
  329. }
  330. }
  331. MouseInput::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) {
  332. switch (button) {
  333. case Qt::LeftButton:
  334. return MouseInput::MouseButton::Left;
  335. case Qt::RightButton:
  336. return MouseInput::MouseButton::Right;
  337. case Qt::MiddleButton:
  338. return MouseInput::MouseButton::Wheel;
  339. case Qt::BackButton:
  340. return MouseInput::MouseButton::Backward;
  341. case Qt::ForwardButton:
  342. return MouseInput::MouseButton::Forward;
  343. case Qt::TaskButton:
  344. return MouseInput::MouseButton::Task;
  345. default:
  346. return MouseInput::MouseButton::Extra;
  347. }
  348. }
  349. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  350. // Touch input is handled in TouchBeginEvent
  351. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  352. return;
  353. }
  354. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  355. // coordinates and map them to the current render area
  356. const auto pos = mapFromGlobal(QCursor::pos());
  357. const auto [x, y] = ScaleTouch(pos);
  358. const auto button = QtButtonToMouseButton(event->button());
  359. input_subsystem->GetMouse()->PressButton(x, y, button);
  360. if (event->button() == Qt::LeftButton) {
  361. this->TouchPressed(x, y, 0);
  362. }
  363. emit MouseActivity();
  364. }
  365. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  366. // Touch input is handled in TouchUpdateEvent
  367. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  368. return;
  369. }
  370. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  371. // coordinates and map them to the current render area
  372. const auto pos = mapFromGlobal(QCursor::pos());
  373. const auto [x, y] = ScaleTouch(pos);
  374. const int center_x = width() / 2;
  375. const int center_y = height() / 2;
  376. input_subsystem->GetMouse()->MouseMove(x, y, center_x, center_y);
  377. this->TouchMoved(x, y, 0);
  378. if (Settings::values.mouse_panning) {
  379. QCursor::setPos(mapToGlobal({center_x, center_y}));
  380. }
  381. emit MouseActivity();
  382. }
  383. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  384. // Touch input is handled in TouchEndEvent
  385. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  386. return;
  387. }
  388. const auto button = QtButtonToMouseButton(event->button());
  389. input_subsystem->GetMouse()->ReleaseButton(button);
  390. if (event->button() == Qt::LeftButton) {
  391. this->TouchReleased(0);
  392. }
  393. }
  394. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  395. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  396. for (const auto& touch_point : touch_points) {
  397. if (!TouchUpdate(touch_point)) {
  398. TouchStart(touch_point);
  399. }
  400. }
  401. }
  402. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  403. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  404. for (const auto& touch_point : touch_points) {
  405. if (!TouchUpdate(touch_point)) {
  406. TouchStart(touch_point);
  407. }
  408. }
  409. // Release all inactive points
  410. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  411. if (!TouchExist(touch_ids[id], touch_points)) {
  412. touch_ids[id] = 0;
  413. this->TouchReleased(id + 1);
  414. }
  415. }
  416. }
  417. void GRenderWindow::TouchEndEvent() {
  418. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  419. if (touch_ids[id] != 0) {
  420. touch_ids[id] = 0;
  421. this->TouchReleased(id + 1);
  422. }
  423. }
  424. }
  425. bool GRenderWindow::TouchStart(const QTouchEvent::TouchPoint& touch_point) {
  426. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  427. if (touch_ids[id] == 0) {
  428. touch_ids[id] = touch_point.id() + 1;
  429. const auto [x, y] = ScaleTouch(touch_point.pos());
  430. this->TouchPressed(x, y, id + 1);
  431. return true;
  432. }
  433. }
  434. return false;
  435. }
  436. bool GRenderWindow::TouchUpdate(const QTouchEvent::TouchPoint& touch_point) {
  437. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  438. if (touch_ids[id] == static_cast<std::size_t>(touch_point.id() + 1)) {
  439. const auto [x, y] = ScaleTouch(touch_point.pos());
  440. this->TouchMoved(x, y, id + 1);
  441. return true;
  442. }
  443. }
  444. return false;
  445. }
  446. bool GRenderWindow::TouchExist(std::size_t id,
  447. const QList<QTouchEvent::TouchPoint>& touch_points) const {
  448. return std::any_of(touch_points.begin(), touch_points.end(), [id](const auto& point) {
  449. return id == static_cast<std::size_t>(point.id() + 1);
  450. });
  451. }
  452. bool GRenderWindow::event(QEvent* event) {
  453. if (event->type() == QEvent::TouchBegin) {
  454. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  455. return true;
  456. } else if (event->type() == QEvent::TouchUpdate) {
  457. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  458. return true;
  459. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  460. TouchEndEvent();
  461. return true;
  462. }
  463. return QWidget::event(event);
  464. }
  465. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  466. QWidget::focusOutEvent(event);
  467. input_subsystem->GetKeyboard()->ReleaseAllKeys();
  468. input_subsystem->GetMouse()->ReleaseAllButtons();
  469. this->TouchReleased(0);
  470. }
  471. void GRenderWindow::resizeEvent(QResizeEvent* event) {
  472. QWidget::resizeEvent(event);
  473. OnFramebufferSizeChanged();
  474. }
  475. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  476. #ifdef HAS_OPENGL
  477. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  478. auto c = static_cast<OpenGLSharedContext*>(main_context.get());
  479. // Bind the shared contexts to the main surface in case the backend wants to take over
  480. // presentation
  481. return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
  482. child_widget->windowHandle());
  483. }
  484. #endif
  485. return std::make_unique<DummyContext>();
  486. }
  487. bool GRenderWindow::InitRenderTarget() {
  488. ReleaseRenderTarget();
  489. {
  490. // Create a dummy render widget so that Qt
  491. // places the render window at the correct position.
  492. const RenderWidget dummy_widget{this};
  493. }
  494. first_frame = false;
  495. switch (Settings::values.renderer_backend.GetValue()) {
  496. case Settings::RendererBackend::OpenGL:
  497. if (!InitializeOpenGL()) {
  498. return false;
  499. }
  500. break;
  501. case Settings::RendererBackend::Vulkan:
  502. if (!InitializeVulkan()) {
  503. return false;
  504. }
  505. break;
  506. }
  507. // Update the Window System information with the new render target
  508. window_info = GetWindowSystemInfo(child_widget->windowHandle());
  509. child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  510. layout()->addWidget(child_widget);
  511. // Reset minimum required size to avoid resizing issues on the main window after restarting.
  512. setMinimumSize(1, 1);
  513. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  514. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  515. OnFramebufferSizeChanged();
  516. BackupGeometry();
  517. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  518. if (!LoadOpenGL()) {
  519. return false;
  520. }
  521. }
  522. return true;
  523. }
  524. void GRenderWindow::ReleaseRenderTarget() {
  525. if (child_widget) {
  526. layout()->removeWidget(child_widget);
  527. child_widget->deleteLater();
  528. child_widget = nullptr;
  529. }
  530. main_context.reset();
  531. }
  532. void GRenderWindow::CaptureScreenshot(u32 res_scale, const QString& screenshot_path) {
  533. VideoCore::RendererBase& renderer = system.Renderer();
  534. if (res_scale == 0) {
  535. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  536. }
  537. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  538. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  539. renderer.RequestScreenshot(
  540. screenshot_image.bits(),
  541. [=, this](bool invert_y) {
  542. const std::string std_screenshot_path = screenshot_path.toStdString();
  543. if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
  544. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  545. } else {
  546. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  547. }
  548. },
  549. layout);
  550. }
  551. bool GRenderWindow::IsLoadingComplete() const {
  552. return first_frame;
  553. }
  554. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  555. setMinimumSize(minimal_size.first, minimal_size.second);
  556. }
  557. bool GRenderWindow::InitializeOpenGL() {
  558. #ifdef HAS_OPENGL
  559. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  560. // WA_DontShowOnScreen, WA_DeleteOnClose
  561. auto child = new OpenGLRenderWidget(this);
  562. child_widget = child;
  563. child_widget->windowHandle()->create();
  564. auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
  565. main_context = context;
  566. child->SetContext(
  567. std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));
  568. return true;
  569. #else
  570. QMessageBox::warning(this, tr("OpenGL not available!"),
  571. tr("yuzu has not been compiled with OpenGL support."));
  572. return false;
  573. #endif
  574. }
  575. bool GRenderWindow::InitializeVulkan() {
  576. auto child = new VulkanRenderWidget(this);
  577. child_widget = child;
  578. child_widget->windowHandle()->create();
  579. main_context = std::make_unique<DummyContext>();
  580. return true;
  581. }
  582. bool GRenderWindow::LoadOpenGL() {
  583. auto context = CreateSharedContext();
  584. auto scope = context->Acquire();
  585. if (!gladLoadGL()) {
  586. QMessageBox::warning(
  587. this, tr("Error while initializing OpenGL!"),
  588. tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
  589. return false;
  590. }
  591. const QString renderer =
  592. QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
  593. if (!GLAD_GL_VERSION_4_6) {
  594. LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
  595. QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
  596. tr("Your GPU may not support OpenGL 4.6, or you do not have the "
  597. "latest graphics driver.<br><br>GL Renderer:<br>%1")
  598. .arg(renderer));
  599. return false;
  600. }
  601. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  602. if (!unsupported_gl_extensions.empty()) {
  603. QMessageBox::warning(
  604. this, tr("Error while initializing OpenGL!"),
  605. tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
  606. "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
  607. "extensions:<br>%2")
  608. .arg(renderer)
  609. .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
  610. return false;
  611. }
  612. return true;
  613. }
  614. QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
  615. QStringList unsupported_ext;
  616. // Extensions required to support some texture formats.
  617. if (!GLAD_GL_EXT_texture_compression_s3tc) {
  618. unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
  619. }
  620. if (!GLAD_GL_ARB_texture_compression_rgtc) {
  621. unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
  622. }
  623. if (!unsupported_ext.empty()) {
  624. LOG_ERROR(Frontend, "GPU does not support all required extensions: {}",
  625. glGetString(GL_RENDERER));
  626. }
  627. for (const QString& ext : unsupported_ext) {
  628. LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  629. }
  630. return unsupported_ext;
  631. }
  632. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  633. this->emu_thread = emu_thread;
  634. }
  635. void GRenderWindow::OnEmulationStopping() {
  636. emu_thread = nullptr;
  637. }
  638. void GRenderWindow::showEvent(QShowEvent* event) {
  639. QWidget::showEvent(event);
  640. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  641. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  642. Qt::UniqueConnection);
  643. }
  644. bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
  645. if (event->type() == QEvent::HoverMove) {
  646. if (Settings::values.mouse_panning) {
  647. auto* hover_event = static_cast<QMouseEvent*>(event);
  648. mouseMoveEvent(hover_event);
  649. return false;
  650. }
  651. emit MouseActivity();
  652. }
  653. return false;
  654. }