Reconstruct lab story, interactions, patrol and jet pack practice flow

This commit is contained in:
UnixNight committed 2026-10-24 20:33:03 -04:00
1 parent 58424120bb
commit c929f942e1
84 files changed
+7957 -305

No files matched your search

+358 -19
View File
@@ -13,7 +13,16 @@ internal static class Program
{
public static int Main(string[] args)
{
try { return Run(args); }
try
{
OriginalSave? carriedSave = null;
while (true)
{
var result = Run(args, carriedSave, out var continuation);
if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save;
}
}
catch (Exception error) { Console.Error.WriteLine(error); return 1; }
}
@@ -26,8 +35,11 @@ internal static class Program
return args[i + 1];
}
private static int Run(string[] args)
private sealed record SceneContinuation(string[] Args, OriginalSave Save);
private static int Run(string[] args, OriginalSave? carriedSave, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
{
Console.WriteLine("""
@@ -40,15 +52,30 @@ internal static class Program
--original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--with-player Use prepared jimstop animation in scene
--walk Controllable lab (default with prepared lab)
--walk Play prepared scene with recovered story/interactions
--inspect Pause simulation and inspect scene/animation
--smoke-walk Deterministic 240-step movement/jump check
--story Execute recovered original CAM/MCA/AI trigger sequence
--story-time N Headless scene-sequence time for GPU comparisons
--skip-intro Fast-forward original intro actions and restore control
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM
--frames N Exit after N frames (headless default: 1)
--audio PATH Play recovered WAV; --loop-audio repeats it
--audio-smoke PATH Verify audio-stream consumption
--scene-audio-smoke PATH Verify music/speech streams from entities.json
--effects-audio-smoke PATH Verify default effect bank and loop lifetime
--smoke-transition Headless VR01 RETURN / renderer-recreation check
--smoke-lab-route Headless source lab contact route / next-scene rebuild
--smoke-practice-prompt Headless original jet pack practice prompt
--smoke-practice-transition Headless lab-to-VR04 practice transition
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack Headless 300-step powered-jump/release check in VR04
--verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more)
--no-validation Disable development validation
@@ -56,12 +83,53 @@ internal static class Program
C pauses into inspection / resumes chase camera. F11 fullscreen, Escape quit.
Inspector: arrows/WASD orbit, +/- zoom,
F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch.
Collision/pivot/cadence and animation timing are provisional. Intro/interactions remain incomplete.
Collision/pivot/cadence and animation timing are provisional. Full gameplay remains incomplete.
""");
return 0;
}
var root = AssetPath.FindOriginal(Option(args, "--assets"));
var saveOutput = Option(args, "--write-save");
if (saveOutput != null)
{
saveOutput = Path.GetFullPath(saveOutput);
if (saveOutput.StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Save output must be outside original asset directory");
for (var parent = new DirectoryInfo(Path.GetDirectoryName(saveOutput)!); parent != null; parent = parent.Parent)
if (parent.Exists && parent.LinkTarget != null) throw new ArgumentException("Save output directory must not redirect through a symbolic link");
}
if (args.Contains("--verify-assets")) return VerifyAssets(root);
if (Option(args, "--effects-audio-smoke") is { } effectsManifest)
{
using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest));
mixer.Effect(59, "bars"); mixer.Effect(58);
var before = mixer.QueuedEffectBytes;
Thread.Sleep(200);
var consumed = mixer.QueuedEffectBytes < before;
mixer.Pump();
mixer.StopLoop("bars");
var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1;
mixer.Effect(230);
var mixed = mixer.EffectCount == 2;
mixer.StopEffects();
Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}.");
return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2;
}
if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest)
{
var bank = new PreparedEntityResources(sceneAudioManifest);
using var mixer = new SceneAudio(bank);
mixer.Music("musicsecretlab.omt", 0);
mixer.Speech("voiceneighborhood.omt", 36);
var beforeMusic = mixer.QueuedMusicBytes;
var beforeSpeech = mixer.QueuedSpeechBytes;
Thread.Sleep(500);
var consumed = mixer.QueuedMusicBytes < beforeMusic && mixer.QueuedSpeechBytes < beforeSpeech;
mixer.StopSpeech();
mixer.Speech("voiceneighborhood.omt", 46);
var restarted = mixer.QueuedMusicBytes > 0 && mixer.QueuedSpeechBytes > 0;
Console.WriteLine($"Scene music and speech consumed independently: {consumed}; speech replacement retained music: {restarted}.");
return consumed && restarted ? 0 : 2;
}
if (Option(args, "--audio-smoke") is { } audioSmoke)
{
using var sound = new SdlAudio(audioSmoke);
@@ -73,6 +141,19 @@ internal static class Program
}
var scene = Option(args, "--scene");
var loadedSave = carriedSave ?? (Option(args, "--load-save") is { } savePath ? OriginalSave.Load(savePath) : null);
string? savedLevelPath = null;
if (loadedSave != null && carriedSave == null)
{
savedLevelPath = Directory.EnumerateFiles(AssetPath.Resolve(root, "gam"))
.Where(p => p.EndsWith(".gam", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(p => GamLevel.Load(p).Code == loadedSave.LevelCode)
?? throw new FileNotFoundException($"No GAM matches saved level {loadedSave.LevelCode}");
var prepared = new[] { "artifacts/extracted", Path.Combine(AppContext.BaseDirectory, "scenes") }
.FirstOrDefault(p => Directory.Exists(Path.Combine(p, "animations")))
?? throw new DirectoryNotFoundException("Prepare original scenes before loading saves");
scene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(savedLevelPath) + "/scene.json");
}
var defaultScene = false;
if (scene == null && Option(args, "--model") == null)
{
@@ -80,9 +161,12 @@ internal static class Program
Path.Combine(AppContext.BaseDirectory, "scenes/level1b/scene.json") }.FirstOrDefault(File.Exists);
defaultScene = scene != null;
}
var levelPath = Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null);
var levelPath = savedLevelPath == null ? Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null)
: "gam/" + Path.GetFileName(savedLevelPath);
GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath));
var originalStart = level?.FindStart();
var startTag = Option(args, "--start") ?? loadedSave?.StartPoint;
if (string.Equals(startTag, "none", StringComparison.OrdinalIgnoreCase)) startTag = null;
var originalStart = level?.FindStart(startTag);
if (level != null) Console.WriteLine($"Decoded GAM {level.Code}: {level.Entities.Count} entities.");
var originalCamera = args.Contains("--original-camera") || defaultScene;
if (originalCamera && originalStart == null)
@@ -90,6 +174,7 @@ internal static class Program
var mesh = scene != null ? Mesh.LoadSceneJson(scene)
: AseMesh.Load(AssetPath.Resolve(root, Option(args, "--model") ?? "ASE/jimstop.ase"));
var world = mesh;
var texture = scene != null ? PngImage.White
: PngImage.Load(AssetPath.Resolve(root, Option(args, "--texture") ?? "png/jimycarl.png"));
var bounds = mesh.Bounds();
@@ -97,9 +182,18 @@ internal static class Program
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
var animationPath = Option(args, "--animation");
var walkSmoke = args.Contains("--smoke-walk");
var jetpackSmoke = args.Contains("--smoke-jetpack");
var practiceWindowSmoke = args.Contains("--smoke-practice-window");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode.");
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (args.Contains("--walk") || walkSmoke
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (story || args.Contains("--walk") || walkSmoke
|| defaultScene && animationPath == null && !args.Contains("--time"));
if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null)
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
@@ -107,6 +201,19 @@ internal static class Program
throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null;
SceneDirector? director = null;
SceneActorVisuals? actorVisuals = null;
SceneSpriteVisuals? spriteVisuals = null;
StaticSceneVisuals? staticVisuals = null;
PreparedEntityResources? resources = null;
SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null;
SceneHud? hud = null;
JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt();
var objectiveOffset = -69f;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null;
var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity;
if (animationPath != null)
@@ -115,7 +222,8 @@ internal static class Program
throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y);
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y)
{ LevelCode = level!.Code };
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh);
@@ -124,15 +232,79 @@ internal static class Program
else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
}
if (story)
{
resources = new PreparedEntityResources(Path.Combine(Path.GetDirectoryName(scene!)!, "entities/entities.json"),
Path.Combine(Path.GetDirectoryName(scene!)!, "../effects/effects.json"));
var save = loadedSave ?? OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var tasks = new TaskStates(save.Tasks);
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save, level!.Code);
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
mechanisms = new SceneMechanisms(director);
interactions.Transition += request => transitionRequest ??= request;
interactions.PracticeRequested += practice.Show;
practice.Chosen += (mode, accepted) =>
{
if (!accepted) return;
// Player43B5A0 receives current/requested GAM and latest STRT tag
// as return context;42AF00's runtime checkpoint is separate.
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
transitionRequest ??= new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1);
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}.");
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{
var physics = new OriginalScenePhysics(world);
var grounded = false;
var patrol = new ActorPatrol(actor, director.FindActor, (body, dt) =>
{
var resolved = physics.Step(body.Position, body.Velocity,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardRadius : 100,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardFactor : .75f, grounded, dt);
grounded = resolved.Supported;
return new(resolved.Body.Position, resolved.Body.Velocity);
});
patrols.Add(actor.Tag, patrol);
director.RegisterPatrolConsumer(actor.Tag);
director.ActorChanged += changed => { if (ReferenceEquals(changed, actor)) patrol.SynchronizeAuthoredState(); };
}
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh;
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
mesh = staticVisuals.Mesh;
simulation!.DynamicRootResolver = (previous, position, radius) =>
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
}
Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : headless ? "1" : "0"));
if (args.Contains("--smoke-transition") && (!headless || level?.Code is not ("VR01" or "VR04") || interactions == null))
throw new ArgumentException("Transition smoke requires headless story playback of VR01 or VR04.");
if (args.Contains("--smoke-lab-route") && (!headless || level?.Code != "LV1B" || interactions == null || loadedSave != null))
throw new ArgumentException("Lab route smoke requires fresh headless story playback of LV1B.");
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : headless ? "1" : "0"));
if (jetpackSmoke && (!headless || level?.Code != "VR04" || frames < 300))
throw new ArgumentException("Jetpack smoke requires headless VR04 and at least300 frames");
if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames.");
var smoke = args.Contains("--smoke-window");
if (frames < 0 || (smoke && (headless || frames < 6)))
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null))
throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames.");
nint window = 0;
if (!headless)
{
@@ -146,6 +318,56 @@ internal static class Program
using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation"));
using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio")) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
double initialPoseTime = 0;
if (director != null)
{
if (sceneAudio != null)
{
director.Speech += sceneAudio.Speech;
interactions!.SoundEffect += id => sceneAudio.Effect(id);
mechanisms!.Sound += (actor, id, loop) => sceneAudio.Effect(id, loop ? actor.Tag : null);
mechanisms.StopSound += actor => sceneAudio.StopLoop(actor.Tag);
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!);
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (args.Contains("--skip-intro") || jetpackSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--smoke-transition"))
{
director.Skip();
interactions!.Update(level!.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest == null) throw new InvalidOperationException("Original VR01 RETURN contact did not request a transition");
}
if (args.Contains("--smoke-lab-route"))
{
LabRouteSmoke.Run(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (transitionRequest?.LevelFile != "level1.gam")
throw new InvalidOperationException("Original lab exit did not request level1.gam");
}
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions!.Update(director.FindActor("shrinkray")!.Position);
if (!practice.Active) throw new InvalidOperationException("Original lab pickup did not open practice modal");
if (args.Contains("--smoke-practice-transition")) practice.Key(28, Vector2.Zero);
}
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active; tick++)
{
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh);
spriteVisuals!.Step(FixedStepClock.Step);
}
}
var keys = new HashSet<uint>();
var running = true;
var fullscreen = false;
@@ -158,12 +380,20 @@ internal static class Program
var active = true;
var mouseJump = false;
var stepClock = new FixedStepClock();
double poseTime = 0;
double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput);
var sawWalkKeys = 0;
var sawPracticeDismiss = false;
var sawPracticePause = false;
double last = clock.Elapsed.TotalSeconds;
float angle = 0.6f, elevation = 0.32f;
var count = 0;
Vector2 Pointer()
{
Sdl.SDL_GetMouseState(out var x, out var y);
if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero;
return new(x * 640 / w, y * 480 / h);
}
while (running)
{
if (walkSmoke && !headless)
@@ -187,6 +417,14 @@ internal static class Program
{ keys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown)
{
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) mouseJump = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown)
@@ -194,7 +432,11 @@ internal static class Program
keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0;
if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode == 41) running = false;
if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false })
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false;
if (e.Scancode == 18 && e.Repeat == 0 && director is { Controlled: true, InventoryEnabled: true })
objectiveOffset = objectiveOffset == -69 ? 0 : -69;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{
animationStarted = clock.Elapsed.TotalSeconds;
@@ -214,7 +456,12 @@ internal static class Program
}
else originalCamera = !originalCamera;
}
if (!inspecting && e.Scancode == 21 && e.Repeat == 0) { simulation!.Reset(); poseTime = 0; }
if (!inspecting && e.Scancode == 21 && e.Repeat == 0)
{
simulation!.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset();
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
if (e.Scancode == 68 && e.Repeat == 0)
{
fullscreen = !fullscreen;
@@ -227,17 +474,35 @@ internal static class Program
var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1);
last = now;
if (simulation != null && !inspecting && (active || headless || walkSmoke))
if (simulation != null && !inspecting && !practice.Active && (active || headless || walkSmoke))
{
var steps = headless || walkSmoke ? 1 : stepClock.Advance(elapsed);
var steps = headless || walkSmoke || practiceWindowSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
var input = jetpackSmoke ? new PlayerInput(false, false, false, false, simulation.Steps < 180)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98));
simulation.Step(input);
if (animations!.SelectPose(simulation.Pose)) poseTime = 0;
if (director?.Controlled != false)
{
simulation.Step(input);
interactions?.UpdateEnergy(simulation.Energy);
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
director?.Touch(level!.Player!.Tag!, simulation.ActorRoot);
interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius);
if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; }
mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius);
}
mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step);
var switched = director is { Controlled: false }
? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)
: animations!.SelectPose(simulation.Pose);
if (switched) poseTime = 0;
poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh);
spriteVisuals?.Step(FixedStepClock.Step);
}
characterModel = simulation.Model;
}
@@ -256,8 +521,22 @@ internal static class Program
var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY)
: Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY);
var renderEye = originalCamera ? originalStart!.CameraPosition : eye;
var renderTarget = originalCamera ? originalStart!.Position + new Vector3(0,80,0) : target;
if (simulation != null && !inspecting)
{
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget;
}
if (!inspecting && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget)
{
view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY);
renderEye = storyEye; renderTarget = storyTarget;
}
staticVisuals?.Update(mesh);
jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && director!.Controlled, practice.Active, objectiveOffset);
var far = level?.Code == "LV1B" ? 10000 : 3200;
var projection = originalCamera || simulation != null && !inspecting
? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far)
@@ -266,12 +545,21 @@ internal static class Program
if (animations != null)
{
animations.Current.Sample(simulation != null && !inspecting ? poseTime
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted), mesh.Vertices.AsSpan(characterOffset), characterModel);
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted),
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
renderer.UpdateVertices(mesh.Vertices);
}
renderer.Render(view * projection);
count++;
audio?.Pump();
sceneAudio?.Pump();
if (practiceWindowSmoke && count == 1)
{
sawPracticePause = practice.Active && simulation!.Steps == 0;
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 17, Down = 1 };
if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
}
if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 1)
@@ -285,8 +573,9 @@ internal static class Program
if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error);
}
}
if ((smoke || walkSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if ((smoke || walkSmoke || practiceWindowSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if (frames > 0 && count >= frames) break;
if (transitionRequest != null) break;
}
if (Option(args, "--screenshot") is { } screenshot)
{
@@ -299,6 +588,50 @@ internal static class Program
if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++;
Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s).");
if (simulation != null) Console.WriteLine(simulation.Report);
if (jetpackSmoke)
{
Console.WriteLine($"Powered jump: bursts={simulation!.Bursts}, remaining={simulation.JetpackRemaining:F3}, energy={simulation.Energy:F3}, grounded={simulation.Grounded}.");
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded) return 2;
}
if (director != null)
{
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
foreach (var issue in director.Issues) Console.WriteLine($"Unrecovered scene behavior {issue.Tag}: {issue.Detail}");
foreach (var missing in actorVisuals!.UnsupportedAnimations) Console.WriteLine($"Unrecovered animation alias {missing}");
foreach (var missing in interactions!.Unsupported) Console.WriteLine(missing);
foreach (var missing in mechanisms!.Unsupported) Console.WriteLine(missing);
foreach (var (tag, patrol) in patrols)
Console.WriteLine($"Patrol {tag}: root={director.FindActor(tag)!.Position}, waypoint={patrol.CurrentWaypoint ?? "none"}, velocity={patrol.Velocity}; recovered support, provisional wall response.");
}
if (interactions != null && saveOutput is { } output)
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag! };
var temporary = output + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) stream.Write(snapshot.Encode());
File.Move(temporary, output, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
Console.WriteLine($"Wrote original-format checkpoint state: {output}");
}
if (transitionRequest != null && renderer.ValidationErrors == 0)
{
var prepared = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."));
var nextScene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(transitionRequest.LevelFile) + "/scene.json");
var nextArgs = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--smoke-transition" or "--smoke-lab-route" or "--smoke-practice-prompt" or "--smoke-practice-transition") continue;
if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time") { i++; continue; }
nextArgs.Add(args[i]);
}
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with { StartPoint = transitionRequest.StartPoint });
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
}
if (walkSmoke && !simulation!.SmokePassed) return 2;
if (walkSmoke && !headless)
{
@@ -315,6 +648,12 @@ internal static class Program
if (!animationSwitched || !animations.Current.HasVertexMotion) return 2;
}
}
if (practiceWindowSmoke)
{
var resumed = !practice.Active && simulation!.Steps > 0;
Console.WriteLine($"Practice SDL check: paused={sawPracticePause}, N dismiss={sawPracticeDismiss}, resumed={resumed}, resize800x600={didResize}.");
if (!sawPracticePause || !sawPracticeDismiss || !resumed || !didResize) return 2;
}
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
}
finally