197 lines
9.6 KiB
C#
197 lines
9.6 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Diagnostics;
|
|
using System.Text;
|
|
|
|
namespace EonaCat.XSBOX.Launcher;
|
|
|
|
internal sealed partial class LauncherForm
|
|
{
|
|
const string PreloadPrefix = "EONACAT_PRELOAD|";
|
|
const int MaxOutputChars = 250_000;
|
|
const int KeptOutputChars = 180_000;
|
|
const int MaxLinesPerTick = 500;
|
|
|
|
// Engine output arrives on thread-pool threads. It is queued here and drained by a UI timer in
|
|
// batches, instead of posting one UI message (and one TextBox append) per line.
|
|
readonly ConcurrentQueue<(string Text, bool FromGame)> pendingLines = new();
|
|
Process? gameProcess;
|
|
bool engineBusy;
|
|
|
|
void LaunchGame()
|
|
{
|
|
SaveSettings();
|
|
if (gameProcess is { HasExited: false })
|
|
{
|
|
status.Text = "The game is already running.";
|
|
return;
|
|
}
|
|
if (!File.Exists(exe)) { MessageBox.Show(this, "eonacat-xsbox.exe was not found. Build the project first using build.bat.", "Engine not built", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
|
|
var selectedExe = selectedGame?.Executable;
|
|
if (string.IsNullOrWhiteSpace(selectedExe) || !File.Exists(selectedExe))
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(gamePath.Text) && File.Exists(gamePath.Text)) selectedExe = gamePath.Text;
|
|
else { BrowseGame(); if (!File.Exists(gamePath.Text)) return; selectedExe = gamePath.Text; }
|
|
}
|
|
|
|
var p = new ProcessStartInfo(exe)
|
|
{
|
|
UseShellExecute = false, CreateNoWindow = true,
|
|
RedirectStandardOutput = true, RedirectStandardError = true,
|
|
WorkingDirectory = root
|
|
};
|
|
p.Environment["EONACAT_XS_HOME"] = home;
|
|
// Use the values chosen in the launcher (fullscreen defaults to "stretch") instead of forcing "1".
|
|
SetEngineEnvironment(p, "EONACAT_XS_FULLSCREEN", "stretch");
|
|
SetEngineEnvironment(p, "EONACAT_XS_MOUSE_CAPTURE", "1");
|
|
p.ArgumentList.Add("play"); p.ArgumentList.Add(selectedExe!);
|
|
var process = new Process { StartInfo = p, EnableRaisingEvents = true };
|
|
process.OutputDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, true)); };
|
|
process.ErrorDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, true)); };
|
|
process.Exited += (_, _) =>
|
|
{
|
|
if (IsDisposed || !IsHandleCreated) return;
|
|
try
|
|
{
|
|
BeginInvoke(new Action(() =>
|
|
{
|
|
PumpEngineOutput();
|
|
preloadDialog?.Close(); preloadDialog = null;
|
|
status.Text = "Game process exited.";
|
|
if (ReferenceEquals(gameProcess, process)) gameProcess = null;
|
|
process.Dispose();
|
|
}));
|
|
}
|
|
catch (InvalidOperationException) { } // window closed while the game was shutting down
|
|
};
|
|
try
|
|
{
|
|
if (!process.Start()) { process.Dispose(); MessageBox.Show(this, "The game engine could not be started.", "Launch failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
process.Dispose();
|
|
MessageBox.Show(this, "The game engine could not be started: " + ex.Message, "Launch failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
|
return;
|
|
}
|
|
gameProcess = process;
|
|
process.BeginOutputReadLine(); process.BeginErrorReadLine();
|
|
status.Text = $"Launching {selectedGame?.Name ?? Path.GetFileName(Path.GetDirectoryName(selectedExe!))}…";
|
|
}
|
|
|
|
void SetEngineEnvironment(ProcessStartInfo info, string key, string fallback)
|
|
{
|
|
var value = editors.TryGetValue(key, out var editor) && editor is ComboBox combo
|
|
? combo.SelectedItem?.ToString() ?? fallback
|
|
: fallback;
|
|
if (string.IsNullOrEmpty(value)) info.Environment.Remove(key); // "Auto"/off: leave it unset
|
|
else info.Environment[key] = value;
|
|
}
|
|
|
|
/// <summary>Drains queued engine output on the UI thread: one parse pass, one TextBox append.</summary>
|
|
void PumpEngineOutput()
|
|
{
|
|
if (IsDisposed || pendingLines.IsEmpty) return;
|
|
var text = new StringBuilder();
|
|
for (var n = 0; n < MaxLinesPerTick && pendingLines.TryDequeue(out var item); n++)
|
|
{
|
|
if (item.FromGame && HandlePreloadSignal(item.Text)) continue;
|
|
if (item.FromGame) preloadDialog?.SetDetail(item.Text);
|
|
text.AppendLine(item.Text);
|
|
}
|
|
if (text.Length > 0) AppendOutput(text.ToString());
|
|
}
|
|
|
|
void AppendOutput(string text)
|
|
{
|
|
output.AppendText(text);
|
|
if (output.TextLength > MaxOutputChars)
|
|
{
|
|
output.Text = output.Text[^KeptOutputChars..];
|
|
output.SelectionStart = output.TextLength;
|
|
output.ScrollToCaret();
|
|
}
|
|
}
|
|
|
|
/// <summary>Returns true when the line was a preload control signal (and so is not shown in the log).</summary>
|
|
bool HandlePreloadSignal(string line)
|
|
{
|
|
if (!line.StartsWith(PreloadPrefix, StringComparison.Ordinal)) return false;
|
|
var signal = line[PreloadPrefix.Length..].Trim();
|
|
if (signal == "START")
|
|
{
|
|
preloadDialog?.Close();
|
|
preloadDialog = new PreloadProgressDialog();
|
|
preloadDialog.Show(this);
|
|
status.Text = "Preparing shaders and graphics pipelines…";
|
|
}
|
|
else if (signal == "SHADERS") preloadDialog?.SetStage("Compiling shaders", "Translating the game's shader library and filling the shader cache.");
|
|
else if (signal == "PIPELINES") preloadDialog?.SetStage("Building graphics pipelines", "Compiling pipeline states for your graphics adapter.");
|
|
else if (signal.StartsWith("DONE", StringComparison.Ordinal))
|
|
{
|
|
preloadDialog?.Complete(signal == "DONE");
|
|
status.Text = signal == "DONE" ? "Shader and pipeline preparation complete." : "Preload finished with warnings; starting the game.";
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async Task InstallDetectedGpuRuntime()
|
|
{
|
|
string gpu = DetectGpuVendor();
|
|
if (gpu == "NVIDIA") await RunEngineCommand("get-dlss");
|
|
else if (gpu == "AMD")
|
|
{
|
|
var answer = MessageBox.Show(this, "An AMD Radeon adapter was detected. The AMD FidelityFX package supplies the FSR 3 frame-generation runtime only; it does NOT add an AMD Radeon rendering backend. Download the AMD runtime anyway?", "AMD runtime compatibility", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
|
|
if (answer == DialogResult.Yes) await RunEngineCommand("get-fsr");
|
|
}
|
|
else MessageBox.Show(this, "No supported NVIDIA or AMD adapter was identified automatically. Choose the appropriate vendor installer manually, or update your graphics driver.", "GPU not identified", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
}
|
|
|
|
static string DetectGpuVendor()
|
|
{
|
|
try
|
|
{
|
|
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}");
|
|
if (key != null)
|
|
foreach (var sub in key.GetSubKeyNames().Where(n => n.Length == 4 && int.TryParse(n, out _)))
|
|
{
|
|
using var item = key.OpenSubKey(sub);
|
|
var desc = (item?.GetValue("DriverDesc")?.ToString() ?? "") + " " + (item?.GetValue("ProviderName")?.ToString() ?? "");
|
|
if (desc.Contains("NVIDIA", StringComparison.OrdinalIgnoreCase)) return "NVIDIA";
|
|
if (desc.Contains("AMD", StringComparison.OrdinalIgnoreCase) || desc.Contains("Radeon", StringComparison.OrdinalIgnoreCase)) return "AMD";
|
|
}
|
|
}
|
|
catch { }
|
|
return "Unknown";
|
|
}
|
|
|
|
async Task RunEngineCommand(string command, string? argument = null)
|
|
{
|
|
if (!File.Exists(exe)) { MessageBox.Show(this, "Build eonacat-xsbox.exe first with build.bat.", "Engine not built", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
|
|
if (engineBusy) { status.Text = "Another engine command is still running. Please wait for it to finish."; return; }
|
|
engineBusy = true;
|
|
try
|
|
{
|
|
PumpEngineOutput();
|
|
AppendOutput($"> eonacat-xsbox.exe {command}{(argument == null ? "" : " " + argument)}{Environment.NewLine}");
|
|
tabs.SelectedTab = tabs.TabPages["Installer log"];
|
|
var psi = new ProcessStartInfo(exe) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = root, CreateNoWindow = true };
|
|
psi.Environment["EONACAT_XS_HOME"] = home;
|
|
psi.ArgumentList.Add(command);
|
|
if (!string.IsNullOrWhiteSpace(argument)) psi.ArgumentList.Add(argument);
|
|
using var proc = new Process { StartInfo = psi, EnableRaisingEvents = true };
|
|
proc.OutputDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue((e.Data, false)); };
|
|
proc.ErrorDataReceived += (_, e) => { if (e.Data != null) pendingLines.Enqueue(("ERROR: " + e.Data, false)); };
|
|
proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine();
|
|
await proc.WaitForExitAsync();
|
|
PumpEngineOutput();
|
|
status.Text = proc.ExitCode == 0 ? $"{command} completed." : $"{command} failed (exit {proc.ExitCode}). See Installer log.";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
AppendOutput($"ERROR: {ex.Message}{Environment.NewLine}");
|
|
status.Text = $"{command} could not run: {ex.Message}";
|
|
}
|
|
finally { engineBusy = false; }
|
|
}
|
|
}
|