main.cpp 16 KB

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