bootmanager.cpp 26 KB

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