bootmanager.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. 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. : QWidget(parent), emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)} {
  240. setWindowTitle(QStringLiteral("yuzu %1 | %2-%3")
  241. .arg(QString::fromUtf8(Common::g_build_name),
  242. QString::fromUtf8(Common::g_scm_branch),
  243. QString::fromUtf8(Common::g_scm_desc)));
  244. setAttribute(Qt::WA_AcceptTouchEvents);
  245. auto* layout = new QHBoxLayout(this);
  246. layout->setContentsMargins(0, 0, 0, 0);
  247. setLayout(layout);
  248. input_subsystem->Initialize();
  249. this->setMouseTracking(true);
  250. connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete);
  251. connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram,
  252. Qt::QueuedConnection);
  253. }
  254. void GRenderWindow::ExecuteProgram(std::size_t program_index) {
  255. emit ExecuteProgramSignal(program_index);
  256. }
  257. GRenderWindow::~GRenderWindow() {
  258. input_subsystem->Shutdown();
  259. }
  260. void GRenderWindow::OnFrameDisplayed() {
  261. if (!first_frame) {
  262. first_frame = true;
  263. emit FirstFrameDisplayed();
  264. }
  265. }
  266. bool GRenderWindow::IsShown() const {
  267. return !isMinimized();
  268. }
  269. // On Qt 5.0+, this correctly gets the size of the framebuffer (pixels).
  270. //
  271. // Older versions get the window size (density independent pixels),
  272. // and hence, do not support DPI scaling ("retina" displays).
  273. // The result will be a viewport that is smaller than the extent of the window.
  274. void GRenderWindow::OnFramebufferSizeChanged() {
  275. // Screen changes potentially incur a change in screen DPI, hence we should update the
  276. // framebuffer size
  277. const qreal pixel_ratio = windowPixelRatio();
  278. const u32 width = this->width() * pixel_ratio;
  279. const u32 height = this->height() * pixel_ratio;
  280. UpdateCurrentFramebufferLayout(width, height);
  281. }
  282. void GRenderWindow::BackupGeometry() {
  283. geometry = QWidget::saveGeometry();
  284. }
  285. void GRenderWindow::RestoreGeometry() {
  286. // We don't want to back up the geometry here (obviously)
  287. QWidget::restoreGeometry(geometry);
  288. }
  289. void GRenderWindow::restoreGeometry(const QByteArray& geometry) {
  290. // Make sure users of this class don't need to deal with backing up the geometry themselves
  291. QWidget::restoreGeometry(geometry);
  292. BackupGeometry();
  293. }
  294. QByteArray GRenderWindow::saveGeometry() {
  295. // If we are a top-level widget, store the current geometry
  296. // otherwise, store the last backup
  297. if (parent() == nullptr) {
  298. return QWidget::saveGeometry();
  299. }
  300. return geometry;
  301. }
  302. qreal GRenderWindow::windowPixelRatio() const {
  303. return devicePixelRatioF();
  304. }
  305. std::pair<u32, u32> GRenderWindow::ScaleTouch(const QPointF& pos) const {
  306. const qreal pixel_ratio = windowPixelRatio();
  307. return {static_cast<u32>(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})),
  308. static_cast<u32>(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))};
  309. }
  310. void GRenderWindow::closeEvent(QCloseEvent* event) {
  311. emit Closed();
  312. QWidget::closeEvent(event);
  313. }
  314. void GRenderWindow::keyPressEvent(QKeyEvent* event) {
  315. if (!event->isAutoRepeat()) {
  316. input_subsystem->GetKeyboard()->PressKey(event->key());
  317. }
  318. }
  319. void GRenderWindow::keyReleaseEvent(QKeyEvent* event) {
  320. if (!event->isAutoRepeat()) {
  321. input_subsystem->GetKeyboard()->ReleaseKey(event->key());
  322. }
  323. }
  324. MouseInput::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) {
  325. switch (button) {
  326. case Qt::LeftButton:
  327. return MouseInput::MouseButton::Left;
  328. case Qt::RightButton:
  329. return MouseInput::MouseButton::Right;
  330. case Qt::MiddleButton:
  331. return MouseInput::MouseButton::Wheel;
  332. case Qt::BackButton:
  333. return MouseInput::MouseButton::Backward;
  334. case Qt::ForwardButton:
  335. return MouseInput::MouseButton::Forward;
  336. case Qt::TaskButton:
  337. return MouseInput::MouseButton::Task;
  338. default:
  339. return MouseInput::MouseButton::Extra;
  340. }
  341. }
  342. void GRenderWindow::mousePressEvent(QMouseEvent* event) {
  343. // Touch input is handled in TouchBeginEvent
  344. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  345. return;
  346. }
  347. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  348. // coordinates and map them to the current render area
  349. const auto pos = mapFromGlobal(QCursor::pos());
  350. const auto [x, y] = ScaleTouch(pos);
  351. const auto button = QtButtonToMouseButton(event->button());
  352. input_subsystem->GetMouse()->PressButton(x, y, button);
  353. if (event->button() == Qt::LeftButton) {
  354. this->TouchPressed(x, y, 0);
  355. }
  356. emit MouseActivity();
  357. }
  358. void GRenderWindow::mouseMoveEvent(QMouseEvent* event) {
  359. // Touch input is handled in TouchUpdateEvent
  360. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  361. return;
  362. }
  363. // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse
  364. // coordinates and map them to the current render area
  365. const auto pos = mapFromGlobal(QCursor::pos());
  366. const auto [x, y] = ScaleTouch(pos);
  367. const int center_x = width() / 2;
  368. const int center_y = height() / 2;
  369. input_subsystem->GetMouse()->MouseMove(x, y, center_x, center_y);
  370. this->TouchMoved(x, y, 0);
  371. if (Settings::values.mouse_panning) {
  372. QCursor::setPos(mapToGlobal({center_x, center_y}));
  373. }
  374. emit MouseActivity();
  375. }
  376. void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) {
  377. // Touch input is handled in TouchEndEvent
  378. if (event->source() == Qt::MouseEventSynthesizedBySystem) {
  379. return;
  380. }
  381. const auto button = QtButtonToMouseButton(event->button());
  382. input_subsystem->GetMouse()->ReleaseButton(button);
  383. if (event->button() == Qt::LeftButton) {
  384. this->TouchReleased(0);
  385. }
  386. }
  387. void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) {
  388. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  389. for (const auto& touch_point : touch_points) {
  390. if (!TouchUpdate(touch_point)) {
  391. TouchStart(touch_point);
  392. }
  393. }
  394. }
  395. void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) {
  396. QList<QTouchEvent::TouchPoint> touch_points = event->touchPoints();
  397. for (const auto& touch_point : touch_points) {
  398. if (!TouchUpdate(touch_point)) {
  399. TouchStart(touch_point);
  400. }
  401. }
  402. // Release all inactive points
  403. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  404. if (!TouchExist(touch_ids[id], touch_points)) {
  405. touch_ids[id] = 0;
  406. this->TouchReleased(id + 1);
  407. }
  408. }
  409. }
  410. void GRenderWindow::TouchEndEvent() {
  411. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  412. if (touch_ids[id] != 0) {
  413. touch_ids[id] = 0;
  414. this->TouchReleased(id + 1);
  415. }
  416. }
  417. }
  418. bool GRenderWindow::TouchStart(const QTouchEvent::TouchPoint& touch_point) {
  419. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  420. if (touch_ids[id] == 0) {
  421. touch_ids[id] = touch_point.id() + 1;
  422. const auto [x, y] = ScaleTouch(touch_point.pos());
  423. this->TouchPressed(x, y, id + 1);
  424. return true;
  425. }
  426. }
  427. return false;
  428. }
  429. bool GRenderWindow::TouchUpdate(const QTouchEvent::TouchPoint& touch_point) {
  430. for (std::size_t id = 0; id < touch_ids.size(); ++id) {
  431. if (touch_ids[id] == static_cast<std::size_t>(touch_point.id() + 1)) {
  432. const auto [x, y] = ScaleTouch(touch_point.pos());
  433. this->TouchMoved(x, y, id + 1);
  434. return true;
  435. }
  436. }
  437. return false;
  438. }
  439. bool GRenderWindow::TouchExist(std::size_t id,
  440. const QList<QTouchEvent::TouchPoint>& touch_points) const {
  441. return std::any_of(touch_points.begin(), touch_points.end(), [id](const auto& point) {
  442. return id == static_cast<std::size_t>(point.id() + 1);
  443. });
  444. }
  445. bool GRenderWindow::event(QEvent* event) {
  446. if (event->type() == QEvent::TouchBegin) {
  447. TouchBeginEvent(static_cast<QTouchEvent*>(event));
  448. return true;
  449. } else if (event->type() == QEvent::TouchUpdate) {
  450. TouchUpdateEvent(static_cast<QTouchEvent*>(event));
  451. return true;
  452. } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
  453. TouchEndEvent();
  454. return true;
  455. }
  456. return QWidget::event(event);
  457. }
  458. void GRenderWindow::focusOutEvent(QFocusEvent* event) {
  459. QWidget::focusOutEvent(event);
  460. input_subsystem->GetKeyboard()->ReleaseAllKeys();
  461. input_subsystem->GetMouse()->ReleaseAllButtons();
  462. this->TouchReleased(0);
  463. }
  464. void GRenderWindow::resizeEvent(QResizeEvent* event) {
  465. QWidget::resizeEvent(event);
  466. OnFramebufferSizeChanged();
  467. }
  468. std::unique_ptr<Core::Frontend::GraphicsContext> GRenderWindow::CreateSharedContext() const {
  469. #ifdef HAS_OPENGL
  470. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  471. auto c = static_cast<OpenGLSharedContext*>(main_context.get());
  472. // Bind the shared contexts to the main surface in case the backend wants to take over
  473. // presentation
  474. return std::make_unique<OpenGLSharedContext>(c->GetShareContext(),
  475. child_widget->windowHandle());
  476. }
  477. #endif
  478. return std::make_unique<DummyContext>();
  479. }
  480. bool GRenderWindow::InitRenderTarget() {
  481. ReleaseRenderTarget();
  482. {
  483. // Create a dummy render widget so that Qt
  484. // places the render window at the correct position.
  485. const RenderWidget dummy_widget{this};
  486. }
  487. first_frame = false;
  488. switch (Settings::values.renderer_backend.GetValue()) {
  489. case Settings::RendererBackend::OpenGL:
  490. if (!InitializeOpenGL()) {
  491. return false;
  492. }
  493. break;
  494. case Settings::RendererBackend::Vulkan:
  495. if (!InitializeVulkan()) {
  496. return false;
  497. }
  498. break;
  499. }
  500. // Update the Window System information with the new render target
  501. window_info = GetWindowSystemInfo(child_widget->windowHandle());
  502. child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  503. layout()->addWidget(child_widget);
  504. // Reset minimum required size to avoid resizing issues on the main window after restarting.
  505. setMinimumSize(1, 1);
  506. resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  507. OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size);
  508. OnFramebufferSizeChanged();
  509. BackupGeometry();
  510. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) {
  511. if (!LoadOpenGL()) {
  512. return false;
  513. }
  514. }
  515. return true;
  516. }
  517. void GRenderWindow::ReleaseRenderTarget() {
  518. if (child_widget) {
  519. layout()->removeWidget(child_widget);
  520. child_widget->deleteLater();
  521. child_widget = nullptr;
  522. }
  523. main_context.reset();
  524. }
  525. void GRenderWindow::CaptureScreenshot(u32 res_scale, const QString& screenshot_path) {
  526. auto& renderer = Core::System::GetInstance().Renderer();
  527. if (res_scale == 0) {
  528. res_scale = VideoCore::GetResolutionScaleFactor(renderer);
  529. }
  530. const Layout::FramebufferLayout layout{Layout::FrameLayoutFromResolutionScale(res_scale)};
  531. screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32);
  532. renderer.RequestScreenshot(
  533. screenshot_image.bits(),
  534. [=, this](bool invert_y) {
  535. const std::string std_screenshot_path = screenshot_path.toStdString();
  536. if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) {
  537. LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path);
  538. } else {
  539. LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path);
  540. }
  541. },
  542. layout);
  543. }
  544. bool GRenderWindow::IsLoadingComplete() const {
  545. return first_frame;
  546. }
  547. void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair<u32, u32> minimal_size) {
  548. setMinimumSize(minimal_size.first, minimal_size.second);
  549. }
  550. bool GRenderWindow::InitializeOpenGL() {
  551. #ifdef HAS_OPENGL
  552. // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
  553. // WA_DontShowOnScreen, WA_DeleteOnClose
  554. auto child = new OpenGLRenderWidget(this);
  555. child_widget = child;
  556. child_widget->windowHandle()->create();
  557. auto context = std::make_shared<OpenGLSharedContext>(child->windowHandle());
  558. main_context = context;
  559. child->SetContext(
  560. std::make_unique<OpenGLSharedContext>(context->GetShareContext(), child->windowHandle()));
  561. return true;
  562. #else
  563. QMessageBox::warning(this, tr("OpenGL not available!"),
  564. tr("yuzu has not been compiled with OpenGL support."));
  565. return false;
  566. #endif
  567. }
  568. bool GRenderWindow::InitializeVulkan() {
  569. auto child = new VulkanRenderWidget(this);
  570. child_widget = child;
  571. child_widget->windowHandle()->create();
  572. main_context = std::make_unique<DummyContext>();
  573. return true;
  574. }
  575. bool GRenderWindow::LoadOpenGL() {
  576. auto context = CreateSharedContext();
  577. auto scope = context->Acquire();
  578. if (!gladLoadGL()) {
  579. QMessageBox::warning(
  580. this, tr("Error while initializing OpenGL!"),
  581. tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver."));
  582. return false;
  583. }
  584. const QString renderer =
  585. QString::fromUtf8(reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
  586. if (!GLAD_GL_VERSION_4_6) {
  587. LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString());
  588. QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"),
  589. tr("Your GPU may not support OpenGL 4.6, or you do not have the "
  590. "latest graphics driver.<br><br>GL Renderer:<br>%1")
  591. .arg(renderer));
  592. return false;
  593. }
  594. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  595. if (!unsupported_gl_extensions.empty()) {
  596. QMessageBox::warning(
  597. this, tr("Error while initializing OpenGL!"),
  598. tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you "
  599. "have the latest graphics driver.<br><br>GL Renderer:<br>%1<br><br>Unsupported "
  600. "extensions:<br>%2")
  601. .arg(renderer)
  602. .arg(unsupported_gl_extensions.join(QStringLiteral("<br>"))));
  603. return false;
  604. }
  605. return true;
  606. }
  607. QStringList GRenderWindow::GetUnsupportedGLExtensions() const {
  608. QStringList unsupported_ext;
  609. // Extensions required to support some texture formats.
  610. if (!GLAD_GL_EXT_texture_compression_s3tc) {
  611. unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc"));
  612. }
  613. if (!GLAD_GL_ARB_texture_compression_rgtc) {
  614. unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc"));
  615. }
  616. if (!unsupported_ext.empty()) {
  617. LOG_ERROR(Frontend, "GPU does not support all required extensions: {}",
  618. glGetString(GL_RENDERER));
  619. }
  620. for (const QString& ext : unsupported_ext) {
  621. LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  622. }
  623. return unsupported_ext;
  624. }
  625. void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread) {
  626. this->emu_thread = emu_thread;
  627. }
  628. void GRenderWindow::OnEmulationStopping() {
  629. emu_thread = nullptr;
  630. }
  631. void GRenderWindow::showEvent(QShowEvent* event) {
  632. QWidget::showEvent(event);
  633. // windowHandle() is not initialized until the Window is shown, so we connect it here.
  634. connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged,
  635. Qt::UniqueConnection);
  636. }
  637. bool GRenderWindow::eventFilter(QObject* object, QEvent* event) {
  638. if (event->type() == QEvent::HoverMove) {
  639. if (Settings::values.mouse_panning) {
  640. auto* hover_event = static_cast<QMouseEvent*>(event);
  641. mouseMoveEvent(hover_event);
  642. return false;
  643. }
  644. emit MouseActivity();
  645. }
  646. return false;
  647. }