"use strict"; // Graphics card choice (client-freeze, 2026-10-08; docs/client/client-freeze.md). Chromium picks its GPU when the // process starts, so this runs in the launcher before app "ready" and a change applies at the next start. // The renderer's Options > Display > Graphics "Graphics card" (khaos/graphicsAutoTune.js) stores options.khaosGpuMode in // /settings.json: // "auto" (default) the dedicated GPU when the PC has one (force_high_performance_gpu). On a laptop with an // integrated + a dedicated GPU, Chromium otherwise draws on the integrated one (Windows' default // adapter), while games (Unity: the official Dofus 3 client) ask for the dedicated one. A PC with one // GPU, or a desktop whose screen is on the dedicated GPU, gets the same adapter as before (measured). // "integrated" the power-saving GPU (force_low_power_gpu): battery, heat, or a dedicated GPU whose driver crashes. // "software" no graphics card at all: WebGL runs on the CPU. Windows / macOS: hardware acceleration off (Windows' // WARP renderer). Linux has no WARP and Chromium 146 gives no WebGL at all with acceleration off, so // there it is ANGLE's SwiftShader (the "software" rung below). // KHAOS_GPU_MODE overrides the setting (tests). // // // Graphics fallback ladder (Linux player report 2026-11-15; Windows: player SOMALO 2026-11-25, a first-generation // Intel HD Graphics on a 2012 driver: Chromium's driver bug list entry 92 "Old Intel drivers cannot reliably support // D3D11" (driver <= 9.18) sends ANGLE to Direct3D 9, which has OpenGL ES 2.0 only, so no WebGL2). When the renderer // cannot start WebGL2 it calls fallback() (desktopIpc "app:gpu-fallback"), which records the failure in // /gpu-fallback.json (the profile's, nowhere else) and restarts Khaos once on the next rung: // "native" Chromium's defaults: every PC where WebGL2 works, unchanged (no file is kept) // "compat" Windows: --ignore-gpu-blocklist --use-angle=d3d11 --disable-gpu-driver-bug-workarounds (D3D11 on a // D3D10.x card gives OpenGL ES 3.0, so WebGL2, once entry 92 no longer turns D3D11 off) // Linux: --ignore-gpu-blocklist, and X11 (XWayland) instead of native Wayland when both are there. The // X11 choice is a real command-line argument of the restart (rungArgs): Electron picks its Ozone platform // before main.cjs runs, so an appended --ozone-platform=x11 only reached the child processes, a GPU // process on X11 under a browser on Wayland, which crashed (exit 139) at every start (F11 #155, Arch + // Wayland + NVIDIA, 2026-11-26) // "software" ANGLE on SwiftShader (--use-angle=swiftshader --enable-unsafe-swiftshader): the CPU draws, slow, no GPU // driver involved (Windows, Electron 41: WebGL 2.0 on "SwiftShader Device (Subzero)", 2026-11-25) // "warp" Windows / macOS "software" Graphics card option only: hardware acceleration off (WebGL2 on Windows' // WARP); when it fails the next rung is "software" // One automatic restart per process at most. A rung the ladder chose counts as working once the renderer says WebGL2 // is up (ready(), "app:gpu-ready"). A start on such a rung that never got there and did not quit cleanly (a crash, a // freeze, a killed process) sends the next start to the next rung, without a restart. The rung that works stays in // the file, so later starts begin there. The file is reset when the Electron version or the "Graphics card" option // changes, when the player asks for it (reset(), "app:gpu-reset": the software-mode notice, the option; retryAll(): // "Retry" in the final message) and when the GPU driver list changes (checked by ready() and fallback()). After the // last rung failed the file keeps "exhausted" with the GPU drivers: later starts show the final message at once (what // was tried, the GL renderer and Chromium's feature status) instead of restarting through every rung again. // startCheck() runs before the first window (2026-11-26): a rung without WebGL2 steps at start, not after "Play". // KHAOS_GPU_FALLBACK= forces a rung (support, manual checks) and then never steps. // KHAOS_GPU_FALLBACK_LADDER=1 turns the ladder on on macOS and KHAOS_GPU_FALLBACK_FAIL=, makes those rungs fail // (Windows: --use-angle=d3d9, ES 2.0 like player SOMALO's Intel; elsewhere --use-gl=disabled): local checks only. const fs = require("fs"); const path = require("path"); const { spawn } = require("child_process"); const MODES = ["auto", "integrated", "software"]; const RUNGS = ["native", "compat", "software"]; const ALL_RUNGS = [...RUNGS, "warp"]; const STATE_FILE = "gpu-fallback.json"; /** The stored choice ("auto" when absent, unreadable or unknown). */ function readGpuMode(userData, env = process.env) { if (MODES.includes(env.KHAOS_GPU_MODE)) return env.KHAOS_GPU_MODE; try { const mode = JSON.parse(fs.readFileSync(path.join(userData, "settings.json"), "utf8"))?.options?.khaosGpuMode; return MODES.includes(mode) ? mode : "auto"; } catch { return "auto"; } } const ladderOn = (env, platform) => platform === "linux" || platform === "win32" || env.KHAOS_GPU_FALLBACK_LADDER === "1"; /** The rung after `rung` (null: none left). */ function nextRung(rung) { return rung === "warp" ? "software" : RUNGS[RUNGS.indexOf(rung) + 1] ?? null; } /** First rung of a fresh ladder for a "Graphics card" option. */ function firstRung(mode, platform) { if (mode !== "software") return "native"; return platform === "linux" ? "software" : "warp"; } /** Chromium switches of a rung ([name] or [name, value]), appended before app "ready". */ function rungSwitches(rung, env = process.env, platform = process.platform) { let switches; if (platform === "linux") { // (X11 under Wayland is not a switch: rungArgs) switches = rung === "compat" ? [["ignore-gpu-blocklist"]] : rung === "software" ? [["use-angle", "swiftshader"], ["enable-unsafe-swiftshader"]] : []; } else { switches = rung === "compat" ? [["ignore-gpu-blocklist"], ["use-angle", "d3d11"], ["disable-gpu-driver-bug-workarounds"]] : rung === "software" ? [["use-angle", "swiftshader"], ["enable-unsafe-swiftshader"]] : []; } // A rung made to fail (local checks): Windows = ANGLE on Direct3D 9, ES 2.0 and WebGL 1 only, what player SOMALO's // old Intel driver gives; elsewhere no GL at all. const failing = String(env.KHAOS_GPU_FALLBACK_FAIL || "").split(","); if (failing.includes(rung)) { if (platform === "win32") switches = [...switches.filter(([name]) => name !== "use-angle"), ["use-angle", "d3d9"]]; else switches.push(["use-gl", "disabled"]); } return switches; } /** * Command-line arguments a restart onto `rung` adds. Linux, Wayland session with XWayland, compat / software: * --ozone-platform=x11 (X11 is the path Chromium's GPU code has been tested on longest). Only a real argument works: * Electron reads the Ozone platform before main.cjs (rungSwitches would reach the child processes alone). None when * the start already names an Ozone platform (the player's own, or an earlier restart's). */ function rungArgs(rung, env = process.env, platform = process.platform, argv = process.argv) { if (platform !== "linux" || (rung !== "compat" && rung !== "software")) return []; if (!env.WAYLAND_DISPLAY || !env.DISPLAY) return []; if (argv.some((arg) => /^--ozone-platform(=|$)/.test(String(arg)))) return []; return ["--ozone-platform=x11"]; } function readState(userData) { try { const state = JSON.parse(fs.readFileSync(path.join(userData, STATE_FILE), "utf8")); return state && typeof state === "object" && !Array.isArray(state) ? state : null; } catch { return null; } } function writeState(userData, state) { const file = path.join(userData, STATE_FILE); if (state === null) return fs.rmSync(file, { force: true }); fs.writeFileSync(file, JSON.stringify(state, null, 2)); } function tryWrite(userData, state) { try { writeState(userData, state); return true; } catch { return false; } } const isSoftware = (rung) => rung === "software" || rung === "warp"; // What applyGpuMode decided (fallback() / ready() step from it). let current = null; /** Applies the choice; call before app "ready". Returns the mode applied (for the stability log). */ function applyGpuMode(app, userData, env = process.env, platform = process.platform) { const mode = readGpuMode(userData, env); current = null; if (!ladderOn(env, platform)) { if (mode === "software") app.disableHardwareAcceleration(); else app.commandLine.appendSwitch(mode === "integrated" ? "force_low_power_gpu" : "force_high_performance_gpu"); return mode; } const electron = process.versions.electron || ""; const forced = ALL_RUNGS.includes(env.KHAOS_GPU_FALLBACK) ? env.KHAOS_GPU_FALLBACK : null; const stored = readState(userData); let state = stored; if (!state || state.electron !== electron || state.mode !== mode || !ALL_RUNGS.includes(state.rung)) { state = { electron, mode, rung: firstRung(mode, platform), failures: [] }; } let rung = forced ?? state.rung; // The last start on a rung the ladder chose never got WebGL2 and did not quit cleanly: the next rung, at once. if (!forced && rung !== "native" && state.running === rung && state.confirmed !== rung) { const failures = [...(state.failures ?? []), { rung, reason: "the last start on this mode ended before WebGL2 was up (crash, freeze or killed)", at: new Date().toISOString() }].slice(-6); const next = nextRung(rung); // On the last rung a crash proves nothing about WebGL2 (a slow software start killed by the player, a closed // terminal): Khaos stays on it. Only a real "no WebGL2" (start check, renderer) ends in the final message. state = next ? { ...state, rung: next, failures, running: null } : { ...state, failures, running: null }; rung = state.rung; } // Linux "software" option = the "software" rung (Chromium 146 gives no WebGL with acceleration off there); Windows / // macOS "software" option = acceleration off, the "warp" rung. if (rung === "warp") app.disableHardwareAcceleration(); else if (mode !== "software") app.commandLine.appendSwitch(mode === "integrated" ? "force_low_power_gpu" : "force_high_performance_gpu"); for (const [name, value] of rungSwitches(rung, env, platform)) { if (value === undefined) app.commandLine.appendSwitch(name); else app.commandLine.appendSwitch(name, value); } // A start on a rung not known to work yet: marked running until WebGL2 is up or Khaos quits cleanly. const watched = !forced && rung !== "native" && state.confirmed !== rung; if (watched) state = { ...state, running: rung }; // (a rung forced by KHAOS_GPU_FALLBACK leaves the file as it is) if (!forced && (watched || state !== stored)) { const nothingToKeep = rung === "native" && !state.exhausted && !(state.failures ?? []).length; if (!nothingToKeep) tryWrite(userData, state); else if (stored) tryWrite(userData, null); } current = { userData, state, rung, platform, // a rung forced by KHAOS_GPU_FALLBACK, or the Linux "software" option (already the last rung), never steps forced: forced !== null || (mode === "software" && platform === "linux"), envForced: forced !== null, stepping: false, settled: false, }; if (watched && typeof app.on === "function") { app.on("will-quit", () => { // a clean quit before WebGL2 (e.g. the game data folder step closed) is not a crash if (!current || current.stepping || current.settled || current.state.running !== rung) return; current.state = { ...current.state, running: null }; tryWrite(userData, current.state); }); } return mode; } /** The graphics rung in use ("" when the ladder is off), for the stability log. */ function fallbackRung() { return current ? current.rung : ""; } function withTimeout(promise, ms) { let timer; return Promise.race([promise, new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); })]).finally(() => clearTimeout(timer)); } /** The GPU adapters and their drivers ("8086:46 8.15.10.2900, ..."), sorted: a new driver or card changes it. */ async function gpuSignature(app) { try { const info = await withTimeout(app.getGPUInfo("basic"), 3000); return (info?.gpuDevice ?? []) .map((d) => `${Number(d.vendorId).toString(16)}:${Number(d.deviceId).toString(16)} ${d.driverVersion || "?"}`) .sort() .join(", "); } catch { return ""; } } /** What a player can send: rungs tried, the GL renderer, Chromium's feature status, the display session. */ async function describeGpu(app, env = process.env, failures = []) { const lines = []; for (const failure of failures) lines.push(`${failure.rung}: ${failure.reason || "?"}`); try { const info = await withTimeout(app.getGPUInfo("complete"), 3000); const aux = info?.auxAttributes ?? {}; const devices = (info?.gpuDevice ?? []) .map((d) => `${Number(d.vendorId).toString(16)}:${Number(d.deviceId).toString(16)}${d.driverVendor ? ` ${d.driverVendor}` : ""}${d.driverVersion ? ` ${d.driverVersion}` : ""}${d.active ? " (active)" : ""}`) .join(", "); lines.push(`GL: ${aux.glRenderer || "?"} | ${aux.glVersion || "?"}${aux.glImplementationParts ? ` | ${aux.glImplementationParts}` : ""}`); if (devices) lines.push(`GPU: ${devices}`); } catch { lines.push("GL: ?"); } try { const status = app.getGPUFeatureStatus(); lines.push(`Chromium: ${["webgl", "gpu_compositing", "rasterization", "opengl", "vulkan"].map((k) => `${k}=${status[k] ?? "?"}`).join(" ")}`); } catch {} const session = process.platform === "linux" ? `, session ${env.XDG_SESSION_TYPE || "?"}${env.WAYLAND_DISPLAY ? " (Wayland)" : ""}${env.DISPLAY ? " (X)" : ""}` : ""; lines.push(`${process.platform} ${process.arch}, Electron ${process.versions.electron || "?"}${session}`); return lines.join("\n").slice(0, 2000); } /** * The installed client's launcher (player.cjs) adds its variables to process.env before main.cjs loads, and a * restarted Khaos inherits this process's environment: it must start from the one Khaos was started with (an inherited * KHAOS_GAME_DATA_ROOT would skip the game data folder checks, player.cjs GAME_DATA_SETUP). */ function restoreLaunchEnv(launchEnv = globalThis.__khaosLaunchEnv, target = process.env) { if (!launchEnv || typeof launchEnv !== "object") return; for (const key of Object.keys(target)) if (!Object.hasOwn(launchEnv, key)) delete target[key]; for (const [key, value] of Object.entries(launchEnv)) if (target[key] !== value) target[key] = value; } /** * Starts Khaos again once this process is gone (an AppImage's mount goes with it: start the AppImage file itself), with * the arguments the next rung adds (rungArgs). */ function relaunch(app, env = process.env, rung = null, platform = process.platform) { const appImage = env.APPIMAGE; const args = [...process.argv.slice(1), ...(rung ? rungArgs(rung, env, platform) : [])]; if (env === process.env) restoreLaunchEnv(); if (appImage) { const child = spawn("/bin/sh", ["-c", 'pid="$1"; shift; while kill -0 "$pid" 2>/dev/null; do sleep 0.3; done; exec "$@"', "khaos-relaunch", String(process.pid), appImage, ...args], { detached: true, stdio: "ignore", }); child.unref(); } else { app.relaunch({ args }); } app.quit(); // a window that refuses to close must not keep the old process (and its single-instance lock) alive setTimeout(() => app.exit(0), 8000).unref(); } /** * The renderer could not start WebGL2 (`reason`: its failure text). With the ladder on and a rung left: records the * failure, restarts Khaos on the next rung and answers { retrying: true }. Otherwise { retrying: false, details }. */ async function fallback(app, reason, env = process.env) { const text = typeof reason === "string" ? reason.slice(0, 500) : ""; if (!current) return { retrying: false, details: await describeGpu(app, env) }; if (current.stepping) return { retrying: true, rung: current.next }; const failures = [...(current.state.failures ?? []), { rung: current.rung, reason: text, at: new Date().toISOString() }].slice(-6); const gpu = await gpuSignature(app); // Every rung already failed on this PC: no restart, the final message at once (player SOMALO 2026-11-26: each start // went through every restart again and looked like a loop). A new GPU driver or card opens the ladder again. const exhausted = current.state.exhausted === true && !(gpu && current.state.gpu && gpu !== current.state.gpu); const next = current.forced || exhausted ? null : nextRung(current.rung); if (next) { current.stepping = true; current.next = next; const state = { ...current.state, rung: next, failures, running: null, confirmed: null, ...(gpu ? { gpu } : {}) }; delete state.exhausted; if (!tryWrite(current.userData, state)) { current.stepping = false; return { retrying: false, details: await describeGpu(app, env, failures) }; } relaunch(app, env, next, current.platform); return { retrying: true, rung: next }; } const details = await describeGpu(app, env, failures); current.settled = true; // Every rung failed: kept (with the GPU drivers) so the next starts show the final message without restarting through // every rung again; "Retry" in that message (reset), a new driver, a new Electron or another Graphics card option // starts the ladder from the top. A rung forced by KHAOS_GPU_FALLBACK keeps its file as it was. const { electron, mode } = current.state; tryWrite(current.userData, current.envForced ? { ...current.state, failures, running: null } : { electron, mode, rung: firstRung(mode, current.platform), failures, exhausted: true, ...(gpu ? { gpu } : {}) }); return { retrying: false, details, exhausted: !current.envForced }; } /** * Before the first window (DesktopApplication boot, globalThis.__khaosGpuStartCheck): is WebGL2 there on this rung? The * renderer only starts WebGL2 after the player's "Play" (server assets first), so a failing rung used to restart Khaos * back on the login screen, once per rung (player SOMALO 2026-11-26: "the launcher starts again by itself when I click * Play"). Chromium's GL version answers cheaply: OpenGL ES 3 or later = WebGL2 possible (every working PC, no probe). * Anything else (ES 2.0 on Direct3D 9, "Disabled", unknown) is checked with `probe()` (a hidden page asking for a WebGL2 * context); a failure steps the ladder now. Answers { proceed, retrying, details, glVersion, probed }: proceed false = * Khaos is restarting on the next rung (retrying) or the final message must show (details). */ async function startCheck(app, probe, env = process.env) { if (!current) return { proceed: true, glVersion: "", probed: false }; let glVersion = ""; try { glVersion = String((await withTimeout(app.getGPUInfo("complete"), 5000))?.auxAttributes?.glVersion ?? ""); } catch {} const es = /OpenGL ES (\d+)/.exec(glVersion); if (es && Number(es[1]) >= 3) return { proceed: true, glVersion, probed: false }; let result; try { result = await probe(); } catch (error) { result = { ok: false, reason: `probe failed: ${error instanceof Error ? error.message : String(error)}` }; } if (result?.ok) return { proceed: true, glVersion, probed: true }; const answer = await fallback(app, `start check: ${result?.reason || "no WebGL2"} (GL ${glVersion || "?"})`, env); return { proceed: false, glVersion, probed: true, ...answer }; } /** "Retry" in the final message: the ladder from the top, at once. */ function retryAll(app, env = process.env) { reset(); relaunch(app, env, null, current?.platform); } /** * The renderer has WebGL2. A rung the ladder chose is kept as working; a changed GPU driver list (a new driver, * another card) resets the ladder, so the next start tries the normal mode again. * Answers { rung ("" when the ladder is off), software, first (first start that worked on this rung), driverChanged }. */ async function ready(app) { const answer = (fields = {}) => ({ rung: current?.rung ?? "", software: isSoftware(current?.rung), first: false, driverChanged: false, ...fields }); if (!current || current.settled || current.stepping) return answer(); current.settled = true; if (current.envForced) return answer(); const { state, rung } = current; if (rung === "native") { // the normal mode works: nothing to remember if (readState(current.userData)) tryWrite(current.userData, null); return answer(); } const gpu = await gpuSignature(app); if (state.confirmed === rung && state.gpu && gpu && gpu !== state.gpu) { tryWrite(current.userData, null); return answer({ driverChanged: true, gpu, previousGpu: state.gpu }); } const next = { ...state, running: null, confirmed: rung, ...(gpu ? { gpu } : {}) }; delete next.exhausted; current.state = next; tryWrite(current.userData, next); return answer({ first: state.confirmed !== rung }); } /** The player asked to try the normal graphics mode again (from the next start on). */ function reset() { if (!current) return false; current.settled = true; return tryWrite(current.userData, null); } module.exports = { MODES, RUNGS, readGpuMode, applyGpuMode, fallbackRung, rungSwitches, rungArgs, nextRung, describeGpu, fallback, startCheck, retryAll, ready, reset, restoreLaunchEnv };