using System.Globalization;
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Application;
public sealed record DebugScene(string LevelFile, string Code, string[] Starts);
public enum DebugAction { None, Resume, Camera, SkipCutscene, RefillEnergy, GiveJetpack, ApplySceneTask, LoadScene, Reset, ForceControl, ToggleOverlay,
Noclip, NoclipSpeed, StopMotion, ShowObjective, ReturnNoclipEntry, LevelAvailability, InputOrder, ApplyJetpackState,
CameraObstruction, MuteMusic, MuteSpeech, MuteEffects, RestartMusic, StopEffects, SaveCheckpoint, LoadCheckpoint, Practice,
GiveInvisible, UnequipGadget, GiveBubble, GiveBaseball }
public sealed record DebugMenuView(string[] Lines, int SelectedLine);
public sealed record DebugStatus(string Level, string Start, Vector3 Root, float Yaw, float Speed,
bool Grounded, float Energy, int Score, int SceneTask, string Cutscene, bool Controlled,
int Issues, float FarPlane, bool Inspecting, bool ForcedControl = false, bool DiagnosticsVisible = false, string? CameraMode = null,
DebugSystems? Systems = null);
public sealed record DebugSystems
{
public bool Noclip { get; init; }
public float NoclipSpeed { get; init; } = 600;
public Vector3 Velocity { get; init; }
public Vector3 PendingImpulse { get; init; }
public int MovementMode { get; init; }
public bool InputAfterPlayer { get; init; }
public int JumpState { get; init; }
public float JumpHold { get; init; }
public float BurnRemaining { get; init; }
public int JetpackAvailability { get; init; }
public float InvisibleRemaining { get; init; }
public float InvisibleRecharge { get; init; }
public bool Targetable { get; init; } = true;
public string BubblePhase { get; init; } = "OFF";
public string BaseballState { get; init; } = "OFF";
public float BodyRadius { get; init; } = 60;
public float BodyFactor { get; init; } = 1.265f;
public int Objective { get; init; }
public float ObjectiveTime { get; init; }
public bool? CameraObstruction { get; init; }
public int CameraPolygons { get; init; }
public int CameraWallPolygons { get; init; }
public int CameraTests { get; init; }
public bool AudioAvailable { get; init; }
public bool MusicMuted { get; init; }
public bool SpeechMuted { get; init; }
public bool EffectsMuted { get; init; }
public int MusicBytes { get; init; }
public int SpeechBytes { get; init; }
public int EffectBytes { get; init; }
}
/// Modern investigation tools, deliberately separate from recovered game UI.
public sealed class DebugMenu
{
public const uint ToggleKey = 58; // SDL scancode F1; F11 remains fullscreen.
public const uint NoclipKey = 60; // F3; F2 remains live diagnostics.
public const int ItemCount = 12;
public const int PageCount = 3;
public int Page { get; private set; }
public int PageItems => Page switch { 1 => 14, 2 => 9, _ => ItemCount };
private static readonly float[] FlySpeeds = [300, 600, 1200, 2400];
private int flySpeedIndex = 1, jetpackStateIndex = 1;
private static readonly int[] JetpackStates = [0, 1, 4];
public float FlySpeed => FlySpeeds[flySpeedIndex];
public int JetpackState => JetpackStates[jetpackStateIndex];
public bool Open { get; private set; }
public int Selected { get; private set; }
public int SceneTask { get; private set; }
public string Message { get; set; } = "";
private readonly DebugScene[] scenes;
private int sceneIndex, startIndex;
public DebugScene? Scene => scenes.Length == 0 ? null : scenes[sceneIndex];
public string? Start => Scene is { } scene ? scene.Starts[startIndex] : null;
public DebugScene? FindScene(string code) => scenes.FirstOrDefault(s => s.Code == code);
public DebugMenu(IEnumerable scenes, string? currentLevel, string? currentStart)
{
this.scenes = scenes.ToArray();
if (this.scenes.Any(s => s.Starts.Length == 0)) throw new ArgumentException("Debug scenes require a startpoint");
sceneIndex = Math.Max(0, Array.FindIndex(this.scenes,
s => string.Equals(s.LevelFile, currentLevel, StringComparison.OrdinalIgnoreCase)));
if (Scene is { } selected)
startIndex = Math.Max(0, Array.FindIndex(selected.Starts,
s => string.Equals(s, currentStart, StringComparison.OrdinalIgnoreCase)));
}
public void Toggle(int currentSceneTask)
{
Open = !Open;
if (Open) { SceneTask = currentSceneTask; Message = ""; }
}
public void Close() => Open = false;
public DebugAction Key(uint scancode, bool repeat = false)
{
if (!Open) return DebugAction.None;
if (scancode == 41) { Close(); return DebugAction.None; }
if (scancode == 43 && !repeat) { Page = (Page + 1) % PageCount; Selected = 0; return DebugAction.None; }
if (scancode is 82 or 81)
Selected = (Selected + (scancode == 82 ? PageItems - 1 : 1)) % PageItems;
else if (scancode is 80 or 79 or 75 or 78)
{
var direction = scancode is 80 or 78 ? -1 : 1;
if (Page == 1 && Selected == 1)
flySpeedIndex = (flySpeedIndex + FlySpeeds.Length + direction) % FlySpeeds.Length;
else if (Page == 1 && Selected == 7)
jetpackStateIndex = (jetpackStateIndex + JetpackStates.Length + direction) % JetpackStates.Length;
else if (Page == 0 && Selected == 5)
SceneTask = (int)Math.Clamp((long)SceneTask + direction * (scancode is 75 or 78 ? 10 : 1), 0, 999);
else if (Page == 0 && Selected == 6 && scenes.Length > 0)
{ sceneIndex = (sceneIndex + scenes.Length + direction) % scenes.Length; startIndex = 0; }
else if (Page == 0 && Selected == 7 && Scene is { } scene)
startIndex = (startIndex + scene.Starts.Length + direction) % scene.Starts.Length;
}
else if (scancode is 40 or 88 && !repeat)
{
if (Page == 1) return Selected switch
{
0 => DebugAction.Noclip, 1 => DebugAction.NoclipSpeed, 2 => DebugAction.StopMotion,
3 => DebugAction.ShowObjective, 4 => DebugAction.ReturnNoclipEntry,
5 => DebugAction.LevelAvailability, 6 => DebugAction.InputOrder,
8 => DebugAction.ApplyJetpackState, 9 => DebugAction.RefillEnergy,
10 => DebugAction.GiveInvisible, 11 => DebugAction.UnequipGadget, 12 => DebugAction.GiveBubble,
13 => DebugAction.GiveBaseball, _ => DebugAction.None
};
if (Page == 2) return Selected switch
{
0 => DebugAction.CameraObstruction, 1 => DebugAction.MuteMusic, 2 => DebugAction.MuteSpeech,
3 => DebugAction.MuteEffects, 4 => DebugAction.RestartMusic, 5 => DebugAction.StopEffects,
6 => DebugAction.SaveCheckpoint, 7 => DebugAction.LoadCheckpoint, 8 => DebugAction.Practice,
_ => DebugAction.None
};
return Selected switch
{
0 => DebugAction.Resume, 1 => DebugAction.Camera, 2 => DebugAction.SkipCutscene,
3 => DebugAction.RefillEnergy, 4 => DebugAction.GiveJetpack, 5 => DebugAction.ApplySceneTask,
8 => Scene == null ? DebugAction.None : DebugAction.LoadScene, 9 => DebugAction.Reset,
10 => DebugAction.ForceControl,
11 => DebugAction.ToggleOverlay,
_ => DebugAction.None
};
}
return DebugAction.None;
}
public DebugMenuView View(DebugStatus status)
{
if (!Open) return new([], -1);
var c = CultureInfo.InvariantCulture;
string F(float value) => value.ToString("0.0", c);
var system = status.Systems ?? new();
if (Page != 0)
{
string V(Vector3 v) => $"{F(v.X)} {F(v.Y)} {F(v.Z)}";
string[] header = ["NEUTRON DEBUG MENU - F1", $"PAUSED - PAGE {Page + 1}/3: {(Page == 1 ? "PLAYER" : "SYSTEMS")}",
$"LEVEL {status.Level} / START {status.Start}", $"ROOT {V(status.Root)} NOCLIP {system.Noclip}",
Page == 1 ? $"VEL {V(system.Velocity)} MODE {system.MovementMode}" : $"STATIC POLYS {system.CameraPolygons} WALLS {system.CameraWallPolygons} TESTS {system.CameraTests}",
Page == 1 ? $"PENDING {V(system.PendingImpulse)}" : $"AUDIO BYTES MUSIC {system.MusicBytes} VOICE {system.SpeechBytes}",
Page == 1 ? $"JUMP {system.JumpState} HOLD {F(system.JumpHold)} BURN {F(system.BurnRemaining)}"
: $"EFFECT BYTES {system.EffectBytes} AUDIO AVAILABLE {system.AudioAvailable}",
$"OBJECTIVE {system.Objective} TIME {F(system.ObjectiveTime)} GADGET STATE {system.JetpackAvailability}",
$"INVISIBLE {F(system.InvisibleRemaining)} RECHARGE {F(system.InvisibleRecharge)}/7 TARGETABLE {system.Targetable}",
$"BUBBLE {system.BubblePhase} BODY R {F(system.BodyRadius)} FACTOR {system.BodyFactor.ToString("0.000",c)}",
$"BASEBALL {system.BaseballState}", ""];
string[] items = Page == 1 ? [
$"NOCLIP (F3): {system.Noclip} (ENTER TOGGLE)",
$"FLY SPEED: {F(FlySpeed)} LIVE {F(system.NoclipSpeed)} (ENTER APPLIES)", "STOP MOTION / CLEAR QUEUED JUMP", "SHOW CURRENT OBJECTIVE",
"RETURN TO NOCLIP ENTRY POSITION", "APPLY THIS LEVEL'S GADGET AVAILABILITY",
$"INPUT AFTER PLAYER: {system.InputAfterPlayer} (TOGGLE)",
$"JET PACK STATE: {JetpackState} (0 NONE / 1 OWNED / 4 DISABLED)", "APPLY JET PACK STATE", "REFILL ENERGY TO 100",
"GIVE / SELECT INVISIBLE", "UNEQUIP CURRENT GADGET", "GIVE / SELECT BUBBLE", "GIVE / SELECT BASEBALL"] : [
$"STATIC CAMERA OBSTRUCTION: {(system.CameraObstruction?.ToString() ?? "UNAVAILABLE")}",
$"MUTE MUSIC: {system.MusicMuted}", $"MUTE SPEECH: {system.SpeechMuted}", $"MUTE EFFECTS: {system.EffectsMuted}",
"RESTART SELECTED MUSIC", "STOP ALL EFFECTS / LOOPS", "SAVE DEBUG CHECKPOINT", "LOAD DEBUG CHECKPOINT", "SHOW JET PACK PRACTICE PROMPT"];
return new([.. header, .. items, "", "TAB NEXT PAGE UP/DOWN SELECT ENTER APPLY",
Page == 1 ? "FLY: WASD/ARROWS SPACE/E UP CTRL/Q DOWN SHIFT FAST" : "CHECKPOINT: DEBUG-CHECKPOINT.TSK BESIDE EXECUTABLE",
"F1 / ESC CLOSE - ACTIONS USE EXISTING SYSTEMS", Message], header.Length + Selected);
}
return new([
"NEUTRON DEBUG MENU - F1",
"PAUSED - MODERN DEBUG TOOLS",
$"LEVEL {status.Level} / START {status.Start}",
$"ROOT X {F(status.Root.X)} Y {F(status.Root.Y)} Z {F(status.Root.Z)}",
$"YAW {F(status.Yaw)} SPEED {F(status.Speed)} GROUNDED {status.Grounded}",
$"ENERGY {F(status.Energy)} SCORE {status.Score} SCENE {status.SceneTask}",
$"CONTROL {status.Controlled} CUTSCENE {status.Cutscene}",
$"ISSUES {status.Issues} FAR {F(status.FarPlane)} CAMERA {status.CameraMode ?? (status.Inspecting ? "ORBIT" : "GAMEPLAY")}",
"",
"RESUME",
$"CAMERA: {(status.Inspecting ? "SWITCH TO GAMEPLAY" : "SWITCH TO ORBIT")}",
"SKIP CURRENT CUTSCENE",
"REFILL ENERGY TO 100",
"GIVE / SELECT JET PACK",
$"SCENE TASK: {SceneTask} (ENTER APPLIES)",
$"LEVEL: {Scene?.LevelFile ?? "UNAVAILABLE"}",
$"START: {Start ?? "UNAVAILABLE"}",
"LOAD SELECTED LEVEL / START",
"RESET CURRENT START",
$"FORCE CONTROL: {status.ForcedControl} (ENTER TOGGLE)",
$"LIVE OVERLAY: {status.DiagnosticsVisible} (F2 / ENTER TOGGLE)",
"",
"TAB NEXT PAGE UP/DOWN SELECT LEFT/RIGHT CHANGE",
"ENTER APPLIES SCENE TASK: PAGE UP/DOWN CHANGES BY 10",
"F1 / ESC CLOSE F3 NOCLIP - GAME INPUT CAPTURED",
Message
], 9 + Selected);
}
public static DebugScene[] AvailableScenes(string assets, string prepared)
{
var scenes = new List();
foreach (var path in Directory.EnumerateFiles(AssetPath.Resolve(assets, "gam"))
.Where(p => p.EndsWith(".gam", StringComparison.OrdinalIgnoreCase)).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase))
{
try { AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(path) + "/scene.json"); }
catch (FileNotFoundException) { continue; }
var level = GamLevel.Load(path);
var starts = level.Entities.Where(e => e.Kind == "STRT" && e.Tag is { Length: > 0 }).Select(e => e.Tag!).ToArray();
if (level.Player != null && starts.Length > 0) scenes.Add(new(Path.GetFileName(path), level.Code, starts));
}
return scenes.ToArray();
}
}