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

@@ -9,6 +9,8 @@
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/GamLevel.cs" Link="GamLevel.cs" />
<Compile Include="../../src/GamePort/Assets/OriginalSave.cs" Link="OriginalSave.cs" />
<Compile Include="../../src/GamePort/Assets/PreparedEntityResources.cs" Link="PreparedEntityResources.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" />
<Compile Include="../../src/GamePort/Assets/AseMesh.cs" Link="AseMesh.cs" />
+55
View File
@@ -17,6 +17,31 @@ foreach (var file in files)
}
Require(entities == 3299, "Original entity total differs");
var initial = GamLevel.Load(Path.Combine(root, "gam/level1b.gam"));
var saves = Directory.GetFiles(root, "*.tsk");
Require(saves.Length == 12, "Expected original save corpus");
foreach (var file in saves)
{
var raw = File.ReadAllBytes(file);
var save = OriginalSave.Parse(raw);
Require(save.Encode().SequenceEqual(raw), $"TSK byte round-trip differs: {file}");
foreach (var length in new[] { 0, 4, 18, 16000, raw.Length - 1 }) RejectSave(raw[..length]);
RejectSave([.. raw, 0]);
}
var newGame = OriginalSave.Load(Path.Combine(root, "NewGame.tsk"));
Require(newGame.LevelCode == "LV1B" && newGame.StartPoint == "STARTEXP", "Wrong new-game resume data");
var tasks = new TaskStates(newGame.Tasks);
Require(tasks.Get("scene") == 30 && tasks.Get("missing") == 0, "Original task query semantics differ");
var assignments = 0;
tasks.Assigned += (_, _) => assignments++;
tasks.SetExisting("ScEnE", 35);
tasks.SetExisting("missing", 77);
tasks.SetExisting("SCENE", 35);
Require(tasks.Get("SCENE") == 35 && tasks.Get("missing") == 0 && tasks.Snapshot().Length == 12 && assignments == 3,
"Task assignment must broadcast without creating missing entries");
var changed = newGame with { Score = 15, Tasks = tasks.Snapshot() };
Require(OriginalSave.Parse(changed.Encode()).Score == 15 && OriginalSave.Parse(changed.Encode()).Tasks[3].State == 35,
"Modified original save did not persist recovered fields");
Console.WriteLine("PASS: all12 original TSK files byte-round-trip, malformed saves reject, task query/assignment and mutations persist.");
Require(initial.Code == "LV1B" && initial.Entities.Count == 129, "Wrong initial scene");
Require(initial.Player!.Position.X == 5071.93310546875f, "Original player X changed");
Require(initial.FindStart()!.CameraPosition.Y == 235.64761352539062f, "Original camera Y changed");
@@ -113,6 +138,29 @@ foreach (var key in new[] { 31u, 32u, 33u })
Require(clips.Select(30) && !clips.Current.HasVertexMotion, "Idle selection did not restore original still pose");
Console.WriteLine($"PASS: original lab grounding (+{placement.VerticalCorrection:F3} Y), ceiling/proxy rejection, and explicit idle/run/jump/scratch selection.");
var preparedFixture = Path.Combine(Path.GetTempPath(), "neutron-bank-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(preparedFixture);
try
{
string WaveManifest(string name, string database, string payload)
{
File.WriteAllText(Path.Combine(preparedFixture, name + ".wav"), payload);
var path = Path.Combine(preparedFixture, name + ".json");
File.WriteAllText(path, System.Text.Json.JsonSerializer.Serialize(new { resources = new[] {
new { database, type = "Wave", id = 59, path = name + ".wav", audio = new { seconds = 1.0 } } } }));
return path;
}
var first = WaveManifest("scene", "omt/soundeffects.omt", "same-source-riff");
var second = WaveManifest("bank", "SoundEffects.omt", "same-source-riff");
var merged = new PreparedEntityResources(first, second);
Require(merged.Wave("SOUNDEFFECTS.OMT", 59)?.Seconds == 1, "Explicit bank/scene identity did not merge");
File.WriteAllText(Path.Combine(preparedFixture, "bank.wav"), "different-source-riff");
try { _ = new PreparedEntityResources(first, second); throw new Exception("Conflicting audio identities accepted"); }
catch (InvalidDataException) { }
Console.WriteLine("PASS: explicit bank/scene resource merge accepts identical waves and rejects conflicting identities.");
}
finally { Directory.Delete(preparedFixture, true); }
static void Require(bool condition, string message)
{
if (!condition) throw new Exception(message);
@@ -124,3 +172,10 @@ static void Reject(byte[] data)
catch (InvalidDataException) { return; }
throw new Exception("Malformed GAM was accepted");
}
static void RejectSave(byte[] data)
{
try { OriginalSave.Parse(data); }
catch (InvalidDataException) { return; }
throw new Exception("Malformed TSK was accepted");
}
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs"/><Compile Include="../../src/GamePort/Assets/*.cs"/><Compile Include="../../src/GamePort/Game/*.cs"/><Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs"/><Compile Include="../../src/GamePort/Application/SceneActorVisuals.cs"/><Compile Include="../../src/GamePort/Application/SceneSpriteVisuals.cs"/><Compile Include="../../src/GamePort/Application/StaticSceneVisuals.cs"/></ItemGroup>
</Project>
+175
View File
@@ -0,0 +1,175 @@
using System.Buffers.Binary;
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var level = GamLevel.Load(AssetPath.Resolve(root,"gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(root,"NewGame.tsk"));
var tasks = new TaskStates(save.Tasks);
var director = new SceneDirector(level,tasks,(_,_)=>.1);
var cues = 0;
director.Speech += (_,_)=>cues++;
director.Begin(level.FindStart()!);
Check(!director.Controlled && director.CurrentTag == "LABEXP1", "STRT must freeze into original first camera");
for(var i=0;i<200 && !director.Controlled;i++) director.Step(.1f);
Check(director.Controlled && !director.Blocked && cues>10, "Complete original intro trigger/camera chain");
Check(tasks.Get("SCENE")==30, "Intro must not invent a progression/task advance");
var endGoddard = director.FindActor("C3DGODDARD")!.Position;
Check(endGoddard==director.FindActor("phone2")!.Position,"AI teleport position actions must execute");
Check(director.Issues.Any(x=>x.Detail.Contains("Patrol")),"Unsupported patrol must remain explicit");
Console.WriteLine($"PASS original lab sequence: {cues} original speech cues, correct task30, control restored");
var skip = new SceneDirector(level,new TaskStates(save.Tasks),(_,_)=>10);
var skipCues=0;
skip.Speech += (_,_)=>skipCues++;
skip.Begin(level.FindStart()!);
skip.Skip();
Check(skip.Controlled && !skip.Blocked && skipCues==1,"Skip must fast-forward voices and return control");
Check(skip.FindActor("C3DGODDARD")!.Position==endGoddard,"Skip must preserve AI/toggle actions");
Console.WriteLine("PASS original intro skip preserves action sequence");
foreach(var type in new[]{0,1,2,3,4})
{
var camera=Entity("3MCA","camera",("CameraTarget0","actor"),("SoundDatabase","voice"),("SoundIndex0",1),("CameraType0",type),("LookatVOffset0",100f),("NextTrigger","default"));
var actor=Entity("3CAR","actor",("PositionX",50f),("PositionY",20f),("PositionZ",70f));
var test=new SceneDirector(new("TEST",[camera,actor]),new TaskStates([]),(_,_)=>20);
test.Trigger("camera");test.Step(1);
var expected=type switch {1=>new Vector3(0,140,285),2=>new(0,240,465),3=>new(200,240,645),4=>new(-200,190,645),_=>new(0,40,200)};
Near(test.CameraEye!.Value,actor.Position+expected,"Recovered MCA eye");
Near(test.CameraTarget!.Value,actor.Position+new Vector3(0,40,0),"Recovered MCA target offset minus60");
}
Console.WriteLine("PASS all five recovered MCA framing/zoom formulas");
var target=Entity("3CAR","actor",("PositionX",20f),("PositionY",30f),("PositionZ",40f));
var cam=Entity("3CAM","camera",("CameraTarget","actor"),("SoundDatabase","voice"),("SoundIndex",1),("CameraType",2),("PositionX",200f),("PositionY",300f),("PositionZ",400f));
var fixedCam=new SceneDirector(new("TEST",[target,cam]),new TaskStates([]),(_,_)=>10);
fixedCam.Trigger("camera");Near(fixedCam.CameraEye!.Value,cam.Position,"CAM type2 authored eye");Near(fixedCam.CameraTarget!.Value,target.Position,"CAM type2 no offset");
var zoom=Entity("3CAM","camera",("CameraTarget","actor"),("SoundDatabase","voice"),("SoundIndex",1),("CameraType",0),("ViewFromCamera",0),("InitialDist",300f),("MinDist",100f),("MaxDist",500f),("ZoomSpeed",20f),("TargOffsetX",12f),("TargOffsetY",40f),("LookVoffset",90f));
var zoomCam=new SceneDirector(new("TEST",[target,zoom]),new TaskStates([]),(_,_)=>10);zoomCam.Trigger("camera");zoomCam.Step(1);
Near(zoomCam.CameraEye!.Value,target.Position+new Vector3(12,40,280),"CAM local zoom");Near(zoomCam.CameraTarget!.Value,target.Position+new Vector3(0,90,0),"CAM look offset");
Console.WriteLine("PASS CAM authored/local camera and zoom");
var gated=Entity("3CAR","gate",("RequiredLevel",30),("ExactLevel",-1),("RemoveLevel",60));
Check(TaskActivation.Animated(gated,29)==false && TaskActivation.Animated(gated,30)==true && TaskActivation.Animated(gated,59)==true && TaskActivation.Animated(gated,60)==false,"Threshold and exclusive removal");
var exact=Entity("3CAR","exact",("RequiredLevel",100),("ExactLevel",35),("RemoveLevel",20));
Check(TaskActivation.Animated(exact,35)==true && TaskActivation.Animated(exact,36)==false,"Exact numeric level takes precedence");
Check(TaskActivation.Animated(Entity("3CAR","unchanged",("RequiredLevel",-1)),999)==null,"-1 leaves activation unchanged");
var load=Entity("LOAD","load",("RequiredTask","SCENE"),("RequiredLevel",30),("ExactLevel",60));
Check(!TaskActivation.Load(load,tasks),"LOAD exact numeric60 must reject30");tasks.SetExisting("SCENE",60);Check(TaskActivation.Load(load,tasks),"LOAD gate60");tasks.SetExisting("SCENE",-1);Check(TaskActivation.Load(load,tasks),"LOAD task-1 bypass");
Console.WriteLine("PASS recovered task activation and LOAD gates");
var cycle=Entity("3AIT","cycle",("NextTrigger","cycle"),("TimesToTrigger",-1));
var cyclic=new SceneDirector(new("TEST",[cycle]),new TaskStates([]),(_,_)=>1);cyclic.Trigger("cycle");Check(cyclic.Blocked && cyclic.Issues.Count==1,"Malformed cycle must stop bounded");
Console.WriteLine("PASS bounded trigger-cycle handling");
var manifest="artifacts/extracted/level1b/entities/entities.json";
var resources=new PreparedEntityResources(manifest);
Check(resources.Duration("voiceneighborhood.omt",36)>0,"Original voice duration");
var real=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);real.Begin(level.FindStart()!);
for(var i=0;i<180 && !real.Controlled;i++)real.Step(1);
Check(real.Controlled && !real.Blocked,"Actual WAV-duration intro reaches original DEFAULT");
Console.WriteLine("PASS original decoded speech durations drive lab intro completion");
var once = new SpriteSequence(3,10,0);once.Start();once.Step(.1f);Check(once.Frame==0 && once.Running,"Strict frame interval");
once.Step(.01f);once.Step(.11f);Check(once.Frame==1,"Advance one frame per source call");once.Step(.11f);Check(once.Frame==2 && !once.Running && !once.Hidden,"Loop0 stops on final visible frame");
var hidden = new SpriteSequence(2,10,2);hidden.Start();hidden.Step(.11f);hidden.Step(.11f);Check(hidden.Hidden && !hidden.Running,"Loop2 hides at sequence end");
var repeat = new SpriteSequence(2,10,1);repeat.Start();for(var i=0;i<10;i++)repeat.Step(.5f);Check(repeat.Running && !repeat.Hidden && repeat.Frame==1,"Loop1 repeats, at most one frame/call");
Console.WriteLine("PASS recovered sprite strict timing, repeat and stop/hide modes");
var world=Mesh.LoadSceneJson("artifacts/extracted/level1b/scene.json");
var visualDirector=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);
var actorVisuals=new SceneActorVisuals(world,world,visualDirector,"artifacts/extracted");
var spriteVisuals=new SceneSpriteVisuals(actorVisuals.Mesh,visualDirector,resources);
var staticVisuals=new StaticSceneVisuals(spriteVisuals.Mesh,visualDirector,root,"artifacts/extracted/level1b/models");
var combined=staticVisuals.Mesh;
Check(staticVisuals.ActorCount==9,"Actual lab adds nine explicitly bound model actors");
visualDirector.FindActor("C3DCARL")!.Animation="TALK";
actorVisuals.Update(0,combined);
var before=combined.Vertices.Select(v=>v.Position).ToArray();
actorVisuals.Update(.05,combined);
Check(combined.Vertices.Where((v,i)=>v.Position!=before[i]).Any(),"Appending props must retain live actor animation updates in final buffer");
var spriteOffset=actorVisuals.Mesh.Vertices.Length;
spriteVisuals.FaceCamera(new(4873,235,373),new(5071,126,824),combined);
Check(combined.Vertices[spriteOffset].Position!=Vector3.Zero,"Appending props must retain live sprite updates in final buffer");
var firstSprite=combined.Vertices[spriteOffset].Position;
spriteVisuals.FaceCamera(new(5373,335,373),new(5071,126,824),combined);
Check(combined.Vertices[spriteOffset].Position!=firstSprite,"Sprite quad orientation responds to the rendered camera in final buffer");
Check(combined.Vertices.All(v=>float.IsFinite(v.Position.X+v.Position.Y+v.Position.Z)),"Combined model/sprite geometry must remain finite");
Check(combined.Draws.Count(d=>d.Visible)>world.Draws.Length,"Original actor/sprite/model consumers add visible source geometry");
Console.WriteLine("PASS combined source actor/sprite/model geometry and live animation/billboard buffer updates");
var mechanismDirector=new SceneDirector(level,new TaskStates(save.Tasks),resources.Duration);
var mechanisms=new SceneMechanisms(mechanismDirector);
var bar=mechanismDirector.FindActor("bars")!;
var closed=bar.Position;
var buttons=mechanismDirector.Actors.Where(a=>a.Kind=="3BUT").ToArray();
var moveSounds=0;mechanisms.Sound+=(_,index,loop)=>{if(index==59&&loop)moveSounds++;};
mechanisms.Update(buttons[0].Position+new Vector3(360,0,0));
mechanisms.Step(1);Near(bar.Position,closed,"Strict button contact boundary");
mechanisms.Update(buttons[0].Position);mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*100,"DoorSpeed5 gives a five-second opening of500");
Check(buttons[0].Animation=="DOWN","Player contact presses original DOWN model");
mechanisms.Toggle(bar,1);mechanisms.Step(0);
Near(bar.Position,closed+Vector3.UnitY*100,"Reversal preserves current vertical position");
mechanisms.Step(.5f);Near(bar.Position,closed+Vector3.UnitY*50,"Reversed door closes with remaining fraction");
mechanisms.Step(.5f);Near(bar.Position,closed,"Reversed door finishes at source root");
Check(moveSounds==1,"Reversing an active door retains one looping movement sound");
Console.WriteLine("PASS original lab button strict contact, source door duration, reversal continuity and sound lifetime");
mechanisms.Reset();mechanisms.Update(buttons[0].Position);
for(var i=0;i<4;i++)mechanisms.Step(1);
Check(buttons[0].Animation=="UP","Button returns UP exactly when four-second cooldown expires");
mechanisms.Update(buttons[0].Position);
Check(buttons[0].Animation=="UP","Continuous contact must not press again after cooldown");
mechanisms.Step(1);Near(bar.Position,closed+Vector3.UnitY*500,"Door reaches full source OpenAmount");
for(var i=0;i<3;i++)mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*500,"OpenTime equality does not auto-close");
mechanisms.Step(.1f);mechanisms.Step(1);
Near(bar.Position,closed+Vector3.UnitY*400,"OpenTime strict expiry starts next closing phase");
mechanisms.Update(buttons[1].Position);
Check(buttons[1].Animation=="DOWN","Duplicate button tags preserve distinct contact states by source offset");
Console.WriteLine("PASS source button cooldown, contact-enter persistence, duplicate tags and strict timed door close");
var prompt=new PracticePrompt();
var selections=new List<(int Mode,bool Accepted)>();prompt.Chosen+=(mode,accepted)=>selections.Add((mode,accepted));
prompt.Show(0);prompt.Click(new(225,260));Check(prompt.Active,"Practice hitbox excludes its boundary");
prompt.Click(new(260,260));Check(!prompt.Active && selections[^1]==(0,true),"Practice Yes mouse region");
prompt.Show(0);prompt.Key(40,Vector2.Zero);Check(!prompt.Active && !selections[^1].Accepted,"Enter outside Yes follows original No branch");
prompt.Show(0);prompt.Key(40,new(260,260));Check(!prompt.Active && selections[^1].Accepted,"Enter hovering Yes accepts");
prompt.Show(0);prompt.Key(28,Vector2.Zero);Check(!prompt.Active && selections[^1].Accepted,"Y accepts regardless of pointer");
prompt.Show(0);prompt.Key(17,new(260,260));Check(!prompt.Active && !selections[^1].Accepted,"N declines regardless of pointer");
Check(PracticePrompt.Destination(0)=="VR04.gam" && PracticePrompt.Destination(3)=="VR01.gam","Original practice mode mapping");
Console.WriteLine("PASS original practice keyboard/pointer boundaries and VR04 jet pack mapping");
var vr=GamLevel.Load(AssetPath.Resolve(root,"gam/VR01.gam"));
var vrTasks=new TaskStates(save.Tasks);var vrDirector=new SceneDirector(vr,vrTasks,(_,_)=>1);
var interactions=new SceneInteractions(vrDirector,vrTasks,save);
var stars=vr.Entities.Where(e=>e.Kind=="3PIC").ToArray();
Check(stars.Length==4,"Original VR01 star count");
interactions.Update(stars[0].Position+Vector3.UnitX*160);
Check(interactions.Score==0,"Source sphere boundary is strict");
foreach(var star in stars){interactions.Update(star.Position);interactions.Update(star.Position);}
Check(interactions.Score==20 && stars.All(e=>interactions.Snapshot().ItemStates[e.Integer("PickupIndex")]==1),"Source stars score once and persist acquired flags");
var trophy=vr.Entities.Single(e=>e.Kind=="3TRO");interactions.Update(trophy.Position);interactions.Update(trophy.Position);
Check(interactions.Score==320,"Trophy awards300 once and disables itself");
var restoredDirector=new SceneDirector(vr,new TaskStates(save.Tasks),(_,_)=>1);var restored=new SceneInteractions(restoredDirector,new TaskStates(save.Tasks),OriginalSave.Parse(interactions.Snapshot().Encode()));
Check(restoredDirector.Actors.Where(a=>a.Kind=="3PIC").All(a=>!a.Visible && !a.Active),"Loaded acquired stars must hide before contact");
var transitions=0;LevelTransition? returned=null;interactions.Transition += request=>{transitions++;returned=request;};
var returnGate=vr.Entities.First(e=>e.Kind=="LOAD");interactions.Update(returnGate.Position);interactions.Update(returnGate.Position);
Check(transitions==1 && returned!.LevelFile==save.ReturnLevel && returned.StartPoint==save.ReturnStart,"RETURN uses stored destination and contact-enter gating");
Console.WriteLine("PASS original VR01 star/trophy score, strict contact entry, acquired-state save/reload and RETURN request");
static GamEntity Entity(string kind,string tag,params (string Name,object Value)[] values)
{
var properties=new Dictionary<string,GamProperty>();
foreach(var (name,value) in values.Prepend(("ObjectTag",(object)tag)))
{
uint type;byte[] raw;
if(value is string text){type=1;raw=System.Text.Encoding.Latin1.GetBytes(text);}
else {raw=new byte[4];type=value is float?3u:6u;BinaryPrimitives.WriteInt32BigEndian(raw,value is float number?BitConverter.SingleToInt32Bits(number):(int)value);}
properties[name]=new(name,type,raw);
}
return new(kind,0,properties,new byte[4]);
}
static void Check(bool condition,string message){if(!condition)throw new Exception(message);}
static void Near(Vector3 actual,Vector3 expected,string message)=>Check(Vector3.Distance(actual,expected)<.01f,$"{message}: {actual} != {expected}");
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/DynamicSceneCollision.cs" Link="DynamicSceneCollision.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" Link="OriginalBodySupport.cs" />
<Compile Include="../../src/GamePort/Game/SceneCollision.cs" Link="SceneCollision.cs" />
<Compile Include="../../src/GamePort/Assets/Mesh.cs" Link="Mesh.cs" />
<Compile Include="../../src/GamePort/Assets/PngImage.cs" Link="PngImage.cs" />
<Compile Include="../../src/GamePort/Assets/GamLevel.cs" Link="GamLevel.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,140 @@
using System.Globalization;
using System.Numerics;
using System.Text.RegularExpressions;
using GamePort.Assets;
using GamePort.Game;
var groups = 0;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: {actual} != {expected}");
void Test(string name, Action action) { action(); groups++; Console.WriteLine($"PASS {name}"); }
DynamicBoxCollider Box() => new(4, Vector3.Zero, new(-5), new(5), Matrix4x4.Identity);
DynamicSphereMotion Sphere(float x = 0) => new(new(x, 0, -1), new(x, 0, 0), 60);
Test("door constructor defaults and HasCollision sentinel", () => {
Check(DynamicSceneCollision.DoorRadius == 40 && DynamicSceneCollision.DoorMode == 2, "door dimensions/mode");
Check(DynamicSceneCollision.DoorCollisionFlags(-1) == (true, false), "-1 must preserve pair on/integration off");
Check(DynamicSceneCollision.DoorCollisionFlags(0) == (false, false), "explicit collision off");
Check(DynamicSceneCollision.DoorCollisionFlags(1) == (true, true), "explicit collision on");
});
Test("inclusive quantized-root broadphase and large-cube quirk", () => {
Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(140)), "140 boundary rejected");
Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(140.01f)), "outside 140 accepted");
var large = Box() with { LocalMin = new(-1000), LocalMax = new(1000) };
Check(!DynamicSceneCollision.BroadPhase(large, Sphere(200)), "cube extents silently enlarged root broadphase");
Check(DynamicSceneCollision.BroadPhase(Box(), Sphere(100) with { Mode = 2 }), "box/box boundary");
Check(!DynamicSceneCollision.BroadPhase(Box(), Sphere(100.01f) with { Mode = 2 }), "box/box sum radius exceeded");
});
Test("pair, entity and sphere-geometry gates avoid narrowphase", () => {
DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("disabled narrowphase invoked");
Check(!DynamicSceneCollision.Resolve(Box() with { CollisionEnabled = false }, Sphere(), Fail).Contact, "box gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { CollisionEnabled = false }, Fail).Contact, "sphere gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere() with { GeometryCollisionEnabled = false }, Fail).Contact, "geometry gate");
Check(!DynamicSceneCollision.Resolve(Box(), Sphere(), Fail, false).Contact, "mutual exclusion gate");
});
Test("oriented source-local corners and current translation", () => {
var local = Box() with { LocalMin = new(-1, -2, -3), LocalMax = new(4, 5, 6) };
var corners = DynamicSceneCollision.Corners(local);
Check(corners[0] == local.LocalMin && corners[7] == local.LocalMax, "min/max corners");
Check(corners[1] == new Vector3(-1, -2, 6) && corners[6] == new Vector3(4, 5, -3), "corner bit order");
var transform = Matrix4x4.CreateRotationY(MathF.PI / 2) * Matrix4x4.CreateTranslation(100, 500, -80);
var moved = DynamicSceneCollision.Corners(local with { Root = new(100, 500, -80), LocalToWorld = transform });
for (var i = 0; i < 8; i++) Check(moved[i] == Vector3.Transform(corners[i], transform), "oriented transform");
});
Test("twelve source triangle order, normals and closed surface", () => {
var box = Box(); var corners = DynamicSceneCollision.Corners(box); var triangles = DynamicSceneCollision.Triangles(box);
Check(triangles.Length == 12, "cube triangle count");
Check(triangles[0] == new SupportTriangle(corners[0], corners[1], corners[2], 4, 0), "first original face");
Check(triangles[11] == new SupportTriangle(corners[7], corners[6], corners[2], 4, 11), "last original face");
var edges = new Dictionary<(int, int), int>();
foreach (var triangle in triangles) {
var normal = Vector3.Cross(triangle.B - triangle.A, triangle.C - triangle.A);
Check(Vector3.Dot(normal, (triangle.A + triangle.B + triangle.C) / 3) > 0, "face winding is not outward");
var ids = new[] { Array.IndexOf(corners, triangle.A), Array.IndexOf(corners, triangle.B), Array.IndexOf(corners, triangle.C) };
for (var i = 0; i < 3; i++) {
var a = ids[i]; var b = ids[(i + 1) % 3]; var key = (Math.Min(a, b), Math.Max(a, b));
edges[key] = edges.GetValueOrDefault(key) + 1;
}
}
Check(edges.Count == 18 && edges.Values.All(n => n == 2), "cube surface has a gap/duplicate");
});
Test("injected narrowphase and response-inhibition semantics", () => {
var calls = 0;
DynamicCollisionResponse Query(DynamicBoxSweep sweep) {
calls++; Check(sweep.Triangles.Count == 12 && sweep.Box.Identity == 4 && sweep.Sphere == Sphere(), "sweep contract");
return new(true, new(1, 2, 3));
}
Check(DynamicSceneCollision.Resolve(Box(), Sphere(), Query) == new DynamicCollisionResponse(true, new(1, 2, 3)), "response lost");
Check(DynamicSceneCollision.Resolve(Box() with { InhibitResponse = true }, Sphere(), Query)
== new DynamicCollisionResponse(true, Sphere().Position), "inhibited response moved body");
Check(calls == 2, "response inhibition incorrectly suppressed contact query");
var noContact = DynamicSceneCollision.Resolve(Box(), Sphere(), _ => new(false, new(10)));
Check(!noContact.Contact && noContact.Position == Sphere().Position, "failed query moved body");
});
Test("mode2 second actor bypasses triangle response", () => {
DynamicCollisionResponse Fail(DynamicBoxSweep sweep) => throw new Exception("box/box shortcut swept triangles");
var body = Sphere(80) with { Mode = 2 };
Check(DynamicSceneCollision.Resolve(Box(), body, Fail) == new DynamicCollisionResponse(true, body.Position), "box/box shortcut");
});
Test("source motion changes geometry without a closed-position residue", () => {
var box = Box(); var closed = DynamicSceneCollision.Corners(box);
var open = DynamicSceneCollision.Corners(box with { Root = new(0, 500, 0), LocalToWorld = Matrix4x4.CreateTranslation(0, 500, 0) });
for (var i = 0; i < closed.Length; i++) Check(open[i] - closed[i] == new Vector3(0, 500, 0), "door corner did not move");
});
Test("invalid source cube and transform rejected", () => {
foreach (var box in new[] { Box() with { LocalMin = new(10) }, Box() with { Radius = float.NaN },
Box() with { LocalToWorld = new Matrix4x4() }, Box() with { Root = new(float.PositiveInfinity) } }) {
var threw = false;
try { DynamicSceneCollision.BroadPhase(box, Sphere()); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "malformed collider accepted");
}
});
Test("actual lab bars bounds, closed/open passage with provisional sphere adapter", () => {
var original = Path.GetFullPath("../Original");
var level = GamLevel.Load(Path.Combine(original, "gam/level1b.gam"));
var bars = level.Entities.Single(e => e.Kind == "3DUD" && e.Tag == "bars");
Check(bars.Integer("HasCollision") == -1 && bars.Integer("CanMove") == 1 && bars.Rotation == Vector3.Zero, "lab authored flags");
var asePath = Directory.EnumerateFiles(Path.Combine(original, "ASE")).Single(p => Path.GetFileName(p).Equals("bars.ase", StringComparison.OrdinalIgnoreCase));
var text = File.ReadAllText(asePath);
var count = int.Parse(Regex.Match(text, @"\*MESH_NUMVERTEX\s+(\d+)").Groups[1].Value, CultureInfo.InvariantCulture);
var points = Regex.Matches(text, @"\*MESH_VERTEX\s+\d+\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)")
.Take(count).Select(m => new Vector3(float.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture),
float.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture), float.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture))).ToArray();
Check(points.Length == 42, "source bars vertex count");
var min = points.Aggregate(Vector3.Min); var max = points.Aggregate(Vector3.Max);
Near(min.X, -223.8069f, .0001f, "source xmin"); Near(min.Y, -18.7273f, .0001f, "source ymin");
Near(max.Y, 391.2706f, .0001f, "source ymax"); Near(max.Z, 16.8051f, .0001f, "source zmax");
var box = new DynamicBoxCollider(bars.Offset, bars.Position, min, max, Matrix4x4.CreateTranslation(bars.Position));
var body = new DynamicSphereMotion(bars.Position + new Vector3(0, 76, -100), bars.Position + new Vector3(0, 76, -20), 60);
// This adapter verifies integration/blocked passage only. SceneCollision's
// sweep/slide remains the explicitly provisional consumer, not original47BD80.
var calls = 0;
DynamicCollisionResponse Provisional(DynamicBoxSweep sweep) {
calls++;
var vertices = sweep.Triangles.SelectMany(t => new[] { t.A, t.B, t.C })
.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray();
var mesh = new Mesh(vertices, Enumerable.Range(0, vertices.Length).Select(i => (uint)i).ToArray());
var radius = sweep.Sphere.Radius;
var result = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius,
sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2);
var position = result.Position + Vector3.UnitY * radius;
return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position);
}
var closed = DynamicSceneCollision.Resolve(box, body, Provisional);
Check(closed.Contact && closed.Position.Z < bars.Position.Z - 76, "closed bars did not block source-sized sphere");
var raised = bars.Position + Vector3.UnitY * bars.Number("OpenAmount");
var open = DynamicSceneCollision.Resolve(box with { Root = raised, LocalToWorld = Matrix4x4.CreateTranslation(raised) }, body, Provisional);
Check(!open.Contact && open.Position == body.Position && calls == 1, "raised bars still block closed location");
});
Console.WriteLine($"{groups} dynamic collision groups passed; injected narrowphase/runtime fidelity remain unverified.");
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs"/>
<Compile Include="../../src/GamePort/Assets/Mesh.cs"/>
<Compile Include="../../src/GamePort/Assets/PngImage.cs"/>
<Compile Include="../../src/GamePort/Application/SceneHud.cs"/>
</ItemGroup>
</Project>
+63
View File
@@ -0,0 +1,63 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Application;
var temp = Path.Combine(Path.GetTempPath(), "neutron-hud-" + Guid.NewGuid());
Directory.CreateDirectory(temp);
try
{
var entries = new[] { (120,256,29),(121,256,29),(122,256,29),(156,320,173),(169,207,100),(83,8,8),(84,8,8),(85,8,8) }
.Select(t => new { id=t.Item1, width=t.Item2, height=t.Item3, path=$"{t.Item1}.rgba" }).ToArray();
foreach (var entry in entries) File.WriteAllBytes(Path.Combine(temp, entry.path), new byte[entry.width * entry.height * 4]);
string Manifest(object textures) => JsonSerializer.Serialize(new { version=1, referenceWidth=640, referenceHeight=480, textures });
var path = Path.Combine(temp, "ui.json");
File.WriteAllText(path, Manifest(entries));
var source = new Mesh([new(new(5,6,7), Vector2.Zero, Vector3.One)], [0,0,0]);
var hud = new SceneHud(source, path);
Check(hud.Mesh.Vertices.Length == 33 && hud.Mesh.Indices.Length == 51, "Exact bounded HUD ranges");
Check(hud.Mesh.Draws.Length == 9 && !hud.Mesh.Draws[0].ScreenSpace && hud.Mesh.Draws.Skip(1).All(d => d.ScreenSpace),
"Preserve implicit world draw; explicit HUD overlays");
Check(hud.Mesh.Textures.Count == 8, "Original canvas count");
var final = hud.Mesh with { Vertices = hud.Mesh.Vertices.ToArray(), Draws = hud.Mesh.Draws.Select(d => d with {}).ToArray() };
hud.Update(final, 2, true, true);
Check(final.Vertices[0].Position == new Vector3(5,6,7), "HUD leaves world data unchanged");
Check(hud.Mesh.Vertices[1].Position == Vector3.Zero && final.Vertices[1].Position != Vector3.Zero,
"Update writes final merged buffer after copies");
Near(final.Vertices[1].Position, new(.2f, 2*311f/480-1, 0), "Pad default source offset");
Near(final.Vertices[9].Position, new(.2f, 2*379f/480-1, 0), "Selected objective row position");
Near(final.Vertices[21].Position, new(2*393f/640-1, 2*381f/480-1, 0), "Selected original digit position");
Near(final.Vertices[29].Position, new(2*210f/640-1, 2*210f/480-1, 0), "Practice source position");
Check(final.Draws.Select(d => d.Visible).SequenceEqual(new[] { true,true,false,true,false,false,true,false,true }),
"Only pad, active objective2 and practice visible");
hud.Update(final, 3, true, false, 0);
Check(final.Draws.Select(d => d.Visible).SequenceEqual(new[] { true,true,false,false,true,false,false,true,false }), "Objective3 and dismissed modal");
Near(final.Vertices[1].Position, new(.2f, 2*380f/480-1, 0), "Expanded source HUD offset");
hud.Update(final, 0, true, false);
Check(final.Draws.Skip(1).All(d => !d.Visible), "No invented objective0 image");
Reject(() => hud.Update(source, 1, true, false), "Missing final ranges");
Reject(() => hud.Update(final, 1, true, false, float.NaN), "Nonfinite HUD offset");
File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, width=e.id==120 ? 0 : e.width, e.height, e.path })));
Reject(() => new SceneHud(source,path), "Bad canvas dimensions");
File.WriteAllText(path, Manifest(entries.Select(e => new { e.id, e.width, e.height, path=e.id==120 ? "../outside.rgba" : e.path })));
Reject(() => new SceneHud(source,path), "Escaping texture path");
File.WriteAllText(path, Manifest(entries.Concat(entries.Take(1))));
Reject(() => new SceneHud(source,path), "Unbounded texture count");
if (args.Length == 1)
{
var originalHud = new SceneHud(source, args[0]);
originalHud.Update(originalHud.Mesh,1,true,true);
Check(originalHud.Mesh.Textures.Values.Any(p=>p.Rgba.Any(v=>v!=0)), "Actual original RGBA loaded");
}
Console.WriteLine("PASS original UI geometry/visibility/final buffer and bounded prepared manifest checks");
}
finally { Directory.Delete(temp,true); }
static void Check(bool value,string message) { if(!value)throw new Exception(message); }
static void Near(Vector3 a,Vector3 b,string message) => Check(Vector3.Distance(a,b)<.00001f,message);
static void Reject(Action action,string message)
{
try { action(); }
catch (Exception e) when (e is InvalidDataException or ArgumentException) { return; }
throw new Exception("Accepted invalid input: " + message);
}
+50
View File
@@ -0,0 +1,50 @@
"""Original UI extraction regressions; stdlib only, no original writes."""
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from omt import Database, FormatError, read_canvas
from ui import export_ui
class UiTests(unittest.TestCase):
def test_original_canvases_and_hashes(self):
original = ROOT.parent / 'Original'
screens = Database(original / 'omt' / 'screens.omt')
alpha = Database(original / 'alpha.omt')
before = [hashlib.sha256(db.path.read_bytes()).hexdigest() for db in (screens, alpha)]
with tempfile.TemporaryDirectory() as target:
output = Path(target) / 'ui'
result = export_ui(screens, output, alpha)
self.assertEqual(8, len(result['textures']))
self.assertEqual([120,121,122,156,169,83,84,85], [t['id'] for t in result['textures']])
for entry in result['textures']:
database = alpha if entry['source'] == 'alpha.omt' else screens
raw = next(e for e in database.entries if e.type == 'Canv' and e.id == entry['id'])
rgba = read_canvas(database.payload(raw))['rgba']
self.assertEqual(rgba, (output / entry['path']).read_bytes())
self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256'])
self.assertEqual(result, json.loads((output / 'ui.json').read_text()))
self.assertEqual(before, [hashlib.sha256(db.path.read_bytes()).hexdigest() for db in (screens, alpha)])
def test_missing_canvas_and_original_output_rejected(self):
original = ROOT.parent / 'Original'
screens = Database(original / 'omt' / 'screens.omt')
alpha = Database(original / 'alpha.omt')
with self.assertRaises(ValueError):
export_ui(screens, screens.path.parent / 'generated', alpha)
screens.entries = [e for e in screens.entries if e.id != 120]
with tempfile.TemporaryDirectory() as target:
output = Path(target) / 'ui'
with self.assertRaises(FormatError):
export_ui(screens, output, alpha)
self.assertFalse(output.exists(), 'Validate identities before creating output')
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs"/>
<Compile Include="../../src/GamePort/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/SceneInteractions.cs"/>
<Compile Include="../../src/GamePort/Game/SceneInventory.cs"/>
<Compile Include="../../src/GamePort/Game/SceneDirector.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs"/>
</ItemGroup>
</Project>
+201
View File
@@ -0,0 +1,201 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
var root = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var original = OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var lab = GamLevel.Load(AssetPath.Resolve(root, "gam/level1b.gam"));
var counter = 1;
var tasks = new TaskStates(original.Tasks);
var director = new SceneDirector(lab, tasks, (_, _) => 5);
var interactions = new SceneInteractions(director, tasks, original, lab.Code);
director.Begin(lab.FindStart()!);
interactions.Reset();
director.Skip();
Check(tasks.Get("SCENE") == 30 && director.Controlled, "Intro cannot invent lab completion");
var explanation = lab.Entities.Single(e => e.Tag == "teleportexplanation");
director.Touch("JIM1", explanation.Position);
Check(tasks.Get("SCENE") == 35 && interactions.CurrentObjective == 1, "Original explanation enables objective1/task35");
director.Skip();
var shrinkray = director.FindActor("shrinkray")!;
var checkpoint = Vector3.Zero;
var help = -1;
var selected = -1;
var events = new List<string>();
interactions.CheckpointCaptured += p => { checkpoint = p; events.Add("checkpoint"); };
tasks.Assigned += (name, state) => { if (name == "SCENE" && state == 50) events.Add("task50"); };
interactions.PracticeRequested += page => { help = page; events.Add("help"); };
interactions.Inventory.GadgetSelected += gadget => { selected = gadget; events.Add("gadget"); };
interactions.Collected += (_, points) => events.Add("score" + points);
interactions.Update(shrinkray.Position);
Check(tasks.Get("SCENE") == 50 && interactions.Score == 50, "Shrinkray grants50 and original task35->50");
Check(interactions.Inventory.State(0, 3) == 1 && selected == 3 && help == 0, "Shrinkray inventory/help/gadget side effects");
Check(checkpoint == shrinkray.Position && !shrinkray.Visible && !shrinkray.Active, "Capture current root before hiding acquired shrinkray");
Check(events.SequenceEqual(new[] { "checkpoint", "task50", "help", "gadget", "score50" }), "Recovered special hook ordering");
Check(interactions.Snapshot().ItemStates[301] == 1 && interactions.CurrentObjective == 2, "Acquired state and objective2 persist");
interactions.Update(shrinkray.Position);
Check(interactions.Score == 50 && events.Count == 5, "Repeated overlap cannot recollect");
Console.WriteLine("PASS source intro/explanation/shrinkray state, inventory and event ordering");
var carl = director.FindActor("C3DCARL")!;
Check(carl.Position == director.FindActor("CARLESC3")!.Position && carl.AIstate == 6, "Carl task callback positions state6 at authored marker");
var talkStarted = 0;
var taskAtSpeech = -1;
var scoreAtSpeech = -1;
director.Speech += (_, _) => { taskAtSpeech = tasks.Get("SCENE"); scoreAtSpeech = interactions.Score; };
interactions.ConversationStarted += (_, tag) => { talkStarted++; Check(tag == "neutron1a", "Authored TalkTrigger0"); };
director.SyncActor("JIM1", carl.Position, Vector3.Zero);
interactions.Update(carl.Position);
Check(taskAtSpeech == 60 && scoreAtSpeech == 150, "Carl callback runs before dialogue starts");
Check(tasks.Get("SCENE") == 60 && carl.AIstate == 9 && talkStarted == 1, "Carl ends dispatcher in state9 with scene60");
for (var i = 0; i < 10; i++) interactions.Update(carl.Position);
Check(interactions.Score == 150 && talkStarted == 1, "Talk does not repeat on contact stay");
Check(interactions.CurrentObjective == 3, "Carl transition selects objective3");
director.Skip();
LevelTransition? transition = null;
interactions.Transition += request => transition = request;
var exit = lab.Entities.Single(e => e.Tag == "LABTONEIGH");
interactions.Update(exit.Position);
Check(transition?.LevelFile == "level1.gam" && transition.StartPoint == "level1",
$"Original lab exit task60 gate opens: request={transition}; controlled={director.Controlled}; blocked={director.Blocked}; tag={director.CurrentTag}");
Console.WriteLine("PASS source Carl contact/callback/dialogue/task60 and original lab exit gate");
var snapshot = interactions.Snapshot();
var decoded = OriginalSave.Parse(snapshot.Encode());
Check(decoded.InventoryStates[3] == 1 && decoded.ItemStates[301] == 1 && decoded.Score == 150 && decoded.OtherCounter == 3,
"Original TSK serializes acquired gadget, score and objective selector");
Check(decoded.StoredVector == original.StoredVector, "Unknown saved vector is not overwritten by inferred checkpoint data");
var restoredTasks = new TaskStates(decoded.Tasks);
var restoredDirector = new SceneDirector(lab, restoredTasks, (_, _) => 5);
var restored = new SceneInteractions(restoredDirector, restoredTasks, decoded, lab.Code);
restoredDirector.Begin(lab.FindStart()!); restored.Reset(); restoredDirector.Skip();
Check(!restoredDirector.FindActor("shrinkray")!.Active && restored.Inventory.State(0, 3) == 1, "Resume retains collected shrinkray/inventory");
restored.Update(restoredDirector.FindActor("shrinkray")!.Position);
Check(restored.Score == 150, "Resume cannot award shrinkray twice");
Console.WriteLine("PASS original-format save/resume retains gadget and objective state");
// The source permits collection at other task values, but its special shrinkray
// hook only grants the gadget when SCENE==35. Preserve that awkward boundary.
foreach (var state in new[] { 30, 36, 50 })
{
var boundaryTasks = new TaskStates(original.Tasks.Select(t => t.Name == "SCENE" ? t with { State = state } : t));
var boundaryDirector = new SceneDirector(lab, boundaryTasks, (_, _) => 1);
var boundary = new SceneInteractions(boundaryDirector, boundaryTasks, original, lab.Code);
boundary.Update(boundaryDirector.FindActor("shrinkray")!.Position);
Check(boundaryTasks.Get("SCENE") == state && boundary.Inventory.State(0, 3) == 0 && boundary.Score == 50,
"Shrinkray special effect exact task35 gate, ordinary score remains");
}
Console.WriteLine("PASS exact shrinkray task gate without invented progression");
var body = Entity("3JIM", "jim");
var camera0 = Entity("3CAM", "first", ("CameraTarget", "jim"), ("SoundDatabase", "voice"), ("SoundIndex", 1));
var camera1 = Entity("3CAM", "fallback", ("CameraTarget", "jim"), ("SoundDatabase", "voice"), ("SoundIndex", 2));
foreach (var talkState in new[] { -1, -2, 50, 49 })
{
var friend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", talkState), ("TalkTrigger0", "missing"),
("TalkState1", talkState), ("TalkTrigger1", "first"),
("TalkState2", -2), ("TalkTrigger2", "fallback"));
var testTasks = new TaskStates([new("SCENE", 50)]);
var testDirector = new SceneDirector(new("TEST", [body, friend, camera0, camera1]), testTasks, (_, _) => 5);
var test = new SceneInteractions(testDirector, testTasks, original, "TEST");
test.Update(Vector3.Zero);
Check(testDirector.CurrentTag == (talkState is -2 or 50 ? "first" : "fallback"), "First existing match/wildcard; -1 disabled, missing target skipped");
Check(testTasks.Get("SCENE") == 60 && test.Score == 100, "Selected trigger alone invokes Carl callback");
}
var noneFriend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", 49), ("TalkTrigger0", "first"));
var noTasks = new TaskStates([new("SCENE", 50)]);
var noDirector = new SceneDirector(new("TEST", [body, noneFriend, camera0]), noTasks, (_, _) => 5);
var noTalk = new SceneInteractions(noDirector, noTasks, original, "TEST");
noTalk.Update(Vector3.Zero);
Check(noTasks.Get("SCENE") == 50 && noTalk.Score == 0 && noDirector.FindActor("friend")!.AIstate == 0,
"No matching talk target leaves state0 without award/task mutation");
Console.WriteLine("PASS talk lookup order, missing/disabled/wildcard states and no-match behavior");
foreach (var distance in new[] { 160f, 159.5f })
{
var friend = Entity("3CAR", "friend", ("AIState", 6), ("TargetName", "jim"), ("TaskName", "SCENE"),
("TalkState0", 50), ("TalkTrigger0", "first"));
var edgeTasks = new TaskStates([new("SCENE", 50)]);
var edgeDirector = new SceneDirector(new("TEST", [body, friend, camera0]), edgeTasks, (_, _) => 5);
var edge = new SceneInteractions(edgeDirector, edgeTasks, original, "TEST");
edge.Update(new(distance, 0, 0));
Check(edge.Score == (distance < 160 ? 100 : 0), "Strict original sum-radius Carl contact boundary");
}
var waiting = new SceneDirector(lab, new TaskStates(original.Tasks), (_, _) => 5);
waiting.Begin(lab.FindStart()!);
var locked = new SceneInteractions(waiting, new TaskStates(original.Tasks), original, lab.Code);
locked.Update(waiting.FindActor("shrinkray")!.Position);
Check(locked.Score == 0 && locked.Snapshot().ItemStates[301] == 0, "Noncontrolled intro cannot collect pickups");
Console.WriteLine("PASS strict recovered Carl radius boundary and active-player control gate");
var inventoryRaw = Enumerable.Range(0, 19).Select(i => i == 18 ? int.MinValue : i * 10).ToArray();
var inventory = new SceneInventory(inventoryRaw);
inventoryRaw[3] = 999;
Check(inventory.State(0, 3) == 30 && inventory.State(1, 9) == int.MinValue, "Owned inventory copy preserves unknown signed wire values");
var inventoryCopy = inventory.Snapshot(); inventoryCopy[3] = 888;
Check(inventory.State(0, 3) == 30, "Snapshot owns its storage");
Throws(() => inventory.State(2, 0)); Throws(() => inventory.State(0, 9));
inventory.SetState(0, 3, 0); Throws(() => inventory.SelectGadget(3));
inventory.SetState(0, 3, 1); inventory.SelectGadget(3); Check(inventory.SelectedGadget == 3, "Owned gadget selection");
Console.WriteLine("PASS inventory bounds, ownership, unknown-state preservation and gadget availability");
// Independently recover the original SCENE setter's two dispatch tables rather
// than testing the port's switch against another manually copied switch.
var exe = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe"));
foreach (var (address, expected) in new (int, string)[] {
(0x435fcb, "e800060000"), //Contact invokes special hook before score.
(0x4365fa, "83f823"), //Exact task35.
(0x43663e, "6a016a036a00"), //Inventory group0,item3,state1.
(0x436649, "6a00e84009fdff"), //Help page0.
(0x43667c, "6a03ff9274010000"), //Jimmy gadget3.
(0x413e2f, "680000c842"), //Carl radius100.
(0x40a676, "83be0806000006"), //Carl inherited contact requires state6.
(0x41b7cd, "ff9280010000"), //Derived award before selected trigger.
(0x41b813, "6a64e8a6f50000"), //Base friend awards100.
(0x41b7f0, "c786c806000009000000"), //Talk dispatcher ends in state9.
(0x458880, "8b442404898194040000c20400"), //LOAD task hook only stores value.
})
Check(exe.AsSpan(address - 0x400000, expected.Length / 2).SequenceEqual(Convert.FromHexString(expected)),
"Original interaction instruction evidence at" + address.ToString("X"));
int U32(int address) => BinaryPrimitives.ReadInt32LittleEndian(exe.AsSpan(address - 0x400000, 4));
int ExpectedObjective(int state)
{
int target;
if (state is >= 35 and <= 280) target = U32(0x45fbf0 + 4 * exe[0x45fc48 + state - 35 - 0x400000]);
else if (state == 290) target = 0x45fab6;
else if (state is >= 300 and <= 550) target = U32(0x45fd40 + 4 * exe[0x45fd98 + state - 300 - 0x400000]);
else return 0;
var offset = target - 0x400000;
return exe[offset] == 0x6a && exe[offset + 1] == 1 && exe[offset + 2] == 0x6a ? exe[offset + 3] : 0;
}
for (var state = -1; state <= 600; state++)
Check(SceneInteractions.ObjectiveForScene(state) == ExpectedObjective(state), "Objective map agrees with original jump tables at state" + state);
Console.WriteLine("PASS all SCENE objective milestones against original executable dispatch tables");
void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
void Throws(Action action)
{
try { action(); } catch (ArgumentOutOfRangeException) { return; }
throw new Exception("Expected bounded inventory rejection");
}
GamEntity Entity(string kind, string tag, params (string Name, object Value)[] properties)
{
var values = new Dictionary<string, GamProperty> { ["ObjectTag"] = new("ObjectTag", 1, Encoding.Latin1.GetBytes(tag)) };
foreach (var (name, value) in properties)
{
if (value is string text) values[name] = new(name, 1, Encoding.Latin1.GetBytes(text));
else
{
var bytes = new byte[4];
BinaryPrimitives.WriteInt32BigEndian(bytes, value is float number ? BitConverter.SingleToInt32Bits(number) : (int)value);
values[name] = new(name, value is float ? 3u : 6u, bytes);
}
}
// Distinct source offsets retain duplicate-tag contacts independently.
return new(kind, counter++ * 100, values, []);
}
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs" Link="JetpackBurst.cs" />
</ItemGroup>
</Project>
+189
View File
@@ -0,0 +1,189 @@
using GamePort.Game;
var count = 0;
void Check(bool condition, string message)
{
if (!condition) throw new Exception(message);
}
void Near(float actual, float expected, string message) =>
Check(MathF.Abs(actual - expected) < .0002f, $"{message}: {actual} != {expected}");
void Test(string name, Action action)
{
action();
count++;
Console.WriteLine($"PASS {name}");
}
JetpackBurstInput Input(bool ground = false, bool held = true, float vy = 20,
float distance = 100, int inventory = 1, float energy = 100, string level = "LV1B",
int mode = -1, float dt = .1f, float extra = -264) =>
new(ground, held, vy, distance, inventory, energy, level, mode, dt, extra);
Test("ordinary jump, release and renewed hold", () =>
{
var first = JetpackBurst.Step(new(), Input(ground: true));
Check(first.State.JumpState == 1 && first.State.HoldSeconds == 0, "ordinary takeoff state");
Check(first.Pose == JetpackPose.Jump && first.ImpulseY == 550 && first.VelocityYOverride is null,
"550 queued impulse selects JUMP");
Near(first.ExtraAccelerationY - 800, -1064, "ballistic net acceleration");
var released = JetpackBurst.Step(first.State, Input(held: false));
Check(released.State.JumpState == 2 && released.ImpulseY == 0, "release arms refire");
var refired = JetpackBurst.Step(released.State, Input(dt: 0));
Check(refired.State.JumpState == 3 && refired.State.EffectRemaining == 8, "refire needs no new .4 delay");
Check(refired.Pose == JetpackPose.Fly && refired.VelocityYOverride == 10
&& refired.RadiusOverride == 100 && refired.StartGadget, "powered start commands");
Near(refired.ExtraAccelerationY, first.ExtraAccelerationY, "start invocation remains ballistic");
});
Test("hold is strictly greater than .4 seconds", () =>
{
var state = new JetpackBurstState(1);
state = JetpackBurst.Step(state, Input(dt: .2f)).State;
state = JetpackBurst.Step(state, Input(dt: .2f)).State;
Check(state.JumpState == 1 && state.EffectRemaining == 0, "exactly .4 does not start");
var started = JetpackBurst.Step(state, Input(dt: .001f));
Check(started.StartGadget && started.State.EffectRemaining == 8, "more than .4 starts");
});
Test("disabled long hold stays ballistic and can jump on landing", () =>
{
var denied = JetpackBurst.Step(new(1, .4f), Input(inventory: 0));
Check(denied.State.JumpState == 3 && denied.Pose == JetpackPose.None
&& denied.VelocityYOverride is null && denied.State.EffectRemaining == 0, "disabled transition only enters3");
var expired = JetpackBurst.Step(denied.State, Input(extra: -271));
Check(expired.State.JumpState == 0 && expired.Pose == JetpackPose.Fall
&& expired.ExtraAccelerationY == -271 && expired.StopGadget, "expired guard preserves external acceleration");
var landed = JetpackBurst.Step(expired.State, Input(ground: true, inventory: 0));
Check(landed.ImpulseY == 550 && landed.State.JumpState == 1, "held unavailable gadget repeats ordinary jump");
});
Test("all blocked levels and gadget modes plus VR04 override", () =>
{
foreach (var level in new[] { "LEV6", "LV4B", "LV6A", "LEV3", "LV3A", "LV3B", "LV3C", "LV3D" })
Check(!JetpackBurst.CanStart(level, -1, 1, 100), $"level {level}");
foreach (var mode in new[] { 2, 6, 7 }) Check(!JetpackBurst.CanStart("LV1B", mode, 1, 100), $"mode {mode}");
Check(!JetpackBurst.CanStart("LV1B", -1, 1, 0), "zero energy");
Check(!JetpackBurst.CanStart("LV1B", -1, 4, 100), "inventory state4");
Check(JetpackBurst.CanStart("VR04", 7, 0, -1), "VR04 bypasses every availability gate");
Check(JetpackBurst.CanStart("LV1B", -1, 2, 100), "inventory state2 is accepted");
});
Test("powered distance and vertical-speed thresholds", () =>
{
var state = new JetpackBurstState(3, .5f, 8);
Near(JetpackBurst.Step(state, Input(vy: -1)).ExtraAccelerationY - 800, 80, "exact -1 uses near hover");
Near(JetpackBurst.Step(state, Input(vy: -1.001f)).ExtraAccelerationY - 800, 240, "descending boost");
Near(JetpackBurst.Step(state, Input(distance: 499.999f)).ExtraAccelerationY - 800, 80, "below500");
Near(JetpackBurst.Step(state, Input(distance: 500)).ExtraAccelerationY - 800, -80, "exact500");
Near(JetpackBurst.Step(state, Input(distance: 800, vy: -40)).ExtraAccelerationY - 800, -80, "far distance wins");
});
Test("airborne release stops without radius reset and preserves transition acceleration", () =>
{
var stopped = JetpackBurst.Step(new(3, .5f, 7), Input(held: false));
Check(stopped.State.JumpState == 4 && stopped.State.EffectRemaining == 0
&& stopped.Pose == JetpackPose.Fall && stopped.RadiusOverride is null && stopped.StopGadget,
"air release stop commands");
Near(stopped.ExtraAccelerationY, 880, "release invocation still powered");
var reset = JetpackBurst.Step(stopped.State, Input(held: false, extra: stopped.ExtraAccelerationY));
Check(reset.State.JumpState == 0, "expired state4 resets");
Near(reset.ExtraAccelerationY, 880, "expired guard preserves last powered acceleration");
var ordinary = JetpackBurst.Step(reset.State, Input(held: false, extra: reset.ExtraAccelerationY));
Near(ordinary.ExtraAccelerationY, -264, "next state0 invocation becomes ballistic");
});
Test("held landing stops effect and restores radius60", () =>
{
var stopped = JetpackBurst.Step(new(3, .5f, 7), Input(ground: true));
Check(stopped.State.JumpState == 4 && stopped.State.EffectRemaining == 0
&& stopped.RadiusOverride == 60 && stopped.MovementModeOverride == 1, "held landing commands");
var releasedGround = JetpackBurst.Step(new(3, .5f, 7), Input(ground: true, held: false, extra: 800));
Check(releasedGround.State.JumpState == 0 && releasedGround.State.EffectRemaining == 7
&& releasedGround.RadiusOverride is null && releasedGround.MovementModeOverride == 0,
"outer grounded release precedes air handler");
Near(releasedGround.ExtraAccelerationY, 800, "ground apply owns acceleration");
});
Test("effect subtracts before visibility and energy drain", () =>
{
var effect = JetpackBurst.StepEffect(new(3, 0, .1f), false, .1f, 90, "LV1B");
Check(effect.State.EffectRemaining == 0 && !effect.Visible && effect.Energy == 90,
"exact expiry does not drain");
effect = JetpackBurst.StepEffect(new(3, 0, .1f), false, .2f, 90, "LV1B");
Near(effect.State.EffectRemaining, -.1f, "negative timer is retained");
Check(!effect.Visible && effect.Energy == 90, "overshoot does not drain partial interval");
effect = JetpackBurst.StepEffect(new(3, 0, 8), false, .2f, 90, "LV1B");
Check(effect.Visible, "positive post-subtraction timer shows effect");
Near(effect.State.EffectRemaining, 7.8f, "active remaining");
Near(effect.Energy, 89.9f, ".5 energy per second");
});
Test("grounded effect resets then stores negative dt", () =>
{
var effect = JetpackBurst.StepEffect(new(3, 0, 8), true, .2f, 90, "LV1B");
Near(effect.State.EffectRemaining, -.2f, "grounded timer");
Check(!effect.Visible && effect.Energy == 90, "grounded effect no drain");
effect = JetpackBurst.StepEffect(effect.State, true, .3f, effect.Energy, "LV1B");
Near(effect.State.EffectRemaining, -.3f, "grounded reset happens each invocation");
});
Test("energy clamps and VR01 through VR08 preserve energy", () =>
{
Near(JetpackBurst.AdjustEnergy(.1f, -1, "LV1B"), 0, "lower clamp");
Near(JetpackBurst.AdjustEnergy(99, 5, "LV1B"), 100, "upper clamp");
for (var i = 1; i <= 8; i++)
{
var effect = JetpackBurst.StepEffect(new(3, 0, 8), false, .2f, 90, $"VR0{i}");
Check(effect.Visible && effect.Energy == 90, $"VR0{i} timer runs but energy is immune");
}
Near(JetpackBurst.AdjustEnergy(50, -2, "VR09"), 48, "VR09 outside numeric range");
Near(JetpackBurst.AdjustEnergy(50, -2, "VR00"), 48, "VR00 outside numeric range");
});
Test("energy depletion does not cancel active burn", () =>
{
var effect = JetpackBurst.StepEffect(new(3, .5f, 8), false, 1, .1f, "LV1B");
Check(effect.Energy == 0 && effect.Visible && effect.State.EffectRemaining == 7, "depletion leaves timer active");
var control = JetpackBurst.Step(effect.State, Input(energy: effect.Energy));
Check(control.State.JumpState == 3 && !control.StopGadget, "availability is checked only on start");
Near(control.ExtraAccelerationY, 880, "burn continues at zero energy");
});
Test("explicit phase ordering exposes first-tick timer difference", () =>
{
var initial = new JetpackBurstState(2);
var before = JetpackBurst.StepEffect(initial, false, .1f, 100, "LV1B");
var effectFirst = JetpackBurst.Step(before.State, Input(energy: before.Energy));
var controlFirst = JetpackBurst.Step(initial, Input());
var after = JetpackBurst.StepEffect(controlFirst.State, false, .1f, 100, "LV1B");
Check(effectFirst.State.EffectRemaining == 8 && before.Energy == 100, "effect-first start");
Near(after.State.EffectRemaining, 7.9f, "controller-first start");
Near(after.Energy, 99.95f, "controller-first drain");
});
Test("null effect bypasses expiry and does not assign radius or timer", () =>
{
var start = JetpackBurst.Step(new(2), Input() with { EffectAvailable = false });
Check(start.StartGadget && start.Pose == JetpackPose.Fly && start.VelocityYOverride == 10
&& start.RadiusOverride is null && start.State.EffectRemaining == 0, "null-effect start boundary");
var flying = JetpackBurst.Step(start.State, Input() with { EffectAvailable = false });
Check(flying.State.JumpState == 3, "no expiry guard for null pointer");
Near(flying.ExtraAccelerationY, 880, "null-effect powered branch");
var absentOwner = JetpackBurst.StepEffect(new(3, 0, 8), false, .1f, 50, "LV1B", ownerAvailable: false);
Check(absentOwner.State.EffectRemaining == 8 && absentOwner.Energy == 50, "absent owner leaves fields");
});
Test("bounded inputs reject invalid state, time and nonfinite values", () =>
{
void Throws(Action action)
{
try { action(); }
catch (ArgumentException) { return; }
throw new Exception("invalid input was accepted");
}
Throws(() => JetpackBurst.Step(new(6), Input()));
Throws(() => JetpackBurst.Step(new(), Input(dt: -1)));
Throws(() => JetpackBurst.Step(new(), Input(vy: float.NaN)));
Throws(() => JetpackBurst.StepEffect(new(), false, float.PositiveInfinity, 100, "LV1B"));
});
Console.WriteLine($"Jetpack checks passed: {count}");
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs"/>
<Compile Include="../../src/GamePort/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/ActorPatrol.cs"/>
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs"/>
<Compile Include="../../src/GamePort/Game/SceneDirector.cs"/>
<Compile Include="../../src/GamePort/Game/TaskStates.cs"/>
<Compile Include="../../src/GamePort/Game/TaskActivation.cs"/>
<Compile Include="../../src/GamePort/Game/LabSimulation.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
<Compile Include="../../src/GamePort/Application/PreviewCharacterPlacement.cs"/>
</ItemGroup>
</Project>
+255
View File
@@ -0,0 +1,255 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
{
var inputs = new List<Vector3>();
var rig = Rig([Point("A", new(500, 0, 0), "none")], body: (state, dt) =>
{
inputs.Add(state.Velocity);
return FreeBody(state, dt);
});
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, Vector3.Zero, "First step must consume initial zero velocity");
Near(rig.Patrol.Velocity, new(100, 0, 0), "Next velocity selected after body step");
NearFloat(rig.Actor.Rotation.Y, 0, "First step consumes prior heading");
Check(rig.Actor.Animation == "RUN", "State3 replaces authored walk with Goddard RUN");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "Second step consumes preceding velocity");
NearFloat(rig.Actor.Rotation.Y, -28.8f, "Prior target yaw smoothed by3.2*dt");
Check(inputs.Count == 2 && inputs[0] == Vector3.Zero && inputs[1] == new Vector3(100, 0, 0), "Body integration phase order");
Pass("prior velocity and prior desired-yaw phase, recovered RUN selection");
}
{
var rig = Rig([Point("A", new(50, 0, 0), "B"), Point("B", new(1000, 0, 0), "none")]);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived && rig.Patrol.CurrentWaypoint == "B", "Arrival selects next waypoint once");
Near(rig.Actor.Position, Vector3.Zero, "Arrival must not snap to waypoint");
Near(rig.Patrol.Velocity, new(100, 0, 0), "First arrival retains velocity selected before flag");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "Prior arrival velocity remains for next physical step");
Check(!rig.Patrol.Arrived && rig.Patrol.Velocity == Vector3.Zero && rig.Actor.Animation == "WAG", "Old arrival selects zero/WAG before new distance clears it");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(10, 0, 0), "One-tick pause must remain");
Near(rig.Patrol.Velocity, new(100, 0, 0), "Subsequent update resumes next segment");
Pass("velocity-before-arrival, no snap and the original waypoint-change pause");
}
{
var rig = Rig([Point("A", new(110, 0, 0), "A")], body: HoldBody);
rig.Patrol.Step(.1f);
Check(!rig.Patrol.Arrived, "Initial distance exactly110 must not arrive");
rig.Director.FindActor("A")!.Position = new(109, 0, 0);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived, "Strictly below110 arrives");
rig.Director.FindActor("A")!.Position = new(110, 0, 0);
rig.Patrol.Step(.1f);
Check(rig.Patrol.Arrived, "Exactly110 retains an already-set arrival flag");
rig.Director.FindActor("A")!.Position = new(111, 0, 0);
rig.Patrol.Step(.1f);
Check(!rig.Patrol.Arrived, "Strictly above110 clears arrival");
Pass("strict arrival threshold and equality hysteresis");
}
{
var rig = Rig([Point("A", Vector3.Zero, "B", .25f, "SIT"), Point("B", new(1000, 0, 0), "none")]);
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == 7 && rig.Patrol.WaitRemaining == .25f && rig.Actor.Animation == "SIT", "Wait starts with full authored time after arrival");
rig.Patrol.Step(.125f);
Check(rig.Actor.AIstate == 7 && rig.Patrol.WaitRemaining == .125f, "Positive wait remains active");
rig.Patrol.Step(.125f);
Check(rig.Actor.AIstate == 3 && rig.Patrol.WaitRemaining == 0 && rig.Patrol.CurrentWaypoint == "B" && !rig.Patrol.Arrived,
"Timer reaching exactly zero expires and restores state3");
Near(rig.Actor.Position, Vector3.Zero, "Wait expiry must not consume extra movement");
Near(rig.Patrol.Velocity, Vector3.Zero, "Wait expiry selects waypoint without selecting its velocity yet");
rig.Patrol.Step(.1f);
Check(rig.Patrol.Velocity.Length() > 0 && rig.Actor.Position == Vector3.Zero, "First resumed update still consumes preceding zero velocity");
var overshoot = Rig([Point("A", Vector3.Zero, "B", .125f, "SIT"), Point("B", new(1000, 0, 0), "none")]);
overshoot.Patrol.Step(.5f);
overshoot.Patrol.Step(.5f);
Check(overshoot.Actor.AIstate == 3 && overshoot.Patrol.WaitRemaining == -.375f && overshoot.Actor.Position == Vector3.Zero,
"Wait expiry discards elapsed remainder rather than advancing next segment");
var zeroAtEntry = Rig([Point("A", Vector3.Zero, "none")], state: 7);
zeroAtEntry.Patrol.Step(.1f);
Check(zeroAtEntry.Actor.AIstate == 7, "Original state7 positivity guard retains zero-at-entry timer");
Pass("timed wait, exact-zero expiry, zero-entry guard and discarded remainder");
}
{
foreach (var (next, expectedState) in new[] { ("wAiT", 1), ("sCaN", 6), ("none", 3), ("missing", 3) })
{
var rig = Rig([Point("A", Vector3.Zero, next)], body: HoldBody);
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == expectedState && rig.Patrol.CurrentWaypoint == null, "Unresolved next-name semantics: " + next);
if (expectedState == 3)
{
rig.Patrol.Step(.1f);
Check(rig.Patrol.PreviousWaypoint == "A" && rig.Patrol.Arrived, "Ordinary missing next names restart initial route");
}
}
var realWaitTag = Rig([Point("A", Vector3.Zero, "WAIT"), Point("WAIT", new(1000, 0, 0), "none")]);
realWaitTag.Patrol.Step(.1f);
Check(realWaitTag.Actor.AIstate == 3 && realWaitTag.Patrol.CurrentWaypoint == "WAIT", "Existing actor tag takes precedence over WAIT specialcase");
var timedWaitName = Rig([Point("A", Vector3.Zero, "WAIT", .25f, "SIT")]);
timedWaitName.Patrol.Step(.1f);
timedWaitName.Patrol.Step(.25f);
Check(timedWaitName.Actor.AIstate == 3 && timedWaitName.Patrol.CurrentWaypoint == null, "Timed wait resolution does not interpret WAIT specially");
Pass("WAIT/SCAN lookup precedence, unresolved-none route restart and timed-wait distinction");
}
{
var rig = Rig([Point("A", new(0, 500, 0), "none")], body: (body, _) => body with { Velocity = new(5, -7, 9) }, initial: "missing");
rig.Patrol.Step(.1f);
Check(rig.Actor.AIstate == 1, "Missing initial waypoint enters waiting state1");
Near(rig.Patrol.Velocity, new(0, -7, 0), "Missing initial waypoint preserves Y and clears XZ");
rig.Patrol.Step(.1f);
Near(rig.Patrol.Velocity, Vector3.Zero, "Ordinary state1 clears XYZ after body callback");
var vertical = Rig([Point("A", new(0, 500, 0), "none")]);
vertical.Patrol.Step(.1f);
Near(vertical.Patrol.Velocity, new(0, 100, 0), "Patrol selects fullXYZ velocity rather than retaining body Y");
Pass("missing initial waypoint preserves Y for its transition; ordinary waiting and fullXYZ patrol");
}
{
var rig = Rig([Point("A", new(500, 0, 0), "none")]);
rig.Patrol.Step(.1f);
rig.Patrol.Step(.1f);
var before = rig.Patrol.Velocity;
rig.Actor.Animation = "SIT";
rig.Patrol.SynchronizeAuthoredState();
Check(rig.Patrol.Velocity == before && rig.Patrol.CurrentWaypoint == "A", "Camera-only animation cannot reset body/route");
rig.Actor.Position = new(400, 50, -20);
rig.Actor.Rotation = new(0, 10, 0);
rig.Actor.AIstate = 1;
rig.Actor.Animation = "SIT";
rig.Patrol.SynchronizeAuthoredState();
Check(rig.Patrol.Velocity == Vector3.Zero && rig.Patrol.CurrentWaypoint == null && !rig.Patrol.Arrived,
"Authored teleport resets port motion and route cache");
rig.Patrol.Step(.1f);
Near(rig.Actor.Position, new(400, 50, -20), "Teleport cannot inherit preceding patrol velocity");
NearFloat(rig.Actor.Rotation.Y, 10, "Teleport authored heading retained");
Check(rig.Actor.Animation == "SIT", "Authored state1 SIT retained");
Pass("authored teleport reset and camera-only animation preservation");
}
{
var rig = Rig([Point("A", new(300, 400, 0), "none")], body: HoldBody, magnitude: _ => 1000);
rig.Patrol.Step(.1f);
Near(rig.Patrol.Velocity, new(30, 40, 0), "Injected original magnitude controls normalization");
NearFloat(rig.Patrol.DestinationDistance, 500, "Arrival still uses exact sqrt rather than injected magnitude");
foreach (var dt in new[] { -1f, float.NaN, float.PositiveInfinity, 1.01f })
{
var threw = false;
try { rig.Patrol.Step(dt); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "Invalid dt rejected");
}
rig.Actor.Active = false;
var inactive = rig.Actor.Position;
rig.Patrol.Step(.5f);
Check(rig.Actor.Position == inactive, "Inactive actor must not update");
rig.Actor.Active = true;
rig.Actor.AIstate = 6;
Check(!rig.Patrol.Step(.1f), "Unrecovered scan state reported unsupported");
Pass("injected magnitude remains separate from arrival metric; bounded inactive/unsupported state handling");
}
{
var level = GamLevel.Load(AssetPath.Resolve(original, "gam/level1b.gam"));
var director = new SceneDirector(level, new TaskStates([]), (_, _) => 10);
var actor = director.FindActor("C3DGODDARD")!;
director.Trigger("SITGODDARD", "LABEXP1");
var patrol = new ActorPatrol(actor, director.FindActor, FreeBody);
var sawAuthoredSit = false;
director.ActorChanged += changed =>
{
if (!ReferenceEquals(actor, changed)) return;
sawAuthoredSit |= actor.AIstate == 1 && actor.Animation.Equals("sit", StringComparison.OrdinalIgnoreCase);
patrol.SynchronizeAuthoredState();
};
director.Trigger("GOGODDARD", "GOCARL");
Check(actor.AIstate == 3 && actor.Speed == 260 && actor.Patrol == "GODDARDPAT1", "Original authored patrol input");
var start = actor.Position;
patrol.Step(1 / 60f);
Check(actor.Position == start && actor.Animation == "RUN", "Real route begins after velocity selection; source RUN alias");
var sawSecond = false;
var sawUnresolvedNone = false;
for (var i = 0; i < 800; i++)
{
patrol.Step(1 / 60f);
sawSecond |= patrol.CurrentWaypoint == "GODDARDPAT2";
sawUnresolvedNone |= sawSecond && patrol.CurrentWaypoint == null && actor.AIstate == 3;
Check(float.IsFinite(actor.Position.X + actor.Position.Y + actor.Position.Z), "Finite real route state");
}
Check(sawSecond && sawUnresolvedNone, "Real lab route traverses both points and reaches unresolved-none restart");
director.Trigger("GODDARDDIS", "TELGODDARD");
var destination = director.FindActor("phone2")!.Position;
Check(actor.Position == destination && actor.AIstate == 1 && sawAuthoredSit,
"Original authored patrol interruption must precede the following camera's TALK action");
patrol.Step(1 / 60f);
Check(actor.Position == destination && patrol.Velocity == Vector3.Zero, "Authored phone teleport stops port patrol motion");
Pass("actual lab patrol route and source GODDARDDIS interruption (free-body algorithm test)");
}
{
var carl = Entity("3CAR", "carl", ("AIState", 3), ("PatrolPoint", "A"));
var point = Point("A", new(1000, 0, 0), "WAIT");
var director = new SceneDirector(new("TEST", [carl, point]), new TaskStates([]), (_, _) => 1);
var actor = director.FindActor("carl")!;
Check(actor.Speed == 200, "Carl constructor speed200 is independent of Goddard defaults");
var patrol = new ActorPatrol(actor, director.FindActor, FreeBody);
patrol.Step(.1f);
Check(actor.Animation == "WALK" && actor.Position == Vector3.Zero, "Carl uses WALK with the same prior-velocity phase");
patrol.Step(.1f);
Near(actor.Position, new(20,0,0), "Carl source speed and body phase");
NearFloat(actor.Rotation.Y, -27, "Carl inherited yaw factor3 differs from Goddard3.2");
actor.AIstate = 9;
Check(patrol.Step(.1f), "State9 retains the common base phase without an invented patrol command");
Pass("Carl source WALK/STOP profile, speed200, inherited yaw factor and common state9 phase");
}
Console.WriteLine("All10 actor patrol test groups passed. Free/held body fixtures validate AI order, not original collision fidelity.");
static (SceneDirector Director, DirectorActor Actor, ActorPatrol Patrol) Rig(GamEntity[] points,
Func<PatrolBodyState, float, PatrolBodyState>? body = null, int state = 3, string initial = "A",
Func<Vector3, float>? magnitude = null)
{
var god = Entity("3DOG", "god", ("AIState", state), ("PatrolPoint", initial));
var director = new SceneDirector(new("TEST", new[] { god }.Concat(points).ToArray()), new TaskStates([]), (_, _) => 1);
var actor = director.FindActor("god")!;
actor.Speed = 100;
actor.Animation = "walk";
return (director, actor, new(actor, director.FindActor, body ?? FreeBody, magnitude));
}
static PatrolBodyState FreeBody(PatrolBodyState state, float dt) => state with { Position = state.Position + state.Velocity * dt };
static PatrolBodyState HoldBody(PatrolBodyState state, float dt) => state;
static GamEntity Point(string tag, Vector3 position, string next, float wait = 0, string waitAnimation = "none") => Entity("3PAT", tag,
("PositionX", position.X), ("PositionY", position.Y), ("PositionZ", position.Z), ("NextPatrolPoint", next), ("WaitTime", wait), ("WaitAnim", waitAnimation));
static GamEntity Entity(string kind, string tag, params (string Name, object Value)[] values)
{
var properties = new Dictionary<string, GamProperty>(StringComparer.Ordinal);
foreach (var (name, value) in new[] { ("ObjectTag", (object)tag) }.Concat(values))
{
uint type;
byte[] raw;
switch (value)
{
case string s: type = 1; raw = Encoding.Latin1.GetBytes(s); break;
case int i: type = 6; raw = new byte[4]; BinaryPrimitives.WriteInt32BigEndian(raw, i); break;
case float f: type = 3; raw = new byte[4]; BinaryPrimitives.WriteInt32BigEndian(raw, BitConverter.SingleToInt32Bits(f)); break;
default: throw new ArgumentException("Unsupported test property");
}
properties.Add(name, new(name, type, raw));
}
return new(kind, 0, properties, new byte[4]);
}
static void Near(Vector3 actual, Vector3 expected, string message) => Check(Vector3.Distance(actual, expected) < .001f, message + $": {actual} != {expected}");
static void NearFloat(float actual, float expected, string message) => Check(MathF.Abs(actual - expected) < .001f, message + $": {actual} != {expected}");
static void Check(bool value, string message) { if (!value) throw new InvalidOperationException(message); }
static void Pass(string message) => Console.WriteLine("PASS " + message);
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Game/OriginalBodySupport.cs" Link="OriginalBodySupport.cs" />
</ItemGroup>
</Project>
+168
View File
@@ -0,0 +1,168 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Game;
var count = 0;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
void Near(float actual, float expected, float tolerance, string message) =>
Check(MathF.Abs(actual - expected) <= tolerance, $"{message}: {actual} != {expected}");
void Test(string name, Action action) { action(); count++; Console.WriteLine($"PASS {name}"); }
SupportTriangle Ground(float height = 0, int id = 1) =>
new(new(-10000, height, -10000), new(10000, height, -10000), new(0, height, 10000), 1, id);
SupportHit? Query(Vector3 start, Vector3 end, bool sides) => OriginalBodySupport.Trace([Ground()], start, end, sides);
SupportBody Body(float y = 20) => new(new(0, y, 0), new(0, y, 0),
new(80, -16, 20), new(2, -800, 3), OriginalBodySupport.JimmyRadius, OriginalBodySupport.JimmyFactor);
Test("quantized magnitude axes, signs, permutation and scale", () => {
Near(OriginalBodySupport.QuickMagnitude(new(10, 0, 0)), 10, 0, "axis");
Near(OriginalBodySupport.QuickMagnitude(Vector3.Zero), 0, 0, "zero");
var magnitude = OriginalBodySupport.QuickMagnitude(new(3, 4, 0));
Near(magnitude, 5, .002f, "3-4-5 quantization");
Near(OriginalBodySupport.QuickMagnitude(new(-4, 0, -3)), magnitude, 0, "sign/permutation");
Near(OriginalBodySupport.QuickMagnitude(new(30, 40, 0)), magnitude * 10, .00001f, "scale");
var random = new Random(8414);
for (var i = 0; i < 1000; i++) {
var v = new Vector3(random.Next(-1000, 1001), random.Next(-1000, 1001), random.Next(-1000, 1001));
Near(OriginalBodySupport.QuickMagnitude(v) / v.Length(), 1, .001f, "lookup bound");
}
});
Test("isolated original DLL magnitude float-bit references", () => {
// Copied OMT2.dll under isolated Wine32, collision_mode2_probe.c,2026-10-24.
foreach (var (vector, expected) in new (Vector3, uint)[] {
(Vector3.Zero, 0x00000000), (new(10, 0, 0), 0x41200000),
(new(3, 4, 0), 0x40a0001e), (new(-4, 0, -3), 0x40a0001e),
(new(1, 1, 1), 0x3fddb16e), (new(500, 100, 300), 0x4413eb31),
(new(.25f, .125f, .75f), 0x3f4cec46), (new(1.2345f, 678.125f, -90.75f), 0x442b0b21)
}) {
var bits = BitConverter.SingleToUInt32Bits(OriginalBodySupport.QuickMagnitude(vector));
Check(bits == expected, $"original magnitude bits for{vector}: {bits:x8} != {expected:x8}");
}
});
Test("source winding and two-sided override", () => {
var hit = Query(new(0, 20, 0), new(0, -20, 0), false);
Check(hit.HasValue, "source floor winding rejected");
Near(hit!.Value.Position.Y, 0, .00001f, "floor intersection");
Check(Query(new(0, -20, 0), new(0, 20, 0), false) == null, "backface accepted");
Check(Query(new(0, -20, 0), new(0, 20, 0), true).HasValue, "two-sided ray rejected");
});
Test("strict segment endpoint and zero-length ray", () => {
Check(Query(new(0, 20, 0), Vector3.Zero, false) == null, "endpoint must be excluded");
Check(Query(Vector3.Zero, new(0, -20, 0), false).HasValue, "beginning must be included");
Check(Query(Vector3.Zero, Vector3.Zero, false) == null, "zero ray hit");
Check(Query(new(50000, 20, 0), new(50000, -20, 0), false) == null, "outside triangle hit");
});
Test("nearest support retains first equal-distance source identity", () => {
var hit = OriginalBodySupport.Trace([Ground(0, 1), Ground(10, 2), Ground(10, 3)],
new(0, 20, 0), new(0, -20, 0));
Check(hit?.PolygonId == 2, "nearest/tie source identity changed");
});
Test("support root correction and horizontal state preservation", () => {
var result = OriginalBodySupport.Resolve(Body(), false, Query);
Check(result.Supported && result.Landed, "support/landing missing");
Near(result.Body.Position.Y, 75.9f, .00001f, "recovered root clearance");
Check(result.Body.Velocity == new Vector3(80, 0, 20), "horizontal velocity changed");
Check(result.Body.Acceleration == new Vector3(2, 0, 3), "horizontal acceleration changed");
Check(result.SupportAnchor == new Vector3(0, result.Body.Position.Y, 0), "support anchor");
Check(!OriginalBodySupport.Resolve(Body(), true, Query).Landed, "repeated grounded landing");
});
Test("prevent-lowering flag compares root height independently of velocity", () => {
var body = Body(80);
var guarded = OriginalBodySupport.Resolve(body, false, Query);
Check(!guarded.Supported && guarded.Body == body, "falling high root snapped down");
body = body with { Velocity = new(0, 550, 0) };
Check(!OriginalBodySupport.Resolve(body, false, Query).Supported, "ascending root grounded");
var unguarded = OriginalBodySupport.Resolve(body with { PreventLowering = false }, false, Query);
Check(unguarded.Supported, "disabled guard did not lower root");
Near(unguarded.Body.Position.Y, 75.9f, .00001f, "unguarded offset");
});
Test("factor .1 boundary and distinct query/final offsets", () => {
foreach (var (factor, clearance) in new[] { (.099f, 100f), (.1f, 10f), (.3f, 30f), (1f, 100f) }) {
var calls = 0;
Vector3 secondStart = default, secondEnd = default;
SupportHit? Capture(Vector3 start, Vector3 end, bool sides) {
Check(!sides, "support requested two-sided");
if (++calls == 1) return null;
secondStart = start; secondEnd = end;
return new(Vector3.Zero, 4, 8, start.Y);
}
var result = OriginalBodySupport.Resolve(Body(0) with { Radius = 100, Factor = factor }, false, Capture);
Check(calls == 2 && result.Supported, "support query count");
Near(secondStart.Y, clearance, .00001f, "query clearance");
Near(secondEnd.Y, -200, 0, "query lower endpoint");
Near(result.Body.Position.Y, 100 * factor, .00001f, "final offset always product");
}
});
Test("crossed geometry raises support query by remaining motion", () => {
var body = Body(40) with { Position = new(20, 40, 0), PreviousPosition = new(0, 50, 0) };
var calls = 0;
var crossing = new Vector3(10, 45, 0);
var expectedTop = 50 + OriginalBodySupport.QuickMagnitude(body.Position - body.PreviousPosition)
- OriginalBodySupport.QuickMagnitude(crossing - body.PreviousPosition) + body.Radius * body.Factor;
SupportHit? Capture(Vector3 start, Vector3 end, bool sides) {
if (++calls == 1) {
Check(start == body.PreviousPosition && end == body.Position, "motion segment ordering");
return new(crossing, 1, 1, 0);
}
Near(start.Y, expectedTop, .0001f, "obstruction lift");
return null;
}
Check(!OriginalBodySupport.Resolve(body, false, Capture).Supported && calls == 2, "missing floor fabricated support");
});
Test("disabled geometry does not query or mutate state", () => {
var body = Body();
SupportHit? Fail(Vector3 start, Vector3 end, bool sides) => throw new Exception("disabled query invoked");
var result = OriginalBodySupport.Resolve(body, true, Fail, false);
Check(!result.Supported && !result.Landed && result.Body == body, "disabled body mutation");
});
Test("invalid input rejected", () => {
foreach (var body in new[] { Body() with { Radius = 0 }, Body() with { Factor = float.NaN },
Body() with { Position = new(float.PositiveInfinity, 0, 0) } }) {
var threw = false;
try { OriginalBodySupport.Resolve(body, false, Query); } catch (ArgumentOutOfRangeException) { threw = true; }
Check(threw, "invalid body accepted");
}
});
Test("flat-floor repeated gravity and airborne jump", () => {
var body = Body(75.9f) with { Velocity = Vector3.Zero, Acceleration = Vector3.Zero };
var wasGrounded = true;
for (var i = 0; i < 600; i++) {
var velocity = body.Velocity + new Vector3(0, -800f / 60, 0);
body = body with { PreviousPosition = body.Position, Position = body.Position + velocity / 60, Velocity = velocity };
var result = OriginalBodySupport.Resolve(body, wasGrounded, Query);
Check(result.Supported && !result.Landed, "gravity support/landing stability");
body = result.Body; wasGrounded = result.Supported;
Near(body.Position.Y, 75.9f, .00001f, "root drift");
}
body = body with { PreviousPosition = body.Position, Position = body.Position + new Vector3(0, 550f / 60, 0), Velocity = new(0, 550, 0) };
Check(!OriginalBodySupport.Resolve(body, true, Query).Supported, "jump was grounded");
});
Test("original lab triangles retain invisible geometry and recover spawn support", () => {
var path = Path.GetFullPath("artifacts/extracted/level1b/scene.json");
using var document = JsonDocument.Parse(File.ReadAllText(path));
var root = document.RootElement;
var vertices = root.GetProperty("vertices").EnumerateArray().Select(v => new Vector3(v[0].GetSingle(), v[1].GetSingle(), v[2].GetSingle())).ToArray();
var indices = root.GetProperty("indices").EnumerateArray().Select(v => v.GetInt32()).ToArray();
var triangles = Enumerable.Range(0, indices.Length / 3).Select(i => new SupportTriangle(
vertices[indices[3 * i]], vertices[indices[3 * i + 1]], vertices[indices[3 * i + 2]], 0, i)).ToArray();
Check(triangles.Length == 2869, "source geometry count");
var position = new Vector3(5071.93310546875f, 26.661895751953125f, 824.1039428710938f);
SupportHit? Lab(Vector3 start, Vector3 end, bool sides) => OriginalBodySupport.Trace(triangles, start, end, sides);
var result = OriginalBodySupport.Resolve(Body() with { Position = position, PreviousPosition = position }, false, Lab);
Check(result.Supported, "actual lab spawn has no support");
Near(result.Hit!.Value.Position.Y, .5486332f, .001f, "actual floor hit");
Near(result.Body.Position.Y, 76.448635f, .001f, "PostLoad root support prediction");
});
Console.WriteLine($"{count} original support groups passed; full original body collision/runtime fidelity remain unverified.");
+84
View File
@@ -0,0 +1,84 @@
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent / 'Original'
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from entities import prepare_entities, resolve_asset, resource_pairs
from omt import FormatError
class EntityPreparation(unittest.TestCase):
def test_explicit_resource_pairs_preserve_numbered_audio_and_ignore_defaults(self):
pairs = list(resource_pairs({'SpriteDatabase': 'sprites.omt', 'SpriteIndex': 135,
'SoundDatabase': 'voicepractice.omt', 'SoundIndex0': 24,
'SoundIndex1': -1, 'SoundIndex2': 22, 'MusicDatabase': 'none', 'MusicIndex': 0}))
self.assertEqual(pairs, [('SpriteIndex', 'sprites.omt', 'Canv', 135),
('SoundIndex0', 'voicepractice.omt', 'Wave', 24),
('SoundIndex2', 'voicepractice.omt', 'Wave', 22)])
self.assertEqual(list(resource_pairs({'SoundIndex': 3})), [])
def test_case_lookup_and_traversal_rejection(self):
self.assertEqual(resolve_asset(ORIGINAL, 'GaM/vr01.GAM').name, 'VR01.gam')
for name in ('../readme.txt', '/gam/VR01.gam', 'gam//VR01.gam', 'gam/./VR01.gam'):
with self.assertRaises(FormatError): resolve_asset(ORIGINAL, name)
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
(root / 'File').touch()
(root / 'FILE').touch()
with self.assertRaises(FormatError): resolve_asset(root, 'file')
def test_vr01_data_and_decoded_source_references(self):
source = ORIGINAL / 'gam/VR01.gam'
before = source.read_bytes()
with tempfile.TemporaryDirectory() as temporary:
output = Path(temporary) / 'prepared'
report = prepare_entities(ORIGINAL, 'vr01.GAM', output, decode=True)
self.assertEqual(report['level'], 'VR01')
self.assertEqual(len(report['entities']), 16)
self.assertEqual(report['counts']['3PIC'], 4)
self.assertEqual(report['sha256'], hashlib.sha256(before).hexdigest())
pickups = [e for e in report['entities'] if e['kind'] == '3PIC']
self.assertEqual([e['properties']['PickupIndex'] for e in pickups], [3001, 3002, 3003, 3004])
self.assertEqual([e['properties']['PointValue'] for e in pickups], [5] * 4)
self.assertEqual(pickups[0]['offset'], 0x1ba7)
self.assertIn('Radius', pickups[0]['propertyEvidence'])
self.assertEqual(report['duplicateTags']['c3dloadlevel'], [4, 9])
intro = next(e for e in report['entities'] if e['tag'] == 'bu')
target = next(r for r in intro['objectReferences'] if r['property'] == 'CameraTarget0')
self.assertEqual(target['candidateOrdinals'], [6])
star = next(r for r in report['resources'] if r['database'] == 'omt/sprites.omt' and r['id'] == 135)
self.assertEqual(star['name'], 'star')
self.assertEqual((output / star['path']).stat().st_size, star['width'] * star['height'] * 4)
self.assertTrue((output / star['png']).read_bytes().startswith(b'\x89PNG'))
voice = next(r for r in report['resources'] if r['database'] == 'omt/voicepractice.omt' and r['id'] == 24)
self.assertGreater(voice['audio']['seconds'], 0)
self.assertEqual((output / voice['path']).read_bytes()[:4], b'RIFF')
self.assertEqual(json.loads((output / 'entities.json').read_text()), report)
self.assertEqual(source.read_bytes(), before)
def test_lab_duplicates_authored_files_and_casefold_links(self):
with tempfile.TemporaryDirectory() as temporary:
report = prepare_entities(ORIGINAL, 'level1b.gam', Path(temporary) / 'prepared')
self.assertEqual(len(report['entities']), 129)
self.assertEqual(report['counts']['3OMT'], 4)
door = next(e for e in report['entities'] if e['tag'] == 'bars')
self.assertEqual({r['source'].lower() for r in door['fileReferences']}, {'ase/bars.ase', 'png/chain.png'})
self.assertTrue(report['duplicateTags']['c3dpickupitem'])
startup = next(e for e in report['entities'] if e['tag'] == 'STARTEXP')
link = next(r for r in startup['objectReferences'] if r['property'] == 'StartTrigger')
labexp = next(e for e in report['entities'] if e['tag'] == 'labexp')
self.assertEqual(link['candidateOrdinals'], [labexp['ordinal']])
self.assertTrue(all('unresolved' not in r for r in report['resources']))
def test_output_cannot_overlap_original_directory(self):
for path in (ORIGINAL, ORIGINAL / 'generated', ORIGINAL.parent):
with self.assertRaises(FormatError): prepare_entities(ORIGINAL, 'VR01.gam', path)
if __name__ == '__main__':
unittest.main()
+194
View File
@@ -0,0 +1,194 @@
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent / 'Original'
sys.path.insert(0, str(ROOT / 'tools' / 'extractors'))
from models import prepare_models, export_omt_model
from omt import Database, FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Local original assets required')
class StaticModelPreparation(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix='neutron-model-tests-')
cls.output = Path(cls.temporary.name)
cls.lab = prepare_models(ORIGINAL, 'level1b.gam', cls.output / 'lab')
cls.vr = prepare_models(ORIGINAL, 'VR01.gam', cls.output / 'vr')
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def test_exact_instance_bindings_preserve_duplicate_tags(self):
self.assertEqual((self.lab['level'], len(self.lab['actors']), len(self.lab['models'])), ('LV1B', 9, 6))
buttons = [a for a in self.lab['actors'] if a['kind'] == '3BUT']
self.assertEqual([a['offset'] for a in buttons], [42261, 42998])
self.assertEqual([a['tag'] for a in buttons], ['C3DBUTTON', 'C3DBUTTON'])
self.assertEqual(buttons[0]['variants'], buttons[1]['variants'])
self.assertTrue(all(a['defaultVariant'] == 'UP' for a in buttons))
self.assertEqual(len([a for a in self.lab['actors'] if a['kind'] == '3OMT']), 4)
self.assertEqual(len([a for a in self.vr['actors'] if a['kind'] == '3PHO']), 2)
self.assertEqual(len(self.vr['models']), 1)
self.assertEqual(self.lab['unresolved'], [])
self.assertEqual(self.vr['unresolved'], [])
def test_phone_is_original_omt_and_keeps_every_material_range(self):
model = next(m for m in self.lab['models'] if m['source'].get('database') == 'phone.omt')
self.assertEqual(model['source']['shapeId'], 0)
self.assertEqual((model['source']['triangles'], model['source']['textures']), (90, 3))
scene = json.loads((self.output / 'lab' / model['path']).read_text())
self.assertEqual({m['id']: m['texture']['id'] for m in scene['materials']}, {0: 1, 1: 0, 2: 2})
self.assertEqual([m['indexCount'] for m in scene['meshes']], [120, 6, 12, 6, 126])
self.assertEqual(sum(m['indexCount'] for m in scene['meshes']), len(scene['indices']))
self.assertEqual(len(model['source']['resources']), 7) # 1 shape + 3 materials + 3 Canv.
self.assertFalse(any(r['type'] in ('0HDR', 'mCTy') for r in model['source']['resources']))
for texture in scene['textures']:
path = self.output / 'lab' / Path(model['path']).parent / texture['path']
self.assertEqual(path.stat().st_size, texture['width'] * texture['height'] * 4)
def test_explicit_ase_and_png_pairings_are_used(self):
models = {m['key']: m for m in self.lab['models']}
bars = next(a for a in self.lab['actors'] if a['tag'] == 'bars')
source = models[bars['variants']['STATIC']]['source']
self.assertEqual((source['ase'].casefold(), source['png'].casefold(), source['triangles']), ('bars.ase', 'chain.png', 54))
button = next(a for a in self.lab['actors'] if a['kind'] == '3BUT')
for variant, filename in (('UP', 'buttonup.ase'), ('DOWN', 'buttondown.ase')):
source = models[button['variants'][variant]]['source']
self.assertEqual((source['ase'].casefold(), source['png'], source['triangles']), (filename, 'switch.png', 16))
def test_prop_models_do_not_include_other_archive_geometry(self):
for model in self.lab['models']:
if model['source'].get('database') != 'objects.omt':
continue
resources = model['source']['resources']
shapes = [r for r in resources if r['type'] == '3DSh']
self.assertEqual(len(shapes), 1)
self.assertIn(shapes[0]['id'], (27, 28))
self.assertEqual(len(resources), 3)
self.assertEqual(len([m for m in self.lab['models'] if m['source'].get('shapeId') == 28]), 1)
def test_original_hashes_and_output_boundary(self):
paths = [ORIGINAL / 'omt' / name for name in ('objects.omt', 'phone.omt')]
before = {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
prepare_models(ORIGINAL, 'Vr01.GAM', self.output / 'again')
self.assertEqual(before, {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in paths})
for output in (ORIGINAL, ORIGINAL / 'models', ORIGINAL.parent):
with self.assertRaises(FormatError):
prepare_models(ORIGINAL, 'VR01.gam', output)
def test_missing_explicit_mapping_is_reported_without_substitution(self):
report = prepare_models(ORIGINAL, 'Level3C.gam', self.output / 'level3c')
missing = next(e for e in report['unresolved'] if e['offset'] == 33909)
self.assertEqual(missing['kind'], '3BUT')
self.assertNotIn(33909, {e['offset'] for e in report['actors']})
def test_selective_export_retains_null_material_geometry(self):
db = Database(ORIGINAL / 'omt' / 'level1b.omt')
# Missing original material18 resolves to a null runtime pointer.
from omt import read_shape
material_ids = {e.id for e in db.entries if e.type == '3DMa'}
entry = next(e for e in db.entries if e.type == '3DSh'
and any(p['material'] is None or p['material']['id'] not in material_ids
for p in read_shape(db.payload(e))['polygons']))
destination = self.output / 'null-original'
report = export_omt_model(db, entry.id, destination)
scene = json.loads((destination / 'scene.json').read_text())
self.assertIn(18, report['nullMaterialIds'])
self.assertTrue(any(m['material'] == 18 for m in scene['meshes']))
self.assertNotIn(18, {m['id'] for m in scene['materials']})
self.assertGreater(len(scene['indices']), 0)
def test_managed_consumer_transform_draw_visibility_and_texture_identity(self):
dotnet = shutil.which('dotnet') or str(ROOT / '.tools' / 'dotnet' / 'dotnet')
if not Path(dotnet).is_file():
self.skipTest('Local .NET10 SDK not provisioned')
harness = self.output / 'managed'
harness.mkdir(exist_ok=True)
source = ROOT / 'src' / 'GamePort'
includes = [*sorted((source / 'Assets').glob('*.cs')), *sorted((source / 'Game').glob('*.cs')),
source / 'Application' / 'StaticSceneVisuals.cs']
project = '<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup><ItemGroup><Compile Include="Program.cs"/>'
project += ''.join('<Compile Include="' + str(p) + '"/>' for p in includes)
project += '</ItemGroup></Project>'
(harness / 'Harness.csproj').write_text(project)
(harness / 'NuGet.Config').write_text('<configuration><packageSources><clear/></packageSources></configuration>')
(harness / 'Program.cs').write_text(MANAGED_CHECKS)
environment = os.environ.copy()
environment.update(DOTNET_CLI_TELEMETRY_OPTOUT='1', DOTNET_CLI_HOME=str(ROOT / '.dotnet-home'),
NUGET_PACKAGES=str(ROOT / '.nuget' / 'packages'))
result = subprocess.run([dotnet, 'run', '--project', str(harness / 'Harness.csproj'), '--',
str(ORIGINAL), str(self.output / 'lab')],
cwd=ROOT, env=environment, text=True, capture_output=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout + '\n' + result.stderr)
self.assertIn('PASS static model runtime', result.stdout)
MANAGED_CHECKS = r'''
using System.Numerics;
using System.Text.Json;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
static void Check(bool condition, string name) { if (!condition) throw new Exception(name); }
static void Near(Vector3 actual, Vector3 expected, string name) => Check(Vector3.Distance(actual, expected) < .002f, name);
var original = args[0]; var prepared = args[1];
var level = GamLevel.Load(AssetPath.Resolve(original, "gam/level1b.gam"));
var save = OriginalSave.Load(AssetPath.Resolve(original, "NewGame.tsk"));
var director = new SceneDirector(level, new TaskStates(save.Tasks), (_,_) => 1);
var seed = new Mesh(new[] { new MeshVertex(new(1,2,3),Vector2.Zero,Vector3.One),
new MeshVertex(new(4,5,6),Vector2.Zero,Vector3.One), new MeshVertex(new(7,8,9),Vector2.Zero,Vector3.One) }, [0,1,2])
{ HasExplicitDraws = true, Draws = [new MeshDraw(0,3,5)], Textures = new() { [5] = PngImage.White } };
var visuals = new StaticSceneVisuals(seed, director, original, prepared);
Check(visuals.ActorCount == 9, "actual lab has nine model actor instances");
Check(visuals.Mesh.Draws.Length == 20, "all nineteen original model draw ranges retained");
Check(visuals.Mesh.Textures.Count == 16, "each model instance/variant has distinct texture identities");
Check(visuals.Mesh.Textures.Keys.Where(i => i != 5).All(i => i >= int.MinValue+20000 && i < int.MinValue+20015), "reserved texture identity range");
Check(visuals.Mesh.Draws.All(d => d.TextureId == -1 || visuals.Mesh.Textures.ContainsKey(d.TextureId)), "all draw textures resolve globally");
Check(visuals.Mesh.Vertices.Take(3).Select(v => v.Position).SequenceEqual(seed.Vertices.Select(v => v.Position)), "existing scene vertices retained");
var phone = director.Actors.Single(a => a.SourceGam?.Offset == 1729);
phone.Position = new(100,200,300); phone.Rotation = Vector3.Zero; phone.Visible = true;
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(prepared,"models.json")));
var firstModel = manifest.RootElement.GetProperty("models")[0].GetProperty("path").GetString()!;
var local = Mesh.LoadSceneJson(Path.Combine(prepared,firstModel)).Vertices[0].Position;
var final = visuals.Mesh with { Vertices = visuals.Mesh.Vertices.Concat(new MeshVertex[3]).ToArray() };
visuals.Update(final);
Near(final.Vertices[3].Position, local + phone.Position, "exact actor root translation, no floor correction");
phone.Rotation = new(0,90,0); visuals.Update(final);
Near(final.Vertices[3].Position, new Vector3(-local.Z,local.Y,local.X) + phone.Position, "recovered yaw convention");
phone.Visible = false; visuals.Update(final);
Check(final.Draws.Skip(1).Take(5).All(d => !d.Visible), "all five phone material draws hide together");
Check(final.Draws[6].Visible, "duplicate phone instance remains visible");
var firstButton = director.Actors.Single(a => a.SourceGam?.Offset == 42261);
var secondButton = director.Actors.Single(a => a.SourceGam?.Offset == 42998);
firstButton.Visible = secondButton.Visible = true; firstButton.Animation = "HIDOWN"; secondButton.Animation = "UP";
visuals.Update(final);
Check(!final.Draws[12].Visible && final.Draws[13].Visible && final.Draws[14].Visible && !final.Draws[15].Visible,
"duplicate button tags choose independent up/down variants by source offset");
var conflict = seed with { Textures = new() { [int.MinValue+20000] = PngImage.White } };
try { _ = new StaticSceneVisuals(conflict,director,original,prepared); throw new Exception("texture conflict accepted"); }
catch (InvalidDataException) { }
// An explicit empty material table must retain geometry without inventing any draw.
var nullRoot = Path.Combine(prepared,"null-runtime"); Directory.CreateDirectory(nullRoot);
File.WriteAllText(Path.Combine(nullRoot,"scene.json"), """
{"vertices":[[0,0,0],[1,0,0],[0,1,0]],"uvs":[[0,0],[0,0],[0,0]],"indices":[0,1,2],"materials":[],"textures":[],"meshes":[{"firstIndex":0,"indexCount":3,"material":-1}]}
""");
File.WriteAllText(Path.Combine(nullRoot,"models.json"), """
{"schema":1,"models":[{"key":"null","path":"scene.json"}],"actors":[{"offset":1729,"kind":"3PHO","defaultVariant":"STATIC","variants":{"STATIC":"null"}}]}
""");
var invisible = new StaticSceneVisuals(seed,director,original,nullRoot);
Check(invisible.Mesh.Indices.Length == 6 && invisible.Mesh.Draws.Length == 1, "null material keeps geometry and skips draw");
Console.WriteLine("PASS static model runtime: transforms, visibility, nineteen ranges, texture IDs, duplicate tags, variants, null materials");
'''
if __name__ == '__main__': unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Original bank identity/RIFF regression checks, including the bars sounds."""
import hashlib
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'tools/extractors'))
from omt import Database, FormatError
from sound_bank import export_sound_bank
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
class SoundBankTests(unittest.TestCase):
def test_exact_original_identities_and_riff_bytes(self):
source = ORIGINAL/'omt/soundeffects.omt'
before = hashlib.sha256(source.read_bytes()).hexdigest()
database = Database(source)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)
manifest = export_sound_bank(ORIGINAL, output)
self.assertEqual(len(manifest['resources']), 251)
entries = {e.id: e for e in database.entries if e.type == 'Wave'}
for item in manifest['resources']:
payload = database.payload(entries[item['id']])
start = payload.index(b'RIFF')
size = struct.unpack_from('<I', payload, start+4)[0]+8
decoded = (output/item['path']).read_bytes()
self.assertEqual(decoded, payload[start:start+size])
self.assertEqual(hashlib.sha256(decoded).hexdigest(), item['sha256'])
by_id = {r['id']: r for r in manifest['resources']}
self.assertEqual(by_id[58]['name'], 'door closing')
self.assertEqual(by_id[59]['name'], 'Door opening loop')
self.assertEqual(by_id[230]['name'], 'winning prize2')
self.assertEqual(json.loads((output/'effects.json').read_text()), manifest)
self.assertEqual(hashlib.sha256(source.read_bytes()).hexdigest(), before)
def test_original_output_boundary_and_executable_bank_reference(self):
with self.assertRaises(FormatError):
export_sound_bank(ORIGINAL, ORIGINAL/'not-created')
exe = (ORIGINAL/'Neutron.exe').read_bytes()
self.assertEqual(exe[0x23642:0x23647], bytes.fromhex('68 8c e0 4e 00'))
self.assertEqual(exe[0xee08c:0xee09d], b'SoundEffects.omt\0')
self.assertEqual(exe[0x589de:0x589e3], bytes.fromhex('e8 5d 4c 02 00'))
self.assertEqual(exe[0x7d3bc:0x7d3c2], bytes.fromhex('56 68 65 76 61 57'))
if __name__ == '__main__':
unittest.main()