bootmanager.cpp 25 KB

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