Restore tutorial return placement and source terrain collision eligibility

This commit is contained in:
UnixNight committed 2026-10-25 01:30:09 -04:00
1 parent ca08c468ba
commit 8d60a68511
36 files changed
+991 -69

No files matched your search

+17 -2
View File
@@ -39,11 +39,23 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray();
if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices.");
if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh.");
// Level loaders omit NC-prefixed SHAPE names from terrain registration
// (LV1B44DD2F..44DD70). Material names and draw visibility are separate.
var shapeNames = new Dictionary<int, string>();
if (root.TryGetProperty("meshes", out var shapeMeshes))
foreach (var shape in shapeMeshes.EnumerateArray())
{
if (!shape.TryGetProperty("shapeId", out var id) || !shape.TryGetProperty("name", out var name)) continue;
var text = name.GetString() ?? "";
if (shapeNames.TryGetValue(id.GetInt32(), out var existing) && existing != text)
throw new InvalidDataException("Conflicting source shape names");
shapeNames[id.GetInt32()] = text;
}
var collisionPolygons = root.TryGetProperty("collisionPolygons", out var polygonList)
? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(),
p.GetProperty("polygonIndex").GetInt32(),
new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()),
p.GetProperty("materialName").GetString())).ToArray() : [];
p.GetProperty("materialName").GetString(), shapeNames.GetValueOrDefault(p.GetProperty("shapeId").GetInt32()))).ToArray() : [];
if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3
|| collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z))))
throw new InvalidDataException("Invalid source collision polygon metadata");
@@ -84,7 +96,10 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
}
}
public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName);
public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName, string? ShapeName = null)
{
public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true;
}
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{
+2 -1
View File
@@ -6,7 +6,8 @@ namespace GamePort.Assets;
public sealed record SavedTask(string Name, int State);
/// <summary>Original TSK wire layout recovered at EXE0x45FEE0/0x4603F0; unknown fields retained.</summary>
/// <summary>Original TSK wire layout at EXE0x45FEE0/0x4603F0; unknown fields retained.
/// StoredVector is the transition departure root, not Jimmy42AF00's separate checkpoint.</summary>
public sealed record OriginalSave(string LevelCode, float PlayerValue, short Counter,
int Score, int OtherCounter, int[] ItemStates, int[] LevelCounters,
string StartPoint, string ReservedName, string ReturnLevel, string ReturnStart,
+10
View File
@@ -85,6 +85,16 @@ public sealed class LabSimulation
CameraEye = DesiredEye();
}
/// <summary>Jimmy PostLoad423A90..423ABF restores the saved RETURN root.
/// Yaw remains the authored STRT yaw; the source stores only XYZ here.</summary>
public void RestoreReturnRoot(Vector3 root)
{
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z))
throw new ArgumentOutOfRangeException(nameof(root));
Position = root - Vector3.UnitY * rootHeight;
CameraEye = DesiredEye();
}
// EXE 0x47F940 truncates, then degree lookup masks to the 16384-entry table.
// Table generated with modern trig; x87 bit-identical table recovery is pending.
public static (float Sin, float Cos) Trig(float degrees)
+1 -1
View File
@@ -19,7 +19,7 @@ public sealed class OriginalScenePhysics
throw new InvalidDataException("Prepare source collision polygon metadata before original root support");
walls = new SceneCollision(world, wallsAndCeilingsOnly: true);
support = Enumerable.Range(0, world.Indices.Length / 3)
.Where(i => !Checkpoint(world.CollisionPolygons[i].MaterialName))
.Where(i => world.CollisionPolygons[i].TerrainCollision && !Checkpoint(world.CollisionPolygons[i].MaterialName))
.Select(i => new SupportTriangle(world.Vertices[world.Indices[i * 3]].Position,
world.Vertices[world.Indices[i * 3 + 1]].Position, world.Vertices[world.Indices[i * 3 + 2]].Position,
world.CollisionPolygons[i].ShapeId, world.CollisionPolygons[i].PolygonIndex)).ToArray();
+40
View File
@@ -0,0 +1,40 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>
/// Player43B5A0 stages a level transition. Ordinary departure captures the current
/// root at complete+9A8; RETURN preserves it using complete+9A5. PostLoad restores
/// that root and STRT suppresses its initial trigger using the separate+954 flag.
/// This is distinct from Jimmy42AF00's currently unconsumed+1E38 checkpoint.
/// </summary>
public sealed class RuntimeCheckpoint
{
public Vector3 Root { get; }
public bool Returning { get; }
public bool ActivateStartTrigger => !Returning;
private RuntimeCheckpoint(Vector3 root, bool returning)
{
Root = root;
Returning = returning;
}
/// <summary>
/// Only RETURN restores a root on scene entry. No rotation is captured here;
/// the destination STRT remains the source of authored spawn rotation.
/// Root is the same vector serialized in OriginalSave.StoredVector.
/// </summary>
public static RuntimeCheckpoint Stage(Vector3 storedRoot, Vector3 currentRoot, bool returning)
{
Validate(storedRoot, nameof(storedRoot));
Validate(currentRoot, nameof(currentRoot));
return new(returning ? storedRoot : currentRoot, returning);
}
private static void Validate(Vector3 root, string name)
{
if (!float.IsFinite(root.X) || !float.IsFinite(root.Y) || !float.IsFinite(root.Z))
throw new ArgumentOutOfRangeException(name, "Transition roots must be finite");
}
}
+4 -2
View File
@@ -5,8 +5,8 @@ namespace GamePort.Game;
/// <summary>
/// Provisional geometric reconstruction for the controllable-scene checkpoint.
/// Uses source triangles, including invisible proxies, without claiming the
/// original game's unrecovered collision-mask/state rules or solver tolerances.
/// Uses source terrain-eligible triangles, including invisible proxies. NC shape
/// exclusion is recovered; remaining masks/state rules and solver are provisional.
/// Positions are the bottom of a vertical capsule in original Y-up world units.
/// </summary>
public sealed class SceneCollision
@@ -35,6 +35,8 @@ public sealed class SceneCollision
// proxies remain present and block movement in this provisional policy.
for (var i = 0; i < mesh.Indices.Length; i += 3)
{
if (mesh.CollisionPolygons.Length == mesh.Indices.Length / 3
&& !mesh.CollisionPolygons[i / 3].TerrainCollision) continue;
// EXE4798B3 registers only stored normal.Y<.7 in the wall/ceiling
// grid. Render normals and a recomputed cross product differ.
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].Normal.Y >= .7f) continue;
+4 -2
View File
@@ -113,7 +113,7 @@ public sealed class SceneDirector
tasks.Assigned += OnTaskAssigned;
}
public void Begin(GamEntity start)
public void Begin(GamEntity start, bool activateStartTrigger = true)
{
if (start.Kind != "STRT") throw new ArgumentException("Expected original STRT entity", nameof(start));
shot = null; pending.Clear(); activations.Clear();
@@ -131,7 +131,9 @@ public sealed class SceneDirector
actor.SpritePlaying = initial.SpritePlaying; actor.SpriteRevision++;
ApplyTask(actor, tasks.Get(source.Text("TaskName")));
}
var trigger = start.Text("StartTrigger");
// RETURN sets Jimmy+954; STRT4427F2..44282A consumes that flag and
// suppresses its trigger once. Do not fast-forward the trigger's actions.
var trigger = activateStartTrigger ? start.Text("StartTrigger") : null;
ControlledTag = IsNone(trigger) ? level.Player?.Tag : null; // EXE4426B7.
if (!IsNone(trigger)) Trigger(trigger!, start.Tag);
}
+4 -3
View File
@@ -3,7 +3,7 @@ using GamePort.Assets;
namespace GamePort.Game;
public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType);
public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType, bool Returning = false);
/// <summary>
/// Recovered star/trophy/lab jetpack contacts, Carl talk dispatch and LOAD gates. Uses source root spheres
@@ -122,11 +122,12 @@ public sealed class SceneInteractions
if (!TaskActivation.Load(source, tasks)) break;
var destination = source.Text("LevelName") ?? "none";
var start = source.Text("StartPoint") ?? "none";
if (string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase))
var returning = string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase);
if (returning)
{ destination = ReturnLevel; start = ReturnStart; }
if (string.Equals(destination, "none", StringComparison.OrdinalIgnoreCase))
{ unsupported.Add("RETURN has no stored destination"); break; }
Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType")));
Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType"), returning));
break;
}
}
+56 -14
View File
@@ -16,11 +16,12 @@ internal static class Program
try
{
OriginalSave? carriedSave = null;
var returning = false;
while (true)
{
var result = Run(args, carriedSave, out var continuation);
var result = Run(args, carriedSave, returning, out var continuation);
if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save;
args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning;
}
}
catch (Exception error) { Console.Error.WriteLine(error); return 1; }
@@ -35,9 +36,9 @@ internal static class Program
return args[i + 1];
}
private sealed record SceneContinuation(string[] Args, OriginalSave Save);
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning);
private static int Run(string[] args, OriginalSave? carriedSave, out SceneContinuation? continuation)
private static int Run(string[] args, OriginalSave? carriedSave, bool returning, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
@@ -75,6 +76,7 @@ internal static class Program
--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-return Headless lab/VR04/RETURN root and intro-suppression check
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack 300-step powered steering/jump check in VR04
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
@@ -225,11 +227,12 @@ internal static class Program
if (Option(args, "--smoke-jump-key") != null && !(walkSmoke || jetpackSmoke))
throw new ArgumentException("Jump binding smoke option requires a movement smoke mode");
var practiceWindowSmoke = args.Contains("--smoke-practice-window");
var practiceReturnSmoke = args.Contains("--smoke-practice-return");
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 || carlSmoke || objectiveSmoke;
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || objectiveSmoke;
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.");
@@ -255,6 +258,15 @@ internal static class Program
ObjectivePanel? objectivePanel = null;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null;
Vector3 returnRoot = loadedSave?.StoredVector ?? Vector3.Zero;
void RequestTransition(LevelTransition request)
{
if (transitionRequest != null) return;
//43B5A0 captures live root for ordinary outbound transitions;
//RETURN preserves it for the destination PostLoad restore.
returnRoot = RuntimeCheckpoint.Stage(returnRoot, simulation!.ActorRoot, request.Returning).Root;
transitionRequest = request;
}
var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity;
if (animationPath != null)
@@ -265,6 +277,7 @@ internal static class Program
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y)
{ LevelCode = level!.Code };
if (walking && returning) simulation!.RestoreReturnRoot(returnRoot);
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh);
@@ -278,6 +291,7 @@ internal static class Program
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"));
returnRoot = save.StoredVector;
var tasks = new TaskStates(save.Tasks);
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save, level!.Code);
@@ -286,15 +300,14 @@ internal static class Program
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
mechanisms = new SceneMechanisms(director);
interactions.Transition += request => transitionRequest ??= request;
interactions.Transition += RequestTransition;
interactions.PracticeRequested += practice.Show;
practice.Chosen += (mode, accepted) =>
{
if (!accepted) { objectivePanel.Show(); return; }
// Player43B5A0 receives current/requested GAM and latest STRT tag
// as return context;42AF00's runtime checkpoint is separate.
// Player43B5A0 captures root separately from42AF00's pickup checkpoint.
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
transitionRequest ??= new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1);
RequestTransition(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"))
@@ -332,6 +345,8 @@ internal static class Program
var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless");
if (practiceReturnSmoke && (!headless || level?.Code is not ("LV1B" or "VR04") || carriedSave == null && loadedSave != null))
throw new ArgumentException("Practice RETURN check requires a fresh headless lab or its carried tutorial/return");
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))
@@ -379,11 +394,29 @@ internal static class Program
mechanisms.StopSound += actor => sceneAudio.StopLoop(actor.Tag);
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!);
director.Begin(originalStart!, activateStartTrigger: !returning);
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (returning && director.FindActor("C3DGODDARD") is { } companion)
director.SyncActor(companion.Tag, returnRoot, companion.Rotation); //423AE3..423B1E, no offset.
if (practiceReturnSmoke && returning)
{
var restored = director.Controlled && !director.Playing && director.CurrentTag == null
&& Vector3.Distance(simulation.ActorRoot, returnRoot) < .001f
&& Vector2.Distance(new(returnRoot.X, returnRoot.Z), new(originalStart!.Position.X, originalStart.Position.Z)) > 100;
var companionRestored = director.FindActor("C3DGODDARD")?.Position == returnRoot;
restored &= companionRestored;
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}.");
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
}
if (args.Contains("--skip-intro") || jetpackSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (practiceReturnSmoke && level.Code == "VR04")
{
director.Skip();
interactions!.Update(level.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest is not { Returning: true }) throw new InvalidOperationException("VR04 exit did not preserve RETURN identity");
}
if (args.Contains("--smoke-transition"))
{
director.Skip();
@@ -405,15 +438,23 @@ internal static class Program
if (interactions!.CurrentObjective != 1) throw new InvalidOperationException("Original explanation did not assign objective1");
if (objectiveWindowSmoke) objectivePanel!.Step(9);
}
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke)
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke
|| practiceReturnSmoke && level.Code == "LV1B" && !returning)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
if (practiceReturnSmoke)
{
// Move the real player away from STRT so an accidental
// restart at the authored spawn cannot pass this check.
for (var tick = 0; tick < 45; tick++) simulation.Step(new(true, false, false, false, false));
director.SyncActor(level.Player!.Tag!, simulation.ActorRoot, new(0, simulation.Yaw, 0));
}
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);
if (args.Contains("--smoke-practice-transition") || practiceReturnSmoke) practice.Key(28, Vector2.Zero);
}
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active; tick++)
{
@@ -720,7 +761,7 @@ internal static class Program
if (interactions != null && saveOutput is { } output)
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag! };
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag!, StoredVector = returnRoot };
var temporary = output + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
@@ -743,7 +784,8 @@ internal static class Program
}
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with { StartPoint = transitionRequest.StartPoint });
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with {
StartPoint = transitionRequest.StartPoint, StoredVector = returnRoot }, transitionRequest.Returning);
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
}
if (walkSmoke && !simulation!.SmokePassed) return 2;