main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #include <QCoreApplication>
  2. #include <QDateTime>
  3. #include <QDebug>
  4. #include <QDir>
  5. #include <QFile>
  6. #include <QGuiApplication>
  7. #include <QOffscreenSurface>
  8. #include <QOpenGLContext>
  9. #include <QOpenGLFunctions>
  10. #include <QQmlApplicationEngine>
  11. #include <QQmlContext>
  12. #include <QQuickWindow>
  13. #include <QSGRendererInterface>
  14. #include <QSurfaceFormat>
  15. #include <QTextStream>
  16. #include <QUrl>
  17. #include <cstdio>
  18. #include <memory>
  19. #include <qglobal.h>
  20. #include <qguiapplication.h>
  21. #include <qnamespace.h>
  22. #include <qobject.h>
  23. #include <qqml.h>
  24. #include <qqmlapplicationengine.h>
  25. #include <qsgrendererinterface.h>
  26. #include <qstringliteral.h>
  27. #include <qstringview.h>
  28. #include <qsurfaceformat.h>
  29. #include <qurl.h>
  30. #ifdef Q_OS_WIN
  31. #include <QProcess>
  32. #include <gl/gl.h>
  33. #include <windows.h>
  34. #pragma comment(lib, "opengl32.lib")
  35. #endif
  36. #include "app/core/game_engine.h"
  37. #include "app/core/language_manager.h"
  38. #include "app/models/graphics_settings_proxy.h"
  39. #include "ui/gl_view.h"
  40. #include "ui/theme.h"
  41. // Constants replacing magic numbers
  42. constexpr int k_depth_buffer_bits = 24;
  43. constexpr int k_stencil_buffer_bits = 8;
  44. #ifdef Q_OS_WIN
  45. // Test OpenGL using native Win32 API (before any Qt initialization)
  46. // Returns true if OpenGL is available, false otherwise
  47. static bool testNativeOpenGL() {
  48. WNDCLASSA wc = {};
  49. wc.lpfnWndProc = DefWindowProcA;
  50. wc.hInstance = GetModuleHandle(nullptr);
  51. wc.lpszClassName = "OpenGLTest";
  52. if (!RegisterClassA(&wc)) {
  53. return false;
  54. }
  55. HWND hwnd = CreateWindowExA(0, "OpenGLTest", "", WS_OVERLAPPEDWINDOW, 0, 0, 1,
  56. 1, nullptr, nullptr, wc.hInstance, nullptr);
  57. if (!hwnd) {
  58. UnregisterClassA("OpenGLTest", wc.hInstance);
  59. return false;
  60. }
  61. HDC hdc = GetDC(hwnd);
  62. if (!hdc) {
  63. DestroyWindow(hwnd);
  64. UnregisterClassA("OpenGLTest", wc.hInstance);
  65. return false;
  66. }
  67. PIXELFORMATDESCRIPTOR pfd = {};
  68. pfd.nSize = sizeof(pfd);
  69. pfd.nVersion = 1;
  70. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  71. pfd.iPixelType = PFD_TYPE_RGBA;
  72. pfd.cColorBits = 24;
  73. pfd.cDepthBits = 24;
  74. pfd.cStencilBits = 8;
  75. pfd.iLayerType = PFD_MAIN_PLANE;
  76. int pixelFormat = ChoosePixelFormat(hdc, &pfd);
  77. bool success = false;
  78. if (pixelFormat != 0 && SetPixelFormat(hdc, pixelFormat, &pfd)) {
  79. HGLRC hglrc = wglCreateContext(hdc);
  80. if (hglrc) {
  81. if (wglMakeCurrent(hdc, hglrc)) {
  82. // Successfully created OpenGL context
  83. const char *vendor = (const char *)glGetString(GL_VENDOR);
  84. const char *renderer = (const char *)glGetString(GL_RENDERER);
  85. const char *version = (const char *)glGetString(GL_VERSION);
  86. if (vendor && renderer && version) {
  87. fprintf(stderr,
  88. "[OpenGL Test] Native context created successfully\n");
  89. fprintf(stderr, "[OpenGL Test] Vendor: %s\n", vendor);
  90. fprintf(stderr, "[OpenGL Test] Renderer: %s\n", renderer);
  91. fprintf(stderr, "[OpenGL Test] Version: %s\n", version);
  92. success = true;
  93. }
  94. wglMakeCurrent(nullptr, nullptr);
  95. }
  96. wglDeleteContext(hglrc);
  97. }
  98. }
  99. ReleaseDC(hwnd, hdc);
  100. DestroyWindow(hwnd);
  101. UnregisterClassA("OpenGLTest", wc.hInstance);
  102. return success;
  103. }
  104. // Windows crash handler to detect OpenGL failures and suggest fallback
  105. static bool g_opengl_crashed = false;
  106. static LONG WINAPI crashHandler(EXCEPTION_POINTERS *exceptionInfo) {
  107. if (exceptionInfo->ExceptionRecord->ExceptionCode ==
  108. EXCEPTION_ACCESS_VIOLATION) {
  109. // Log crash
  110. FILE *crash_log = fopen("opengl_crash.txt", "w");
  111. if (crash_log) {
  112. fprintf(crash_log,
  113. "OpenGL/Qt rendering crash detected (Access Violation)\n");
  114. fprintf(crash_log, "Try running with: run_debug_softwaregl.cmd\n");
  115. fprintf(crash_log,
  116. "Or set environment variable: QT_QUICK_BACKEND=software\n");
  117. fclose(crash_log);
  118. }
  119. qCritical() << "=== CRASH DETECTED ===";
  120. qCritical() << "OpenGL rendering failed. This usually means:";
  121. qCritical() << "1. Graphics drivers are outdated";
  122. qCritical() << "2. Running in a VM with incomplete OpenGL support";
  123. qCritical() << "3. GPU doesn't support required OpenGL version";
  124. qCritical() << "";
  125. qCritical() << "To fix: Run run_debug_softwaregl.cmd instead";
  126. qCritical() << "Or set: set QT_QUICK_BACKEND=software";
  127. g_opengl_crashed = true;
  128. }
  129. return EXCEPTION_CONTINUE_SEARCH;
  130. }
  131. #endif
  132. auto main(int argc, char *argv[]) -> int {
  133. #ifdef Q_OS_WIN
  134. // Install crash handler to detect OpenGL failures
  135. SetUnhandledExceptionFilter(crashHandler);
  136. // Test OpenGL BEFORE any Qt initialization (using native Win32 API)
  137. fprintf(stderr, "[Pre-Init] Testing native OpenGL availability...\n");
  138. bool opengl_available = testNativeOpenGL();
  139. if (!opengl_available) {
  140. fprintf(stderr, "[Pre-Init] WARNING: OpenGL test failed!\n");
  141. fprintf(stderr, "[Pre-Init] Forcing software rendering mode\n");
  142. _putenv("QT_QUICK_BACKEND=software");
  143. _putenv("QT_OPENGL=software");
  144. } else {
  145. fprintf(stderr, "[Pre-Init] OpenGL test passed\n");
  146. }
  147. // Check if we should use software rendering
  148. bool use_software = qEnvironmentVariableIsSet("QT_QUICK_BACKEND") &&
  149. qEnvironmentVariable("QT_QUICK_BACKEND") == "software";
  150. if (use_software) {
  151. qInfo() << "=== SOFTWARE RENDERING MODE ===";
  152. qInfo() << "Using Qt Quick Software renderer (CPU-based)";
  153. qInfo() << "Performance will be limited but should work on all systems";
  154. }
  155. #endif
  156. // Setup message handler for debugging
  157. qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context,
  158. const QString &msg) {
  159. QByteArray const local_msg = msg.toLocal8Bit();
  160. const char *file = (context.file != nullptr) ? context.file : "";
  161. const char *function =
  162. (context.function != nullptr) ? context.function : "";
  163. FILE *out = stderr;
  164. switch (type) {
  165. case QtDebugMsg:
  166. fprintf(out, "[DEBUG] %s (%s:%u, %s)\n", local_msg.constData(), file,
  167. context.line, function);
  168. break;
  169. case QtInfoMsg:
  170. fprintf(out, "[INFO] %s\n", local_msg.constData());
  171. break;
  172. case QtWarningMsg:
  173. fprintf(out, "[WARNING] %s (%s:%u, %s)\n", local_msg.constData(), file,
  174. context.line, function);
  175. // Check for critical OpenGL warnings
  176. if (msg.contains("OpenGL", Qt::CaseInsensitive) ||
  177. msg.contains("scene graph", Qt::CaseInsensitive) ||
  178. msg.contains("RHI", Qt::CaseInsensitive)) {
  179. fprintf(out, "[HINT] If you see crashes, try software rendering: set "
  180. "QT_QUICK_BACKEND=software\n");
  181. }
  182. break;
  183. case QtCriticalMsg:
  184. fprintf(out, "[CRITICAL] %s (%s:%u, %s)\n", local_msg.constData(), file,
  185. context.line, function);
  186. fprintf(
  187. out,
  188. "[CRITICAL] Try running with software rendering if this persists\n");
  189. break;
  190. case QtFatalMsg:
  191. fprintf(out, "[FATAL] %s (%s:%u, %s)\n", local_msg.constData(), file,
  192. context.line, function);
  193. fprintf(out, "[FATAL] === RECOVERY SUGGESTION ===\n");
  194. fprintf(out, "[FATAL] Run: run_debug_softwaregl.cmd\n");
  195. fprintf(out, "[FATAL] Or set: QT_QUICK_BACKEND=software\n");
  196. abort();
  197. }
  198. fflush(out);
  199. });
  200. qInfo() << "=== Standard of Iron - Starting ===";
  201. qInfo() << "Qt version:" << QT_VERSION_STR;
  202. // Linux-specific: prefer X11 over Wayland for better OpenGL compatibility
  203. #ifndef Q_OS_WIN
  204. if (qEnvironmentVariableIsSet("WAYLAND_DISPLAY") &&
  205. qEnvironmentVariableIsSet("DISPLAY")) {
  206. qputenv("QT_QPA_PLATFORM", "xcb");
  207. qInfo() << "Linux: Using X11 (xcb) platform";
  208. }
  209. #endif
  210. qInfo() << "Setting OpenGL environment...";
  211. qputenv("QT_OPENGL", "desktop");
  212. qputenv("QSG_RHI_BACKEND", "opengl");
  213. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  214. qInfo() << "Setting graphics API to OpenGLRhi...";
  215. QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGLRhi);
  216. #endif
  217. qInfo() << "Configuring OpenGL surface format...";
  218. QSurfaceFormat fmt;
  219. fmt.setVersion(3, 3);
  220. fmt.setProfile(QSurfaceFormat::CoreProfile);
  221. fmt.setDepthBufferSize(k_depth_buffer_bits);
  222. fmt.setStencilBufferSize(k_stencil_buffer_bits);
  223. fmt.setSamples(0);
  224. #ifdef Q_OS_WIN
  225. // Windows: Request compatibility profile for better driver support
  226. // Some Windows drivers have issues with Core profile on older hardware
  227. fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
  228. qInfo() << "Windows detected: Using OpenGL Compatibility Profile";
  229. #endif
  230. QSurfaceFormat::setDefaultFormat(fmt);
  231. qInfo() << "Surface format configured: OpenGL" << fmt.majorVersion() << "."
  232. << fmt.minorVersion();
  233. qInfo() << "Creating QGuiApplication...";
  234. QGuiApplication app(argc, argv);
  235. qInfo() << "QGuiApplication created successfully";
  236. // Use unique_ptr with custom deleter for Qt objects
  237. // This ensures proper cleanup order and prevents segfaults
  238. std::unique_ptr<LanguageManager> language_manager;
  239. std::unique_ptr<GameEngine> game_engine;
  240. std::unique_ptr<App::Models::GraphicsSettingsProxy> graphics_settings;
  241. std::unique_ptr<QQmlApplicationEngine> engine;
  242. qInfo() << "Creating LanguageManager...";
  243. language_manager = std::make_unique<LanguageManager>(&app);
  244. qInfo() << "LanguageManager created";
  245. qInfo() << "Creating GameEngine...";
  246. game_engine = std::make_unique<GameEngine>(&app);
  247. qInfo() << "GameEngine created";
  248. qInfo() << "Creating GraphicsSettingsProxy...";
  249. graphics_settings =
  250. std::make_unique<App::Models::GraphicsSettingsProxy>(&app);
  251. qInfo() << "GraphicsSettingsProxy created";
  252. qInfo() << "Setting up QML engine...";
  253. engine = std::make_unique<QQmlApplicationEngine>();
  254. qInfo() << "Adding context properties...";
  255. engine->rootContext()->setContextProperty("languageManager",
  256. language_manager.get());
  257. engine->rootContext()->setContextProperty("game", game_engine.get());
  258. engine->rootContext()->setContextProperty("graphicsSettings",
  259. graphics_settings.get());
  260. qInfo() << "Adding import path...";
  261. engine->addImportPath("qrc:/StandardOfIron/ui/qml");
  262. engine->addImportPath("qrc:/");
  263. qInfo() << "Registering QML types...";
  264. qmlRegisterType<GLView>("StandardOfIron", 1, 0, "GLView");
  265. // Register Theme singleton
  266. qmlRegisterSingletonType<Theme>("StandardOfIron", 1, 0, "Theme",
  267. &Theme::create);
  268. // Register StyleGuide singleton from QML file
  269. qmlRegisterSingletonType(QUrl("qrc:/StandardOfIron/ui/qml/StyleGuide.qml"),
  270. "StandardOfIron", 1, 0, "StyleGuide");
  271. qInfo() << "Loading Main.qml...";
  272. qInfo() << "Loading Main.qml...";
  273. engine->load(QUrl(QStringLiteral("qrc:/StandardOfIron/ui/qml/Main.qml")));
  274. qInfo() << "Checking if QML loaded...";
  275. if (engine->rootObjects().isEmpty()) {
  276. qWarning() << "Failed to load QML file";
  277. return -1;
  278. }
  279. qInfo() << "QML loaded successfully, root objects count:"
  280. << engine->rootObjects().size();
  281. // Connect language changed signal to retranslate QML
  282. qInfo() << "Connecting language change handler...";
  283. QObject::connect(language_manager.get(), &LanguageManager::languageChanged,
  284. engine.get(), &QQmlApplicationEngine::retranslate);
  285. qInfo() << "Language change handler connected";
  286. qInfo() << "Finding QQuickWindow...";
  287. auto *root_obj = engine->rootObjects().first();
  288. auto *window = qobject_cast<QQuickWindow *>(root_obj);
  289. if (window == nullptr) {
  290. qInfo() << "Root object is not a window, searching children...";
  291. window = root_obj->findChild<QQuickWindow *>();
  292. }
  293. if (window == nullptr) {
  294. qWarning() << "No QQuickWindow found for OpenGL initialization.";
  295. return -2;
  296. }
  297. qInfo() << "QQuickWindow found";
  298. qInfo() << "Setting window in GameEngine...";
  299. game_engine->setWindow(window);
  300. qInfo() << "Window set successfully";
  301. qInfo() << "Connecting scene graph signals...";
  302. qInfo() << "Connecting scene graph signals...";
  303. QObject::connect(
  304. window, &QQuickWindow::sceneGraphInitialized, window, [window]() {
  305. qInfo() << "Scene graph initialized!";
  306. if (auto *renderer_interface = window->rendererInterface()) {
  307. const auto api = renderer_interface->graphicsApi();
  308. QString name;
  309. switch (api) {
  310. case QSGRendererInterface::OpenGLRhi:
  311. name = "OpenGLRhi";
  312. break;
  313. case QSGRendererInterface::VulkanRhi:
  314. name = "VulkanRhi";
  315. break;
  316. case QSGRendererInterface::Direct3D11Rhi:
  317. name = "D3D11Rhi";
  318. break;
  319. case QSGRendererInterface::MetalRhi:
  320. name = "MetalRhi";
  321. break;
  322. case QSGRendererInterface::Software:
  323. name = "Software";
  324. break;
  325. default:
  326. name = "Unknown";
  327. break;
  328. }
  329. qInfo() << "QSG graphicsApi:" << name;
  330. }
  331. });
  332. QObject::connect(window, &QQuickWindow::sceneGraphError, &app,
  333. [&](QQuickWindow::SceneGraphError, const QString &msg) {
  334. qCritical()
  335. << "Failed to initialize OpenGL scene graph:" << msg;
  336. QGuiApplication::exit(3);
  337. });
  338. qInfo() << "Starting event loop...";
  339. int const result = QGuiApplication::exec();
  340. // Explicitly destroy in correct order to prevent segfault
  341. qInfo() << "Shutting down...";
  342. // Destroy QML engine first (destroys OpenGL context)
  343. engine.reset();
  344. qInfo() << "QML engine destroyed";
  345. // Then destroy game engine
  346. // OpenGL cleanup in destructors will be skipped if no valid context
  347. game_engine.reset();
  348. qInfo() << "GameEngine destroyed";
  349. // Finally destroy language manager
  350. language_manager.reset();
  351. qInfo() << "LanguageManager destroyed";
  352. #ifdef Q_OS_WIN
  353. // Check if we crashed during OpenGL initialization
  354. if (g_opengl_crashed) {
  355. qCritical() << "";
  356. qCritical() << "========================================";
  357. qCritical() << "OPENGL CRASH RECOVERY";
  358. qCritical() << "========================================";
  359. qCritical() << "";
  360. qCritical() << "The application crashed during OpenGL initialization.";
  361. qCritical()
  362. << "This is a known issue with Qt + some Windows graphics drivers.";
  363. qCritical() << "";
  364. qCritical() << "SOLUTION: Set environment variable before running:";
  365. qCritical() << " set QT_QUICK_BACKEND=software";
  366. qCritical() << "";
  367. qCritical() << "Or use the provided launcher:";
  368. qCritical() << " run_debug_softwaregl.cmd";
  369. qCritical() << "";
  370. return -1;
  371. }
  372. #endif
  373. return result;
  374. }