Files

514 lines
33 KiB
C#

using System.Buffers.Binary;
using System.Numerics;
using System.Text.Json;
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"));
// Original Carl413F30 owns its complete base+derived task callback. Observers
// must never see a generic-only Carl state or wait for SceneInteractions to fix it.
var orderedTasks = new TaskStates(save.Tasks);
var orderedDirector = new SceneDirector(level, orderedTasks, (_, _) => 1);
var orderedCarl = orderedDirector.FindActor("C3DCARL")!;
var orderedMarker = orderedDirector.FindActor("CARLESC3")!;
var notifiedCarl = false;
var notifiedAfterCarl = false;
orderedDirector.ActorChanged += actor =>
{
if (ReferenceEquals(actor, orderedCarl))
{
Check(orderedTasks.Get("SCENE") == 50 && actor.Active && actor.Visible && actor.AIstate == 6
&& actor.Position == orderedMarker.Position, "Carl callback observer sees final derived state");
notifiedCarl = true;
}
else if (notifiedCarl)
{
Check(orderedCarl.Position == orderedMarker.Position && orderedCarl.AIstate == 6,
"Later actor callbacks observe completed Carl override");
notifiedAfterCarl = true;
}
};
orderedCarl.Position = Vector3.Zero; orderedCarl.AIstate = 0;
orderedTasks.SetExisting("SCENE", 50);
Check(notifiedCarl && notifiedAfterCarl, "Authored registry includes Carl followed by task actors");
foreach (var scene in new[] { -1, 0, 30, 31, 59, 60, 61 })
{
var boundaryTasks = new TaskStates(save.Tasks.Select(t => t.Name == "SCENE" ? t with { State = scene } : t));
var boundaryDirector = new SceneDirector(level, boundaryTasks, (_, _) => 1);
var actor = boundaryDirector.FindActor("C3DCARL")!;
var generic = TaskActivation.Animated(actor.SourceGam!, scene);
Check(actor.Active == (scene is >= 0 and < 60 || scene == 60 && generic != false),
"LV1B Carl derived activation boundaries and generic result at60");
if (scene is > 30 and <= 60)
Check(actor.AIstate == 6 && actor.Position == boundaryDirector.FindActor("CARLESC3")!.Position,
"Carl marker/state override follows base activation at construction");
}
Console.WriteLine("PASS per-actor Carl task callback order, derived observation and LV1B boundaries");
var tasks = new TaskStates(save.Tasks);
var director = new SceneDirector(level,tasks,(_,_)=>.1);
var cues = 0;
var musicPlaying = true;
var musicRestarts = 0;
director.MusicStopped += () => musicPlaying = false;
director.MusicRestarted += () => { musicPlaying = true; musicRestarts++; };
director.Speech += (_,_)=>{ Check(!musicPlaying,"Lab cutscene music must stop before speech and stay stopped between shots"); 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");
Check(musicPlaying && musicRestarts == 1,"DEFAULT must restart selected music after natural intro completion");
director.Trigger("default");
Check(musicRestarts == 1,"DEFAULT with Jimmy already controlled must not restart music");
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;
var skipMusicPlaying=true;
skip.MusicStopped+=()=>skipMusicPlaying=false;
skip.MusicRestarted+=()=>skipMusicPlaying=true;
skip.Speech += (_,_)=>skipCues++;
skip.Begin(level.FindStart()!);
Check(!skipMusicPlaying,"First CAM must stop gameplay music");
skip.Skip();
Check(skip.Controlled && !skip.Blocked && skipCues==1,"Skip must fast-forward voices and return control");
Check(skipMusicPlaying,"Skipping must restore selected gameplay music");
Check(skip.FindActor("C3DGODDARD")!.Position==endGoddard,"Skip must preserve AI/toggle actions");
Console.WriteLine("PASS original intro skip preserves action sequence");
var forced = new SceneDirector(level, new TaskStates(save.Tasks), (_, _) => .1);
var forcedRestarts = 0;
forced.MusicRestarted += () => forcedRestarts++;
forced.Begin(level.FindStart()!);
var forcedTag = forced.CurrentTag;
forced.DebugForceControl = true;
Check(forced.Controlled && forced.ControlledTag == level.Player!.Tag && forced.Playing && forced.CurrentTag == forcedTag,
"Debug force grants Jimmy input without skipping the source camera chain");
forced.Step(.15f);
Check(forced.Controlled && forced.Playing, "Forced control survives subsequent authored camera control assignments");
forced.DebugForceControl = false;
Check(!forced.Controlled && forced.ControlledTag == null && forced.Playing,
"Disabling force exposes current authored control state");
forced.DebugForceControl = true;
for (var i = 0; i < 300 && forced.Playing; i++) forced.Step(.1f);
Check(forced.Controlled && !forced.Playing && forcedRestarts == 1,
"Force does not suppress normal cutscene completion music restart");
forced.Begin(level.FindStart()!);
Check(!forced.DebugForceControl && !forced.Controlled, "Scene reset clears the debug override");
Console.WriteLine("PASS debug forced control persistence, source state restoration, music handoff and reset");
var returnDirector = new SceneDirector(level, new TaskStates(save.Tasks), (_, _) => 10);
var returnCues = 0;
returnDirector.Speech += (_, _) => returnCues++;
var sourceGoddard = returnDirector.FindActor("C3DGODDARD")!.Position;
returnDirector.Begin(level.FindStart()!, activateStartTrigger: false);
Check(returnDirector.Controlled && !returnDirector.Playing && returnCues == 0,
"RETURN suppresses the start trigger rather than replaying/skipping its dialogue");
Check(returnDirector.FindActor("C3DGODDARD")!.Position == sourceGoddard,
"Suppressing LABEXP must not execute its teleport/patrol actions");
returnDirector.Begin(level.FindStart()!);
Check(!returnDirector.Controlled && returnDirector.CurrentTag == "LABEXP1" && returnCues == 1,
"Return suppression does not persist into a later normal start");
Console.WriteLine("PASS RETURN suppresses STRT actions once and preserves normal start behavior");
foreach (var finishBySkip in new[] { false, true })
{
var carlScene = new SceneDirector(level, new TaskStates(save.Tasks), (_, _) => .1);
carlScene.Begin(level.FindStart()!); carlScene.Skip();
Check(carlScene.Controlled, "Carl test starts with normal player control");
carlScene.Trigger("neutron1a");
Check(carlScene.Playing && carlScene.CurrentTag == "neutron1a" && !carlScene.Controlled,
"Carl MCA must lock input despite serialized completion target JIM1");
if (finishBySkip) carlScene.Skip();
else
for (var tick = 0; tick < 100 && carlScene.Playing; tick++)
{
Check(!carlScene.Controlled, "Every active Carl shot keeps player control locked");
carlScene.Step(.1f);
}
Check(!carlScene.Playing && carlScene.Controlled && !carlScene.Blocked,
"Carl sequence restores original JIM1 completion target on finish or skip");
}
var carlBytes = File.ReadAllBytes(AssetPath.Resolve(root, "Neutron.exe"));
Check(carlBytes.AsSpan(0x3159e, 15).SequenceEqual(Convert.FromHexString("8B0D48995000538B11FF9218010000")),
"Source MCA clears game controlled pointer before playback");
Console.WriteLine("PASS end-of-lab Carl cutscene input lock and natural/skip control restoration");
foreach (var kind in new[] { "3CAM", "3MCA", "3AIT" })
{
var jim = Entity("3JIM", "JIM1", ("RotationX", 12f), ("RotationZ", 22f));
var command = Entity(kind, "command", ("PlayerControlled", "NULL"),
("CameraTarget", "JIM1"), ("CameraTarget0", "JIM1"), ("CameraTarget1", "JIM1"),
("SoundIndex", 1), ("SoundIndex0", 1), ("SoundIndex1", 1), ("SoundDatabase", "voice"),
("NextTrigger", "default"));
var scene = new SceneDirector(new("LV1B", [jim, command]), new TaskStates([]), (_, _) => .1);
var body = ControlBody();
var bag = new SceneInventory(new int[19]); bag.SetState(0, 3, 1); bag.SelectGadget(3);
using var binding = new PlayerSceneBinding(scene, body, bag, "JIM1");
for (var tick = 0; tick < 5; tick++) binding.Step(new(true, false, false, false, false));
//Full Euler sync now reflects the ground input's leveling. Seed the authored
//tilt immediately before the command to isolate preparation ownership.
body.ApplyAuthoredTransform(body.ActorRoot,new Vector3(12,body.Yaw,0));
scene.SyncActor("JIM1",body.ActorRoot,body.Rotation);
var callbacks = new List<ScriptPreparation>();
scene.ActorPreparing += (actor, action) =>
{
Check(actor.Tag == "JIM1" && scene.AuthoredControlledTag == "JIM1", "Preparation observes the prior raw owner");
callbacks.Add(action);
};
var stopObserved = false;
scene.ActorChanged += actor =>
{
if (actor.Tag == "JIM1" && actor.Animation == "STOP")
{
Check(body.Velocity == Vector3.Zero && body.Speed == 0, "Body preparation precedes derived STOP notification");
stopObserved = true;
}
};
scene.Trigger("command");
var expected = kind switch
{
"3CAM" => new[] { ScriptPreparation.ReleaseGadget, ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation },
"3MCA" => new[] { ScriptPreparation.StopMotion, ScriptPreparation.FlattenOrientation, ScriptPreparation.ReleaseGadget },
_ => new[] { ScriptPreparation.StopMotion }
};
Check(stopObserved && callbacks.SequenceEqual(expected) && body.Speed == 0 && body.Velocity == Vector3.Zero,
"CAM/MCA/AI retain their own ordered preparation boundaries");
Check(bag.SelectedGadget == (kind == "3AIT" ? 3 : -1), "AI control loss does not imply camera gadget cleanup");
Check(scene.FindActor("JIM1")!.Rotation.X == (kind == "3AIT" ? 12 : 0), "Only camera preparation flattens pitch/roll");
if (kind == "3AIT") continue; // Its DEFAULT next trigger has already restored control.
var controllers = body.ControllerSteps;
binding.Step(new(true, false, true, false, true));
Check(body.ControllerSteps == controllers && body.Jumps == 0 && body.PhysicsSteps > controllers,
"Input lock leaves body/effect callbacks running");
scene.DebugForceControl = true;
binding.Step(new(true, false, false, false, false));
var speed = body.Speed;
scene.Step(.11f);
Check(callbacks.SequenceEqual(expected), "Later MCA shots/CAM completion do not replay initial preparations");
Check(body.Speed == speed && scene.Controlled, "Force control does not become the raw preparation owner");
scene.DebugForceControl = false;
scene.Trigger("default");
var jumps = body.Jumps;
binding.Step(new(false, false, false, false, true));
Check(body.Jumps == jumps + 1, "DEFAULT restores held jump without an invented fresh-key boundary");
}
Console.WriteLine("PASS ordered CAM/MCA/AI preparations, body continuation, raw-owner force override and held-input restoration");
foreach (var retained in new[] { false, true })
foreach (var dirty in new[] { false, true })
foreach (var kind in new[] { "3CAM", "3MCA" })
{
var scene = kind == "3MCA"
? new SceneDirector(level, new TaskStates(save.Tasks), (_, _) => 10)
: new SceneDirector(new("LV1B", [Entity("3JIM", "JIM1"),
Entity("3CAM", "camera", ("PlayerControlled", "NULL"), ("CameraTarget", "JIM1"),
("SoundDatabase", "voice"), ("SoundIndex", 1))]), new TaskStates([]), (_, _) => 10);
var body = ControlBody();
body.InputAfterPlayerUpdate = retained;
using var binding = new PlayerSceneBinding(scene, body, new SceneInventory(new int[19]), "JIM1");
if (dirty)
{
for (var tick = 0; tick < 8; tick++) binding.Step(new(true, false, true, false, true));
Check(!body.Grounded && body.FacingDirty && body.FacingTarget.X < 0 && body.FacingTarget.Z < 0,
"Cutscene regression enters with a real banked jump and pending airborne destination");
}
// A direct authored yaw must replace the old destination Y at preparation too.
body.ApplyAuthoredTransform(body.ActorRoot, new Vector3(345, body.Yaw + 37, 12));
scene.SyncActor("JIM1", body.ActorRoot, body.Rotation);
var yaw = body.Yaw;
var controllers = body.ControllerSteps;
var physics = body.PhysicsSteps;
var impulse = body.PendingImpulse;
scene.Trigger(kind == "3MCA" ? "neutron1a" : "camera");
Near(body.Rotation, new(0, yaw, 0), "Camera preparation levels current Euler immediately");
Near(body.FacingTarget, new(0, yaw, 0), "Camera preparation also replaces every pending destination axis");
Check(body.FacingDirty == dirty && body.PendingImpulse == impulse && !scene.Controlled,
"Direct destination copy preserves facing dirty, queued impulse and source control lock");
for (var tick = 0; tick < 120; tick++)
{
binding.Step(new(true, false, true, false, true));
Near(body.Rotation, new(0, yaw, 0), "Uncontrolled facing cannot restore the old jump tilt or yaw");
Near(scene.FindActor("JIM1")!.Rotation, body.Rotation, "Director and rendered player share the prepared rotation");
}
Check(!body.FacingDirty && body.ControllerSteps == controllers && body.PhysicsSteps == physics + 120,
"Facing clears equal targets while locked body updates continue without player input");
}
Console.WriteLine("PASS CAM and original Carl MCA banked-jump preparation, destination yaw/dirty ownership and sustained control lock");
foreach (var left in new[] { false, true })
foreach (var skipPlayback in new[] { false, true })
{
var scene = new SceneDirector(level, new TaskStates(save.Tasks), (_, _) => 2);
var body = ControlBody();
//Normal TSK story entry retains the background Jimmy before the new game.
//The application's control-phase smoke separately checks this entry wiring.
body.InputAfterPlayerUpdate = true;
using var binding = new PlayerSceneBinding(scene, body, new SceneInventory(new int[19]), "JIM1");
for (var carlCycle = 0; carlCycle < 2; carlCycle++)
{
for (var tick = 0; tick < 8; tick++) binding.Step(new(true, false, left, !left, true));
Check(!body.Grounded && body.MovementMode == 1 && body.TurnRate != 0,
"Neutral return starts with a banked jump on either turn direction");
scene.SyncActor("JIM1", body.ActorRoot, body.Rotation);
scene.Trigger("neutron1a");
for (var tick = 0; tick < 180; tick++)
{
binding.Step(default);
scene.Step(FixedStepClock.Step);
}
Check(body.Grounded && !scene.Controlled && body.MovementMode == 1 && body.TurnRate != 0,
"Uncontrolled landing retains mode and stored turn before Carl finishes");
var yaw = body.Yaw;
if (skipPlayback) scene.Skip();
else
{
for (var tick = 0; scene.Playing && tick < 1200; tick++)
{
binding.Step(default);
scene.Step(FixedStepClock.Step);
}
}
Check(scene.Controlled && !scene.Playing, "Carl completes naturally or through skip");
for (var tick = 0; tick < 300; tick++)
{
binding.Step(default);
Near(body.Rotation, new(0, yaw, 0), "First and sustained neutral return stay upright with heading preserved");
Near(body.FacingTarget, new(0, yaw, 0), "Neutral return never republishes airborne bank");
Check(body.MovementMode == 0 && body.TurnRate == 0,
"Original grounded controller clears movement state before resumed input");
}
}
}
Console.WriteLine("PASS eight Carl neutral-return trajectories: Left/Right, natural/skip, repeated scenes and first resumed input");
using (var reference = JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "original-camera-rotation-reference.json"))))
{
var cases = 0;
foreach (var observation in reference.RootElement.GetProperty("cases").EnumerateArray())
{
var initialOrientation = observation.GetProperty("before");
var dirty = initialOrientation.GetProperty("dirty").GetInt32() != 0;
var body = ControlBody();
if (dirty) body.Step(new(true, false, true, false, false));
//Camera preparation ignores the old target; actual banked-target
//ownership and the full scene callback chain are exercised above.
body.ApplyAuthoredTransform(body.ActorRoot, Euler(initialOrientation, "current"));
body.FlattenOrientation();
Compare("prepared");
body.Step(default, controlled: false);
Compare("after_facing");
for (var tick = 1; tick < 30; tick++) body.Step(default, controlled: false);
Compare("after_30");
cases++;
void Compare(string stage)
{
var expected = observation.GetProperty(stage);
Near(body.Rotation, Euler(expected, "current"), "Copied-original camera current XYZ: " + stage);
Near(body.FacingTarget, Euler(expected, "target"), "Copied-original camera destination XYZ: " + stage);
Check(body.FacingDirty == (expected.GetProperty("dirty").GetInt32() != 0), "Copied-original camera dirty: " + stage);
}
}
Check(cases == 20, "Complete original CAM/MCA camera rotation reference");
}
Console.WriteLine("PASS 20 copied-original camera preparation/facing XYZ and dirty outputs, including wrapped and negative Euler");
{
var jim = Entity("3JIM", "JIM1");
var command = Entity("3AIT", "move", ("PlayerControlled", "NULL"), ("AITarget", "JIM1"),
("AINewPos", "marker"), ("AINewRotY", 75f));
var marker = Entity("DUMY", "marker", ("PositionX", 200f), ("PositionY", 500f), ("PositionZ", 300f));
var scene = new SceneDirector(new("LV1B", [jim, command, marker]), new TaskStates([]), (_, _) => 1);
var body = ControlBody();
using var binding = new PlayerSceneBinding(scene, body, new SceneInventory(new int[19]), "JIM1");
scene.Trigger("move");
Near(body.ActorRoot, marker.Position, "Authored AI position is applied to the actual player body");
Check(body.Yaw == 75 && !scene.Controlled, "Authored AI yaw follows the logical setter during control loss");
binding.Step(new(true, false, true, false, true));
Check(body.ActorRoot.Y < marker.Position.Y && body.ActorRoot.X == marker.Position.X && body.ControllerSteps == 0,
"Body settles at the scripted location without accepting movement input");
Near(scene.FindActor("JIM1")!.Position, body.ActorRoot, "Physics publishes the new logical player root");
}
Console.WriteLine("PASS authored player teleport/yaw survives uncontrolled body synchronization");
{
var jim = Entity("3JIM", "JIM1");
var empty = Entity("3MCA", "empty", ("CameraTarget0", "none"), ("PlayerControlled", "NULL"), ("NextTrigger", "default"));
var missing = Entity("3CAM", "missing", ("CameraTarget", "absent"), ("SoundIndex", 1), ("PlayerControlled", "NULL"));
var scene = new SceneDirector(new("LV1B", [jim, empty, missing]), new TaskStates([]), (_, _) => 1);
var callbacks = new List<ScriptPreparation>(); scene.ActorPreparing += (_, action) => callbacks.Add(action);
scene.Trigger("empty");
Check(callbacks.Count == 0 && scene.AuthoredControlledTag == "JIM1" && !scene.Playing,
"Initial MCA none target returns without preparation or invoking completion ownership");
scene.Trigger("missing");
Check(callbacks.Count == 3 && scene.AuthoredControlledTag == null && scene.Blocked,
"CAM preparation precedes target-lookup failure");
}
Console.WriteLine("PASS first-MCA none return and CAM failure preparation boundaries");
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!.Returning && returned.LevelFile==save.ReturnLevel && returned.StartPoint==save.ReturnStart,"RETURN uses stored destination, restore flag and contact-enter gating");
Console.WriteLine("PASS original VR01 star/trophy score, strict contact entry, acquired-state save/reload and RETURN request");
static LabSimulation ControlBody()
{
var points = new[] { new Vector3(-10000, 0, -10000), new Vector3(-10000, 0, 10000),
new Vector3(10000, 0, 10000), new Vector3(10000, 0, -10000) };
var floor = new Mesh(points.Select(p => new MeshVertex(p, Vector2.Zero, Vector3.One)).ToArray(), [0, 1, 2, 0, 2, 3]);
var standing = new Mesh([new(new(-20, -20, -20), Vector2.Zero, Vector3.One), new(new(20, 80, 20), Vector2.Zero, Vector3.One)], []);
return new(new SceneCollision(floor), standing, new(0, 25, 0), 0);
}
static Vector3 Euler(JsonElement state, string property)
{
var values = state.GetProperty(property).EnumerateArray().Select(v => v.GetSingle()).ToArray();
return new(values[0], values[1], values[2]);
}
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}");