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);
}