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

@@ -0,0 +1,31 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Original C3DJetpackFire DEFAULT shape/texture, following the owner root/Euler.</summary>
public sealed class JetpackVisuals
{
private readonly MorphAnimation clip;
private readonly int offset;
private readonly MeshDraw draw;
public Mesh Mesh { get; }
public JetpackVisuals(Mesh combined, string preparedRoot)
{
clip = new MorphAnimation(Path.Combine(preparedRoot, "actors/jetpack/fire/animation.json"));
offset = combined.Vertices.Length;
Mesh = clip.AppendTo(combined, int.MinValue + 10_000);
draw = Mesh.Draws[^1]; draw.Visible = false;
}
public void Update(Mesh destination, LabSimulation owner)
{
draw.Visible = owner.JetpackEffectVisible;
if (!draw.Visible) return;
var model = Matrix4x4.CreateRotationY(-owner.Yaw * MathF.PI / 180)
* Matrix4x4.CreateTranslation(owner.ActorRoot);
clip.Sample(owner.Steps / 60d, destination.Vertices.AsSpan(offset, clip.Base.Vertices.Length), model);
}
}
+32
View File
@@ -0,0 +1,32 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>
/// Deterministic integration check using direct contacts at original actor roots.
/// This does not test navigation, player input, physics or original runtime fidelity.
/// </summary>
public static class LabRouteSmoke
{
public static void Run(GamLevel level, SceneDirector director, SceneInteractions interactions, Action? dismissPractice = null)
{
if (level.Code != "LV1B") throw new ArgumentException("Lab route check requires original LV1B");
director.Skip();
var player = level.Player!.Tag!;
director.Touch(player, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions.Update(director.FindActor("shrinkray")!.Position);
dismissPractice?.Invoke();
var carl = director.FindActor("C3DCARL")!;
director.SyncActor(player, carl.Position, Vector3.Zero);
interactions.Update(carl.Position);
director.Skip();
if (!director.Controlled || interactions.Score != 150 || interactions.Inventory.State(0, 3) != 1
|| interactions.CurrentObjective != 3)
throw new InvalidOperationException("Original lab contact route did not reach the recovered exit state");
interactions.Update(level.Entities.Single(e => e.Tag == "LABTONEIGH").Position);
Console.WriteLine("Lab direct-contact integration: explanation, shrinkray, Carl callback and exit; score150, gadget3, objective3. Navigation was not exercised.");
}
}
@@ -8,6 +8,7 @@ public sealed class PreviewAnimationLibrary
{
private readonly Dictionary<uint, (string Name, MorphAnimation Animation)> choices = [];
private readonly Dictionary<PlayerPose, MorphAnimation> movement = [];
private readonly Dictionary<string, MorphAnimation> actions = new(StringComparer.OrdinalIgnoreCase);
public MorphAnimation Current { get; private set; }
public string Name { get; private set; }
public string WindowTitle => $"Jimmy Neutron — scene preview | {Name}{(Current.HasVertexMotion ? "" : " (still pose)")} | 1 idle, 2 run, 3 jump, 4 scratch | C camera";
@@ -46,12 +47,18 @@ public sealed class PreviewAnimationLibrary
if (ReferenceEquals(clip, Current)) Name = label;
}
foreach (var (pose, folder) in new[] { (PlayerPose.Idle, "jimstop"), (PlayerPose.Run, "jimrun"),
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall") })
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly") })
{
var path = Path.Combine(parent, folder, "animation.json");
if (!File.Exists(path)) continue;
movement[pose] = Load(path);
}
foreach (var (action, folder) in new[] { ("STOP", "jimstop"), ("TALK", "jimtalk"), ("RUN", "jimrun"),
("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly") })
{
var path = Path.Combine(parent, folder, "animation.json");
if (File.Exists(path)) actions[action] = Load(path);
}
}
public bool Select(uint scancode)
@@ -70,4 +77,10 @@ public sealed class PreviewAnimationLibrary
Name = pose.ToString();
return true;
}
public bool SelectAction(string action)
{
if (!actions.TryGetValue(action, out var clip) || ReferenceEquals(Current, clip)) return false;
Current = clip; Name = action; return true;
}
}
@@ -0,0 +1,98 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Prepared original Carl/Goddard morphs driven by recovered director state.</summary>
public sealed class SceneActorVisuals
{
private sealed class Visual(DirectorActor actor, Dictionary<string, MorphAnimation> clips,
MorphAnimation initial, string clipName, HashSet<string> ignored, int offset, MeshDraw draw, float correction)
{
public DirectorActor Actor = actor;
public Dictionary<string, MorphAnimation> Clips = clips;
public MorphAnimation Clip = initial;
public string ClipName = clipName;
public HashSet<string> Ignored = ignored;
public int Offset = offset;
public MeshDraw Draw = draw;
public float Correction = correction;
public double Time;
}
private readonly List<Visual> visuals = [];
private readonly HashSet<string> missing = [];
public Mesh Mesh { get; }
public IReadOnlyCollection<string> UnsupportedAnimations => missing;
public SceneActorVisuals(Mesh combined, Mesh world, SceneDirector director, string preparedRoot,
Func<DirectorActor, bool>? usesPhysicsRoot = null)
{
foreach (var actor in director.Actors)
{
var family = actor.Kind switch { "3CAR" => "carl", "3DOG" => "goddard", "3TRO" => "trophy", _ => null };
if (family == null) continue;
var manifest = Path.Combine(preparedRoot, "actors", family, "family.json");
if (!File.Exists(manifest)) throw new FileNotFoundException("Prepare original actor animation resources", manifest);
using var doc = JsonDocument.Parse(File.ReadAllText(manifest));
var clips = new Dictionary<string, MorphAnimation>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in doc.RootElement.GetProperty("actions").EnumerateObject())
clips.Add(entry.Name, new MorphAnimation(Path.Combine(Path.GetDirectoryName(manifest)!, entry.Value.GetString()!)));
var initialName = doc.RootElement.GetProperty("default").GetString()!;
var initial = clips[initialName];
var ignored = doc.RootElement.TryGetProperty("ignoredAnimations", out var ignoredNames)
? new HashSet<string>(ignoredNames.EnumerateArray().Select(n => n.GetString()!), StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var clip in clips.Values)
if (clip.Base.Vertices.Length != initial.Base.Vertices.Length || !clip.Base.Indices.SequenceEqual(initial.Base.Indices)
|| !clip.Base.Vertices.Select(v => v.Uv).SequenceEqual(initial.Base.Vertices.Select(v => v.Uv))
|| !clip.Texture.Rgba.SequenceEqual(initial.Texture.Rgba)) throw new InvalidDataException("Actor morph family mismatch");
var offset = combined.Vertices.Length;
var correction = actor.Kind == "3TRO" || usesPhysicsRoot?.Invoke(actor) == true ? 0
: PreviewCharacterPlacement.Create(world, initial.Base, actor.Position, actor.Rotation.Y).VerticalCorrection;
combined = initial.AppendTo(combined, int.MinValue + 1 + visuals.Count);
visuals.Add(new(actor, clips, initial, initialName, ignored, offset, combined.Draws[^1], correction));
}
Mesh = combined;
Update(0);
// Original animation selection is synchronous. Preserve intermediate
// SIT then ignored TALK requests even if both occur before a render.
director.ActorChanged += actor =>
{
var visual = visuals.Find(v => ReferenceEquals(v.Actor, actor));
if (visual != null) SelectAnimation(visual);
};
}
public void Update(double seconds, Mesh? destination = null)
{
foreach (var visual in visuals)
{
var actor = visual.Actor;
SelectAnimation(visual);
visual.Time += seconds;
var rotation = Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180)
* Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180);
var model = rotation * Matrix4x4.CreateTranslation(actor.Position + Vector3.UnitY * visual.Correction);
visual.Clip.Sample(visual.Time, (destination ?? Mesh).Vertices.AsSpan(visual.Offset, visual.Clip.Base.Vertices.Length), model);
visual.Draw.Visible = actor.Visible;
}
}
private void SelectAnimation(Visual visual)
{
var actor = visual.Actor;
if (visual.Clips.TryGetValue(actor.Animation, out var clip))
{
if (!ReferenceEquals(clip, visual.Clip)) { visual.Clip = clip; visual.Time = 0; }
visual.ClipName = actor.Animation;
}
// EXE40DF18..22: an unregistered definition returns without selecting
// or renaming the current animation. These aliases have no Goddard
// registrations; this is an ignored request, not a made-up asset alias.
else if (visual.Ignored.Contains(actor.Animation)) actor.Animation = visual.ClipName;
else if (actor.Animation != "none") missing.Add(actor.Tag + ":" + actor.Animation);
}
}
+97
View File
@@ -0,0 +1,97 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
namespace GamePort.Application;
/// <summary>Original screens.omt laboratory objectives and PracticeYesNo; positions from EXE 402C40/407070.</summary>
public sealed class SceneHud
{
private sealed record Quad(int Canvas, int VertexOffset, uint FirstIndex, uint Width, uint Height);
private readonly List<Quad> quads = [];
private static readonly Dictionary<int, (uint Width, uint Height)> Dimensions = 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)
};
public Mesh Mesh { get; }
public SceneHud(Mesh combined, string manifest)
{
var full = Path.GetFullPath(manifest);
if (new FileInfo(full).Length > 64 * 1024) throw new InvalidDataException("UI manifest exceeds limit");
var directory = Path.GetDirectoryName(full)!;
using var doc = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 });
var root = doc.RootElement;
if (root.GetProperty("version").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640
|| root.GetProperty("referenceHeight").GetInt32() != 480)
throw new InvalidDataException("Unsupported prepared UI format");
var recovered = new Dictionary<int, PngImage>();
var entries = root.GetProperty("textures");
if (entries.GetArrayLength() != Dimensions.Count) throw new InvalidDataException("Unexpected UI texture count");
foreach (var entry in entries.EnumerateArray())
{
var id = entry.GetProperty("id").GetInt32();
var width = entry.GetProperty("width").GetUInt32();
var height = entry.GetProperty("height").GetUInt32();
if (!Dimensions.TryGetValue(id, out var expected) || expected != (width, height))
throw new InvalidDataException("Unexpected UI canvas identity/dimensions");
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("UI resource escapes prepared directory");
var bytes = checked((long)width * height * 4);
if (new FileInfo(path).Length != bytes) throw new InvalidDataException("Invalid prepared UI pixel count");
if (!recovered.TryAdd(id, new(width, height, File.ReadAllBytes(path))))
throw new InvalidDataException("Duplicate prepared UI canvas");
}
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.Draws.ToList();
if (!combined.HasExplicitDraws && draws.Count == 0 && indices.Count != 0)
draws.Add(new(0, (uint)indices.Count, -1));
var textures = new Dictionary<int, PngImage>(combined.Textures);
// Pad precedes writing; modal follows the HUD, exactly as layered screen elements.
foreach (var id in new[] { 156, 120, 121, 122, 83, 84, 85, 169 })
{
var image = recovered[id];
var texture = int.MinValue;
while (textures.ContainsKey(texture)) texture++;
textures.Add(texture, image);
var first = (uint)vertices.Count;
quads.Add(new(id, vertices.Count, (uint)indices.Count, image.Width, image.Height));
vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0, 0), Vector3.One),
new MeshVertex(Vector3.Zero, new(1, 0), Vector3.One),
new MeshVertex(Vector3.Zero, new(1, 1), Vector3.One),
new MeshVertex(Vector3.Zero, new(0, 1), Vector3.One) });
draws.Add(new((uint)indices.Count, 6, texture) { ScreenSpace = true, Visible = false });
indices.AddRange(new[] { first, first + 1, first + 2, first, first + 2, first + 3 });
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true,
Textures = textures, CollisionPolygons = combined.CollisionPolygons };
}
/// <summary>Writes the final merged buffer, including when later visual composers copied these vertices.</summary>
public void Update(Mesh destination, int currentObjective, bool objectivesVisible, bool practiceVisible,
float objectiveYOffset = -69)
{
if (!float.IsFinite(objectiveYOffset) || objectiveYOffset < -480 || objectiveYOffset > 480)
throw new ArgumentOutOfRangeException(nameof(objectiveYOffset));
if (destination.Vertices.Length < Mesh.Vertices.Length || destination.Indices.Length < Mesh.Indices.Length)
throw new ArgumentException("Destination omits HUD ranges", nameof(destination));
foreach (var quad in quads)
{
var draw = destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex && d.ScreenSpace
&& d.IndexCount == 6) ?? throw new ArgumentException("Destination omits HUD draws", nameof(destination));
draw.Visible = quad.Canvas == 169 ? practiceVisible : objectivesVisible && currentObjective is >= 1 and <= 3
&& (quad.Canvas == 156 || quad.Canvas == 119 + currentObjective || quad.Canvas == 82 + currentObjective);
var digit = quad.Canvas is >= 83 and <= 85;
var x = quad.Canvas == 169 ? 210f : digit ? 393f : 384f;
var y = quad.Canvas == 169 ? 210f : (quad.Canvas == 156 ? 380f : digit ? 450f : 448f) + objectiveYOffset;
Vector3 Position(float px, float py) => new(2 * px / 640 - 1, 2 * py / 480 - 1, 0);
destination.Vertices[quad.VertexOffset].Position = Position(x, y);
destination.Vertices[quad.VertexOffset + 1].Position = Position(x + quad.Width, y);
destination.Vertices[quad.VertexOffset + 2].Position = Position(x + quad.Width, y + quad.Height);
destination.Vertices[quad.VertexOffset + 3].Position = Position(x, y + quad.Height);
}
}
}
@@ -0,0 +1,92 @@
using System.Numerics;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Source-sized, center-aligned Canv quads. Camera-facing orientation is still a port approximation.</summary>
public sealed class SceneSpriteVisuals
{
private sealed class Visual(DirectorActor actor, int offset, MeshDraw[] draws, SpriteSequence sequence)
{
public DirectorActor Actor = actor;
public int Offset = offset;
public MeshDraw[] Draws = draws;
public SpriteSequence Sequence = sequence;
public int Revision = actor.SpriteRevision;
}
private readonly List<Visual> visuals = [];
public Mesh Mesh { get; }
public SceneSpriteVisuals(Mesh combined, SceneDirector director, PreparedEntityResources resources)
{
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.Draws.ToList();
var textures = new Dictionary<int, PngImage>(combined.Textures);
foreach (var actor in director.Actors)
{
if (actor.Kind is not ("3PIC" or "3ANI") || actor.SourceGam is not { } source) continue;
var database = source.Text("SpriteDatabase") ?? "none";
var identities = actor.Kind == "3ANI" ? Enumerable.Range(1, 9)
.Select(i => source.Integer("Sprite" + i, -1)).TakeWhile(i => i >= 0).ToArray()
: [source.Integer("SpriteIndex", -1)];
if (identities.Length == 0) continue;
var frameDraws = new List<MeshDraw>();
var offset = vertices.Count;
var color = new Vector3(source.Number("Red", 1), source.Number("Green", 1), source.Number("Blue", 1));
foreach (var identity in identities)
{
var canvas = resources.Canvas(database, identity) ?? throw new FileNotFoundException($"Missing original canvas {database}:{identity}");
var texture = int.MinValue + 1000 + textures.Count;
textures.Add(texture, canvas);
var first = (uint)vertices.Count;
vertices.AddRange(new[] { new MeshVertex(Vector3.Zero, new(0,1),color), new MeshVertex(Vector3.Zero,new(1,1),color),
new MeshVertex(Vector3.Zero,new(1,0),color),new MeshVertex(Vector3.Zero,new(0,0),color) });
var draw = new MeshDraw((uint)indices.Count, 6, texture);
indices.AddRange(new[] { first, first+1, first+2, first, first+2, first+3 });
draws.Add(draw); frameDraws.Add(draw);
}
var sequence = new SpriteSequence(identities.Length, source.Number("FPS", 1), source.Integer("Loop", 1));
if (actor.Kind == "3ANI" && actor.SpritePlaying) sequence.Start();
visuals.Add(new(actor, offset, frameDraws.ToArray(), sequence));
}
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures };
}
public void Step(float dt)
{
foreach (var visual in visuals)
{
if (visual.Revision != visual.Actor.SpriteRevision)
{
visual.Revision = visual.Actor.SpriteRevision;
if (visual.Actor.SpritePlaying) visual.Sequence.Start();
}
if (visual.Actor.SpritePlaying) visual.Sequence.Step(dt);
}
}
public void FaceCamera(Vector3 eye, Vector3 target, Mesh? destination = null)
{
var output = destination ?? Mesh;
if (output.Vertices.Length < Mesh.Vertices.Length)
throw new ArgumentException("Destination omits sprite vertex ranges", nameof(destination));
var direction = target - eye;
if (direction.LengthSquared() < .000001f) direction = Vector3.UnitZ;
var right = Vector3.Cross(Vector3.UnitY, direction);
right = right.LengthSquared() < .000001f ? Vector3.UnitX : Vector3.Normalize(right);
var up = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(direction), right));
foreach (var visual in visuals)
{
var half = visual.Actor.SourceGam!.Integer("SpriteSize", 50) * .5f;
var center = visual.Actor.Position;
var corners = new[] { center-right*half-up*half, center+right*half-up*half,
center+right*half+up*half, center-right*half+up*half };
for (var frame = 0; frame < visual.Draws.Length; frame++)
{
visual.Draws[frame].Visible = visual.Actor.Visible && !visual.Sequence.Hidden && frame == visual.Sequence.Frame;
for (var corner = 0; corner < 4; corner++) output.Vertices[visual.Offset + frame * 4 + corner].Position = corners[corner];
}
}
}
}
@@ -0,0 +1,160 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Assets;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>
/// Prepared original OMT props, phone booths and explicitly authored ASE models.
/// Keeps source-local positions, every non-null material draw, and director visibility.
/// </summary>
public sealed class StaticSceneVisuals
{
private sealed record Variant(string Name, MeshVertex[] LocalVertices, int Offset, MeshDraw[] Draws);
private sealed record Visual(DirectorActor Actor, string DefaultVariant, Variant[] Variants,
(Vector3 Min, Vector3 Max)? LocalBounds);
private readonly List<Visual> visuals = [];
public Mesh Mesh { get; }
public int ActorCount => visuals.Count;
public StaticSceneVisuals(Mesh combined, SceneDirector director, string assetsRoot, string preparedRoot)
{
// All authored ASE/PNG data is prepared locally too; runtime does not
// invent model defaults or silently fall back to an unrelated file.
_ = assetsRoot;
var root = Path.GetFullPath(preparedRoot);
using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "models.json")));
if (document.RootElement.GetProperty("schema").GetInt32() != 1)
throw new InvalidDataException("Unsupported prepared static model manifest");
string Resolve(string relative)
{
if (Path.IsPathRooted(relative)) throw new InvalidDataException("Static model path must be relative");
var path = Path.GetFullPath(Path.Combine(root, relative));
if (!path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Prepared static model escapes its directory");
return path;
}
var models = new Dictionary<string, Mesh>(StringComparer.Ordinal);
var bounds = new Dictionary<string, (Vector3 Min, Vector3 Max)>(StringComparer.Ordinal);
foreach (var model in document.RootElement.GetProperty("models").EnumerateArray())
{
models.Add(model.GetProperty("key").GetString()!, Mesh.LoadSceneJson(Resolve(model.GetProperty("path").GetString()!)));
if (model.TryGetProperty("source", out var source) && source.TryGetProperty("localBounds", out var box))
{
Vector3 Read(string key) => new(box.GetProperty(key)[0].GetSingle(), box.GetProperty(key)[1].GetSingle(), box.GetProperty(key)[2].GetSingle());
bounds.Add(model.GetProperty("key").GetString()!, (Read("min"), Read("max")));
}
}
var sourceActors = director.Actors.Where(a => a.SourceGam is not null)
.ToDictionary(a => a.SourceGam!.Offset);
var vertices = combined.Vertices.ToList();
var indices = combined.Indices.ToList();
var draws = combined.HasExplicitDraws ? combined.Draws.ToList()
: [new MeshDraw(0, (uint)combined.Indices.Length, -1)];
var textures = new Dictionary<int, PngImage>(combined.Textures);
var nextTexture = int.MinValue + 20_000;
var added = new HashSet<int>();
foreach (var entry in document.RootElement.GetProperty("actors").EnumerateArray())
{
var sourceOffset = entry.GetProperty("offset").GetInt32();
if (!added.Add(sourceOffset) || !sourceActors.TryGetValue(sourceOffset, out var actor)
|| actor.Kind != entry.GetProperty("kind").GetString())
throw new InvalidDataException("Prepared static model actor does not match its source GAM offset");
var variants = new List<Variant>();
var tint = new Vector3(actor.SourceGam!.Number("Red", 1), actor.SourceGam.Number("Green", 1),
actor.SourceGam.Number("Blue", 1));
foreach (var variant in entry.GetProperty("variants").EnumerateObject())
{
var model = models[variant.Value.GetString()!];
var local = model.Vertices.Select(v => new MeshVertex(v.Position, v.Uv, v.Color * tint)).ToArray();
var vertexOffset = vertices.Count;
var indexOffset = indices.Count;
var identities = new Dictionary<int, int>();
foreach (var texture in model.Textures)
{
if (textures.ContainsKey(nextTexture))
throw new InvalidDataException("Reserved static model texture identity is already in use");
identities.Add(texture.Key, nextTexture);
textures.Add(nextTexture++, texture.Value);
}
vertices.AddRange(local);
indices.AddRange(model.Indices.Select(i => checked(i + (uint)vertexOffset)));
var retained = new List<MeshDraw>();
// LoadSceneJson intentionally omits null-material draws. Never
// replace an empty explicit list with a white whole-model draw.
var modelDraws = model.HasExplicitDraws ? model.Draws
: [new MeshDraw(0, (uint)model.Indices.Length, -1)];
foreach (var draw in modelDraws)
{
var textureId = draw.TextureId == -1 ? -1
: identities.TryGetValue(draw.TextureId, out var mapped) ? mapped
: throw new InvalidDataException("Static model draw references a missing texture");
var retainedDraw = new MeshDraw(checked(draw.FirstIndex + (uint)indexOffset), draw.IndexCount, textureId);
retained.Add(retainedDraw);
draws.Add(retainedDraw);
}
variants.Add(new(variant.Name, local, vertexOffset, retained.ToArray()));
}
var defaultVariant = entry.GetProperty("defaultVariant").GetString()!;
if (!variants.Any(v => Equal(v.Name, defaultVariant)))
throw new InvalidDataException("Missing default static model variant");
var defaultKey = entry.GetProperty("variants").GetProperty(defaultVariant).GetString()!;
visuals.Add(new(actor, defaultVariant, variants.ToArray(), bounds.TryGetValue(defaultKey, out var box) ? box : null));
}
Mesh = new(vertices.ToArray(), indices.ToArray())
{
Draws = draws.ToArray(), HasExplicitDraws = true, Textures = textures
};
Update(Mesh);
}
/// <summary>Apply the director's current root transform/visibility to retained model ranges.</summary>
public void Update(Mesh destination)
{
if (destination.Vertices.Length < Mesh.Vertices.Length)
throw new ArgumentException("Destination omits static model vertex ranges", nameof(destination));
foreach (var visual in visuals)
{
var actor = visual.Actor;
var selected = visual.DefaultVariant;
if (actor.Kind == "3BUT")
{
if (Equal(actor.Animation, "DOWN") || Equal(actor.Animation, "HIDOWN")) selected = "DOWN";
else if (Equal(actor.Animation, "UP") || Equal(actor.Animation, "HIUP")) selected = "UP";
}
var transform = Transform(actor);
foreach (var variant in visual.Variants)
{
for (var i = 0; i < variant.LocalVertices.Length; i++)
{
var vertex = variant.LocalVertices[i];
vertex.Position = Vector3.Transform(vertex.Position, transform);
destination.Vertices[variant.Offset + i] = vertex;
}
foreach (var draw in variant.Draws)
draw.Visible = actor.Visible && Equal(variant.Name, selected);
}
}
}
public IEnumerable<DynamicBoxCollider> DoorColliders()
{
foreach (var visual in visuals)
{
if (visual.Actor.Kind != "3DUD") continue;
var box = visual.LocalBounds ?? throw new InvalidDataException("Prepare original local door bounds before dynamic collision");
var flags = DynamicSceneCollision.DoorCollisionFlags(visual.Actor.SourceGam!.Integer("HasCollision", -1));
yield return new(visual.Actor.SourceGam.Offset, visual.Actor.Position, box.Min, box.Max,
Transform(visual.Actor), CollisionEnabled: flags.EntityCollision);
}
}
private static Matrix4x4 Transform(DirectorActor actor) =>
Matrix4x4.CreateRotationX(actor.Rotation.X * MathF.PI / 180)
* Matrix4x4.CreateRotationY(-actor.Rotation.Y * MathF.PI / 180)
* Matrix4x4.CreateRotationZ(actor.Rotation.Z * MathF.PI / 180)
* Matrix4x4.CreateTranslation(actor.Position);
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
+17 -2
View File
@@ -14,6 +14,7 @@ public struct MeshVertex(Vector3 position, Vector2 uv, Vector3 color)
public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
{
public MeshPolygonSource[] CollisionPolygons { get; init; } = [];
public MeshDraw[] Draws { get; init; } = [];
public bool HasExplicitDraws { get; init; }
public Dictionary<int,PngImage> Textures { get; init; } = [];
@@ -38,6 +39,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
var indices = root.GetProperty("indices").EnumerateArray().Select(p => p.GetUInt32()).ToArray();
if (indices.Length % 3 != 0 || indices.Any(i => i >= vertices.Length)) throw new InvalidDataException("Invalid scene triangle indices.");
if (vertices.Length == 0 || indices.Length == 0) throw new InvalidDataException("Empty scene mesh.");
var collisionPolygons = root.TryGetProperty("collisionPolygons", out var polygonList)
? polygonList.EnumerateArray().Select(p => new MeshPolygonSource(p.GetProperty("shapeId").GetInt32(),
p.GetProperty("polygonIndex").GetInt32(),
new Vector3(p.GetProperty("normal")[0].GetSingle(), p.GetProperty("normal")[1].GetSingle(), p.GetProperty("normal")[2].GetSingle()),
p.GetProperty("materialName").GetString())).ToArray() : [];
if (collisionPolygons.Length != 0 && (collisionPolygons.Length != indices.Length / 3
|| collisionPolygons.Any(p => !float.IsFinite(p.Normal.X + p.Normal.Y + p.Normal.Z))))
throw new InvalidDataException("Invalid source collision polygon metadata");
var textures = new Dictionary<int,PngImage>();
if(root.TryGetProperty("textures",out var textureList)) foreach(var t in textureList.EnumerateArray())
{
@@ -71,8 +80,14 @@ public sealed record Mesh(MeshVertex[] Vertices, uint[] Indices)
for(var i=first;i<first+count;i++)vertices[indices[i]].Color=material.Item2;
draws.Add(new MeshDraw(first,count,material.Item1));
}
return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures};
return new Mesh(vertices, indices){Draws=draws.ToArray(),HasExplicitDraws=true,Textures=textures,CollisionPolygons=collisionPolygons};
}
}
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId);
public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, Vector3 Normal, string? MaterialName);
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
{
public bool Visible { get; set; } = true;
public bool ScreenSpace { get; init; }
}
+4 -3
View File
@@ -72,18 +72,19 @@ public sealed class MorphAnimation
}
}
public Mesh AppendTo(Mesh scene)
public Mesh AppendTo(Mesh scene, int textureId = int.MinValue)
{
var vertices = new MeshVertex[scene.Vertices.Length + Base.Vertices.Length];
scene.Vertices.CopyTo(vertices, 0);
Base.Vertices.CopyTo(vertices, scene.Vertices.Length);
var indices = scene.Indices.Concat(Base.Indices.Select(i => checked(i + (uint)scene.Vertices.Length))).ToArray();
var draws = scene.HasExplicitDraws ? scene.Draws : [new MeshDraw(0, (uint)scene.Indices.Length, -1)];
var textures = new Dictionary<int, PngImage>(scene.Textures) { [int.MinValue] = Texture };
if (scene.Textures.ContainsKey(textureId)) throw new InvalidDataException("Actor texture identity already in use");
var textures = new Dictionary<int, PngImage>(scene.Textures) { [textureId] = Texture };
return new Mesh(vertices, indices)
{
HasExplicitDraws = true,
Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, int.MinValue)],
Draws = [.. draws, new MeshDraw((uint)scene.Indices.Length, (uint)Base.Indices.Length, textureId)],
Textures = textures
};
}
+114
View File
@@ -0,0 +1,114 @@
using System.Buffers.Binary;
using System.Numerics;
using System.Text;
namespace GamePort.Assets;
public sealed record SavedTask(string Name, int State);
/// <summary>Original TSK wire layout recovered at EXE0x45FEE0/0x4603F0; unknown fields retained.</summary>
public sealed record OriginalSave(string LevelCode, float PlayerValue, short Counter,
int Score, int OtherCounter, int[] ItemStates, int[] LevelCounters,
string StartPoint, string ReservedName, string ReturnLevel, string ReturnStart,
Vector3 StoredVector, int[] InventoryStates, SavedTask[] Tasks)
{
public const int ItemCount = 4200, LevelCounterCount = 29, InventoryCount = 19;
public static OriginalSave Load(string path) => Parse(File.ReadAllBytes(path));
public static OriginalSave Parse(ReadOnlySpan<byte> bytes)
{
var reader = new Reader(bytes);
var code = reader.Text(4);
if (code.Any(c => !char.IsAsciiLetterOrDigit(c))) throw new InvalidDataException("Invalid TSK level code");
var playerValue = reader.Float();
var counter = reader.Short();
var score = reader.Integer();
var otherCounter = reader.Integer();
var items = reader.Integers(ItemCount);
var levels = reader.Integers(LevelCounterCount);
var start = reader.Pascal();
var reserved = reader.Pascal();
var returnLevel = reader.Pascal();
var returnStart = reader.Pascal();
var vector = new Vector3(reader.Float(), reader.Float(), reader.Float());
var inventory = reader.Integers(InventoryCount);
var count = reader.Integer();
if (count < 0 || count > reader.Remaining / 5) throw new InvalidDataException("Invalid TSK task count");
var tasks = new SavedTask[count];
for (var i = 0; i < count; i++) tasks[i] = new(reader.Pascal(), reader.Integer());
if (reader.Remaining != 0) throw new InvalidDataException("Unexpected TSK trailing bytes");
return new(code, playerValue, counter, score, otherCounter, items, levels, start, reserved,
returnLevel, returnStart, vector, inventory, tasks);
}
public byte[] Encode()
{
using var output = new MemoryStream();
void Integer(int value)
{
Span<byte> raw = stackalloc byte[4];
BinaryPrimitives.WriteInt32BigEndian(raw, value);
output.Write(raw);
}
void Float(float value)
{
if (!float.IsFinite(value)) throw new InvalidDataException("Nonfinite TSK float");
Integer(BitConverter.SingleToInt32Bits(value));
}
void Text(string value, bool pascal)
{
if (value.Any(c => c > 255) || pascal && value.Length > 255)
throw new InvalidDataException("TSK text must fit original Latin1 Pascal string");
if (pascal) output.WriteByte((byte)value.Length);
output.Write(Encoding.Latin1.GetBytes(value));
}
void Table(int[] values, int length)
{
if (values.Length != length) throw new InvalidDataException("Invalid fixed TSK table length");
foreach (var value in values) Integer(value);
}
if (LevelCode.Length != 4 || LevelCode.Any(c => !char.IsAsciiLetterOrDigit(c)))
throw new InvalidDataException("Invalid TSK level code");
Text(LevelCode, false);
Float(PlayerValue);
Span<byte> shortBytes = stackalloc byte[2];
BinaryPrimitives.WriteInt16BigEndian(shortBytes, Counter);
output.Write(shortBytes);
Integer(Score); Integer(OtherCounter);
Table(ItemStates, ItemCount); Table(LevelCounters, LevelCounterCount);
Text(StartPoint, true); Text(ReservedName, true); Text(ReturnLevel, true); Text(ReturnStart, true);
Float(StoredVector.X); Float(StoredVector.Y); Float(StoredVector.Z);
Table(InventoryStates, InventoryCount);
Integer(Tasks.Length);
foreach (var task in Tasks) { Text(task.Name, true); Integer(task.State); }
return output.ToArray();
}
private ref struct Reader(ReadOnlySpan<byte> data)
{
private readonly ReadOnlySpan<byte> bytes = data;
private int offset;
public int Remaining => bytes.Length - offset;
private ReadOnlySpan<byte> Take(int count)
{
if (count < 0 || count > Remaining) throw new InvalidDataException($"Truncated TSK at0x{offset:X}");
var value = bytes.Slice(offset, count); offset += count; return value;
}
public string Text(int count) => Encoding.Latin1.GetString(Take(count));
public string Pascal() => Text(Take(1)[0]);
public short Short() => BinaryPrimitives.ReadInt16BigEndian(Take(2));
public int Integer() => BinaryPrimitives.ReadInt32BigEndian(Take(4));
public float Float()
{
var value = BitConverter.Int32BitsToSingle(Integer());
return float.IsFinite(value) ? value : throw new InvalidDataException("Nonfinite TSK float");
}
public int[] Integers(int count)
{
if (count > Remaining / 4) throw new InvalidDataException("Truncated fixed TSK table");
var values = new int[count];
for (var i = 0; i < count; i++) values[i] = Integer();
return values;
}
}
}
@@ -0,0 +1,60 @@
using System.Text.Json;
namespace GamePort.Assets;
public sealed record PreparedWave(string Path, double Seconds);
/// <summary>Original database/type/id resource identities retained by entities.py.</summary>
public sealed class PreparedEntityResources
{
private readonly Dictionary<(string Database, int Id), PreparedWave> waves = [];
private readonly Dictionary<(string Database, int Id), PngImage> canvases = [];
public PreparedEntityResources(params string[] manifests)
{
foreach (var manifest in manifests) Load(manifest);
}
private void Load(string manifest)
{
var directory = Path.GetDirectoryName(Path.GetFullPath(manifest))!;
string Resolve(string relative)
{
var full = Path.GetFullPath(Path.Combine(directory, relative));
if (!full.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
throw new InvalidDataException("Prepared resource escapes its directory");
return full;
}
using var doc = JsonDocument.Parse(File.ReadAllText(manifest));
foreach (var resource in doc.RootElement.GetProperty("resources").EnumerateArray())
{
if (!resource.TryGetProperty("path", out var path)) continue;
var key = (Normalize(resource.GetProperty("database").GetString()!), resource.GetProperty("id").GetInt32());
switch (resource.GetProperty("type").GetString())
{
case "Wave":
var seconds = resource.GetProperty("audio").GetProperty("seconds").GetDouble();
if (!double.IsFinite(seconds) || seconds < 0) throw new InvalidDataException("Invalid prepared audio duration");
var resolved = Resolve(path.GetString()!);
if (waves.TryGetValue(key, out var previous))
{
if (previous.Seconds != seconds || !File.ReadAllBytes(previous.Path).AsSpan().SequenceEqual(File.ReadAllBytes(resolved)))
throw new InvalidDataException("Conflicting prepared wave identity");
}
else waves.Add(key, new(resolved, seconds));
break;
case "Canv":
var width = resource.GetProperty("width").GetUInt32();
var height = resource.GetProperty("height").GetUInt32();
var rgba = File.ReadAllBytes(Resolve(path.GetString()!));
if (width == 0 || height == 0 || width > 8192 || height > 8192 || rgba.Length != checked((int)(width * height * 4)))
throw new InvalidDataException("Invalid prepared canvas");
canvases.Add(key, new(width, height, rgba));
break;
}
}
}
private static string Normalize(string name) => Path.GetFileName(name.Replace('\\', '/')).ToUpperInvariant();
public PreparedWave? Wave(string database, int id) => waves.GetValueOrDefault((Normalize(database), id));
public PngImage? Canvas(string database, int id) => canvases.GetValueOrDefault((Normalize(database), id));
public double Duration(string database, int id) => Wave(database, id)?.Seconds
?? throw new FileNotFoundException($"Prepare original speech resource {database}:Wave:{id}");
}
+61
View File
@@ -0,0 +1,61 @@
using GamePort.Assets;
namespace GamePort.Audio;
/// <summary>Independent original music and sequential speech streams.</summary>
public sealed class SceneAudio : IDisposable
{
private readonly PreparedEntityResources resources;
private SdlAudio? music, speech;
private readonly List<SdlAudio> effects = [];
private readonly Dictionary<string, SdlAudio> loops = new(StringComparer.OrdinalIgnoreCase);
public int EffectCount => effects.Count;
public int LoopCount => loops.Count;
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
public int QueuedMusicBytes => music?.QueuedBytes ?? 0;
public int QueuedSpeechBytes => speech?.QueuedBytes ?? 0;
public SceneAudio(PreparedEntityResources resources) => this.resources = resources;
public void Music(string database, int id)
{
music?.Dispose(); music = null;
if (resources.Wave(database, id) is { } wave) music = new(wave.Path, true);
}
public void Speech(string database, int id)
{
StopSpeech();
var wave = resources.Wave(database, id) ?? throw new FileNotFoundException($"Missing prepared speech: {database}:{id}");
speech = new(wave.Path);
}
public void StopSpeech() { speech?.Dispose(); speech = null; }
// Default current bank set by Jimmy PostLoad423642..656; positional attenuation
// and original channel/volume policy are separate unrecovered consumers.
public void Effect(int id, string? loopOwner = null)
{
var wave = resources.Wave("SoundEffects.omt", id)
?? throw new FileNotFoundException($"Missing original default sound effect {id}");
if (loopOwner == null) effects.Add(new(wave.Path));
else
{
StopLoop(loopOwner);
loops.Add(loopOwner, new(wave.Path, true));
}
}
public void StopLoop(string owner)
{
if (loops.Remove(owner, out var stream)) stream.Dispose();
}
public void StopEffects()
{
foreach (var effect in effects) effect.Dispose();
foreach (var effect in loops.Values) effect.Dispose();
effects.Clear(); loops.Clear();
}
public void Pump()
{
music?.Pump(); speech?.Pump();
foreach (var effect in loops.Values) effect.Pump();
for (var i = effects.Count - 1; i >= 0; i--)
if (effects[i].QueuedBytes == 0) { effects[i].Dispose(); effects.RemoveAt(i); }
}
public void Dispose() { StopEffects(); StopSpeech(); music?.Dispose(); music = null; }
}
+214
View File
@@ -0,0 +1,214 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>Root state exchanged with the separately implemented body solver.</summary>
public readonly record struct PatrolBodyState(Vector3 Position, Vector3 Velocity);
/// <summary>
/// Goddard/Carl's ordinary state3 patrol and state7 waypoint wait. The original base
/// update consumes the preceding velocity/heading before choosing the next ones.
/// Physical collision/gravity are supplied by the caller. Magnitude uses the
/// recovered OMT table algorithm; flat atan2 heading and modern table-generation
/// trig still require comparison against original angle/x87 results.
/// See docs/analysis/patrol.md for recovered order, addresses and limitations.
/// </summary>
public sealed class ActorPatrol
{
public const float ArrivalDistance = 110;
public const float YawFactor = 3.2f;
private readonly DirectorActor actor;
private readonly Func<string, DirectorActor?> findActor;
private readonly Func<PatrolBodyState, float, PatrolBodyState> integrateBody;
private readonly Func<Vector3, float> magnitude;
private readonly float yawFactor;
private readonly string movingAnimation, waitingAnimation;
private DirectorActor? waypoint;
private DirectorActor? previousWaypoint;
private Vector3 publishedPosition, publishedRotation;
private string? publishedPatrol;
private int publishedState, previousState;
private float desiredYaw;
public Vector3 Velocity { get; private set; }
public Vector3 DestinationDelta { get; private set; }
public float DestinationDistance { get; private set; }
public bool Arrived { get; private set; }
public float WaitRemaining { get; private set; }
public string? CurrentWaypoint => waypoint?.Tag;
public string? PreviousWaypoint => previousWaypoint?.Tag;
public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6;
public ActorPatrol(DirectorActor actor, Func<string, DirectorActor?> findActor,
Func<PatrolBodyState, float, PatrolBodyState> integrateBody,
Func<Vector3, float>? magnitude = null)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(findActor);
ArgumentNullException.ThrowIfNull(integrateBody);
if (actor.Kind is not ("3DOG" or "3CAR")) throw new ArgumentException("Recovered patrol requires Goddard or Carl", nameof(actor));
this.actor = actor;
this.findActor = findActor;
this.integrateBody = integrateBody;
this.magnitude = magnitude ?? OriginalBodySupport.QuickMagnitude;
// Carl413BFC..43 installs WALK/STOP; his Y factor remains3 (407CF8).
yawFactor = actor.Kind == "3DOG" ? YawFactor : 3;
movingAnimation = actor.Kind == "3DOG" ? "RUN" : "WALK";
waitingAnimation = actor.Kind == "3DOG" ? "WAG" : "STOP";
desiredYaw = actor.Rotation.Y;
Publish();
}
/// <summary>
/// Observe authored AI/teleport actions without changing their animation.
/// Teleports reset the port body's motion/route cache; their full original
/// physics bookkeeping is not yet recovered. Camera-only animation changes
/// leave the body and waypoint intact. Internal patrol changes emit no event.
/// </summary>
public void SynchronizeAuthoredState()
{
if (actor.Position != publishedPosition)
{
Velocity = Vector3.Zero;
ResetRoute();
desiredYaw = actor.Rotation.Y;
}
if (actor.Rotation != publishedRotation) desiredYaw = actor.Rotation.Y;
if (!Equal(actor.Patrol, publishedPatrol)
|| actor.AIstate != publishedState && actor.AIstate == 3)
ResetRoute();
Publish();
}
/// <returns>False when the current AI state lies outside this recovered subset.</returns>
public bool Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
SynchronizeAuthoredState();
if (!SupportedState) return false;
if (!actor.Active) return true;
if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed");
// EXE408023->40E050: the body consumes the *previous* velocity first.
var body = integrateBody(new(actor.Position, Velocity), dt);
if (!Finite(body.Position) || !Finite(body.Velocity))
throw new InvalidOperationException("Goddard body solver produced nonfinite state");
actor.Position = body.Position;
Velocity = body.Velocity;
var yawError = (desiredYaw - actor.Rotation.Y) % 360;
if (yawError > 180) yawError -= 360;
if (yawError < -180) yawError += 360;
actor.Rotation = actor.Rotation with { Y = actor.Rotation.Y + yawError * yawFactor * dt };
switch (actor.AIstate)
{
case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration.
case 3: StepPatrol(); break;
case 7: StepWait(dt); break;
// State9 jumps directly to the common finisher408911. State6 calls
// sensing409CC0 first; source player-contact dispatch is implemented
// by SceneInteractions, while general FOV/visibility sensing is open.
case 6: case 9: break;
}
// States1/6/7 return before selecting a destination angle (409186..19B).
// Retain the old destination on a waypoint change, as the source does.
if (actor.AIstate == 3 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0)
desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI);
Publish();
return true;
}
private void StepPatrol()
{
waypoint ??= findActor(actor.Patrol ?? "none");
if (waypoint == null)
{
SetState(1);
Velocity = new(0, Velocity.Y, 0); // Missing initial waypoint preserves Y.
}
else
{
DestinationDelta = waypoint.Position - actor.Position;
DestinationDistance = DestinationDelta.Length();
if (!float.IsFinite(DestinationDistance)) throw new InvalidOperationException("Patrol destination exceeds finite arithmetic range");
}
// This remains after the waypoint resolver even if it changed state1.
actor.Animation = movingAnimation;
if (waypoint == null) return;
if (Arrived)
{
Velocity = Vector3.Zero;
actor.Animation = waitingAnimation;
}
else if (DestinationDelta == Vector3.Zero) Velocity = Vector3.Zero;
else
{
var length = magnitude(DestinationDelta);
if (!float.IsFinite(length) || length <= 0) throw new InvalidOperationException("Invalid patrol magnitude");
Velocity = DestinationDelta / length * actor.Speed;
}
// EXE408BC0 compares distance only after selecting the next velocity.
if (DestinationDistance < ArrivalDistance) Arrived = true;
else if (DestinationDistance > ArrivalDistance) Arrived = false;
if (!Arrived || waypoint.Kind != "3PAT" || waypoint.SourceGam is not { } point) return;
var wait = point.Number("WaitTime");
if (wait > 0)
{
SetState(7);
actor.Animation = point.Text("WaitAnim") ?? "none";
WaitRemaining = wait;
Velocity = Vector3.Zero;
return;
}
previousWaypoint = waypoint;
var next = point.Text("NextPatrolPoint") ?? "none";
waypoint = findActor(next);
if (waypoint != null) return;
if (Equal(next, "WAIT")) SetState(1);
else if (Equal(next, "SCAN")) SetState(6);
// Ordinary unresolved names, including "none", retain state3. Next tick
// resolves the initial PatrolPoint; there is no terminal-route snap.
}
private void StepWait(float dt)
{
Velocity = Vector3.Zero;
if (WaitRemaining <= 0) return; // Source checks positivity before subtract.
WaitRemaining -= dt;
if (WaitRemaining > 0) return; // Equality expires: EXE4083B0 testah41/je.
SetState(previousState);
Arrived = false;
// The timed-wait branch does not interpret WAIT/SCAN specially.
waypoint = waypoint?.SourceGam is { } point && waypoint.Kind == "3PAT"
? findActor(point.Text("NextPatrolPoint") ?? "none") : null;
}
private void SetState(int state)
{
previousState = actor.AIstate;
actor.AIstate = state;
if (state == 1) actor.Animation = waitingAnimation;
else if (state == 3) actor.Animation = movingAnimation;
}
private void ResetRoute()
{
waypoint = previousWaypoint = null;
Arrived = false;
WaitRemaining = 0;
DestinationDelta = Vector3.Zero;
DestinationDistance = 0;
}
private void Publish()
{
publishedPosition = actor.Position;
publishedRotation = actor.Rotation;
publishedPatrol = actor.Patrol;
publishedState = actor.AIstate;
}
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
}
+34
View File
@@ -0,0 +1,34 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Explicit provisional narrowphase adapter. Source mode2 gates/corners/order
/// come from DynamicSceneCollision; sweep/slide uses the modern sphere kernel.
/// This is not a translation of original47BD80.
/// </summary>
public static class DynamicBodyResponse
{
public static Vector3 Resolve(IEnumerable<DynamicBoxCollider> boxes, Vector3 previous, Vector3 position, float radius)
{
foreach (var box in boxes)
{
var response = DynamicSceneCollision.Resolve(box, new(previous, position, radius), Sweep);
if (response.Contact) position = response.Position;
}
return position;
}
private static DynamicCollisionResponse Sweep(DynamicBoxSweep sweep)
{
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 moved = new SceneCollision(mesh).Move(sweep.Sphere.PreviousPosition - Vector3.UnitY * radius,
sweep.Sphere.Position - sweep.Sphere.PreviousPosition, radius, radius * 2);
var position = moved.Position + Vector3.UnitY * radius;
return new(Vector3.DistanceSquared(position, sweep.Sphere.Position) > .0001f, position);
}
}
+128
View File
@@ -0,0 +1,128 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>
/// A mode2 entity's original local shape cube and current transform. Drawing
/// visibility and own physics integration are independent of CollisionEnabled.
/// </summary>
public readonly record struct DynamicBoxCollider(
int Identity, Vector3 Root, Vector3 LocalMin, Vector3 LocalMax, Matrix4x4 LocalToWorld,
float Radius = 40, bool CollisionEnabled = true, bool InhibitResponse = false);
public readonly record struct DynamicSphereMotion(
Vector3 PreviousPosition, Vector3 Position, float Radius,
bool CollisionEnabled = true, bool GeometryCollisionEnabled = true, int Mode = 1);
public sealed record DynamicBoxSweep(
DynamicBoxCollider Box, DynamicSphereMotion Sphere, IReadOnlyList<SupportTriangle> Triangles);
public readonly record struct DynamicCollisionResponse(bool Contact, Vector3 Position);
/// <summary>
/// Recovered mode2 dispatch, broadphase and oriented local-cube triangulation
/// from EXE47A430/47A5E0. The narrowphase is injected because47BD80 and its
/// static-world response have not been fully translated. See dynamic-collision.md.
/// </summary>
public static class DynamicSceneCollision
{
// C3DDoorUpDown constructor/PostLoad: pair tests on, own integration off,
// mode2 and current radius40. HasCollision=-1 preserves those defaults.
public const float DoorRadius = 40;
public const int DoorMode = 2;
public const bool DoorEntityCollisionDefault = true;
public const bool DoorIntegrationDefault = false;
// Corner bits X=4,Y=2,Z=1. Source jump table47B3AC selects these12 triples.
private static readonly int[] triangleCorners = [
0, 1, 2, 1, 3, 2, 0, 2, 4, 2, 6, 4,
4, 6, 5, 6, 7, 5, 5, 7, 3, 5, 3, 1,
0, 4, 1, 4, 5, 1, 2, 3, 7, 7, 6, 2
];
public static (bool EntityCollision, bool Integrate) DoorCollisionFlags(int hasCollision) =>
hasCollision == -1 ? (DoorEntityCollisionDefault, DoorIntegrationDefault)
: (hasCollision != 0, hasCollision != 0);
/// <summary>
/// Preserve the original inclusive root-distance gate. Normal sphere-mode
/// bodies use 2*boxRadius+sphereRadius, even for a large shape-local cube.
/// Mode2-vs-mode2 instead uses the radius sum and skips the triangle sweep.
/// </summary>
public static bool BroadPhase(DynamicBoxCollider box, DynamicSphereMotion sphere)
{
Validate(box, sphere);
if (!box.CollisionEnabled || !sphere.CollisionEnabled || !sphere.GeometryCollisionEnabled) return false;
var limit = sphere.Mode == 2 ? box.Radius + sphere.Radius : 2 * box.Radius + sphere.Radius;
return OriginalBodySupport.QuickMagnitude(sphere.Position - box.Root) <= limit;
}
public static Vector3[] Corners(DynamicBoxCollider box)
{
ValidateBox(box);
var corners = new Vector3[8];
for (var i = 0; i < corners.Length; i++)
{
var local = new Vector3((i & 4) == 0 ? box.LocalMin.X : box.LocalMax.X,
(i & 2) == 0 ? box.LocalMin.Y : box.LocalMax.Y,
(i & 1) == 0 ? box.LocalMin.Z : box.LocalMax.Z);
corners[i] = Vector3.Transform(local, box.LocalToWorld);
RequireFinite(corners[i]);
}
return corners;
}
public static SupportTriangle[] Triangles(DynamicBoxCollider box)
{
var corners = Corners(box);
return Enumerable.Range(0, 12).Select(i => new SupportTriangle(
corners[triangleCorners[3 * i]], corners[triangleCorners[3 * i + 1]],
corners[triangleCorners[3 * i + 2]], box.Identity, i)).ToArray();
}
/// <summary>
/// Caller supplies mutual exclusion/class gates via pairAllowed and the current
/// source cube/transform. Triangle geometry follows the moving box's current
/// root; no invented relative-door sweep or permanent closed-position mesh.
/// </summary>
public static DynamicCollisionResponse Resolve(DynamicBoxCollider box, DynamicSphereMotion sphere,
Func<DynamicBoxSweep, DynamicCollisionResponse> narrowPhase, bool pairAllowed = true)
{
ArgumentNullException.ThrowIfNull(narrowPhase);
var unchanged = new DynamicCollisionResponse(false, sphere.Position);
if (!pairAllowed || !BroadPhase(box, sphere)) return unchanged;
// EXE47A712..47A72C returns contact directly for a second mode2 entity.
if (sphere.Mode == 2) return new(true, sphere.Position);
var response = narrowPhase(new(box, sphere, Triangles(box)));
if (!response.Contact) return unchanged;
RequireFinite(response.Position);
// EXE47B2EF checks the box's iface1E0 flag after narrowphase; touch events
// can still occur even when its ordinary root response is inhibited.
return new(true, box.InhibitResponse ? sphere.Position : response.Position);
}
private static void Validate(DynamicBoxCollider box, DynamicSphereMotion sphere)
{
ValidateBox(box);
RequireFinite(sphere.Position); RequireFinite(sphere.PreviousPosition);
if (!float.IsFinite(sphere.Radius) || sphere.Radius < 0)
throw new ArgumentOutOfRangeException(nameof(sphere), "Finite nonnegative sphere radius required");
}
private static void ValidateBox(DynamicBoxCollider box)
{
RequireFinite(box.Root); RequireFinite(box.LocalMin); RequireFinite(box.LocalMax);
if (box.LocalMin.X > box.LocalMax.X || box.LocalMin.Y > box.LocalMax.Y || box.LocalMin.Z > box.LocalMax.Z
|| !float.IsFinite(box.Radius) || box.Radius < 0)
throw new ArgumentOutOfRangeException(nameof(box), "Ordered source cube and finite nonnegative radius required");
var m = box.LocalToWorld;
if (new[] { m.M11, m.M12, m.M13, m.M14, m.M21, m.M22, m.M23, m.M24,
m.M31, m.M32, m.M33, m.M34, m.M41, m.M42, m.M43, m.M44 }.Any(v => !float.IsFinite(v))
|| m.M14 != 0 || m.M24 != 0 || m.M34 != 0 || m.M44 != 1)
throw new ArgumentOutOfRangeException(nameof(box), "Finite affine source transform required");
}
private static void RequireFinite(Vector3 v)
{
if (!float.IsFinite(v.X) || !float.IsFinite(v.Y) || !float.IsFinite(v.Z))
throw new ArgumentOutOfRangeException(nameof(v), "Finite source coordinates required");
}
}
+202
View File
@@ -0,0 +1,202 @@
namespace GamePort.Game;
public readonly record struct JetpackBurstState(
int JumpState = 0, float HoldSeconds = 0, float EffectRemaining = 0);
public readonly record struct JetpackBurstInput(
bool Grounded, bool JumpHeld, float VelocityY, float ShadowDistance,
int InventoryState, float Energy, string LevelCode, int GadgetMode,
float DeltaSeconds, float CurrentExtraAccelerationY,
bool EffectAvailable = true, float GravityY = -800);
public enum JetpackPose { None, Jump, Fall, Fly }
public readonly record struct JetpackBurstResult(
JetpackBurstState State, float ImpulseY, float? VelocityYOverride,
float ExtraAccelerationY, JetpackPose Pose, float? RadiusOverride,
bool StartGadget, bool StopGadget, int? MovementModeOverride);
public readonly record struct JetpackEffectResult(
JetpackBurstState State, float Energy, bool Visible);
/// <summary>
/// The jump/jetpack branches of EXE437F90 and effect timer of EXE421FB0.
/// Controller and effect phases are separate: their full-scene order has not
/// been recovered. The caller must explicitly choose an order. Horizontal
/// movement, shadow queries, visuals and sound callbacks belong to the caller.
/// </summary>
public static class JetpackBurst
{
public const float Duration = 8;
public const float HoldThreshold = .4f;
public const float JumpImpulse = 550;
public const float BurstInitialVelocityY = 10;
public const float BurstRadius = 100;
public const float LandingRadius = 60;
public const float EnergyPerSecond = .5f;
/// <summary>
/// Includes the outer update's ordinary grounded/released reset (437B9E).
/// CurrentExtraAccelerationY is required because the expired-effect branch
/// returns before writing acceleration. Results describe this invocation;
/// a newly started/stopped burst changes acceleration on the next call.
/// </summary>
public static JetpackBurstResult Step(JetpackBurstState state, JetpackBurstInput input)
{
ValidateState(state);
ValidateSeconds(input.DeltaSeconds);
RequireFinite(input.VelocityY);
RequireFinite(input.ShadowDistance);
RequireFinite(input.Energy);
RequireFinite(input.CurrentExtraAccelerationY);
RequireFinite(input.GravityY);
ArgumentNullException.ThrowIfNull(input.LevelCode);
var extra = input.CurrentExtraAccelerationY;
JetpackBurstResult Result(float impulse = 0, float? velocity = null,
JetpackPose pose = JetpackPose.None, float? radius = null,
bool start = false, bool stop = false, int? mode = null) =>
new(state, impulse, velocity, extra, pose, radius, start, stop, mode);
if (input.Grounded && !input.JumpHeld)
{
// This path runs ground apply instead of air apply; it does not
// itself clear the effect timer or restore the radius.
state = state with { JumpState = 0 };
return Result(mode: 0);
}
if (state.JumpState < 3)
extra = input.GravityY * 1.33f - input.GravityY;
else
{
if (input.EffectAvailable && state.EffectRemaining <= 0 && state.JumpState is 3 or 4)
{
state = state with { JumpState = 0, EffectRemaining = 0 };
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
}
// The near-floor constants are doubles in the original; the far
// branch uses float .1. Preserve those distinct constant widths.
extra = input.ShadowDistance < 500
? (float)(-input.GravityY - (input.VelocityY < -1 ? .3 : .1) * input.GravityY)
: .1f * input.GravityY - input.GravityY;
}
if (!input.JumpHeld)
{
switch (state.JumpState)
{
case 1:
state = state with { JumpState = 2 };
break;
case 3:
state = state with { JumpState = 4,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(pose: JetpackPose.Fall, stop: true, mode: 1);
case 4:
// Table4387C4 entry3 jumps directly43879A. Only state5's
// entry checks grounded at43878C (outer reset above too).
state = state with { JumpState = 0 };
break;
}
return Result();
}
switch (state.JumpState)
{
case 0:
if (!input.Grounded) return Result(pose: JetpackPose.Fall, stop: true);
state = state with { JumpState = 1, HoldSeconds = 0,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(impulse: JumpImpulse, pose: JetpackPose.Jump);
case 1:
state = state with { HoldSeconds = state.HoldSeconds + input.DeltaSeconds };
if (state.HoldSeconds <= HoldThreshold) return Result();
break;
case 2:
break;
case 3:
if (!input.Grounded) return Result();
state = state with { JumpState = 4,
EffectRemaining = input.EffectAvailable ? 0 : state.EffectRemaining };
return Result(pose: JetpackPose.Fall, radius: LandingRadius, stop: true, mode: 1);
case 5:
if (input.Grounded) state = state with { JumpState = 0 };
return Result();
default:
return Result();
}
// Both the >.4-second and released-then-held branches enter state3
// even when no gadget is available. The next expired-effect guard
// then returns to state0, preserving the ballistic acceleration.
state = state with { JumpState = 3 };
if (!CanStart(input.LevelCode, input.GadgetMode, input.InventoryState, input.Energy)) return Result();
if (input.EffectAvailable) state = state with { EffectRemaining = Duration };
return Result(velocity: BurstInitialVelocityY, pose: JetpackPose.Fly,
radius: input.EffectAvailable ? BurstRadius : null, start: true);
}
public static bool CanStart(string levelCode, int gadgetMode, int inventoryState, float energy)
{
ArgumentNullException.ThrowIfNull(levelCode);
RequireFinite(energy);
if (levelCode == "VR04") return true;
return levelCode is not ("LEV6" or "LV4B" or "LV6A" or "LEV3" or "LV3A" or "LV3B" or "LV3C" or "LV3D")
&& gadgetMode is not (2 or 6 or 7) && energy > 0 && inventoryState is not (0 or 4);
}
/// <summary>
/// Effect421FB0 resets grounded remaining time to0, subtracts dt (including
/// when inactive), then drains only if the stored result is positive.
/// Owner/effect absence leaves timer and energy unchanged. Energy reaching
/// zero does not cancel an already running burst. Visibility is this phase's
/// request; the controller phase does not itself show/hide the effect.
/// </summary>
public static JetpackEffectResult StepEffect(JetpackBurstState state, bool grounded,
float deltaSeconds, float energy, string levelCode,
bool ownerAvailable = true, bool effectAvailable = true)
{
ValidateState(state);
ValidateSeconds(deltaSeconds);
RequireFinite(energy);
ArgumentNullException.ThrowIfNull(levelCode);
if (!ownerAvailable || !effectAvailable) return new(state, energy, false);
var remaining = (grounded ? 0 : state.EffectRemaining) - deltaSeconds;
state = state with { EffectRemaining = remaining };
if (remaining <= 0) return new(state, energy, false);
return new(state, AdjustEnergy(energy, -deltaSeconds * EnergyPerSecond, levelCode), true);
}
/// <summary>EXE42A920 numeric VR01..VR08 immunity and [0,100] clamp. SFX are external.</summary>
public static float AdjustEnergy(float energy, float delta, string levelCode)
{
RequireFinite(energy);
RequireFinite(delta);
ArgumentNullException.ThrowIfNull(levelCode);
// The source compares a big-endian FourCC numerically, not by prefix.
if (levelCode.Length == 4)
{
var code = ((uint)levelCode[0] << 24) | ((uint)levelCode[1] << 16)
| ((uint)levelCode[2] << 8) | levelCode[3];
if (code is >= 0x56523031 and <= 0x56523038) return energy;
}
return Math.Clamp(energy + delta, 0, 100);
}
private static void ValidateState(JetpackBurstState state)
{
if (state.JumpState is < 0 or > 5) throw new ArgumentOutOfRangeException(nameof(state));
RequireFinite(state.HoldSeconds);
RequireFinite(state.EffectRemaining);
}
private static void ValidateSeconds(float seconds)
{
if (!float.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
}
private static void RequireFinite(float value)
{
if (!float.IsFinite(value)) throw new ArgumentOutOfRangeException(nameof(value));
}
}
+57 -27
View File
@@ -4,7 +4,7 @@ using GamePort.Assets;
namespace GamePort.Game;
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump);
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall }
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly }
/// <summary>
/// No-gadget walking checkpoint. Recovered input/arithmetic is described in
@@ -16,9 +16,18 @@ public sealed class LabSimulation
public const float BodyRadius = 24; // Provisional, not a recovered collider dimension.
private readonly SceneCollision collision;
private readonly Vector3 sourceStart;
private readonly float startYaw, modelMinimumY, rootHeight;
private float targetYaw, jumpHeldTime;
private int jumpState;
private readonly float startYaw, modelMinimumY, rootHeight, startFloor;
private float targetYaw, extraAirAcceleration, shadowDistance;
private JetpackBurstState jumpState;
private bool forceFall;
public Func<int>? JetpackInventoryState { get; set; }
public string LevelCode { get; set; } = "LV1B";
public int GadgetMode { get; set; } = -1;
public float Energy { get; set; } = 20;
public float InteractionRadius { get; private set; } = 60;
public bool JetpackEffectVisible { get; private set; }
public float JetpackRemaining => jumpState.EffectRemaining;
public int Bursts { get; private set; }
public float BodyHeight { get; }
public Vector3 Position { get; private set; } // Feet, not original actor root.
public Vector3 Velocity { get; private set; }
@@ -26,13 +35,15 @@ public sealed class LabSimulation
public float Speed { get; private set; }
public bool Grounded { get; private set; }
public PlayerPose Pose => Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
: Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
public int Steps { get; private set; }
public int Jumps { get; private set; }
public int Landings { get; private set; }
public int WallHits { get; private set; }
public float Travel { get; private set; }
public float MaximumRise { get; private set; }
public Func<Vector3, Vector3, float, Vector3>? DynamicRootResolver { get; set; }
public Vector3 ActorRoot => Position + Vector3.UnitY * rootHeight;
public Vector3 CameraEye { get; private set; }
public Vector3 CameraTarget => ActorRoot + new Vector3(0, 99, 0);
@@ -49,7 +60,11 @@ public sealed class LabSimulation
BodyHeight = bounds.Max.Y - bounds.Min.Y;
var floor = collision.GroundHeight(start, 2500)
?? throw new InvalidDataException("No support below GAM startpoint");
rootHeight = start.Y - floor;
startFloor = floor;
// Normal Jimmy PostLoad4236A3..BA and support47BAE1 place the actor
// root at floor+60*1.265. Serialized spawnY is settled by physics.
// Feet collision and sole-based visual placement remain provisional.
rootHeight = OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
Reset();
}
@@ -59,8 +74,10 @@ public sealed class LabSimulation
Position = new(sourceStart.X, floor + SceneCollision.Skin, sourceStart.Z);
Velocity = Vector3.Zero;
Yaw = targetYaw = startYaw;
Speed = jumpHeldTime = 0;
jumpState = 0;
Speed = extraAirAcceleration = shadowDistance = 0;
jumpState = default;
forceFall = JetpackEffectVisible = false;
InteractionRadius = 60; Bursts = 0;
Grounded = true;
Steps = Jumps = Landings = WallHits = 0;
Travel = MaximumRise = 0;
@@ -83,7 +100,7 @@ public sealed class LabSimulation
float lateral = 0;
if (Grounded)
{
if (!input.Jump) jumpState = 0;
InteractionRadius = 60; // Jimmy's ordinary grounded update42469B.
float yawDelta = 0;
if (input.Left) { yawDelta += 20; lateral = -1000; Speed = RecoveredMotion.AddSpeed(Speed); }
else if (input.Right) { yawDelta -= 20; lateral = 1000; Speed = RecoveredMotion.AddSpeed(Speed); }
@@ -97,34 +114,47 @@ public sealed class LabSimulation
var (sin, cos) = Trig(Yaw);
var velocity = new Vector3(-sin * Speed, Velocity.Y, cos * Speed);
if (Grounded) velocity += new Vector3(cos, 0, sin) * (lateral * dt);
var impulse = Vector3.Zero;
if (Grounded && input.Jump && jumpState == 0)
{
impulse.Y = RecoveredMotion.JumpImpulse;
jumpState = 1;
jumpHeldTime = 0;
Grounded = false;
Jumps++;
}
if (!Grounded && jumpState == 1)
{
if (!input.Jump) jumpState = 2;
else if ((jumpHeldTime += dt) > 0.4f) jumpState = 0; // Zero-fuel jetpack path resets to FALL.
}
else if (!Grounded && jumpState == 2 && input.Jump)
jumpState = 0; // Renewed hold enters the same disabled-gadget reset path.
if (collision.GroundHeight(ActorRoot, 2500) is { } shadowFloor)
shadowDistance = MathF.Abs(ActorRoot.Y - shadowFloor - 13);
var air = JetpackBurst.Step(jumpState, new(Grounded, input.Jump, velocity.Y, shadowDistance,
JetpackInventoryState?.Invoke() ?? 0, Energy, LevelCode, GadgetMode, dt, extraAirAcceleration));
jumpState = air.State; extraAirAcceleration = air.ExtraAccelerationY;
var impulse = new Vector3(0, air.ImpulseY, 0);
if (air.ImpulseY != 0) { Grounded = false; Jumps++; }
if (air.VelocityYOverride is { } vertical) velocity.Y = vertical;
if (air.RadiusOverride is { } radius) InteractionRadius = radius;
if (air.Pose == JetpackPose.Fall) forceFall = true;
else if (air.Pose is JetpackPose.Jump or JetpackPose.Fly) forceFall = false;
if (air.StartGadget) Bursts++;
var displacement = RecoveredMotion.Integrate(ref velocity, ref impulse,
RecoveredMotion.Gravity * 0.33f, RecoveredMotion.Gravity, dt);
Vector3.UnitY * extraAirAcceleration, RecoveredMotion.Gravity, dt);
var before = Position;
var result = collision.Move(Position, displacement, BodyRadius, BodyHeight);
Position = result.Position;
if (DynamicRootResolver != null)
{
var root = ActorRoot;
var resolved = DynamicRootResolver(before + Vector3.UnitY * rootHeight, root, InteractionRadius);
if (resolved != root)
{
// Original47A5E0 re-clips against static geometry before storing
// the new root. Here both kernels remain explicitly provisional.
result = collision.Move(Position, resolved - root, BodyRadius, BodyHeight);
Position = result.Position;
}
}
Grounded = result.Grounded && velocity.Y <= 0;
if (Grounded && velocity.Y < 0 || result.HitCeiling && velocity.Y > 0) velocity.Y = 0;
if (Grounded) { extraAirAcceleration = 0; forceFall = false; }
Velocity = velocity;
// Explicit port phase policy: controller, collision, then effect update.
// Original global object iteration order has not yet been matched.
var effect = JetpackBurst.StepEffect(jumpState, Grounded, dt, Energy, LevelCode);
jumpState = effect.State; Energy = effect.Energy; JetpackEffectVisible = effect.Visible;
if (!wasGrounded && Grounded) Landings++;
if (result.HitWall) WallHits++;
Travel += Vector2.Distance(new(before.X, before.Z), new(Position.X, Position.Z));
MaximumRise = Math.Max(MaximumRise, Position.Y - sourceStart.Y + rootHeight);
MaximumRise = Math.Max(MaximumRise, Position.Y - startFloor);
Steps++;
var desired = DesiredEye();
var delta = (desired - CameraEye) * new Vector3(1.6f, 1.2f, 1.6f) * dt;
+167
View File
@@ -0,0 +1,167 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct SupportTriangle(Vector3 A, Vector3 B, Vector3 C, int ShapeId = 0, int PolygonId = 0);
public readonly record struct SupportHit(Vector3 Position, int ShapeId, int PolygonId, float Distance);
public delegate SupportHit? SupportSegmentQuery(Vector3 start, Vector3 end, bool twoSided);
public readonly record struct SupportBody(
Vector3 Position, Vector3 PreviousPosition, Vector3 Velocity, Vector3 Acceleration,
float Radius, float Factor, bool PreventLowering = true);
public readonly record struct SupportResult(
SupportBody Body, bool Supported, bool Landed, SupportHit? Hit, Vector3 SupportAnchor);
/// <summary>
/// Bounded translation of EXE47B890 and its source triangle query. This handles
/// root support, not the wall/ceiling sphere solver or entity collisions. Lookup
/// tables use the recovered initializer constants with modern trig; exact x87
/// table values and full original frame ordering still require comparison.
/// </summary>
public static class OriginalBodySupport
{
public const float JimmyRadius = 60;
public const float JimmyFactor = 1.265f;
public const float GoddardRadius = 130;
public const float GoddardFactor = 0.3f;
private const float TriangleEpsilon = 1.1920928955078125e-7f;
private static readonly float[] sine = BuildSine();
private static readonly ushort[] halfAcos = BuildHalfAcos();
/// <summary>OMT1001FF70: largest component divided by a quantized sine lookup.</summary>
public static float QuickMagnitude(Vector3 vector)
{
RequireFinite(vector);
var x = (double)MathF.Abs(vector.X);
var y = (double)MathF.Abs(vector.Y);
var z = (double)MathF.Abs(vector.Z);
if (x > y) { if (x > z) (x, z) = (z, x); }
else if (y > z) (y, z) = (z, y);
// The original passes 0/0 through _ftol. The port handles zero directly
// instead of depending on an invalid x87 conversion/control-word mode.
if (z == 0) return 0;
var otherSquared = x * x + y * y;
var index = (int)(otherSquared * 16384 / (otherSquared + z * z)) & 0x3fff;
return (float)(z / sine[halfAcos[index] & 0x3fff]);
}
/// <summary>
/// Apply support after motion/wall resolution. The caller captures previous
/// grounded state and clears its current grounded flag before this phase.
/// A successful support preserves horizontal velocity/acceleration, sets their
/// Y components to zero and emits a landing only on an ungrounded-to-grounded step.
/// </summary>
public static SupportResult Resolve(SupportBody body, bool wasGrounded,
SupportSegmentQuery query, bool geometryEnabled = true)
{
ArgumentNullException.ThrowIfNull(query);
RequireFinite(body.Position); RequireFinite(body.PreviousPosition);
RequireFinite(body.Velocity); RequireFinite(body.Acceleration);
if (!float.IsFinite(body.Radius) || body.Radius <= 0 || !float.IsFinite(body.Factor))
throw new ArgumentOutOfRangeException(nameof(body), "Finite support factor and positive finite radius required");
var unchanged = new SupportResult(body, false, false, null, Vector3.Zero);
if (!geometryEnabled) return unchanged;
var product = body.Radius * body.Factor;
var top = MathF.Max(body.Position.Y, body.PreviousPosition.Y);
var motionHit = query(body.PreviousPosition, body.Position, false);
if (motionHit is { } crossed)
top += QuickMagnitude(body.Position - body.PreviousPosition)
- QuickMagnitude(crossed.Position - body.PreviousPosition);
// EXE48D920 is .1f, not .5f. Final root offset always uses r*factor.
var clearance = body.Factor == 1 || body.Factor < 0.1f ? body.Radius : product;
var start = new Vector3(body.Position.X, top + clearance, body.Position.Z);
var end = new Vector3(body.Position.X, body.Position.Y - 2 * body.Radius, body.Position.Z);
var hit = query(start, end, false);
if (hit is not { } floor) return unchanged;
var supportedY = floor.Position.Y + product;
// EXE47BAF3 queries iface208. It rejects a downward root correction,
// independently of vertical velocity, when this flag is enabled.
if (body.PreventLowering && body.Position.Y > supportedY) return unchanged;
var grounded = body with {
Position = new(body.Position.X, supportedY, body.Position.Z),
Velocity = new(body.Velocity.X, 0, body.Velocity.Z),
Acceleration = new(body.Acceleration.X, 0, body.Acceleration.Z)
};
return new SupportResult(grounded, true, !wasGrounded, floor, new Vector3(0, supportedY, 0));
}
/// <summary>
/// EXE469B70/47C6E0 source-winding segment query. Null-material polygons must
/// be included. The caller supplies the statically registered polygons;
/// checkpoint/material and game-specific registration filters are separate.
/// A linear scan replaces the original 260x260 broad phase. Equal-distance
/// selection follows input order, which can differ from original grid order.
/// </summary>
public static SupportHit? Trace(IEnumerable<SupportTriangle> triangles,
Vector3 start, Vector3 end, bool twoSided = false)
{
ArgumentNullException.ThrowIfNull(triangles);
RequireFinite(start); RequireFinite(end);
var direction = end - start;
var length = QuickMagnitude(direction);
if (length == 0) return null;
direction /= length;
SupportHit? nearest = null;
var nearestDistance = length;
foreach (var triangle in triangles)
{
RequireFinite(triangle.A); RequireFinite(triangle.B); RequireFinite(triangle.C);
var edge1 = triangle.B - triangle.A;
var edge2 = triangle.C - triangle.A;
var p = Cross(direction, edge2);
var determinant = Dot(edge1, p);
// Source indices use the opposite sign from a conventional right-
// handed visible-front-face test. Preserve the actual serialized order.
if (twoSided ? MathF.Abs(determinant) < TriangleEpsilon : determinant > -TriangleEpsilon)
continue;
var inverse = 1 / determinant;
var relative = start - triangle.A;
var u = Dot(relative, p) * inverse;
if (u < 0 || u > 1) continue;
var q = Cross(relative, edge1);
var v = Dot(q, direction) * inverse;
if (v < 0 || u + v > 1) continue;
var distance = Dot(q, edge2) * inverse;
// Source accepts the beginning, but rejects its endpoint and equal
// distance candidates. No invented extra ray distance or skin is used.
if (distance < 0 || distance >= length) continue;
var position = start + direction * distance;
var fromStart = QuickMagnitude(position - start);
if (fromStart >= nearestDistance) continue;
nearestDistance = fromStart;
nearest = new SupportHit(position, triangle.ShapeId, triangle.PolygonId, fromStart);
}
return nearest;
}
private static float Dot(Vector3 a, Vector3 b) =>
(float)((double)a.X * b.X + (double)a.Y * b.Y + (double)a.Z * b.Z);
private static Vector3 Cross(Vector3 a, Vector3 b) => new(
(float)((double)a.Y * b.Z - (double)a.Z * b.Y),
(float)((double)a.Z * b.X - (double)a.X * b.Z),
(float)((double)a.X * b.Y - (double)a.Y * b.X));
private static float[] BuildSine()
{
var table = new float[16384];
// DLL100EDC21 uses this stored double, rather than Math.Tau/16384.
for (var i = 0; i < table.Length; i++) table[i] = (float)Math.Sin(i * 0.0003834951969604492);
table[0] = table[8192] = 0; table[4096] = 1; table[12288] = -1;
return table;
}
private static ushort[] BuildHalfAcos()
{
var table = new ushort[16384];
// DLL100EDC8C..100EDCB4 truncates half of the acos angular-unit result.
for (var i = 0; i < table.Length; i++)
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1) * 2607.5945876921437 * 0.5);
return table;
}
private static void RequireFinite(Vector3 vector)
{
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
throw new ArgumentOutOfRangeException(nameof(vector), "Finite source coordinates required");
}
}
+45
View File
@@ -0,0 +1,45 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// Recovered source wall-grid selection and root-support phase, with the port's
/// provisional swept-sphere wall response. This is not the full original solver.
/// The caller supplies body radius/factor from the actual actor class.
/// </summary>
public sealed class OriginalScenePhysics
{
private readonly SceneCollision walls;
private readonly SupportTriangle[] support;
public OriginalScenePhysics(Mesh world)
{
if (world.CollisionPolygons.Length != world.Indices.Length / 3)
throw new InvalidDataException("Prepare source collision polygon metadata before original root support");
walls = new SceneCollision(world, wallsAndCeilingsOnly: true);
support = Enumerable.Range(0, world.Indices.Length / 3)
.Where(i => !Checkpoint(world.CollisionPolygons[i].MaterialName))
.Select(i => new SupportTriangle(world.Vertices[world.Indices[i * 3]].Position,
world.Vertices[world.Indices[i * 3 + 1]].Position, world.Vertices[world.Indices[i * 3 + 2]].Position,
world.CollisionPolygons[i].ShapeId, world.CollisionPolygons[i].PolygonIndex)).ToArray();
}
public SupportResult Step(Vector3 position, Vector3 velocity, float radius, float factor, bool wasGrounded, float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
var previous = position;
velocity += RecoveredMotion.Gravity * dt;
// A capsule with height=diameter is a sphere. Floor polygons are handled
// by the separate original support query, not by this wall response.
var moved = walls.Move(position - Vector3.UnitY * radius, velocity * dt, radius, radius * 2);
position = moved.Position + Vector3.UnitY * radius;
if (moved.HitCeiling && velocity.Y > 0) velocity.Y = 0;
return OriginalBodySupport.Resolve(new(position, previous, velocity, Vector3.Zero, radius, factor),
wasGrounded, (start, end, twoSided) => OriginalBodySupport.Trace(support, start, end, twoSided));
}
private static bool Checkpoint(string? name) => name != null
&& (name.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| name.Length == 7 && name.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && name[6] is >= '1' and <= '9');
}
+46
View File
@@ -0,0 +1,46 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>EXE404523..404D1E keyboard and pointer selection for PracticeYesNo.</summary>
public sealed class PracticePrompt
{
public bool Active { get; private set; }
public int Mode { get; private set; }
public event Action<int, bool>? Chosen;
public void Show(int mode)
{
if (mode is < 0 or > 3) throw new NotSupportedException("Practice mode is outside recovered VR04..VR01 mapping");
if (Active) return;
Mode = mode; Active = true;
}
public void Key(uint scancode, Vector2 pointer)
{
if (!Active) return;
if (scancode == 28) Choose(true); // Y.
else if (scancode == 17) Choose(false); // N.
else if (scancode is 40 or 88) Choose(Yes(pointer)); // Enter / keypad Enter.
}
public void Click(Vector2 pointer)
{
if (!Active) return;
if (Yes(pointer)) Choose(true);
else if (pointer.X > 315 && pointer.X < 395 && pointer.Y > 240 && pointer.Y < 300) Choose(false);
}
public static string Destination(int mode) => mode switch
{
0 => "VR04.gam", 1 => "VR03.gam", 2 => "VR02.gam", 3 => "VR01.gam",
_ => throw new NotSupportedException("Unrecovered practice destination")
};
private void Choose(bool accepted)
{
Active = false;
Chosen?.Invoke(Mode, accepted);
}
private static bool Yes(Vector2 p) => p.X > 225 && p.X < 305 && p.Y > 240 && p.Y < 300;
}
+9 -1
View File
@@ -25,14 +25,22 @@ public sealed class SceneCollision
public float DistanceSquared => Vector3.DistanceSquared(Capsule, Surface);
}
public SceneCollision(Mesh mesh)
public SceneCollision(Mesh mesh, bool wallsAndCeilingsOnly = false)
{
if (mesh.Indices.Length % 3 != 0) throw new ArgumentException("Collision indices must be triangles", nameof(mesh));
if (wallsAndCeilingsOnly && mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original wall grid requires prepared source polygon normals");
var result = new List<Triangle>();
// Render visibility is not a proven collision mask. Original null-material
// proxies remain present and block movement in this provisional policy.
for (var i = 0; i < mesh.Indices.Length; i += 3)
{
// EXE4798B3 registers only stored normal.Y<.7 in the wall/ceiling
// grid. Render normals and a recomputed cross product differ.
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].Normal.Y >= .7f) continue;
if (wallsAndCeilingsOnly && mesh.CollisionPolygons[i / 3].MaterialName is { } material
&& (material.Equals("cstart", StringComparison.OrdinalIgnoreCase)
|| material.Length == 7 && material.StartsWith("ccheck", StringComparison.OrdinalIgnoreCase) && material[6] is >= '1' and <= '9')) continue;
if (mesh.Indices[i] >= mesh.Vertices.Length || mesh.Indices[i + 1] >= mesh.Vertices.Length
|| mesh.Indices[i + 2] >= mesh.Vertices.Length)
throw new ArgumentException("Collision index outside vertex table", nameof(mesh));
+527
View File
@@ -0,0 +1,527 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Mutable source-entity state for the reconstructed trigger/camera interpreter.</summary>
public sealed class DirectorActor
{
public GamEntity? SourceGam { get; }
public string Tag { get; }
public string Kind { get; }
public bool ConstructorCreated => SourceGam is null;
public Vector3 Position { get; internal set; }
public Vector3 Rotation { get; internal set; }
public bool Visible { get; internal set; }
public bool Active { get; internal set; }
public string Animation { get; internal set; } = "STOP";
public int AIstate { get; internal set; }
public float Speed { get; internal set; }
public string? Patrol { get; internal set; }
public int SpriteRevision { get; internal set; }
public bool SpritePlaying { get; internal set; }
internal DirectorActor(GamEntity? source, string tag, string kind, Vector3 position)
{
SourceGam = source; Tag = tag; Kind = kind; Position = position;
Rotation = source?.Rotation ?? Vector3.Zero;
Visible = source?.Integer("InitiallyVisible", -1) != 0;
Active = source?.Integer("InitallyActive", source?.Integer("Activated", 1) ?? 1) != 0;
if (kind == "3PIC") Visible = Active;
AIstate = source?.Integer("AIState", kind == "3DOG" ? 4 : 0) ?? (kind == "3DOG" ? 4 : 0);
Speed = kind switch { "3CAR" => 200, "3DOG" => 1, _ => 0 }; // EXE413BCB /41C8FA.
if (kind == "3DOG") Animation = "none"; // Initial pose selection is not recovered; no fabricated STOP alias.
Patrol = source?.Text("PatrolPoint");
SpritePlaying = (source?.Integer("Activated") ?? 0) != 0;
}
}
public sealed record DirectorIssue(string Tag, string Kind, string Detail);
/// <summary>
/// Recovered synchronous AI-trigger dispatch and audio-duration-driven CAM/MCA
/// sequence. See lab-progression.md. Actor physics/AI, sprites, inventory effects
/// and fades remain separate consumers; unsupported execution is reported.
/// </summary>
public sealed class SceneDirector
{
private readonly GamLevel level;
private readonly TaskStates tasks;
private readonly Func<string, int, double> soundDuration;
private readonly Dictionary<string, GamEntity> entities = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DirectorActor> actors = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<int, int> activations = [];
private readonly Queue<(string Tag, string? Caller)> pending = [];
private readonly List<DirectorIssue> issues = [];
private readonly HashSet<string> reported = new(StringComparer.Ordinal);
private readonly HashSet<string> patrolConsumers = new(StringComparer.OrdinalIgnoreCase);
private Shot? shot;
private bool draining, skipping;
private string? blockedNext, blockedCaller;
private sealed class Shot(GamEntity source, int index, DirectorActor target, double duration)
{
public GamEntity Source { get; } = source;
public int Index { get; } = index; // -1 for a single CAM.
public DirectorActor Target { get; } = target;
public double Duration { get; } = duration;
public double Elapsed { get; set; }
}
public List<DirectorActor> Actors { get; } = [];
public IReadOnlyList<DirectorIssue> Issues => issues;
public bool Controlled => Equal(ControlledTag, level.Player?.Tag);
public string? ControlledTag { get; private set; }
public bool InventoryEnabled { get; private set; } = true;
public bool Blocked { get; private set; }
public bool Playing => shot is not null;
public string? CurrentTag => shot?.Source.Tag;
public int CurrentShot => shot?.Index ?? -1;
public Vector3? CameraEye { get; private set; }
public Vector3? CameraTarget { get; private set; }
public event Action<string, int>? Speech;
public event Action<DirectorActor>? ActorChanged;
public event Action<string, string>? Unsupported;
public SceneDirector(GamLevel level, TaskStates tasks, Func<string, int, double> soundDuration)
{
this.level = level;
this.tasks = tasks;
this.soundDuration = soundDuration;
foreach (var entity in level.Entities)
{
if (entity.Tag is not { Length: > 0 } tag) continue;
// Original tag lookup scans in object-list order and returns the first.
entities.TryAdd(tag, entity);
var actor = new DirectorActor(entity, tag, entity.Kind, entity.Position);
Actors.Add(actor);
actors.TryAdd(tag, actor);
}
// Jimmy creates Goddard in EXE423C98->41C810, independently of GAM.
// LV1B's explicit SITGODDARD command positions him at gstart before his
// first shot. This initial binding is a documented placement inference.
if (!actors.ContainsKey("C3DGODDARD") && entities.TryGetValue("gstart", out var goddardStart))
{
var goddard = new DirectorActor(null, "C3DGODDARD", "3DOG", goddardStart.Position);
Actors.Add(goddard);
actors.Add(goddard.Tag, goddard);
}
ControlledTag = level.Player?.Tag;
foreach (var actor in Actors) ApplyTask(actor, tasks.Get(actor.SourceGam?.Text("TaskName")));
tasks.Assigned += OnTaskAssigned;
}
public void Begin(GamEntity start)
{
if (start.Kind != "STRT") throw new ArgumentException("Expected original STRT entity", nameof(start));
shot = null; pending.Clear(); activations.Clear();
Blocked = skipping = false; blockedNext = blockedCaller = null;
CameraEye = CameraTarget = null;
InventoryEnabled = true;
foreach (var actor in Actors)
{
if (actor.SourceGam is not { } source) continue;
var initial = new DirectorActor(source, actor.Tag, actor.Kind, source.Position);
actor.Position = initial.Position; actor.Rotation = initial.Rotation;
actor.Visible = initial.Visible; actor.Active = initial.Active;
actor.Animation = initial.Animation; actor.AIstate = initial.AIstate;
actor.Speed = initial.Speed; actor.Patrol = initial.Patrol;
actor.SpritePlaying = initial.SpritePlaying; actor.SpriteRevision++;
ApplyTask(actor, tasks.Get(source.Text("TaskName")));
}
var trigger = start.Text("StartTrigger");
ControlledTag = IsNone(trigger) ? level.Player?.Tag : null; // EXE4426B7.
if (!IsNone(trigger)) Trigger(trigger!, start.Tag);
}
public void Trigger(string tag, string? callerTag = null)
{
if (tag.Length > 100) throw new ArgumentException("Trigger tag exceeds original field size", nameof(tag));
pending.Enqueue((tag, callerTag));
Drain();
}
/// <summary>
/// Port contact query: point against the source trigger radius. Original
/// collision callback selection/radius combination is not yet reproduced.
/// The actual AI trigger's actor, animation and task-child checks are retained.
/// </summary>
public void Touch(string activatorTag, Vector3 position)
{
if (!Finite(position)) throw new ArgumentOutOfRangeException(nameof(position));
foreach (var entity in level.Entities)
{
if (entity.Kind != "3AIT" || entity.Integer("TouchActivated") == 0) continue;
var radius = entity.Number("Radius");
if (radius < 0 || Vector3.DistanceSquared(position, entity.Position) > radius * radius) continue;
if (entity.Tag is { } tag) pending.Enqueue((tag, activatorTag));
}
Drain();
}
public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag);
public void RegisterPatrolConsumer(string tag) => patrolConsumers.Add(tag);
public void SyncActor(string tag, Vector3 position, Vector3 rotation)
{
if (!Finite(position) || !Finite(rotation)) throw new ArgumentOutOfRangeException(nameof(position));
if (!actors.TryGetValue(tag, out var actor)) return;
actor.Position = position; actor.Rotation = rotation;
if (shot is not null) UpdateCamera(shot);
}
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
foreach (var actor in Actors)
if (actor.Kind == "3TRO") actor.Rotation = actor.Rotation with { Y = (actor.Rotation.Y + dt * 90) % 360 };
var remaining = (double)dt;
for (var count = 0; count < 256 && shot is not null; count++)
{
var current = shot;
var untilEnd = Math.Max(0, current.Duration - current.Elapsed);
var consumed = Math.Min(remaining, untilEnd);
current.Elapsed += consumed;
remaining -= consumed;
UpdateCamera(current);
if (current.Elapsed + 1e-8 < current.Duration) return;
FinishShot(current);
if (remaining <= 0 && (shot is null || shot.Duration > 0)) return;
}
if (shot is not null && shot.Duration <= 0)
Block(shot.Source, "Zero-duration scene sequence exceeded bounded dispatch", shot.Source.Text("NextTrigger"));
}
/// <summary>Escape/Space original chain skip: preserve AI/toggle actions and skip remaining speech/shots.</summary>
public void Skip()
{
skipping = true;
if (Blocked)
{
Blocked = false;
if (blockedNext is { } next) pending.Enqueue((next, blockedCaller));
blockedNext = blockedCaller = null;
}
if (shot is { } current)
{
shot = null;
DeactivateAnimation(current);
if (current.Index >= 0) FinishMulti(current.Source);
else EnqueueNext(current.Source);
}
Drain();
}
private void Drain()
{
if (draining || Blocked) return;
draining = true;
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
for (var count = 0; pending.Count > 0 && !Blocked; count++)
{
var (tag, caller) = pending.Dequeue();
if (IsNone(tag)) continue;
if (Equal(tag, "default")) { RestoreControl(); continue; }
if (count >= 256 || !visited.Add(tag))
{
Report(tag, "cycle", "Synchronous trigger cycle or dispatch limit");
pending.Clear(); Blocked = true; return;
}
if (!entities.TryGetValue(tag, out var entity))
{
Report(tag, "missing", "Trigger target absent from original GAM");
Blocked = true; return;
}
switch (entity.Kind)
{
case "3AIT": ExecuteAi(entity, caller); break;
case "3CAM": StartCamera(entity, -1); break;
case "3MCA": StartMulti(entity); break;
default: Block(entity, "Trigger class execution not recovered", entity.Text("NextTrigger")); break;
}
}
}
finally { draining = false; }
}
private void ExecuteAi(GamEntity entity, string? caller)
{
var by = entity.Text("ActivateBy");
var isA = entity.Text("IsA");
var matchesActor = !IsNone(by) && Equal(by, caller);
if (!IsNone(isA))
{
Report(entity.Tag!, entity.Kind, "IsA predicate requires original class hierarchy; trigger not executed");
return;
}
if (!IsNone(by) && !matchesActor) return;
var byAnimation = entity.Text("ActivateByAnim");
if (!IsNone(byAnimation) && (!actors.TryGetValue(caller ?? "", out var callerActor)
|| !Equal(byAnimation, callerActor.Animation))) return;
var times = entity.Integer("TimesToTrigger", -1);
var number = activations.GetValueOrDefault(entity.Offset) + 1;
activations[entity.Offset] = number;
if (times != -1 && number > times) return;
SetControl(entity);
var targetTag = entity.Text("AITarget");
if (!IsNone(targetTag))
{
if (!actors.TryGetValue(targetTag!, out var target))
Report(entity.Tag!, entity.Kind, $"AI target {targetTag} absent");
else
{
var hide = entity.Integer("AIHideObj", -1);
if (hide != -1) target.Visible = hide == 0;
var positionTag = entity.Text("AINewPos");
if (!IsNone(positionTag))
{
if (actors.TryGetValue(positionTag!, out var marker)) target.Position = marker.Position;
else Report(entity.Tag!, entity.Kind, $"AINewPos {positionTag} absent");
}
var animation = entity.Text("AIAnim");
if (!IsNone(animation)) target.Animation = animation!;
target.AIstate = entity.Integer("AIState", target.AIstate);
var speed = entity.Integer("AISpeed", -1);
if (speed != -1) target.Speed = speed;
var patrol = entity.Text("AIPatrol");
if (!IsNone(patrol)) target.Patrol = patrol;
var yaw = entity.Number("AINewRotY", -1);
if (yaw != -1) target.Rotation = target.Rotation with { Y = yaw };
ActorChanged?.Invoke(target);
if (target.AIstate == 3 && (target.Kind is "3DOG" or "3CAR") && !patrolConsumers.Contains(target.Tag))
Report(target.Tag, target.Kind, "Patrol motion/arrival is not yet reconstructed; actor-state callback emitted");
}
}
Toggle(entity);
var conditional = ConditionalChild(entity);
// EXE40CB43: the nearby teleport explanation advances the task before its camera chain.
if (Equal(entity.Tag, "teleportexplanation") && tasks.Get("SCENE") is 30 or 31)
tasks.SetExisting("SCENE", 35);
pending.Enqueue((conditional ?? entity.Text("NextTrigger") ?? "none", entity.Tag));
}
private string? ConditionalChild(GamEntity entity)
{
var state = tasks.Get(entity.Text("TaskName"));
for (var i = 0; i < 5; i++)
{
var desired = entity.Integer($"ActivateState{i}", -1);
var target = entity.Text($"ActivateObject{i}");
if (desired != -1 && desired == state && !IsNone(target) && entities.ContainsKey(target!)) return target;
}
return null;
}
private void StartMulti(GamEntity entity)
{
SetControl(entity);
Toggle(entity);
if (skipping) { FinishMulti(entity); return; }
StartCamera(entity, 0, applyCommon: false);
}
private void StartCamera(GamEntity entity, int index, bool applyCommon = true)
{
if (applyCommon) { SetControl(entity); Toggle(entity); }
if (entity.Integer("DeactivateInv") != 0) InventoryEnabled = false;
if (skipping)
{
if (index >= 0) FinishMulti(entity);
else EnqueueNext(entity);
return;
}
var suffix = index < 0 ? "" : index.ToString(System.Globalization.CultureInfo.InvariantCulture);
var targetTag = entity.Text("CameraTarget" + suffix);
var sound = entity.Integer("SoundIndex" + suffix, -1);
if (index >= 8 || IsNone(targetTag) || sound == -1)
{
if (index >= 0) FinishMulti(entity);
else Block(entity, "CAM target/sound unavailable", entity.Text("NextTrigger"));
return;
}
if (!actors.TryGetValue(targetTag!, out var target))
{
Block(entity, $"Camera target {targetTag} absent", entity.Text("NextTrigger"));
return;
}
var database = entity.Text("SoundDatabase") ?? "none";
var duration = soundDuration(database, sound);
if (!double.IsFinite(duration) || duration < 0)
{
Block(entity, $"Missing original sound duration {database}:{sound}", entity.Text("NextTrigger"));
return;
}
var animation = entity.Text(index < 0 ? "TargetActAnim" : "TargetAnim" + suffix);
if (!IsNone(animation)) { target.Animation = animation!; ActorChanged?.Invoke(target); }
shot = new Shot(entity, index, target, duration);
UpdateCamera(shot);
Speech?.Invoke(database, sound);
}
private void FinishShot(Shot current)
{
if (shot != current) return;
shot = null;
DeactivateAnimation(current);
if (current.Index < 0) EnqueueNext(current.Source);
else StartCamera(current.Source, current.Index + 1, applyCommon: false);
Drain();
}
private void DeactivateAnimation(Shot current)
{
var animation = current.Source.Text("TargetDeactAnim");
if (!IsNone(animation))
{
current.Target.Animation = animation!;
ActorChanged?.Invoke(current.Target);
}
}
private void FinishMulti(GamEntity entity)
{
// MCA finisher4311F0 preserves 'none'/NULL semantics for PlayerControlled.
SetControl(entity);
EnqueueNext(entity);
}
private void EnqueueNext(GamEntity entity)
{
pending.Enqueue((entity.Text("NextTrigger") ?? "none", entity.Tag));
}
private void UpdateCamera(Shot current)
{
var source = current.Source;
var target = current.Target;
var t = (float)current.Elapsed;
if (current.Index >= 0)
{
var suffix = current.Index.ToString(System.Globalization.CultureInfo.InvariantCulture);
var type = source.Integer("CameraType" + suffix);
var local = type switch
{
1 => new Vector3(0, 140, MathF.Max(100, 300 - 15 * t)),
2 => new Vector3(0, 240, MathF.Max(100, 500 - 35 * t)),
3 => new Vector3(200, 240, MathF.Max(100, 700 - 55 * t)),
4 => new Vector3(-200, 190, MathF.Max(100, 700 - 55 * t)),
_ => new Vector3(0, 40, 200),
};
CameraEye = TransformLocal(target, local);
CameraTarget = target.Position + Vector3.UnitY * (source.Number("LookatVOffset" + suffix, 100) - 60);
return;
}
if (source.Integer("CameraType") == 2)
{
CameraEye = source.Position;
CameraTarget = target.Position;
return;
}
var minimum = source.Number("MinDist", 100);
var maximum = source.Number("MaxDist", 1000);
var distance = Math.Clamp(source.Number("InitialDist", 200) - source.Number("ZoomSpeed") * t,
MathF.Min(minimum, maximum), MathF.Max(minimum, maximum));
var offset = new Vector3(source.Number("TargOffsetX"), source.Number("TargOffsetY"), source.Number("TargOffsetZ"));
if (source.Integer("ViewFromCamera") == 0)
{
CameraEye = TransformLocal(target, offset with { Z = distance });
CameraTarget = target.Position + Vector3.UnitY * source.Number("LookVoffset");
}
else
{
var point = TransformLocal(target, offset);
var direction = source.Position - point;
if (direction.LengthSquared() < .000001f)
{
Report(source.Tag!, source.Kind, "CAM eye coincides with target offset; original normalization undefined");
CameraEye = source.Position;
}
else CameraEye = point + Vector3.Normalize(direction) * distance;
CameraTarget = point;
}
}
private static Vector3 TransformLocal(DirectorActor target, Vector3 point)
{
// Original OMT Euler local-to-world routine472980; quantized modern
// sin/cos here retains the source angular grid, not x87 bit identity.
var (sx, cx) = LabSimulation.Trig(target.Rotation.X);
var (sy, cy) = LabSimulation.Trig(target.Rotation.Y);
var (sz, cz) = LabSimulation.Trig(target.Rotation.Z);
var x = point.X * cz - point.Y * sz;
var y = point.X * sz + point.Y * cz;
var z = point.Z;
var pitchedY = y * cx - z * sx;
var pitchedZ = y * sx + z * cx;
return target.Position + new Vector3(x * cy - pitchedZ * sy, pitchedY, x * sy + pitchedZ * cy);
}
private void SetControl(GamEntity entity)
{
var control = entity.Text("PlayerControlled");
if (IsNone(control)) return;
if (Equal(control, "NULL")) ControlledTag = null;
else if (actors.ContainsKey(control!)) ControlledTag = control;
else Report(entity.Tag!, entity.Kind, $"PlayerControlled target {control} absent");
}
private void Toggle(GamEntity entity)
{
var tag = entity.Text("ToggleObject");
var toggle = entity.Integer("Toggle", -1);
if (toggle is not (0 or 1) || IsNone(tag)) return;
if (!actors.TryGetValue(tag!, out var actor)) { Report(entity.Tag!, entity.Kind, $"ToggleObject {tag} absent"); return; }
actor.Visible = actor.Active = toggle == 1;
if (actor.Kind == "3ANI") { actor.SpritePlaying = toggle == 1; actor.SpriteRevision++; }
ActorChanged?.Invoke(actor);
}
private void RestoreControl()
{
shot = null;
ControlledTag = level.Player?.Tag;
InventoryEnabled = true;
CameraEye = CameraTarget = null;
skipping = false;
// Original DEFAULT invokes a Jimmy help/inventory callback at SCENE30;
// it does not assign a new task value or complete the lab.
}
private void OnTaskAssigned(string name, int state)
{
foreach (var actor in Actors)
if (Equal(actor.SourceGam?.Text("TaskName"), name)) ApplyTask(actor, state);
}
private void ApplyTask(DirectorActor actor, int state)
{
if (actor.SourceGam is not { } source) return;
// LOAD.RequiredLevel belongs to its RequiredTask contact gate, not the
// animated actor's TaskName activation contract. Applying the latter
// here disables the lab exit even when SCENE reaches60.
if (source.Kind == "LOAD") return;
var active = source.Kind == "3PIC" ? TaskActivation.Pickup(source, state) : TaskActivation.Animated(source, state);
if (active.HasValue) { actor.Active = actor.Visible = active.Value; ActorChanged?.Invoke(actor); }
}
private void Block(GamEntity source, string detail, string? next)
{
shot = null; Blocked = true;
blockedNext = next; blockedCaller = source.Tag;
Report(source.Tag ?? "?", source.Kind, detail);
}
private void Report(string tag, string kind, string detail)
{
if (!reported.Add(tag + "\0" + kind + "\0" + detail)) return;
issues.Add(new DirectorIssue(tag, kind, detail));
Unsupported?.Invoke(tag, kind);
}
private static bool Equal(string? a, string? b) => a is not null && b is not null && string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool IsNone(string? value) => string.IsNullOrEmpty(value) || Equal(value, "none");
private static bool Finite(Vector3 p) => float.IsFinite(p.X) && float.IsFinite(p.Y) && float.IsFinite(p.Z);
}
+240
View File
@@ -0,0 +1,240 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
public sealed record LevelTransition(string LevelFile, string StartPoint, float FadeTime, int FadeType);
/// <summary>
/// Recovered star/trophy/lab jetpack contacts, Carl talk dispatch and LOAD gates. Uses source root spheres
/// with recovered lookup magnitude (x87 table identity/exclusions/box contacts pending).
/// Other pickup effects and general AI sensing remain explicit unsupported cases.
/// </summary>
public sealed class SceneInteractions
{
private readonly SceneDirector director;
private readonly TaskStates tasks;
private readonly OriginalSave initial;
private readonly string levelCode;
private readonly int[] itemStates;
private readonly HashSet<int> contacts = [];
private readonly HashSet<string> unsupported = [];
public int Score { get; private set; }
public float Energy { get; private set; }
public int CurrentObjective { get; private set; }
public string ReturnLevel { get; private set; }
public string ReturnStart { get; private set; }
public SceneInventory Inventory { get; }
public IReadOnlyCollection<string> Unsupported => unsupported;
public event Action<GamEntity, int>? Collected;
public event Action<LevelTransition>? Transition;
public event Action<int>? SoundEffect;
public event Action<int>? PracticeRequested;
public event Action<Vector3>? CheckpointCaptured;
public event Action<DirectorActor, string>? ConversationStarted;
public event Action<int>? ObjectiveChanged;
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save, string? levelCode = null)
{
this.director = director; this.tasks = tasks; initial = save;
this.levelCode = levelCode ?? save.LevelCode;
Inventory = new SceneInventory(save.InventoryStates);
itemStates = save.ItemStates.ToArray(); Score = save.Score;
Energy = save.PlayerValue;
CurrentObjective = save.OtherCounter;
ReturnLevel = save.ReturnLevel; ReturnStart = save.ReturnStart;
tasks.Assigned += OnTaskAssigned;
Reset();
}
public void UpdateEnergy(float energy)
{
if (!float.IsFinite(energy)) throw new ArgumentOutOfRangeException(nameof(energy));
Energy = energy;
}
public OriginalSave Snapshot() => initial with { Score = Score, PlayerValue = Energy, ItemStates = itemStates.ToArray(),
InventoryStates = Inventory.Snapshot(), Tasks = tasks.Snapshot(), OtherCounter = CurrentObjective,
ReturnLevel = ReturnLevel, ReturnStart = ReturnStart };
public void SetReturnContext(string levelFile, string start)
{
if (levelFile.Length > 100 || start.Length > 100 || !levelFile.EndsWith(".gam", StringComparison.OrdinalIgnoreCase)
|| levelFile.Contains('/') || levelFile.Contains('\\')) throw new ArgumentException("Invalid original return level/start");
ReturnLevel = levelFile; ReturnStart = start;
}
/// <summary>Call after SceneDirector.Begin, including a scene reset.</summary>
public void Reset()
{
contacts.Clear();
HideCollected();
ApplyCarlTask();
}
public void HideCollected()
{
foreach (var actor in director.Actors)
if (actor.SourceGam is { Kind: "3PIC" } source && source.Integer("PickupIndex", -1) is var id
&& id > 0 && id < itemStates.Length && itemStates[id] != 0) actor.Active = actor.Visible = false;
}
public void Update(Vector3 activePlayerRoot, float playerRadius = 60)
{
if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z)
|| !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot));
if (!director.Controlled) return;
HideCollected();
foreach (var actor in director.Actors)
{
if (!director.Controlled) break;
if (actor.SourceGam is not { } source || source.Kind is not ("3PIC" or "3TRO" or "LOAD" or "3CAR")) continue;
// C3DFriend update41B972..988 calls the talk dispatcher every update
// in state0, even when a prior contact found no matching TalkTrigger.
if (source.Kind == "3CAR" && actor.Active && actor.AIstate == 0)
{
TryBeginCarlTalk(actor, source);
if (!director.Controlled) break;
}
// Carl InitObject413E2F..45 sets radius100 and support factor0.75.
var radius = playerRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius"));
var overlaps = actor.Active && OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
if (!overlaps) { contacts.Remove(source.Offset); continue; }
if (!contacts.Add(source.Offset)) continue;
switch (source.Kind)
{
case "3PIC": CollectPickup(actor, source, activePlayerRoot); break;
case "3CAR":
//40A44C..45C/40A676..68D: target contact in state6 sets0.
var player = director.Actors.FirstOrDefault(a => a.Kind == "3JIM");
if (actor.AIstate == 6 && Equal(source.Text("TargetName"), player?.Tag))
{
actor.AIstate = 0;
TryBeginCarlTalk(actor, source);
}
break;
case "3TRO":
Score = Math.Max(0, unchecked(Score + 300));
actor.Active = actor.Visible = false;
SoundEffect?.Invoke(230);
Collected?.Invoke(source, 300);
break;
case "LOAD":
if (!TaskActivation.Load(source, tasks)) break;
var destination = source.Text("LevelName") ?? "none";
var start = source.Text("StartPoint") ?? "none";
if (string.Equals(destination, "RETURN", StringComparison.OrdinalIgnoreCase))
{ destination = ReturnLevel; start = ReturnStart; }
if (string.Equals(destination, "none", StringComparison.OrdinalIgnoreCase))
{ unsupported.Add("RETURN has no stored destination"); break; }
Transition?.Invoke(new(destination, start, source.Number("FadeTime"), source.Integer("FadeType")));
break;
}
}
}
private void CollectPickup(DirectorActor actor, GamEntity source, Vector3 playerRoot)
{
var id = source.Integer("PickupIndex", -1);
// The source tag is SHRINKRAY; original objective art120 calls this
// pickup the jet pack, matching group0/item3 and powered-jump ownership.
var jetpack = Equal(source.Tag, "SHRINKRAY");
var ordinaryStar = id is >= 3000 and < 4000 && source.Integer("PointValue") == 5;
if (id is <= 0 or >= OriginalSave.ItemCount || !(ordinaryStar || jetpack && source.Integer("PointValue") == 50)
|| source.Integer("PIC_NUMBER", -1) != -1
|| source.Integer("PickedUpIndex", -1) != -1 || source.Integer("RequiredPicNum", -1) != -1)
{ unsupported.Add($"Pickup {source.Tag}@0x{source.Offset:X}: inventory/special effect not reconstructed"); return; }
if (itemStates[id] != 0) return;
itemStates[id] = 1; // EXE435E11..31: ordinary acquired state, hide and disable.
actor.Active = actor.Visible = false;
//435FCB invokes the special hook before the positive PointValue award.
if (jetpack && tasks.Get("SCENE") == 35)
{
//436603..67E: Jimmy checkpoint capture42AF00, task35->50, group0
//item3 state1, practice prompt0, then gadget selection3. The checkpoint
//event does not assign the still-unidentified TSK StoredVector.
CheckpointCaptured?.Invoke(playerRoot);
tasks.SetExisting("SCENE", 50);
Inventory.SetState(0, 3, 1);
PracticeRequested?.Invoke(0);
Inventory.SelectGadget(3);
}
var points = source.Integer("PointValue");
Score = Math.Max(0, unchecked(Score + points));
var sound = source.Integer("SoundIndex", -1);
if (sound >= 0) SoundEffect?.Invoke(sound);
Collected?.Invoke(source, points);
var next = source.Text("NextTrigger");
if (!string.IsNullOrEmpty(next) && !string.Equals(next, "none", StringComparison.OrdinalIgnoreCase))
director.Trigger(next, source.Tag);
}
private void TryBeginCarlTalk(DirectorActor actor, GamEntity source)
{
var state = tasks.Get(source.Text("TaskName"));
for (var i = 0; i < 5; i++)
{
var tag = source.Text("TalkTrigger" + i);
var required = source.Integer("TalkState" + i, -1);
if (required == -1 || required != state && required != -2 || string.IsNullOrEmpty(tag)
|| Equal(tag, "none") || director.FindActor(tag) is null) continue;
//41B7B0 calls derived slot180 BEFORE dispatching the selected object.
//Carl413E50 calls base41B810 (+100) then changes SCENE milestones.
Score = Math.Max(0, unchecked(Score + 100));
var scene = tasks.Get("SCENE");
var next = scene switch { 50 => 60, 65 => 70, 270 => 280, _ => scene };
if (next != scene) tasks.SetExisting("SCENE", next);
director.Trigger(tag, tag); //Original target receives itself as caller.
actor.AIstate = 9;
ConversationStarted?.Invoke(actor, tag);
return;
}
}
private void OnTaskAssigned(string name, int value)
{
HideCollected();
if (Equal(name, "SCENE"))
{
//45F990 jump tables ->406F50: clear the transient objective flags,
//select this objective and set its flag1; TSK writes selector4F8194.
var objective = ObjectiveForScene(value);
if (objective != 0) { CurrentObjective = objective; ObjectiveChanged?.Invoke(objective); }
ApplyCarlTask();
}
}
private void ApplyCarlTask()
{
//Carl's override413F30 follows generic activation; LV1B branch414068.
//Other levels' custom visibility/position policies are not ported here.
if (levelCode != "LV1B") return;
var state = tasks.Get("SCENE");
foreach (var actor in director.Actors.Where(a => a.Kind == "3CAR" && Equal(a.SourceGam?.Text("TaskName"), "SCENE")))
{
if (state is < 0 or > 60) { actor.Visible = actor.Active = false; continue; }
if (state > 30 && director.FindActor("CARLESC3") is { } marker)
{
actor.AIstate = 6;
actor.Position = marker.Position;
}
//At60 the override leaves the generic activation result unchanged.
if (state < 60) actor.Active = actor.Visible = true;
}
}
private static bool Equal(string? a, string? b) => a is not null && b is not null
&& string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
public static int ObjectiveForScene(int scene) => scene switch
{
35 => 1, 50 => 2, 60 => 3, 70 => 4, 90 => 5, 100 => 6, 108 => 7,
140 or 141 => 8, 160 => 9, 162 => 10, 168 => 11, 178 => 12,
200 => 13, 205 => 14, 210 => 15, 220 => 16, 230 => 17,
250 => 18, 260 => 19, 270 => 20, 280 => 21, 290 => 22,
300 => 23, 310 => 24, 320 => 25, 330 => 26, 340 => 27,
350 => 28, 360 => 29, 380 => 30, 390 => 31, 400 => 32,
410 => 33, 420 => 34, 430 => 35, 460 => 36, 470 => 37,
480 => 38, 500 => 39, 510 => 40, 520 => 41, 540 => 42, 550 => 43,
_ => 0,
};
}
+43
View File
@@ -0,0 +1,43 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>
/// The two inventory-state groups serialized by the original TSK writer.
/// Preserves unknown existing values; this is not a complete inventory UI or
/// implementation of the separate 29-item consumable-count group.
/// </summary>
public sealed class SceneInventory
{
private readonly int[] states;
public int SelectedGadget { get; private set; } = -1;
public event Action<int>? GadgetSelected;
public SceneInventory(IEnumerable<int> savedStates)
{
states = savedStates.ToArray();
if (states.Length != OriginalSave.InventoryCount)
throw new ArgumentException("Expected the original 19 inventory states", nameof(savedStates));
}
public int State(int group, int item) => states[Offset(group, item)];
public void SetState(int group, int item, int state) => states[Offset(group, item)] = state;
public void SelectGadget(int item)
{
if (item != -1 && (item is < 0 or >= 9 || State(0, item) == 0))
throw new ArgumentOutOfRangeException(nameof(item), "Gadget is outside the recovered group or unavailable");
SelectedGadget = item;
GadgetSelected?.Invoke(item);
}
public int[] Snapshot() => states.ToArray();
private static int Offset(int group, int item) => group switch
{
0 when item is >= 0 and < 9 => item,
1 when item is >= 0 and < 10 => 9 + item,
_ => throw new ArgumentOutOfRangeException(nameof(item), "Only the two serialized inventory groups are recovered here"),
};
}
+176
View File
@@ -0,0 +1,176 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>
/// Recovered player-contact button and vertical-door state machines. Contact
/// broadphase uses the recovered lookup magnitude; moving-object collision and material pulses
/// are separate, still incomplete consumers. See analysis/buttons-doors.md.
/// </summary>
public sealed class SceneMechanisms
{
private sealed class Button(DirectorActor actor)
{
public DirectorActor Actor = actor;
public bool Available;
public bool Down;
public float Cooldown;
}
private sealed class Door(DirectorActor actor)
{
public DirectorActor Actor = actor;
public Vector3 Origin = actor.SourceGam!.Position;
public bool Closed;
public float Remaining;
public float OpenElapsed;
public bool Looping;
public float Duration = actor.SourceGam!.Number("DoorSpeed", 1);
public float OpenTime = actor.SourceGam!.Number("OpenTime", 3);
public float Amount = actor.SourceGam!.Number("OpenAmount", 500);
}
private readonly SceneDirector director;
private readonly List<Button> buttons;
private readonly List<Door> doors;
private readonly HashSet<int> contacts = [];
private readonly HashSet<string> unsupported = [];
public IReadOnlyCollection<string> Unsupported => unsupported;
public event Action<DirectorActor, int, bool>? Sound; // Source bank index and loop flag.
public event Action<DirectorActor>? StopSound;
public SceneMechanisms(SceneDirector director)
{
this.director = director;
buttons = director.Actors.Where(a => a.Kind == "3BUT" && a.SourceGam != null).Select(a => new Button(a)).ToList();
doors = director.Actors.Where(a => a.Kind == "3DUD" && a.SourceGam != null).Select(a => new Door(a)).ToList();
foreach (var door in doors)
if (!float.IsFinite(door.Duration) || door.Duration <= 0 || !float.IsFinite(door.Amount)
|| !float.IsFinite(door.OpenTime)) throw new InvalidDataException("Invalid source door timing or displacement");
Reset();
}
public void Reset()
{
contacts.Clear();
foreach (var button in buttons) ResetButton(button);
foreach (var door in doors)
{
if (door.Looping) StopSound?.Invoke(door.Actor);
door.Closed = door.Actor.SourceGam!.Integer("ItemClosed", 1) != 0;
door.Remaining = door.OpenElapsed = 0;
door.Looping = false;
door.Actor.Position = door.Origin + (door.Closed ? Vector3.Zero : Vector3.UnitY * door.Amount);
}
}
/// <summary>Player contact-enter only; holding overlap never presses repeatedly.</summary>
public void Update(Vector3 root, float radius = 60)
{
if (!Finite(root) || !float.IsFinite(radius) || radius < 0) throw new ArgumentOutOfRangeException(nameof(root));
foreach (var button in buttons)
{
var source = button.Actor.SourceGam!;
// EXE411EF0 PostLoad sets current radius300 after InitObject.
var overlap = button.Actor.Active && OriginalBodySupport.QuickMagnitude(root - button.Actor.Position) < radius + 300;
if (!overlap) { contacts.Remove(source.Offset); continue; }
if (contacts.Add(source.Offset)) Press(button);
}
}
public bool Toggle(DirectorActor actor, int requested)
{
var door = doors.Find(d => ReferenceEquals(d.Actor, actor));
if (door == null) return false;
var current = door.Closed ? 1 : 0;
if (current == requested) return true;
door.Remaining = door.Remaining > 0 ? door.Duration - door.Remaining : door.Duration;
if (!door.Looping)
{
door.Looping = true;
Sound?.Invoke(actor, 59, true);
}
var next = actor.SourceGam!.Text("Next");
if (!string.IsNullOrEmpty(next) && !Equal(next, "none"))
{
var target = director.FindActor(next);
if (target?.Kind == "3AIT") director.Trigger(next, actor.Tag);
else unsupported.Add($"Door {actor.Tag}: chained target {next} class execution is unrecovered");
}
door.Closed = requested switch { 0 => false, 1 => true, _ => !door.Closed };
return true;
}
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
foreach (var button in buttons)
{
if (!button.Actor.Active || button.Cooldown <= 0) continue;
button.Cooldown -= dt;
if (button.Cooldown <= 0) ResetButton(button);
}
foreach (var door in doors)
{
if (!door.Actor.Active) continue;
if (door.Remaining > 0)
{
door.Remaining -= dt;
if (door.Remaining <= 0)
{
door.Remaining = 0;
door.Looping = false;
StopSound?.Invoke(door.Actor);
Sound?.Invoke(door.Actor, 58, false);
}
var fraction = door.Remaining / door.Duration;
if (!door.Closed) door.OpenElapsed = 0;
door.Actor.Position = door.Origin + Vector3.UnitY * door.Amount * (door.Closed ? fraction : 1 - fraction);
}
else if (!door.Closed)
{
door.OpenElapsed += dt;
if (door.OpenElapsed > door.OpenTime)
{
door.OpenElapsed = 0;
Toggle(door.Actor, 1);
}
}
}
}
private void Press(Button button)
{
if (!button.Available || button.Cooldown > 0) return;
if (!button.Down)
{
button.Cooldown = 4; // EXE411C35.
var sound = button.Actor.SourceGam!.Integer("AvailSound", -1);
if (sound != -1) Sound?.Invoke(button.Actor, sound, false);
}
button.Down = !button.Down;
button.Actor.Animation = button.Down ? "DOWN" : "UP";
var targetName = button.Actor.SourceGam!.Text("ActivateButton");
if (string.IsNullOrEmpty(targetName) || Equal(targetName, "none")) return;
var target = director.FindActor(targetName);
if (target == null) return; // Original missing-tag lookup quietly returns.
var toggle = button.Actor.SourceGam.Integer("Toggle", -1);
if (!Toggle(target, toggle) && target.Kind != "3BUT")
unsupported.Add($"Button {button.Actor.Tag}: target {targetName} toggle is unrecovered");
if (button.Down && target.Kind == "3BUT")
{
var linked = buttons.Find(b => ReferenceEquals(b.Actor, target))!;
linked.Available = true;
button.Available = false;
}
}
private static void ResetButton(Button button)
{
button.Available = button.Actor.SourceGam!.Integer("ButtonAvailable", 1) != 0;
button.Down = !button.Available;
button.Cooldown = 0;
button.Actor.Animation = button.Down ? "DOWN" : "UP";
}
private static bool Equal(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static bool Finite(Vector3 v) => float.IsFinite(v.X) && float.IsFinite(v.Y) && float.IsFinite(v.Z);
}
+25
View File
@@ -0,0 +1,25 @@
namespace GamePort.Game;
/// <summary>Animated sprite timing EXE0x40ED40: strict interval, one frame/call, discard remainder.</summary>
public sealed class SpriteSequence(int frames, float fps, int loop)
{
private float elapsed;
private int next;
public int Frame { get; private set; }
public bool Running { get; private set; }
public bool Hidden { get; private set; }
public void Start() { elapsed = 0; next = Frame = 0; Running = true; Hidden = false; }
public void Step(float dt)
{
if (!float.IsFinite(dt) || dt < 0) throw new ArgumentOutOfRangeException(nameof(dt));
if (!Running || frames <= 0 || fps <= 0) return;
elapsed += dt;
if (elapsed <= 1 / fps) return;
elapsed = 0;
Frame = next++;
if (next < frames) return;
next = 0;
if (loop is 0 or 2) Running = false;
if (loop == 2) Hidden = true;
}
}
+37
View File
@@ -0,0 +1,37 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Recovered task gates; -1 sentinels and numeric ExactLevel must retain their original meaning.</summary>
public static class TaskActivation
{
// Animated entity EXE0x40E340. null means keep the prior activation state.
public static bool? Animated(GamEntity entity, int state)
{
var exact = entity.Integer("ExactLevel", -1);
if (exact != -1) return state == exact;
var required = entity.Integer("RequiredLevel", -1);
if (required == -1) return null;
var remove = entity.Integer("RemoveLevel", -1);
return state >= required && (remove == -1 || state < remove);
}
// Pickup EXE0x45F2B0: no RemoveLevel check in this override.
public static bool? Pickup(GamEntity entity, int state)
{
var exact = entity.Integer("ExactLevel", -1);
if (exact != -1) return state == exact;
var required = entity.Integer("RequiredLevel", -1);
return required == -1 ? null : state >= required;
}
// LOAD EXE0x457F32. A stored task state -1 bypasses the requirements.
public static bool Load(GamEntity entity, TaskStates tasks)
{
var name = entity.Text("RequiredTask");
if (string.Equals(name, "none", StringComparison.OrdinalIgnoreCase)) return true;
var state = tasks.Get(name);
var exact = entity.Integer("ExactLevel", -1);
return state == -1 || state >= entity.Integer("RequiredLevel") && (exact == -1 || state == exact);
}
}
+25
View File
@@ -0,0 +1,25 @@
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>EXE0x45FEA0 query/0x45F990 assignment; ASCII case folding, missing returns0.</summary>
public sealed class TaskStates
{
private readonly List<SavedTask> tasks;
public event Action<string, int>? Assigned;
public TaskStates(IEnumerable<SavedTask> initial) => tasks = initial.ToList();
private static bool Equal(string a, string b) => Fold(a) == Fold(b);
private static string Fold(string text) => string.Create(text.Length, text, (span, source) =>
{
for (var i = 0; i < span.Length; i++) span[i] = source[i] is >= 'A' and <= 'Z' ? (char)(source[i] + 32) : source[i];
});
public int Get(string? name) => name == null ? 0 : tasks.FirstOrDefault(t => Equal(t.Name, name))?.State ?? 0;
public void SetExisting(string name, int value)
{
for (var i = 0; i < tasks.Count; i++)
if (Equal(tasks[i].Name, name)) tasks[i] = tasks[i] with { State = value };
// Original broadcasts even repeated assignments and unknown task names.
Assigned?.Invoke(name, value);
}
public SavedTask[] Snapshot() => tasks.ToArray();
}
+2
View File
@@ -43,6 +43,8 @@ internal static unsafe class Sdl
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern byte** SDL_Vulkan_GetInstanceExtensions(out uint count);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_Vulkan_CreateSurface(nint window,nint instance,void* allocator,out ulong surface);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSizeInPixels(nint window,out int w,out int h);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_GetWindowSize(nint window,out int w,out int h);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)]public static extern uint SDL_GetMouseState(out float x,out float y);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowFullscreen(nint window,[MarshalAs(UnmanagedType.I1)]bool fullscreen);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowRelativeMouseMode(nint window,[MarshalAs(UnmanagedType.I1)]bool enabled);
[DllImport(Library,CallingConvention=CallingConvention.Cdecl)] [return:MarshalAs(UnmanagedType.I1)]public static extern bool SDL_SetWindowSize(nint window,int width,int height);
+358 -19
View File
@@ -13,7 +13,16 @@ internal static class Program
{
public static int Main(string[] args)
{
try { return Run(args); }
try
{
OriginalSave? carriedSave = null;
while (true)
{
var result = Run(args, carriedSave, out var continuation);
if (result != 0 || continuation == null) return result;
args = continuation.Args; carriedSave = continuation.Save;
}
}
catch (Exception error) { Console.Error.WriteLine(error); return 1; }
}
@@ -26,8 +35,11 @@ internal static class Program
return args[i + 1];
}
private static int Run(string[] args)
private sealed record SceneContinuation(string[] Args, OriginalSave Save);
private static int Run(string[] args, OriginalSave? carriedSave, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
{
Console.WriteLine("""
@@ -40,15 +52,30 @@ internal static class Program
--original-camera Stored GAM start camera and recovered projection
--animation PATH Prepared Jimmy animation.json; place at GAM startpoint
--with-player Use prepared jimstop animation in scene
--walk Controllable lab (default with prepared lab)
--walk Play prepared scene with recovered story/interactions
--inspect Pause simulation and inspect scene/animation
--smoke-walk Deterministic 240-step movement/jump check
--story Execute recovered original CAM/MCA/AI trigger sequence
--story-time N Headless scene-sequence time for GPU comparisons
--skip-intro Fast-forward original intro actions and restore control
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan
--screenshot PATH Save actual GPU readback as PPM
--frames N Exit after N frames (headless default: 1)
--audio PATH Play recovered WAV; --loop-audio repeats it
--audio-smoke PATH Verify audio-stream consumption
--scene-audio-smoke PATH Verify music/speech streams from entities.json
--effects-audio-smoke PATH Verify default effect bank and loop lifetime
--smoke-transition Headless VR01 RETURN / renderer-recreation check
--smoke-lab-route Headless source lab contact route / next-scene rebuild
--smoke-practice-prompt Headless original jet pack practice prompt
--smoke-practice-transition Headless lab-to-VR04 practice transition
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
--smoke-jetpack Headless 300-step powered-jump/release check in VR04
--verify-assets Decode all original PNG/ASE files
--smoke-window Test keyboard event/resize (requires --frames 6 or more)
--no-validation Disable development validation
@@ -56,12 +83,53 @@ internal static class Program
C pauses into inspection / resumes chase camera. F11 fullscreen, Escape quit.
Inspector: arrows/WASD orbit, +/- zoom,
F11 fullscreen, Escape quit. Animation preview: 1 idle, 2 run, 3 jump, 4 scratch.
Collision/pivot/cadence and animation timing are provisional. Intro/interactions remain incomplete.
Collision/pivot/cadence and animation timing are provisional. Full gameplay remains incomplete.
""");
return 0;
}
var root = AssetPath.FindOriginal(Option(args, "--assets"));
var saveOutput = Option(args, "--write-save");
if (saveOutput != null)
{
saveOutput = Path.GetFullPath(saveOutput);
if (saveOutput.StartsWith(Path.GetFullPath(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Save output must be outside original asset directory");
for (var parent = new DirectoryInfo(Path.GetDirectoryName(saveOutput)!); parent != null; parent = parent.Parent)
if (parent.Exists && parent.LinkTarget != null) throw new ArgumentException("Save output directory must not redirect through a symbolic link");
}
if (args.Contains("--verify-assets")) return VerifyAssets(root);
if (Option(args, "--effects-audio-smoke") is { } effectsManifest)
{
using var mixer = new SceneAudio(new PreparedEntityResources(effectsManifest));
mixer.Effect(59, "bars"); mixer.Effect(58);
var before = mixer.QueuedEffectBytes;
Thread.Sleep(200);
var consumed = mixer.QueuedEffectBytes < before;
mixer.Pump();
mixer.StopLoop("bars");
var stopped = mixer.LoopCount == 0 && mixer.EffectCount == 1;
mixer.Effect(230);
var mixed = mixer.EffectCount == 2;
mixer.StopEffects();
Console.WriteLine($"Original effects: consumed={consumed}, loop stopped={stopped}, independent one-shots={mixed}, cleared={mixer.QueuedEffectBytes == 0}.");
return consumed && stopped && mixed && mixer.QueuedEffectBytes == 0 ? 0 : 2;
}
if (Option(args, "--scene-audio-smoke") is { } sceneAudioManifest)
{
var bank = new PreparedEntityResources(sceneAudioManifest);
using var mixer = new SceneAudio(bank);
mixer.Music("musicsecretlab.omt", 0);
mixer.Speech("voiceneighborhood.omt", 36);
var beforeMusic = mixer.QueuedMusicBytes;
var beforeSpeech = mixer.QueuedSpeechBytes;
Thread.Sleep(500);
var consumed = mixer.QueuedMusicBytes < beforeMusic && mixer.QueuedSpeechBytes < beforeSpeech;
mixer.StopSpeech();
mixer.Speech("voiceneighborhood.omt", 46);
var restarted = mixer.QueuedMusicBytes > 0 && mixer.QueuedSpeechBytes > 0;
Console.WriteLine($"Scene music and speech consumed independently: {consumed}; speech replacement retained music: {restarted}.");
return consumed && restarted ? 0 : 2;
}
if (Option(args, "--audio-smoke") is { } audioSmoke)
{
using var sound = new SdlAudio(audioSmoke);
@@ -73,6 +141,19 @@ internal static class Program
}
var scene = Option(args, "--scene");
var loadedSave = carriedSave ?? (Option(args, "--load-save") is { } savePath ? OriginalSave.Load(savePath) : null);
string? savedLevelPath = null;
if (loadedSave != null && carriedSave == null)
{
savedLevelPath = Directory.EnumerateFiles(AssetPath.Resolve(root, "gam"))
.Where(p => p.EndsWith(".gam", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(p => GamLevel.Load(p).Code == loadedSave.LevelCode)
?? throw new FileNotFoundException($"No GAM matches saved level {loadedSave.LevelCode}");
var prepared = new[] { "artifacts/extracted", Path.Combine(AppContext.BaseDirectory, "scenes") }
.FirstOrDefault(p => Directory.Exists(Path.Combine(p, "animations")))
?? throw new DirectoryNotFoundException("Prepare original scenes before loading saves");
scene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(savedLevelPath) + "/scene.json");
}
var defaultScene = false;
if (scene == null && Option(args, "--model") == null)
{
@@ -80,9 +161,12 @@ internal static class Program
Path.Combine(AppContext.BaseDirectory, "scenes/level1b/scene.json") }.FirstOrDefault(File.Exists);
defaultScene = scene != null;
}
var levelPath = Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null);
var levelPath = savedLevelPath == null ? Option(args, "--level") ?? (defaultScene ? "gam/level1b.gam" : null)
: "gam/" + Path.GetFileName(savedLevelPath);
GamLevel? level = levelPath == null ? null : GamLevel.Load(AssetPath.Resolve(root, levelPath));
var originalStart = level?.FindStart();
var startTag = Option(args, "--start") ?? loadedSave?.StartPoint;
if (string.Equals(startTag, "none", StringComparison.OrdinalIgnoreCase)) startTag = null;
var originalStart = level?.FindStart(startTag);
if (level != null) Console.WriteLine($"Decoded GAM {level.Code}: {level.Entities.Count} entities.");
var originalCamera = args.Contains("--original-camera") || defaultScene;
if (originalCamera && originalStart == null)
@@ -90,6 +174,7 @@ internal static class Program
var mesh = scene != null ? Mesh.LoadSceneJson(scene)
: AseMesh.Load(AssetPath.Resolve(root, Option(args, "--model") ?? "ASE/jimstop.ase"));
var world = mesh;
var texture = scene != null ? PngImage.White
: PngImage.Load(AssetPath.Resolve(root, Option(args, "--texture") ?? "png/jimycarl.png"));
var bounds = mesh.Bounds();
@@ -97,9 +182,18 @@ internal static class Program
var radius = Math.Max(Vector3.Distance(bounds.Min, bounds.Max) * 1.15f, 1);
var animationPath = Option(args, "--animation");
var walkSmoke = args.Contains("--smoke-walk");
var jetpackSmoke = args.Contains("--smoke-jetpack");
var practiceWindowSmoke = args.Contains("--smoke-practice-window");
if (walkSmoke && jetpackSmoke) throw new ArgumentException("Select one movement smoke check");
var defaultStory = (defaultScene || args.Contains("--walk")) && !args.Contains("--inspect") && !walkSmoke && !args.Contains("--smoke-window")
&& animationPath == null && !args.Contains("--time");
var story = defaultStory || loadedSave != null || saveOutput != null || args.Contains("--story") || args.Contains("--story-time")
|| args.Contains("--skip-intro") || jetpackSmoke || practiceWindowSmoke;
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
throw new ArgumentException("Story playback requires its own simulation mode.");
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
if (walkSmoke && args.Contains("--smoke-window")) throw new ArgumentException("Select one window smoke mode.");
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (args.Contains("--walk") || walkSmoke
var walking = !args.Contains("--inspect") && !args.Contains("--smoke-window") && (story || args.Contains("--walk") || walkSmoke
|| defaultScene && animationPath == null && !args.Contains("--time"));
if ((args.Contains("--with-player") || args.Contains("--walk") || defaultScene || walking) && scene != null)
animationPath ??= Path.Combine(Path.GetDirectoryName(scene)!, "../animations/jimstop/animation.json");
@@ -107,6 +201,19 @@ internal static class Program
throw new ArgumentException("Walking requires a scene and matching GAM startpoint.");
PreviewAnimationLibrary? animations = null;
LabSimulation? simulation = null;
SceneDirector? director = null;
SceneActorVisuals? actorVisuals = null;
SceneSpriteVisuals? spriteVisuals = null;
StaticSceneVisuals? staticVisuals = null;
PreparedEntityResources? resources = null;
SceneInteractions? interactions = null;
SceneMechanisms? mechanisms = null;
SceneHud? hud = null;
JetpackVisuals? jetpackVisuals = null;
var practice = new PracticePrompt();
var objectiveOffset = -69f;
var patrols = new Dictionary<string, ActorPatrol>(StringComparer.OrdinalIgnoreCase);
LevelTransition? transitionRequest = null;
var characterOffset = mesh.Vertices.Length;
var characterModel = Matrix4x4.Identity;
if (animationPath != null)
@@ -115,7 +222,8 @@ internal static class Program
throw new ArgumentException("A scene and matching GAM are required to place an animated player.");
animations = new PreviewAnimationLibrary(animationPath);
var standingPose = AseMesh.Load(AssetPath.Resolve(root, "ASE/jimstop.ase"));
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y);
if (walking) simulation = new LabSimulation(new SceneCollision(mesh), standingPose, originalStart.Position, originalStart.Rotation.Y)
{ LevelCode = level!.Code };
var placement = PreviewCharacterPlacement.Create(mesh, standingPose, originalStart.Position, originalStart.Rotation.Y);
characterModel = placement.Model;
mesh = animations.Current.AppendTo(mesh);
@@ -124,15 +232,79 @@ internal static class Program
else
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
}
if (story)
{
resources = new PreparedEntityResources(Path.Combine(Path.GetDirectoryName(scene!)!, "entities/entities.json"),
Path.Combine(Path.GetDirectoryName(scene!)!, "../effects/effects.json"));
var save = loadedSave ?? OriginalSave.Load(AssetPath.Resolve(root, "NewGame.tsk"));
var tasks = new TaskStates(save.Tasks);
director = new SceneDirector(level!, tasks, resources.Duration);
interactions = new SceneInteractions(director, tasks, save, level!.Code);
simulation!.Energy = interactions.Energy;
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
mechanisms = new SceneMechanisms(director);
interactions.Transition += request => transitionRequest ??= request;
interactions.PracticeRequested += practice.Show;
practice.Chosen += (mode, accepted) =>
{
if (!accepted) return;
// Player43B5A0 receives current/requested GAM and latest STRT tag
// as return context;42AF00's runtime checkpoint is separate.
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
transitionRequest ??= new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1);
};
interactions.Collected += (entity, points) => Console.WriteLine($"Collected {entity.Tag}: +{points}; score={interactions.Score}.");
foreach (var actor in director.Actors.Where(a => a.Kind is "3DOG" or "3CAR"))
{
var physics = new OriginalScenePhysics(world);
var grounded = false;
var patrol = new ActorPatrol(actor, director.FindActor, (body, dt) =>
{
var resolved = physics.Step(body.Position, body.Velocity,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardRadius : 100,
actor.Kind == "3DOG" ? OriginalBodySupport.GoddardFactor : .75f, grounded, dt);
grounded = resolved.Supported;
return new(resolved.Body.Position, resolved.Body.Velocity);
});
patrols.Add(actor.Tag, patrol);
director.RegisterPatrolConsumer(actor.Tag);
director.ActorChanged += changed => { if (ReferenceEquals(changed, actor)) patrol.SynchronizeAuthoredState(); };
}
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
actor => patrols.ContainsKey(actor.Tag));
mesh = actorVisuals.Mesh;
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
mesh = spriteVisuals.Mesh;
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
mesh = staticVisuals.Mesh;
simulation!.DynamicRootResolver = (previous, position, radius) =>
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
mesh = jetpackVisuals.Mesh;
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
mesh = hud.Mesh;
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
}
Console.WriteLine($"Loaded original geometry: {mesh.Vertices.Length} vertices, {mesh.Indices.Length / 3} triangles, {mesh.Textures.Count + (scene == null ? 1 : 0)} textures.");
var fixedTimeText = Option(args, "--time");
double? fixedTime = fixedTimeText == null ? null : double.Parse(fixedTimeText, System.Globalization.CultureInfo.InvariantCulture);
var headless = args.Contains("--headless");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : headless ? "1" : "0"));
if (args.Contains("--smoke-transition") && (!headless || level?.Code is not ("VR01" or "VR04") || interactions == null))
throw new ArgumentException("Transition smoke requires headless story playback of VR01 or VR04.");
if (args.Contains("--smoke-lab-route") && (!headless || level?.Code != "LV1B" || interactions == null || loadedSave != null))
throw new ArgumentException("Lab route smoke requires fresh headless story playback of LV1B.");
var storyTime = double.Parse(Option(args, "--story-time") ?? "0", System.Globalization.CultureInfo.InvariantCulture);
if (!double.IsFinite(storyTime) || storyTime < 0 || storyTime > 3600 || storyTime > 0 && !headless)
throw new ArgumentException("Story time must be0..3600 seconds in headless mode.");
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : headless ? "1" : "0"));
if (jetpackSmoke && (!headless || level?.Code != "VR04" || frames < 300))
throw new ArgumentException("Jetpack smoke requires headless VR04 and at least300 frames");
if (walkSmoke && frames < 240) throw new ArgumentException("Walk smoke requires at least 240 frames.");
var smoke = args.Contains("--smoke-window");
if (frames < 0 || (smoke && (headless || frames < 6)))
throw new ArgumentException("Invalid frame count; window smoke requires at least six frames.");
if (practiceWindowSmoke && (headless || frames < 12 || level?.Code != "LV1B" || loadedSave != null))
throw new ArgumentException("Practice window smoke requires fresh LV1B and at least12 windowed frames.");
nint window = 0;
if (!headless)
{
@@ -146,6 +318,56 @@ internal static class Program
using var renderer = new VulkanRenderer(mesh, texture, 960, 720, window, !args.Contains("--no-validation"));
using var audio = Option(args, "--audio") is { } audioFile
? new SdlAudio(audioFile, args.Contains("--loop-audio")) : null;
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
double initialPoseTime = 0;
if (director != null)
{
if (sceneAudio != null)
{
director.Speech += sceneAudio.Speech;
interactions!.SoundEffect += id => sceneAudio.Effect(id);
mechanisms!.Sound += (actor, id, loop) => sceneAudio.Effect(id, loop ? actor.Tag : null);
mechanisms.StopSound += actor => sceneAudio.StopLoop(actor.Tag);
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
}
director.Begin(originalStart!);
interactions!.Reset();
mechanisms!.Reset();
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
if (args.Contains("--skip-intro") || jetpackSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
if (args.Contains("--smoke-transition"))
{
director.Skip();
interactions!.Update(level!.Entities.First(e => e.Kind == "LOAD").Position);
if (transitionRequest == null) throw new InvalidOperationException("Original VR01 RETURN contact did not request a transition");
}
if (args.Contains("--smoke-lab-route"))
{
LabRouteSmoke.Run(level!, director, interactions!, () => practice.Key(17, Vector2.Zero));
if (transitionRequest?.LevelFile != "level1.gam")
throw new InvalidOperationException("Original lab exit did not request level1.gam");
}
if (args.Contains("--smoke-practice-prompt") || args.Contains("--smoke-practice-transition") || practiceWindowSmoke)
{
if ((!headless && !practiceWindowSmoke) || level?.Code != "LV1B") throw new ArgumentException("Practice smoke requires the original lab");
director.Skip();
director.Touch(level!.Player!.Tag!, level.Entities.Single(e => e.Tag == "teleportexplanation").Position);
director.Skip();
interactions!.Update(director.FindActor("shrinkray")!.Position);
if (!practice.Active) throw new InvalidOperationException("Original lab pickup did not open practice modal");
if (args.Contains("--smoke-practice-transition")) practice.Key(28, Vector2.Zero);
}
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active; tick++)
{
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
mechanisms!.Step(FixedStepClock.Step);
director.Step(FixedStepClock.Step);
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
initialPoseTime += FixedStepClock.Step;
actorVisuals!.Update(FixedStepClock.Step, mesh);
spriteVisuals!.Step(FixedStepClock.Step);
}
}
var keys = new HashSet<uint>();
var running = true;
var fullscreen = false;
@@ -158,12 +380,20 @@ internal static class Program
var active = true;
var mouseJump = false;
var stepClock = new FixedStepClock();
double poseTime = 0;
double poseTime = initialPoseTime;
var injectedInput = default(PlayerInput);
var sawWalkKeys = 0;
var sawPracticeDismiss = false;
var sawPracticePause = false;
double last = clock.Elapsed.TotalSeconds;
float angle = 0.6f, elevation = 0.32f;
var count = 0;
Vector2 Pointer()
{
Sdl.SDL_GetMouseState(out var x, out var y);
if (!Sdl.SDL_GetWindowSize(window, out var w, out var h) || w < 1 || h < 1) return Vector2.Zero;
return new(x * 640 / w, y * 480 / h);
}
while (running)
{
if (walkSmoke && !headless)
@@ -187,6 +417,14 @@ internal static class Program
{ keys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
if (practice.Active && e.Type == Sdl.MouseButtonDown)
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; }
if (practice.Active && e.Type == Sdl.KeyDown)
{
if (e.Repeat == 0) practice.Key(e.Scancode, Pointer());
if (practiceWindowSmoke && e.Scancode == 17 && !practice.Active) sawPracticeDismiss = true;
keys.Clear(); mouseJump = false; stepClock.Reset(); continue;
}
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3) mouseJump = true;
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
if (e.Type == Sdl.KeyDown)
@@ -194,7 +432,11 @@ internal static class Program
keys.Add(e.Scancode);
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == 225 ? 4 : 0;
if (smoke && e.Scancode == 79) sawKey = true;
if (e.Scancode == 41) running = false;
if (e.Scancode is 41 or 44 && e.Repeat == 0 && director is { Controlled: false })
{ sceneAudio?.StopSpeech(); director.Skip(); keys.Clear(); mouseJump = false; }
else if (e.Scancode == 41) running = false;
if (e.Scancode == 18 && e.Repeat == 0 && director is { Controlled: true, InventoryEnabled: true })
objectiveOffset = objectiveOffset == -69 ? 0 : -69;
if (inspecting && e.Repeat == 0 && animations?.Select(e.Scancode) == true)
{
animationStarted = clock.Elapsed.TotalSeconds;
@@ -214,7 +456,12 @@ internal static class Program
}
else originalCamera = !originalCamera;
}
if (!inspecting && e.Scancode == 21 && e.Repeat == 0) { simulation!.Reset(); poseTime = 0; }
if (!inspecting && e.Scancode == 21 && e.Repeat == 0)
{
simulation!.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
interactions?.Reset(); mechanisms?.Reset();
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
}
if (e.Scancode == 68 && e.Repeat == 0)
{
fullscreen = !fullscreen;
@@ -227,17 +474,35 @@ internal static class Program
var elapsed = now - last;
var dt = (float)Math.Min(elapsed, 0.1);
last = now;
if (simulation != null && !inspecting && (active || headless || walkSmoke))
if (simulation != null && !inspecting && !practice.Active && (active || headless || walkSmoke))
{
var steps = headless || walkSmoke ? 1 : stepClock.Advance(elapsed);
var steps = headless || walkSmoke || practiceWindowSmoke ? 1 : stepClock.Advance(elapsed);
for (var step = 0; step < steps; step++)
{
var input = walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
var input = jetpackSmoke ? new PlayerInput(false, false, false, false, simulation.Steps < 180)
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
keys.Contains(82), keys.Contains(81), keys.Contains(80), keys.Contains(79),
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98));
simulation.Step(input);
if (animations!.SelectPose(simulation.Pose)) poseTime = 0;
if (director?.Controlled != false)
{
simulation.Step(input);
interactions?.UpdateEnergy(simulation.Energy);
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
director?.Touch(level!.Player!.Tag!, simulation.ActorRoot);
interactions?.Update(simulation.ActorRoot, simulation.InteractionRadius);
if (practice.Active) { keys.Clear(); mouseJump = false; stepClock.Reset(); break; }
mechanisms?.Update(simulation.ActorRoot, simulation.InteractionRadius);
}
mechanisms?.Step(FixedStepClock.Step);
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
director?.Step(FixedStepClock.Step);
var switched = director is { Controlled: false }
? animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)
: animations!.SelectPose(simulation.Pose);
if (switched) poseTime = 0;
poseTime += FixedStepClock.Step;
actorVisuals?.Update(FixedStepClock.Step, mesh);
spriteVisuals?.Step(FixedStepClock.Step);
}
characterModel = simulation.Model;
}
@@ -256,8 +521,22 @@ internal static class Program
var view = originalCamera
? Matrix4x4.CreateLookAtLeftHanded(originalStart!.CameraPosition, originalStart.Position + new Vector3(0, 80, 0), Vector3.UnitY)
: Matrix4x4.CreateLookAt(eye, target, Vector3.UnitY);
var renderEye = originalCamera ? originalStart!.CameraPosition : eye;
var renderTarget = originalCamera ? originalStart!.Position + new Vector3(0,80,0) : target;
if (simulation != null && !inspecting)
{
view = Matrix4x4.CreateLookAtLeftHanded(simulation.CameraEye, simulation.CameraTarget, Vector3.UnitY);
renderEye = simulation.CameraEye; renderTarget = simulation.CameraTarget;
}
if (!inspecting && director?.CameraEye is { } storyEye && director.CameraTarget is { } storyTarget)
{
view = Matrix4x4.CreateLookAtLeftHanded(storyEye, storyTarget, Vector3.UnitY);
renderEye = storyEye; renderTarget = storyTarget;
}
staticVisuals?.Update(mesh);
jetpackVisuals?.Update(mesh, simulation!);
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && director!.Controlled, practice.Active, objectiveOffset);
var far = level?.Code == "LV1B" ? 10000 : 3200;
var projection = originalCamera || simulation != null && !inspecting
? Matrix4x4.CreatePerspectiveFieldOfViewLeftHanded(0xAAA / 16384f * MathF.Tau, (float)renderer.Width / renderer.Height, 20, far)
@@ -266,12 +545,21 @@ internal static class Program
if (animations != null)
{
animations.Current.Sample(simulation != null && !inspecting ? poseTime
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted), mesh.Vertices.AsSpan(characterOffset), characterModel);
: fixedTime ?? (headless ? count / 60.0 : now - animationStarted),
mesh.Vertices.AsSpan(characterOffset, animations.Current.Base.Vertices.Length), characterModel);
renderer.UpdateVertices(mesh.Vertices);
}
renderer.Render(view * projection);
count++;
audio?.Pump();
sceneAudio?.Pump();
if (practiceWindowSmoke && count == 1)
{
sawPracticePause = practice.Active && simulation!.Steps == 0;
var key = new Sdl.Event { Type = Sdl.KeyDown, Scancode = 17, Down = 1 };
if (!Sdl.SDL_PushEvent(ref key) || !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
}
if (walkSmoke && !headless && count == 1 && !Sdl.SDL_SetWindowSize(window, 800, 600))
throw new InvalidOperationException(Sdl.Error);
if (smoke && count == 1)
@@ -285,8 +573,9 @@ internal static class Program
if (!Sdl.SDL_PushEvent(ref cycle)) throw new InvalidOperationException(Sdl.Error);
}
}
if ((smoke || walkSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if ((smoke || walkSmoke || practiceWindowSmoke) && renderer.Width == 800 && renderer.Height == 600) didResize = true;
if (frames > 0 && count >= frames) break;
if (transitionRequest != null) break;
}
if (Option(args, "--screenshot") is { } screenshot)
{
@@ -299,6 +588,50 @@ internal static class Program
if (Math.Abs(pixels[i] - 31) + Math.Abs(pixels[i + 1] - 51) + Math.Abs(pixels[i + 2] - 76) > 6) changed++;
Console.WriteLine($"Rendered {count} frame(s), {changed} non-background pixels, {renderer.ValidationErrors} Vulkan validation error(s).");
if (simulation != null) Console.WriteLine(simulation.Report);
if (jetpackSmoke)
{
Console.WriteLine($"Powered jump: bursts={simulation!.Bursts}, remaining={simulation.JetpackRemaining:F3}, energy={simulation.Energy:F3}, grounded={simulation.Grounded}.");
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded) return 2;
}
if (director != null)
{
Console.WriteLine($"Scene sequence: {director.CurrentTag ?? "none"}, shot={director.CurrentShot}, control={director.Controlled}, blocked={director.Blocked}, issues={director.Issues.Count}.");
foreach (var issue in director.Issues) Console.WriteLine($"Unrecovered scene behavior {issue.Tag}: {issue.Detail}");
foreach (var missing in actorVisuals!.UnsupportedAnimations) Console.WriteLine($"Unrecovered animation alias {missing}");
foreach (var missing in interactions!.Unsupported) Console.WriteLine(missing);
foreach (var missing in mechanisms!.Unsupported) Console.WriteLine(missing);
foreach (var (tag, patrol) in patrols)
Console.WriteLine($"Patrol {tag}: root={director.FindActor(tag)!.Position}, waypoint={patrol.CurrentWaypoint ?? "none"}, velocity={patrol.Velocity}; recovered support, provisional wall response.");
}
if (interactions != null && saveOutput is { } output)
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
var snapshot = interactions.Snapshot() with { LevelCode = level!.Code, StartPoint = originalStart!.Tag! };
var temporary = output + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) stream.Write(snapshot.Encode());
File.Move(temporary, output, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
Console.WriteLine($"Wrote original-format checkpoint state: {output}");
}
if (transitionRequest != null && renderer.ValidationErrors == 0)
{
var prepared = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, ".."));
var nextScene = AssetPath.Resolve(prepared, Path.GetFileNameWithoutExtension(transitionRequest.LevelFile) + "/scene.json");
var nextArgs = new List<string>();
for (var i = 0; i < args.Length; i++)
{
if (args[i] is "--smoke-transition" or "--smoke-lab-route" or "--smoke-practice-prompt" or "--smoke-practice-transition") continue;
if (args[i] is "--scene" or "--level" or "--start" or "--load-save" or "--story-time") { i++; continue; }
nextArgs.Add(args[i]);
}
nextArgs.AddRange(["--scene", nextScene, "--level", "gam/" + transitionRequest.LevelFile,
"--start", transitionRequest.StartPoint]);
continuation = new(nextArgs.ToArray(), interactions!.Snapshot() with { StartPoint = transitionRequest.StartPoint });
Console.WriteLine($"Loading original destination: {transitionRequest.LevelFile}, start={transitionRequest.StartPoint}; fade behavior remains unreconstructed.");
}
if (walkSmoke && !simulation!.SmokePassed) return 2;
if (walkSmoke && !headless)
{
@@ -315,6 +648,12 @@ internal static class Program
if (!animationSwitched || !animations.Current.HasVertexMotion) return 2;
}
}
if (practiceWindowSmoke)
{
var resumed = !practice.Active && simulation!.Steps > 0;
Console.WriteLine($"Practice SDL check: paused={sawPracticePause}, N dismiss={sawPracticeDismiss}, resumed={resumed}, resize800x600={didResize}.");
if (!sawPracticePause || !sawPracticeDismiss || !resumed || !didResize) return 2;
}
return renderer.ValidationErrors > 0 || changed == 0 ? 2 : 0;
}
finally
@@ -29,7 +29,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
private ImageView colorView,depthView;
private RenderPass renderPass;
private Framebuffer framebuffer;
private Pipeline pipeline;
private Pipeline pipeline,overlayPipeline;
private PipelineLayout pipelineLayout;
private DescriptorSetLayout descriptorLayout;
private DescriptorPool descriptorPool;
@@ -312,6 +312,8 @@ public sealed unsafe class VulkanRenderer : IDisposable
var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates};
var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0};
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
ds.DepthTestEnable=false;ds.DepthWriteEnable=false;
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayPipeline),"CreateOverlayPipeline");
}
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
}
@@ -368,13 +370,19 @@ public sealed unsafe class VulkanRenderer : IDisposable
var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height));
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&mvp);
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
foreach(var draw in draws)
foreach(var screenSpace in new[]{false,true})
{
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,screenSpace?overlayPipeline:pipeline);
var transform=screenSpace?Matrix4x4.Identity:mvp;
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&transform);
foreach(var draw in draws)
{
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
}
}
vk.CmdEndRenderPass(command);
if(window==0){Submit();return;}
@@ -410,6 +418,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
vk.DeviceWaitIdle(device);
if(framebuffer.Handle!=0)DestroyTarget();
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null);