bootmanager.cpp 25 KB

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