Implement original gadget panel and playable shrink ray
This commit is contained in:
1 parent
0272f7bef7
commit
7b5230ceb8
57 files changed
+3545
-48
No files matched your search
@@ -0,0 +1,84 @@
|
||||
using System.Numerics;
|
||||
using System.Text.Json;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Game;
|
||||
|
||||
namespace GamePort.Application;
|
||||
|
||||
/// <summary>Original screens.omt gadget art in the existing uniformly scaled UI viewport.</summary>
|
||||
public sealed class GadgetMenuOverlay
|
||||
{
|
||||
private sealed record Quad(int Vertex, uint FirstIndex, uint Width, uint Height);
|
||||
private readonly Dictionary<int, Quad> quads = [];
|
||||
public Mesh Mesh { get; }
|
||||
|
||||
public GadgetMenuOverlay(Mesh combined, string manifest)
|
||||
{
|
||||
var full = Path.GetFullPath(manifest);
|
||||
if (new FileInfo(full).Length > 128 * 1024) throw new InvalidDataException("Gadget manifest exceeds limit");
|
||||
var directory = Path.GetDirectoryName(full)!;
|
||||
using var document = JsonDocument.Parse(File.ReadAllBytes(full), new JsonDocumentOptions { MaxDepth = 12 });
|
||||
var root = document.RootElement;
|
||||
if (root.GetProperty("schema").GetInt32() != 1 || root.GetProperty("referenceWidth").GetInt32() != 640
|
||||
|| root.GetProperty("referenceHeight").GetInt32() != 480)
|
||||
throw new InvalidDataException("Unsupported gadget resource format");
|
||||
var entries = root.GetProperty("textures");
|
||||
if (entries.GetArrayLength() != 54) throw new InvalidDataException("Expected54 original gadget canvases");
|
||||
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);
|
||||
long total = 0;
|
||||
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 (width is 0 or > 640 || height is 0 or > 480) throw new InvalidDataException("Invalid gadget canvas dimensions");
|
||||
var path = Path.GetFullPath(Path.Combine(directory, entry.GetProperty("path").GetString()!));
|
||||
if (!path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal))
|
||||
throw new InvalidDataException("Gadget canvas escapes prepared directory");
|
||||
var bytes = checked((long)width * height * 4);
|
||||
total += bytes;
|
||||
if (total > 16 * 1024 * 1024 || new FileInfo(path).Length != bytes)
|
||||
throw new InvalidDataException("Invalid gadget canvas pixel count");
|
||||
var texture = int.MinValue;
|
||||
while (textures.ContainsKey(texture)) texture++;
|
||||
textures.Add(texture, new(width, height, File.ReadAllBytes(path)));
|
||||
if (!quads.TryAdd(id, new(vertices.Count, (uint)indices.Count, width, height)))
|
||||
throw new InvalidDataException("Duplicate gadget canvas");
|
||||
var first = (uint)vertices.Count;
|
||||
vertices.AddRange([new(Vector3.Zero, new(0,0), Vector3.One), new(Vector3.Zero, new(1,0), Vector3.One),
|
||||
new(Vector3.Zero, new(1,1), Vector3.One), new(Vector3.Zero, new(0,1), Vector3.One)]);
|
||||
indices.AddRange([first, first + 1, first + 2, first, first + 2, first + 3]);
|
||||
draws.Add(new((uint)indices.Count - 6, 6, texture) { ScreenSpace = true, Visible = false });
|
||||
}
|
||||
Mesh = new(vertices.ToArray(), indices.ToArray()) { Draws = draws.ToArray(), HasExplicitDraws = true,
|
||||
Textures = textures, CollisionPolygons = combined.CollisionPolygons,
|
||||
HasCollisionMaterialIds = combined.HasCollisionMaterialIds };
|
||||
}
|
||||
|
||||
public void Update(Mesh destination, IReadOnlyList<GadgetCanvas> visible, uint width, uint height)
|
||||
{
|
||||
if (destination.Vertices.Length < Mesh.Vertices.Length || visible.Count > quads.Count)
|
||||
throw new ArgumentException("Destination omits gadget overlay ranges");
|
||||
foreach (var quad in quads.Values) Draw(quad).Visible = false;
|
||||
var viewport = new UiViewport(width, height);
|
||||
foreach (var canvas in visible)
|
||||
{
|
||||
if (!quads.TryGetValue(canvas.Id, out var quad)) throw new InvalidDataException("Unprepared gadget canvas");
|
||||
var draw = Draw(quad);
|
||||
if (draw.Visible) throw new ArgumentException("Gadget canvas occurs more than once");
|
||||
draw.Visible = true;
|
||||
var point = canvas.Position + viewport.CenterOffset;
|
||||
destination.Vertices[quad.Vertex].Position = viewport.ToNdc(point);
|
||||
destination.Vertices[quad.Vertex + 1].Position = viewport.ToNdc(point + new Vector2(quad.Width, 0));
|
||||
destination.Vertices[quad.Vertex + 2].Position = viewport.ToNdc(point + new Vector2(quad.Width, quad.Height));
|
||||
destination.Vertices[quad.Vertex + 3].Position = viewport.ToNdc(point + new Vector2(0, quad.Height));
|
||||
}
|
||||
MeshDraw Draw(Quad quad) => destination.Draws.FirstOrDefault(d => d.FirstIndex == quad.FirstIndex
|
||||
&& d.IndexCount == 6 && d.ScreenSpace) ?? throw new ArgumentException("Destination omits gadget draws");
|
||||
}
|
||||
}
|
||||
@@ -47,14 +47,14 @@ 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.Fly, "jimfly") })
|
||||
(PlayerPose.Backpedal, "jimbackpedal"), (PlayerPose.Jump, "jimjump"), (PlayerPose.Fall, "jimfall"), (PlayerPose.Fly, "jimfly"), (PlayerPose.Shoot, "jimshoot") })
|
||||
{
|
||||
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") })
|
||||
("JUMP", "jimjump"), ("FALL", "jimfall"), ("SCRATCH", "jimscratch"), ("FLY", "jimfly"), ("SHOOT", "jimshoot") })
|
||||
{
|
||||
var path = Path.Combine(parent, folder, "animation.json");
|
||||
if (File.Exists(path)) actions[action] = Load(path);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Game;
|
||||
|
||||
namespace GamePort.Application;
|
||||
|
||||
/// <summary>Owned original RAY mesh and three texture phases; material alpha0.5, additive default.</summary>
|
||||
public sealed class ShrinkRayVisuals
|
||||
{
|
||||
private readonly MorphAnimation clip;
|
||||
private readonly int offset;
|
||||
private readonly MeshDraw[] phases;
|
||||
public Mesh Mesh { get; }
|
||||
|
||||
public ShrinkRayVisuals(Mesh combined, string preparedRoot, string originalRoot)
|
||||
{
|
||||
clip = new(Path.Combine(preparedRoot,"actors/shrink-ray/ray/animation.json"));
|
||||
offset = combined.Vertices.Length;
|
||||
var id = int.MinValue + 12000;
|
||||
while (combined.Textures.ContainsKey(id)) id++;
|
||||
var mesh = clip.AppendTo(combined,id);
|
||||
phases = new MeshDraw[3]; phases[0] = mesh.Draws[^1];
|
||||
for (var phase = 1; phase < phases.Length; phase++)
|
||||
{
|
||||
do id++; while (mesh.Textures.ContainsKey(id));
|
||||
mesh.Textures.Add(id,PngImage.Load(AssetPath.Resolve(originalRoot,$"png/ray000{phase}.png")));
|
||||
phases[phase] = new(phases[0].FirstIndex,phases[0].IndexCount,id);
|
||||
}
|
||||
foreach (var draw in phases) { draw.Visible = false; draw.Opacity = .5f; draw.Blend = MeshBlend.Additive; }
|
||||
Mesh = mesh with {Draws=[.. mesh.Draws,phases[1],phases[2]]};
|
||||
}
|
||||
|
||||
public void Update(Mesh destination, ShrinkRay ray, double seconds)
|
||||
{
|
||||
for (var phase = 0; phase < phases.Length; phase++) phases[phase].Visible = ray.Visible && ray.TexturePhase == phase;
|
||||
if (!ray.Visible) return;
|
||||
var model = Matrix4x4.CreateRotationY(-ray.Yaw * MathF.PI / 180) * Matrix4x4.CreateTranslation(ray.Position);
|
||||
clip.Sample(seconds,destination.Vertices.AsSpan(offset,clip.Base.Vertices.Length),model);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Game;
|
||||
|
||||
namespace GamePort.Application;
|
||||
|
||||
/// <summary>Original3SOL WALK/SHRINK morphs. No combat or patrol AI is inferred.</summary>
|
||||
public sealed class ShrinkSoldierVisuals
|
||||
{
|
||||
private sealed class Visual(ShrinkSoldier soldier, int offset, MeshDraw draw)
|
||||
{
|
||||
public ShrinkSoldier Soldier = soldier;
|
||||
public int Offset = offset;
|
||||
public MeshDraw Draw = draw;
|
||||
public bool Shrunk;
|
||||
public double Time;
|
||||
}
|
||||
private readonly List<Visual> visuals = [];
|
||||
private readonly MorphAnimation walk, shrink;
|
||||
public Mesh Mesh { get; }
|
||||
|
||||
public ShrinkSoldierVisuals(Mesh combined, IReadOnlyList<ShrinkSoldier> soldiers, string preparedRoot, string level)
|
||||
{
|
||||
var vr = level.Length == 4 && level.StartsWith("VR0",StringComparison.Ordinal) && level[3] is >= '1' and <= '8';
|
||||
var family = Path.Combine(preparedRoot,"actors",vr ? "soldier-vr" : "soldier");
|
||||
walk = new(Path.Combine(family,"soldwalk/animation.json"));
|
||||
shrink = new(Path.Combine(family,"soldshrink/animation.json"));
|
||||
if (walk.Base.Vertices.Length != shrink.Base.Vertices.Length || !walk.Base.Indices.SequenceEqual(shrink.Base.Indices))
|
||||
throw new InvalidDataException("Original soldier morph topology differs");
|
||||
foreach (var soldier in soldiers)
|
||||
{
|
||||
var offset = combined.Vertices.Length;
|
||||
var id = int.MinValue + 13000 + visuals.Count;
|
||||
while (combined.Textures.ContainsKey(id)) id++;
|
||||
combined = walk.AppendTo(combined,id);
|
||||
visuals.Add(new(soldier,offset,combined.Draws[^1]));
|
||||
}
|
||||
Mesh = combined; Update(0,Mesh);
|
||||
}
|
||||
|
||||
public void Update(double seconds, Mesh destination)
|
||||
{
|
||||
foreach (var visual in visuals)
|
||||
{
|
||||
if (visual.Shrunk != visual.Soldier.Shrunk)
|
||||
{
|
||||
//False selector preserves frame ordinal; within-frame clock is
|
||||
//an explicit port approximation. WALK(true) restarts at frame0.
|
||||
var ordinal = (int)Math.Floor(visual.Time / walk.SampleInterval) % walk.FrameCount;
|
||||
visual.Time = visual.Soldier.Shrunk ? Math.Min(ordinal,shrink.FrameCount - 1) * shrink.SampleInterval : 0;
|
||||
visual.Shrunk = visual.Soldier.Shrunk;
|
||||
}
|
||||
visual.Time += seconds;
|
||||
var actor = visual.Soldier.Actor;
|
||||
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 clip = visual.Shrunk ? shrink : walk;
|
||||
clip.Sample(visual.Time,destination.Vertices.AsSpan(visual.Offset,clip.Base.Vertices.Length),
|
||||
rotation * Matrix4x4.CreateTranslation(actor.Position),!visual.Shrunk);
|
||||
visual.Draw.Visible = actor.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
public float RenderedHeight(string tag, Mesh destination)
|
||||
{
|
||||
var visual = visuals.Single(v => v.Soldier.Actor.Tag == tag);
|
||||
var vertices = destination.Vertices.AsSpan(visual.Offset,walk.Base.Vertices.Length);
|
||||
var low = float.PositiveInfinity; var high = float.NegativeInfinity;
|
||||
foreach (var vertex in vertices) { low = MathF.Min(low,vertex.Position.Y); high = MathF.Max(high,vertex.Position.Y); }
|
||||
return high - low;
|
||||
}
|
||||
}
|
||||
@@ -108,8 +108,12 @@ public readonly record struct MeshPolygonSource(int ShapeId, int PolygonIndex, V
|
||||
public bool TerrainCollision => ShapeName?.StartsWith("nc", StringComparison.OrdinalIgnoreCase) != true;
|
||||
}
|
||||
|
||||
public enum MeshBlend { Opaque, Alpha, Additive }
|
||||
|
||||
public sealed record MeshDraw(uint FirstIndex,uint IndexCount,int TextureId)
|
||||
{
|
||||
public bool Visible { get; set; } = true;
|
||||
public bool ScreenSpace { get; init; }
|
||||
public float Opacity { get; set; } = 1;
|
||||
public MeshBlend Blend { get; set; } = MeshBlend.Opaque;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ public sealed class MorphAnimation
|
||||
public PngImage Texture { get; }
|
||||
public double SampleInterval { get; }
|
||||
public bool HasVertexMotion { get; }
|
||||
public int FrameCount => frames.Length;
|
||||
private readonly Mesh[] frames;
|
||||
|
||||
public MorphAnimation(string manifestPath)
|
||||
@@ -54,15 +55,15 @@ public sealed class MorphAnimation
|
||||
Texture = new PngImage(width, height, rgba);
|
||||
}
|
||||
|
||||
public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model)
|
||||
public void Sample(double seconds, Span<MeshVertex> destination, Matrix4x4 model, bool loop = true)
|
||||
{
|
||||
if (!double.IsFinite(seconds) || seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
if (destination.Length != Base.Vertices.Length) throw new ArgumentException("Morph target size differs");
|
||||
// Linear interpolation is recovered from DLL 0x10002F9A. Loop closure
|
||||
// and gameplay-specific speed remain preview policies until recovered.
|
||||
var frame = seconds / SampleInterval;
|
||||
var first = (int)(Math.Floor(frame) % frames.Length);
|
||||
var next = (first + 1) % frames.Length;
|
||||
var first = loop ? (int)(Math.Floor(frame) % frames.Length) : (int)Math.Min(Math.Floor(frame), frames.Length - 1);
|
||||
var next = loop ? (first + 1) % frames.Length : Math.Min(first + 1, frames.Length - 1);
|
||||
var t = (float)(frame - Math.Floor(frame));
|
||||
for (var i = 0; i < destination.Length; i++)
|
||||
{
|
||||
|
||||
@@ -14,6 +14,7 @@ public sealed class SceneAudio : IDisposable
|
||||
public bool MusicMuted { get; private set; }
|
||||
public bool SpeechMuted { get; private set; }
|
||||
public bool EffectsMuted { get; private set; }
|
||||
public bool GameplayEffectsEnabled { get; set; } = true;
|
||||
public int EffectCount => effects.Count;
|
||||
public int LoopCount => loops.Count;
|
||||
public int QueuedEffectBytes => effects.Sum(effect => effect.QueuedBytes) + loops.Values.Sum(effect => effect.QueuedBytes);
|
||||
@@ -43,6 +44,7 @@ public sealed class SceneAudio : IDisposable
|
||||
// and original channel/volume policy are separate unrecovered consumers.
|
||||
public void Effect(int id, string? loopOwner = null)
|
||||
{
|
||||
if (!GameplayEffectsEnabled) return;
|
||||
var wave = resources.Wave("SoundEffects.omt", id)
|
||||
?? throw new FileNotFoundException($"Missing original default sound effect {id}");
|
||||
if (loopOwner == null) effects.Add(new(wave.Path, paused: Paused, muted: EffectsMuted));
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct GadgetCanvas(int Id, Vector2 Position);
|
||||
|
||||
/// <summary>Bounded group0 gadget panel; source425870/425EF0/425B20/427370.</summary>
|
||||
public sealed class GadgetScreen(SceneInventory inventory)
|
||||
{
|
||||
public static IReadOnlyList<Vector2> Positions { get; } = Array.AsReadOnly<Vector2>([new(12,182), new(158,182), new(12,327), new(157,327),
|
||||
new(342,182), new(487,182), new(342,327), new(487,327)]);
|
||||
private static readonly int[] idle = [52,46,47,48,49,50,51,45];
|
||||
private Vector2 pointerOffset;
|
||||
public bool Open { get; private set; }
|
||||
public bool PracticeArmed { get; private set; }
|
||||
public int Hovered { get; private set; } = -1;
|
||||
public event Action<int>? PracticeRequested;
|
||||
public event Action? Changed;
|
||||
|
||||
//UI display3 is the default shrink-ray/jetpack; source equipped word is-1.
|
||||
public static int EquippedMode(int displaySelection) => displaySelection == 3 ? -1 : displaySelection;
|
||||
|
||||
public bool Toggle(bool permitted)
|
||||
{
|
||||
if (Open) { Close(); return true; }
|
||||
if (!permitted) return false;
|
||||
if (EquippedMode(inventory.SelectedGadget) != -1)
|
||||
{
|
||||
inventory.SelectGadget(-1); Changed?.Invoke(); return true;
|
||||
}
|
||||
Open = true; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke(); return true;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (!Open) return;
|
||||
Open = false; Hovered = -1; PracticeArmed = false; pointerOffset = Vector2.Zero; Changed?.Invoke();
|
||||
}
|
||||
|
||||
public Vector2 MovePointer(Vector2 point, Vector2 axis, float seconds)
|
||||
{
|
||||
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
if (!Open) return point;
|
||||
//404080: accumulated source80*dt offsets; neutral clears each axis.
|
||||
pointerOffset.X = axis.X > .5f ? pointerOffset.X + 80 * seconds
|
||||
: axis.X < -.5f ? pointerOffset.X - 80 * seconds : 0;
|
||||
pointerOffset.Y = axis.Y > .5f ? pointerOffset.Y + 80 * seconds
|
||||
: axis.Y < -.5f ? pointerOffset.Y - 80 * seconds : 0;
|
||||
return point + pointerOffset;
|
||||
}
|
||||
|
||||
public bool PracticeAvailable(string level, int task) => task < 500
|
||||
&& !(level.Length == 4 && level.StartsWith("VR0", StringComparison.Ordinal) && level[3] is >= '1' and <= '8');
|
||||
|
||||
public void Point(Vector2 point, string level, int task)
|
||||
{
|
||||
Hovered = -1;
|
||||
if (!Open) return;
|
||||
for (var i = 0; i < Positions.Count; i++)
|
||||
if (inventory.State(0,i) is not (0 or 4) && Inside(point,Positions[i],141,141)) Hovered = i;
|
||||
if (PracticeAvailable(level,task) && Inside(point,new(487,95),141,78)) Hovered = 9;
|
||||
if (Inside(point,new(12,95),141,78)) Hovered = 10;
|
||||
}
|
||||
|
||||
public bool Activate(string level, int task)
|
||||
{
|
||||
if (!Open) return false;
|
||||
if (Hovered == 10) { Close(); return true; }
|
||||
if (Hovered == 9 && PracticeAvailable(level,task))
|
||||
{ PracticeArmed = !PracticeArmed; Changed?.Invoke(); return true; }
|
||||
if (Hovered is < 0 or > 7 || inventory.State(0,Hovered) is 0 or 4) return false;
|
||||
var item = Hovered;
|
||||
var practice = PracticeArmed;
|
||||
Close();
|
||||
inventory.SelectGadget(item);
|
||||
if (practice) PracticeRequested?.Invoke(item);
|
||||
return true;
|
||||
}
|
||||
|
||||
public GadgetCanvas[] Canvases(string level, int task)
|
||||
{
|
||||
if (!Open) return [];
|
||||
List<GadgetCanvas> result = [new(20,Vector2.Zero)];
|
||||
for (var i = 0; i < Positions.Count; i++)
|
||||
{
|
||||
//Known route states0/1/4. Other nonzero states retain an owned tile;
|
||||
//their complete inherited visibility is not claimed recovered here.
|
||||
if (inventory.State(0,i) is 0 or 4) continue;
|
||||
result.Add(new(Hovered == i && inventory.State(0,i) != 3 ? 11+i : idle[i],Positions[i]));
|
||||
}
|
||||
result.Add(new(Hovered == 10 ? 181 : 182,new(12,95)));
|
||||
if (PracticeAvailable(level,task))
|
||||
result.Add(new(Hovered == 9 || PracticeArmed ? 179 : 180,new(487,95)));
|
||||
return result.ToArray();
|
||||
}
|
||||
|
||||
private static bool Inside(Vector2 point, Vector2 start, float width, float height) =>
|
||||
point.X > start.X && point.X < start.X + width && point.Y > start.Y && point.Y < start.Y + height;
|
||||
}
|
||||
@@ -4,8 +4,8 @@ using GamePort.Assets;
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct PlayerInput(bool Forward, bool Backward, bool Left, bool Right, bool Jump,
|
||||
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false);
|
||||
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly }
|
||||
bool Rise = false, bool Descend = false, bool StrafeLeft = false, bool StrafeRight = false, bool Fast = false, bool Fire = false);
|
||||
public enum PlayerPose { Idle, Run, Backpedal, Jump, Fall, Fly, Shoot }
|
||||
|
||||
/// <summary>
|
||||
/// Walking, airborne steering and jetpack checkpoint. Recovered arithmetic is described in
|
||||
@@ -39,6 +39,8 @@ public sealed class LabSimulation
|
||||
//predates source-body integration; burst100 is not an interaction-only size.
|
||||
public float InteractionRadius { get; private set; } = 60;
|
||||
public bool JetpackEffectVisible { get; private set; }
|
||||
public Action<PlayerInput>? InputActions { get; set; }
|
||||
public bool Shooting { get; private set; }
|
||||
public float JetpackRemaining => jumpState.EffectRemaining;
|
||||
public int JumpState => jumpState.JumpState;
|
||||
public float JumpHoldSeconds => jumpState.HoldSeconds;
|
||||
@@ -59,7 +61,7 @@ public sealed class LabSimulation
|
||||
public bool Grounded { get; private set; }
|
||||
public PlayerPose Pose => Noclip ? Velocity.LengthSquared() > 0 ? PlayerPose.Fly : PlayerPose.Idle
|
||||
: pendingImpulse.Y > 0 ? PlayerPose.Jump
|
||||
: Grounded ? Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
|
||||
: Grounded ? Shooting ? PlayerPose.Shoot : Speed < -1 ? PlayerPose.Backpedal : Speed > 1 ? PlayerPose.Run : PlayerPose.Idle
|
||||
: jumpState.JumpState == 3 && jumpState.EffectRemaining > 0 ? PlayerPose.Fly
|
||||
: !forceFall && Velocity.Y > 0 ? PlayerPose.Jump : PlayerPose.Fall;
|
||||
public int Steps { get; private set; }
|
||||
@@ -113,6 +115,7 @@ public sealed class LabSimulation
|
||||
lateralContribution = 0; pendingImpulse = Vector3.Zero; movementMode = 0;
|
||||
jumpState = default;
|
||||
forceFall = JetpackEffectVisible = false;
|
||||
Shooting = false;
|
||||
InteractionRadius = 60; Bursts = 0;
|
||||
Grounded = true;
|
||||
Noclip = HasNoclipEntry = false;
|
||||
@@ -168,7 +171,7 @@ public sealed class LabSimulation
|
||||
StepPhysics();
|
||||
if (controlled && !InputAfterPlayerUpdate) StepInput(input);
|
||||
//42469F..4246DC reasserts ordinary grounded radius before ownership
|
||||
//checks. The scooter's separate radius160 policy remains unimplemented.
|
||||
//checks. Bubble mode0's separate radius160 policy remains unimplemented.
|
||||
if (Grounded) InteractionRadius = 60;
|
||||
//424BE0..424C34 runs this wrapper before437940's ownership gate.
|
||||
StepCeiling();
|
||||
@@ -187,6 +190,9 @@ public sealed class LabSimulation
|
||||
Speed = 0; Velocity = Vector3.Zero;
|
||||
}
|
||||
|
||||
public void StopForPrimaryFire() => Speed = 0;
|
||||
public void SetShooting(bool shooting) => Shooting = shooting;
|
||||
|
||||
private void StepCeiling()
|
||||
{
|
||||
if (Velocity.Y <= 0 || ceilingRay == null
|
||||
@@ -228,6 +234,7 @@ public sealed class LabSimulation
|
||||
|
||||
public void StopDebugMotion()
|
||||
{
|
||||
Shooting = false;
|
||||
Velocity = pendingImpulse = Vector3.Zero;
|
||||
Speed = PublishedSpeed = TurnRate = extraAirAcceleration = lateralContribution = 0;
|
||||
jumpState = default; movementMode = 0; forceFall = JetpackEffectVisible = false;
|
||||
@@ -285,6 +292,7 @@ public sealed class LabSimulation
|
||||
targetYaw = Yaw;
|
||||
}
|
||||
StepCamera(); //438BC0/439900 input path owns follow; still provisional geometry/state.
|
||||
InputActions?.Invoke(input);
|
||||
}
|
||||
|
||||
private void StepPlayer(PlayerInput input)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>OMT2 vector::angles second output used by the original shrink ray.</summary>
|
||||
public static class OriginalHeading
|
||||
{
|
||||
private static readonly ushort[] halfAcos = BuildHalfAcos();
|
||||
|
||||
public static float Degrees(Vector3 vector)
|
||||
{
|
||||
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
|
||||
throw new ArgumentOutOfRangeException(nameof(vector), "A finite direction is required.");
|
||||
|
||||
double x = vector.X, z = vector.Z;
|
||||
if (x == 0 && z == 0) return 0;
|
||||
|
||||
// DLL1001FDCB..1001FE3D: truncate the squared ratio, table lookup,
|
||||
// quadrant correction, negate and mask to the original 14-bit circle.
|
||||
// Double intermediates approximate x87 extended precision; see findings.
|
||||
int index = (int)(16384.0 * z * z / (x * x + z * z));
|
||||
int angle = halfAcos[index];
|
||||
if (z < 0)
|
||||
angle = x < 0 ? 8192 + angle : 8192 - angle;
|
||||
else if (x < 0)
|
||||
angle = 16384 - angle;
|
||||
return ((-angle) & 0x3fff) * 0.02197265625f;
|
||||
}
|
||||
|
||||
private static ushort[] BuildHalfAcos()
|
||||
{
|
||||
var table = new ushort[16385];
|
||||
// Stored DLL constants; final endpoint is explicitly zero at100EDD0D.
|
||||
for (int i = 0; i < 16384; i++)
|
||||
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1)
|
||||
* 2607.5945876921437 * 0.5);
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ public sealed class PlayerSceneBinding : IDisposable
|
||||
this.director = director; this.player = player; this.inventory = inventory; this.tag = tag;
|
||||
director.ActorPreparing += Prepare;
|
||||
director.AuthoredTransformChanged += Transform;
|
||||
inventory.GadgetSelected += Selected;
|
||||
Selected(inventory.SelectedGadget);
|
||||
}
|
||||
|
||||
public bool Step(PlayerInput input)
|
||||
@@ -42,6 +44,8 @@ public sealed class PlayerSceneBinding : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private void Selected(int item) => player.GadgetMode = GadgetScreen.EquippedMode(item);
|
||||
|
||||
private void Transform(DirectorActor actor)
|
||||
{
|
||||
if (string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase))
|
||||
@@ -52,5 +56,6 @@ public sealed class PlayerSceneBinding : IDisposable
|
||||
{
|
||||
director.ActorPreparing -= Prepare;
|
||||
director.AuthoredTransformChanged -= Transform;
|
||||
inventory.GadgetSelected -= Selected;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Numerics;
|
||||
using GamePort.Assets;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
/// <summary>First usable default shrink/jetpack device; special gadgets stay separate.</summary>
|
||||
public sealed class SceneGadgets : IDisposable
|
||||
{
|
||||
private readonly LabSimulation player;
|
||||
private readonly SceneInventory inventory;
|
||||
private readonly OriginalScenePhysics physics;
|
||||
private readonly OriginalCameraRay geometry;
|
||||
private bool loop, busy;
|
||||
public ShrinkRay Ray { get; } = new();
|
||||
public IReadOnlyList<ShrinkSoldier> Soldiers { get; }
|
||||
public int ShrinkHits { get; private set; }
|
||||
public event Action<int, bool>? Sound;
|
||||
public event Action? StopSound;
|
||||
public event Action<int>? ScoreAwarded;
|
||||
|
||||
public SceneGadgets(SceneDirector director, SceneInventory inventory, LabSimulation player, Mesh world)
|
||||
{
|
||||
this.inventory = inventory; this.player = player;
|
||||
//Static source registration game-filter is only recovered for the route.
|
||||
geometry = OriginalCameraRay.FromRouteScene(world, player.LevelCode);
|
||||
physics = new OriginalScenePhysics(world);
|
||||
Soldiers = director.Actors.Where(a => a.Kind == "3SOL").Select(a => new ShrinkSoldier(a)).ToArray();
|
||||
foreach (var soldier in Soldiers) soldier.Actor.Animation = "WALK";
|
||||
player.InputActions += Input;
|
||||
}
|
||||
|
||||
public void StepBodies(float seconds)
|
||||
{
|
||||
Ray.StepTexture(seconds);
|
||||
foreach (var soldier in Soldiers) soldier.StepBody(physics, seconds);
|
||||
}
|
||||
|
||||
public void StepTimers(float seconds)
|
||||
{
|
||||
foreach (var soldier in Soldiers) soldier.StepTimer(seconds);
|
||||
}
|
||||
|
||||
private void Input(PlayerInput input)
|
||||
{
|
||||
if (!input.Fire) { busy = false; Stop(); return; }
|
||||
if (busy || player.GadgetMode != -1) { Stop(); return; }
|
||||
player.StopForPrimaryFire();
|
||||
if (inventory.State(0,3) != 1)
|
||||
{ Sound?.Invoke(117,false); busy = true; Stop(); return; }
|
||||
//426937..426989: ordinary airborne FALL stops/hides the owned beam.
|
||||
if (!player.Grounded && player.Pose == PlayerPose.Fall) { Stop(); return; }
|
||||
player.SetShooting(player.Grounded);
|
||||
if (!loop) { Sound?.Invoke(0,true); loop = true; }
|
||||
const float dt = FixedStepClock.Step;
|
||||
if (!(player.LevelCode.Length == 4 && player.LevelCode.StartsWith("VR0",StringComparison.Ordinal)
|
||||
&& player.LevelCode[3] is >= '1' and <= '8')) player.Energy = Math.Clamp(player.Energy - dt,0,100);
|
||||
//Bridge modern signed float yaw to the source's nonnegative Euler domain.
|
||||
var yaw = (player.Yaw % 360 + 360) % 360;
|
||||
var hits = Ray.Fire(player.ActorRoot,yaw,dt,
|
||||
Soldiers.Select(s => new ShrinkCandidate(s.Actor.Tag,s.Actor.Position,Shrunk:s.Shrunk)),
|
||||
(start,end) => geometry.TraceGeometry(start,end));
|
||||
foreach (var tag in hits)
|
||||
{
|
||||
var soldier = Soldiers.First(s => s.Actor.Tag == tag);
|
||||
soldier.Shrink(); ShrinkHits++;
|
||||
//Ordinary3SOL callback42AD81 awards10, then publishes marker94C.
|
||||
//Other enemy classes/special LIBBYPLANT/C3DDINO callbacks are separate.
|
||||
if (!tag.Equals("LIBBYPLANT",StringComparison.OrdinalIgnoreCase)
|
||||
&& !tag.Equals("C3DDINO",StringComparison.OrdinalIgnoreCase))
|
||||
{ ScoreAwarded?.Invoke(10); soldier.MarkScoredHit(); }
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
Ray.Hide(); player.SetShooting(false);
|
||||
if (loop) StopSound?.Invoke();
|
||||
loop = false;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Stop(); busy = false; Ray.Reset(); ShrinkHits = 0;
|
||||
foreach (var soldier in Soldiers) soldier.Reset();
|
||||
}
|
||||
|
||||
public void Dispose() { player.InputActions -= Input; Stop(); }
|
||||
}
|
||||
@@ -32,6 +32,7 @@ public sealed class SceneInteractions
|
||||
public event Action<Vector3>? CheckpointCaptured;
|
||||
public event Action<DirectorActor, string>? ConversationStarted;
|
||||
public event Action<int>? ObjectiveChanged;
|
||||
public void ChangeScore(int delta) => Score = Math.Max(0,unchecked(Score + delta));
|
||||
|
||||
public SceneInteractions(SceneDirector director, TaskStates tasks, OriginalSave save)
|
||||
{
|
||||
@@ -134,8 +135,8 @@ public sealed class SceneInteractions
|
||||
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.
|
||||
//Group0/item3 is the combined shrink ray/jetpack. Objective120 names its
|
||||
//jetpack action; original gadget tile14 and controls113 also name SHRINK.
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace GamePort.Game;
|
||||
|
||||
public readonly record struct ShrinkCandidate(string Tag, Vector3 Position, bool BodyEnabled = true,
|
||||
bool ShrinkEnabled = true, bool Shrunk = false);
|
||||
|
||||
/// <summary>Ordinary owned-item3/mode-1 continuous426E40 scan, not a projectile.</summary>
|
||||
public sealed class ShrinkRay
|
||||
{
|
||||
private float textureTime;
|
||||
public int TexturePhase { get; private set; }
|
||||
public bool Visible { get; private set; }
|
||||
public Vector3 Position { get; private set; }
|
||||
public float Yaw { get; private set; }
|
||||
|
||||
public void StepTexture(float seconds)
|
||||
{
|
||||
Seconds(seconds);
|
||||
textureTime += seconds;
|
||||
//Float accumulation compared with the source stored double0.1.
|
||||
if ((double)textureTime <= .1) return;
|
||||
TexturePhase = (TexturePhase + 1) % 3;
|
||||
textureTime = 0;
|
||||
}
|
||||
|
||||
public void Hide() => Visible = false;
|
||||
public void Reset() { Visible = false; TexturePhase = 0; textureTime = 0; }
|
||||
|
||||
public IReadOnlyList<string> Fire(Vector3 root, float yaw, float seconds,
|
||||
IEnumerable<ShrinkCandidate> candidates, Func<Vector3, Vector3, SupportHit?> wallQuery)
|
||||
{
|
||||
Seconds(seconds);
|
||||
if (!float.IsFinite(yaw)) throw new ArgumentOutOfRangeException(nameof(yaw));
|
||||
Visible = true; Position = root; Yaw = yaw;
|
||||
List<string> hits = [];
|
||||
foreach (var target in candidates)
|
||||
{
|
||||
if (!target.BodyEnabled || !target.ShrinkEnabled || target.Shrunk
|
||||
|| target.Position.Y <= root.Y - 150 || target.Position.Y >= root.Y + 60) continue;
|
||||
var difference = target.Position - root;
|
||||
var distance = difference.Length();
|
||||
if (distance >= 1500) continue;
|
||||
var heading = OriginalHeading.Degrees(difference);
|
||||
//No added angle-seam wrapping in the recovered comparison.
|
||||
if (heading <= yaw - 5 || heading >= yaw + 5) continue;
|
||||
var (sin, cos) = LabSimulation.Trig(yaw);
|
||||
var start = root + Vector3.UnitY * 150;
|
||||
var end = start + new Vector3(-sin * distance, 0, cos * distance);
|
||||
if (wallQuery(start, end) != null) continue;
|
||||
hits.Add(target.Tag);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
private static void Seconds(float seconds)
|
||||
{
|
||||
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bounded original3SOL body settling and shrink state; combat/path AI remain open.</summary>
|
||||
public sealed class ShrinkSoldier(DirectorActor actor)
|
||||
{
|
||||
public DirectorActor Actor { get; } = actor;
|
||||
public Vector3 Velocity { get; private set; }
|
||||
public bool Grounded { get; private set; }
|
||||
public bool Shrunk { get; private set; }
|
||||
public float Remaining { get; private set; }
|
||||
public int AuthoredMode { get; } = actor.SourceGam?.Integer("AIState",2) ?? 2;
|
||||
public int PreviousMode { get; private set; }
|
||||
public int ShrinkRevision { get; private set; }
|
||||
public float HitMarker { get; private set; }
|
||||
public void MarkScoredHit() => HitMarker = 1;
|
||||
public void Reset()
|
||||
{
|
||||
Velocity = Vector3.Zero; Grounded = Shrunk = false; Remaining = 0;
|
||||
ShrinkRevision = 0; HitMarker = 0; Actor.Animation = "WALK";
|
||||
}
|
||||
|
||||
public void StepBody(OriginalScenePhysics physics, float seconds)
|
||||
{
|
||||
var result = physics.Step(Actor.Position, Velocity, 90, 1, Grounded, seconds);
|
||||
Actor.Position = result.Body.Position; Velocity = result.Body.Velocity; Grounded = result.Supported;
|
||||
}
|
||||
|
||||
public void Shrink()
|
||||
{
|
||||
if (Shrunk) return;
|
||||
PreviousMode = Actor.AIstate; Actor.AIstate = 5;
|
||||
Actor.Animation = "SHRINK"; Remaining = 30; Shrunk = true; ShrinkRevision++;
|
||||
}
|
||||
|
||||
public void StepTimer(float seconds)
|
||||
{
|
||||
if (!float.IsFinite(seconds) || seconds < 0 || seconds >= 1) throw new ArgumentOutOfRangeException(nameof(seconds));
|
||||
if (!Shrunk || Remaining <= 0) return;
|
||||
Remaining -= seconds;
|
||||
//Source44AE85: exact zero does not expire and is skipped next tick.
|
||||
if (Remaining >= 0) return;
|
||||
Remaining = 0; Shrunk = false; HitMarker = 0;
|
||||
PreviousMode = Actor.AIstate;
|
||||
Actor.AIstate = AuthoredMode; Actor.Animation = "WALK"; Actor.Speed = 200;
|
||||
}
|
||||
}
|
||||
+209
-14
@@ -85,6 +85,9 @@ internal static class Program
|
||||
--smoke-practice-return Headless lab/VR04/RETURN root and intro-suppression check
|
||||
--smoke-practice-window SDL practice pause/dismiss/resize check (12 frames)
|
||||
--smoke-jetpack 300-step powered steering/jump check in VR04
|
||||
--smoke-shrink-ray Fire at an actual VR04 soldier; explicit player-placement fixture
|
||||
--gadget-menu Render original gadget panel (--skip-intro); fixture owns item3
|
||||
--smoke-gadget-menu SDL menu input/pause/selection/practice/Return check (24 frames)
|
||||
--smoke-jump-key NAME Replay using shift/right-shift/insert/keypad0/right-mouse
|
||||
--smoke-carl-cutscene Verify input stays locked during the lab conversation
|
||||
--smoke-control-phases Airborne cutscene body/fire and restoration fixture
|
||||
@@ -251,6 +254,7 @@ internal static class Program
|
||||
var animationPath = Option(args, "--animation");
|
||||
var walkSmoke = args.Contains("--smoke-walk");
|
||||
var jetpackSmoke = args.Contains("--smoke-jetpack");
|
||||
var shrinkSmoke = args.Contains("--smoke-shrink-ray");
|
||||
var carlSmoke = args.Contains("--smoke-carl-cutscene");
|
||||
var controlPhaseSmoke = args.Contains("--smoke-control-phases");
|
||||
var objectiveWindowSmoke = args.Contains("--smoke-objective-window");
|
||||
@@ -266,11 +270,12 @@ internal static class Program
|
||||
var debugSmoke = args.Contains("--smoke-debug-menu");
|
||||
var toolsSmoke = args.Contains("--smoke-debug-tools");
|
||||
var diagnosticsSmoke = args.Contains("--smoke-debug-overlay");
|
||||
var gadgetWindowSmoke = args.Contains("--smoke-gadget-menu");
|
||||
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 || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
|
||||
|| args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || practiceReturnSmoke || carlSmoke || controlPhaseSmoke || objectiveSmoke;
|
||||
if (story && (args.Contains("--inspect") || walkSmoke || args.Contains("--smoke-window")))
|
||||
throw new ArgumentException("Story playback requires its own simulation mode.");
|
||||
if (walkSmoke && args.Contains("--inspect")) throw new ArgumentException("Walk smoke cannot run in inspection mode.");
|
||||
@@ -292,6 +297,11 @@ internal static class Program
|
||||
SceneInteractions? interactions = null;
|
||||
SceneMechanisms? mechanisms = null;
|
||||
SceneHud? hud = null;
|
||||
GadgetScreen? gadgetScreen = null;
|
||||
GadgetMenuOverlay? gadgetOverlay = null;
|
||||
SceneGadgets? gadgets = null;
|
||||
ShrinkRayVisuals? rayVisuals = null;
|
||||
ShrinkSoldierVisuals? soldierVisuals = null;
|
||||
JetpackVisuals? jetpackVisuals = null;
|
||||
var practice = new PracticePrompt();
|
||||
ObjectivePanel? objectivePanel = null;
|
||||
@@ -344,7 +354,7 @@ internal static class Program
|
||||
characterModel = placement.Model;
|
||||
mesh = animations.Current.AppendTo(mesh);
|
||||
if (walking)
|
||||
Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; R reset; C pause/inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
|
||||
Console.WriteLine("Controllable lab: arrows move/turn; Shift/Insert/right mouse jump; Enter/Ctrl/left mouse fire; Tab/Space gadgets; R reset; C inspect; F11 fullscreen; Escape quit. Collision, pivot and timing remain provisional.");
|
||||
else
|
||||
Console.WriteLine($"Preview floor correction: +{placement.VerticalCorrection:F3} Y. 1 idle, 2 run, 3 jump, 4 scratch.");
|
||||
}
|
||||
@@ -358,11 +368,17 @@ internal static class Program
|
||||
storyTasks = tasks;
|
||||
director = new SceneDirector(level!, tasks, resources.Duration);
|
||||
interactions = new SceneInteractions(director, tasks, save);
|
||||
gadgetScreen = new GadgetScreen(interactions.Inventory);
|
||||
interactions.Inventory.ApplyLevelAvailability(level!.Code);
|
||||
objectivePanel = new ObjectivePanel(interactions.CurrentObjective);
|
||||
interactions.ObjectiveChanged += objectivePanel.Select;
|
||||
simulation!.Energy = interactions.Energy;
|
||||
simulation.JetpackInventoryState = () => interactions.Inventory.State(0, 3);
|
||||
if (level.Code is "LV1B" or "VR04" or "LEV1")
|
||||
{
|
||||
gadgets = new SceneGadgets(director,interactions.Inventory,simulation,world);
|
||||
gadgets.ScoreAwarded += interactions.ChangeScore;
|
||||
}
|
||||
mechanisms = new SceneMechanisms(director);
|
||||
interactions.Transition += RequestTransition;
|
||||
interactions.PracticeRequested += practice.Show;
|
||||
@@ -373,6 +389,11 @@ internal static class Program
|
||||
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
|
||||
RequestTransition(new(PracticePrompt.Destination(mode), "PHONEBOOTH", 0, -1));
|
||||
};
|
||||
gadgetScreen.PracticeRequested += item =>
|
||||
{
|
||||
interactions.SetReturnContext(Path.GetFileName(levelPath!), originalStart!.Tag!);
|
||||
RequestTransition(new($"VR0{item + 1}.gam", "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"))
|
||||
{
|
||||
@@ -393,6 +414,12 @@ internal static class Program
|
||||
actorVisuals = new SceneActorVisuals(mesh, world, director, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),
|
||||
actor => patrols.ContainsKey(actor.Tag));
|
||||
mesh = actorVisuals.Mesh;
|
||||
if (gadgets != null)
|
||||
{
|
||||
soldierVisuals = new ShrinkSoldierVisuals(mesh,gadgets.Soldiers,
|
||||
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),level!.Code);
|
||||
mesh = soldierVisuals.Mesh;
|
||||
}
|
||||
spriteVisuals = new SceneSpriteVisuals(mesh, director, resources);
|
||||
mesh = spriteVisuals.Mesh;
|
||||
staticVisuals = new StaticSceneVisuals(mesh, director, root, Path.Combine(Path.GetDirectoryName(scene!)!, "models"));
|
||||
@@ -406,10 +433,18 @@ internal static class Program
|
||||
DynamicBodyResponse.Resolve(staticVisuals.DoorColliders(), previous, position, radius);
|
||||
jetpackVisuals = new JetpackVisuals(mesh, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")));
|
||||
mesh = jetpackVisuals.Mesh;
|
||||
if (gadgets != null)
|
||||
{
|
||||
rayVisuals = new ShrinkRayVisuals(mesh,Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene!)!, "..")),root);
|
||||
mesh = rayVisuals.Mesh;
|
||||
}
|
||||
hud = new SceneHud(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../ui/ui.json"));
|
||||
mesh = hud.Mesh;
|
||||
gadgetOverlay = new GadgetMenuOverlay(mesh, Path.Combine(Path.GetDirectoryName(scene!)!, "../gadgets/gadgets.json"));
|
||||
mesh = gadgetOverlay.Mesh;
|
||||
Console.WriteLine($"Prepared source model actors: {staticVisuals.ActorCount}.");
|
||||
}
|
||||
using var gadgetLifetime = gadgets;
|
||||
var debugMenu = new DebugMenu(scene != null && level != null
|
||||
? DebugMenu.AvailableScenes(root, Path.GetFullPath(Path.Combine(Path.GetDirectoryName(scene)!, ".."))) : [],
|
||||
Path.GetFileName(levelPath), originalStart?.Tag);
|
||||
@@ -437,7 +472,11 @@ internal static class Program
|
||||
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" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
|
||||
var frames = int.Parse(Option(args, "--frames") ?? (walkSmoke ? "240" : jetpackSmoke ? "300" : shrinkSmoke ? "90" : gadgetWindowSmoke ? "24" : objectiveWindowSmoke ? "180" : carlSmoke ? "60" : controlPhaseSmoke ? "32" : toolsSmoke ? "20" : debugSmoke ? "16" : diagnosticsSmoke ? "24" : headless ? "1" : "0"));
|
||||
if (gadgetWindowSmoke && (headless || level?.Code != "LV1B" || loadedSave != null || frames < 24))
|
||||
throw new ArgumentException("Gadget menu SDL fixture requires a fresh windowed lab and24 frames");
|
||||
if (shrinkSmoke && (level?.Code != "VR04" || gadgets == null || frames < 60))
|
||||
throw new ArgumentException("Shrink-ray smoke requires actual VR04 and at least60 frames");
|
||||
if (controlPhaseSmoke && (level?.Code != "LV1B" || loadedSave != null || frames < 32 || director == null))
|
||||
throw new ArgumentException("Control-phase fixture needs a fresh lab and at least32 frames");
|
||||
if (toolsSmoke && (headless || frames < 16 || director == null || level?.Code != "LV1B" || loadedSave != null || debugMenu.Open))
|
||||
@@ -467,12 +506,25 @@ internal static class Program
|
||||
walking ? WalkTitle : animations?.WindowTitle ?? "Jimmy Neutron — scene preview | C camera",
|
||||
width, height, !args.Contains("--no-validation"));
|
||||
var window = presentation.Window;
|
||||
ShrinkSoldier? shrinkVictim = null;
|
||||
var shrinkPhaseMask = 0;
|
||||
var sawShrinkKey = false;
|
||||
Console.WriteLine($"Scene presentation: revision={renderer.SceneRevision}, windows={presentation.WindowCreationCount}, renderers={presentation.RendererCreationCount}, window ID={(window == 0 ? 0 : Sdl.SDL_GetWindowID(window))}, size={renderer.Width}x{renderer.Height}.");
|
||||
{
|
||||
using var audio = Option(args, "--audio") is { } audioFile
|
||||
? new SdlAudio(audioFile, args.Contains("--loop-audio"), debugMenu.Open) : null;
|
||||
using var sceneAudio = resources != null && !headless && !args.Contains("--mute") ? new SceneAudio(resources) : null;
|
||||
sceneAudio?.SetPaused(debugMenu.Open);
|
||||
if (gadgets != null)
|
||||
{
|
||||
gadgets.Sound += (id,loop) => sceneAudio?.Effect(id,loop ? "shrink-ray" : null);
|
||||
gadgets.StopSound += () => sceneAudio?.StopLoop("shrink-ray");
|
||||
}
|
||||
if (gadgetScreen != null) gadgetScreen.Changed += () =>
|
||||
{
|
||||
gadgets?.Stop();
|
||||
if (sceneAudio != null) sceneAudio.GameplayEffectsEnabled = !gadgetScreen.Open;
|
||||
};
|
||||
double initialPoseTime = 0;
|
||||
if (director != null)
|
||||
{
|
||||
@@ -488,6 +540,7 @@ internal static class Program
|
||||
sceneAudio.Music(originalStart!.Text("MusicDatabase") ?? "none", originalStart.Integer("MusicIndex", -1));
|
||||
}
|
||||
director.Begin(originalStart!, activateStartTrigger: !returning);
|
||||
gadgets?.Reset();
|
||||
interactions!.Reset();
|
||||
mechanisms!.Reset();
|
||||
director.SyncActor(level!.Player!.Tag!, simulation!.ActorRoot, new Vector3(0, simulation.Yaw, 0));
|
||||
@@ -503,7 +556,8 @@ internal static class Program
|
||||
Console.WriteLine($"Practice RETURN: exact saved root={restored}, root={simulation.ActorRoot}, STRT yaw={simulation.Yaw}, intro suppressed={!director.Playing}, companion restored={companionRestored}, retained player input order={simulation.InputAfterPlayerUpdate}, gadget availability={interactions.Inventory.State(0, 3)}.");
|
||||
if (!restored) throw new InvalidOperationException("RETURN did not restore the live departure root without replaying STRT actions");
|
||||
}
|
||||
if (args.Contains("--skip-intro") || jetpackSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
|
||||
if (args.Contains("--skip-intro") || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke || controlPhaseSmoke) { sceneAudio?.StopSpeech(); director.Skip(); }
|
||||
if (gadgetWindowSmoke) { interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3); }
|
||||
if (controlPhaseSmoke)
|
||||
{
|
||||
interactions.Inventory.SetState(0, 3, 1); interactions.Inventory.SelectGadget(3);
|
||||
@@ -561,7 +615,9 @@ internal static class Program
|
||||
}
|
||||
for (var tick = 0; tick < (int)Math.Round(storyTime * 60) && !practice.Active && !debugMenu.Open; tick++)
|
||||
{
|
||||
gadgets?.StepBodies(FixedStepClock.Step);
|
||||
playerBinding!.Step(default);
|
||||
gadgets?.StepTimers(FixedStepClock.Step);
|
||||
interactions!.UpdateEnergy(simulation!.Energy);
|
||||
foreach (var patrol in patrols.Values) patrol.Step(FixedStepClock.Step);
|
||||
mechanisms!.Step(FixedStepClock.Step);
|
||||
@@ -570,10 +626,51 @@ internal static class Program
|
||||
if (animations!.SelectAction(director.FindActor(level!.Player!.Tag!)!.Animation)) initialPoseTime = 0;
|
||||
initialPoseTime += FixedStepClock.Step;
|
||||
actorVisuals!.Update(FixedStepClock.Step, mesh);
|
||||
soldierVisuals?.Update(FixedStepClock.Step,mesh);
|
||||
spriteVisuals!.Step(FixedStepClock.Step);
|
||||
}
|
||||
if (args.Contains("--gadget-menu"))
|
||||
{
|
||||
interactions!.Inventory.SetState(0,3,1);
|
||||
if (!gadgetScreen!.Toggle(director.Controlled && director.InventoryEnabled))
|
||||
throw new InvalidOperationException("Gadget screen requires player control (--skip-intro)");
|
||||
gadgetScreen.Point(new(200,380), level!.Code, storyTasks!.Get("SCENE"));
|
||||
}
|
||||
if (shrinkSmoke)
|
||||
{
|
||||
//Explicit test placement near an ACTUAL authored soldier.
|
||||
//No invented targets or relocation of the soldier to entry.
|
||||
for (var tick = 0; tick < 600; tick++) gadgets!.StepBodies(FixedStepClock.Step);
|
||||
var floorQuery = new SceneCollision(world);
|
||||
var sourceQuery = OriginalCameraRay.FromRouteScene(world,"VR04");
|
||||
foreach (var soldier in gadgets!.Soldiers)
|
||||
{
|
||||
foreach (var direction in new[] {Vector3.UnitZ,-Vector3.UnitZ,Vector3.UnitX,-Vector3.UnitX})
|
||||
{
|
||||
var candidate = soldier.Actor.Position - direction * 500;
|
||||
var floor = floorQuery.GroundHeight(candidate + Vector3.UnitY * 500,2500);
|
||||
if (floor == null) continue;
|
||||
candidate.Y = floor.Value + OriginalBodySupport.JimmyRadius * OriginalBodySupport.JimmyFactor;
|
||||
if (soldier.Actor.Position.Y <= candidate.Y - 150 || soldier.Actor.Position.Y >= candidate.Y + 60
|
||||
|| sourceQuery.TraceGeometry(candidate + Vector3.UnitY * 150,soldier.Actor.Position + Vector3.UnitY * 150) != null) continue;
|
||||
var fixtureYaw = OriginalHeading.Degrees(soldier.Actor.Position - candidate);
|
||||
var (viewSin,viewCos) = LabSimulation.Trig(fixtureYaw);
|
||||
var fixtureEye = candidate + new Vector3(viewSin*350,180,-viewCos*350);
|
||||
if (sourceQuery.TraceGeometry(fixtureEye,soldier.Actor.Position + Vector3.UnitY*25) != null) continue;
|
||||
simulation!.ApplyAuthoredTransform(candidate,fixtureYaw);
|
||||
simulation.RestoreReturnRoot(candidate); //Fixture camera snap at the explicitly moved player.
|
||||
shrinkVictim = soldier; break;
|
||||
}
|
||||
if (shrinkVictim != null) break;
|
||||
}
|
||||
if (shrinkVictim == null) throw new InvalidOperationException("No supported source ray fixture near actual VR04 soldier");
|
||||
interactions!.Inventory.SetState(0,3,1); interactions.Inventory.SelectGadget(3);
|
||||
Console.WriteLine($"Shrink fixture: actual target={shrinkVictim.Actor.Tag}, target root={shrinkVictim.Actor.Position}, player root={simulation!.ActorRoot}.");
|
||||
}
|
||||
}
|
||||
var keys = new HashSet<uint>();
|
||||
var gadgetHeldKeys = new HashSet<uint>();
|
||||
var gadgetArrows = new HashSet<uint>();
|
||||
var debugCapturedKeys = new HashSet<uint>();
|
||||
var running = true;
|
||||
var sawKey = false;
|
||||
@@ -584,6 +681,7 @@ internal static class Program
|
||||
var inspecting = !walking;
|
||||
var active = presentation.HasInputFocus;
|
||||
var mouseJump = false;
|
||||
var mouseFire = false;
|
||||
var stepClock = new FixedStepClock();
|
||||
double poseTime = initialPoseTime;
|
||||
var injectedInput = default(PlayerInput);
|
||||
@@ -620,12 +718,16 @@ internal static class Program
|
||||
var toolsEntry = simulation?.ActorRoot ?? Vector3.Zero;
|
||||
var controlEntry = simulation?.ActorRoot ?? Vector3.Zero;
|
||||
var phasesLocked = false; var phasesResumed = false;
|
||||
var gadgetChecks = new bool[7];
|
||||
var gadgetEntry = simulation?.ActorRoot ?? Vector3.Zero;
|
||||
var gadgetPausedSteps = 0;
|
||||
void ResetScene()
|
||||
{
|
||||
gadgetScreen?.Close();
|
||||
if (simulation == null) { debugMenu.Message = "RESET REQUIRES PLAY MODE"; return; }
|
||||
if (practice.Active) practice.Key(17, Vector2.Zero);
|
||||
simulation.Reset(); poseTime = 0; sceneAudio?.StopSpeech(); director?.Begin(originalStart!);
|
||||
interactions?.Reset(); mechanisms?.Reset();
|
||||
interactions?.Reset(); mechanisms?.Reset(); gadgets?.Reset(); mouseFire = false;
|
||||
director?.SyncActor(level!.Player!.Tag!, simulation.ActorRoot, new Vector3(0, simulation.Yaw, 0));
|
||||
}
|
||||
void ToggleCamera()
|
||||
@@ -639,6 +741,8 @@ internal static class Program
|
||||
}
|
||||
void DebugInputBoundary()
|
||||
{
|
||||
gadgetArrows.Clear();
|
||||
gadgets?.Stop(); mouseFire = false;
|
||||
debugCapturedKeys.UnionWith(keys);
|
||||
keys.Clear(); mouseJump = false; stepClock.Reset(); last = clock.Elapsed.TotalSeconds;
|
||||
audio?.SetPaused(debugMenu.Open); sceneAudio?.SetPaused(debugMenu.Open);
|
||||
@@ -764,6 +868,33 @@ internal static class Program
|
||||
}
|
||||
while (running)
|
||||
{
|
||||
if (gadgetWindowSmoke)
|
||||
{
|
||||
void Key(uint key,bool down) { var e=new Sdl.Event {Type=down?Sdl.KeyDown:Sdl.KeyUp,Scancode=key,Down=down?(byte)1:(byte)0};
|
||||
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
|
||||
void Click(bool down) { var e=new Sdl.Event {Type=down?Sdl.MouseButtonDown:Sdl.MouseButtonUp,MouseButton=1};
|
||||
if(!Sdl.SDL_PushEvent(ref e))throw new InvalidOperationException(Sdl.Error); }
|
||||
void Aim(Vector2 point) { Sdl.SDL_GetWindowSize(window,out var w,out var h);var v=new UiViewport(renderer.Width,renderer.Height);
|
||||
var p=v.ToNdc(point+v.CenterOffset);Sdl.SDL_WarpMouseInWindow(window,(p.X+1)*w/2,(p.Y+1)*h/2); }
|
||||
if(count==0)Key(43,true);
|
||||
if(count==1){gadgetPausedSteps=simulation!.Steps;Key(44,true);}
|
||||
if(count==2){gadgetChecks[0]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(43,false);}
|
||||
if(count==3){gadgetChecks[1]=gadgetScreen!.Open&&simulation!.Steps==gadgetPausedSteps;Key(41,true);}
|
||||
if(count==4){gadgetChecks[2]=!gadgetScreen!.Open&&running;Key(41,false);Key(44,false);Key(43,true);}
|
||||
if(count==5){Aim(new(200,380));Key(40,true);}
|
||||
if(count==6){gadgetChecks[3]=!gadgetScreen!.Open&&interactions!.Inventory.SelectedGadget==3
|
||||
&&simulation!.GadgetMode==-1&&gadgets?.Ray.Visible!=true;Key(40,false);Key(43,false);Key(43,true);}
|
||||
if(count==7){Aim(new(520,120));Click(true);}
|
||||
if(count==8){gadgetChecks[4]=gadgetScreen!.PracticeArmed;Click(false);Aim(new(50,120));Click(true);}
|
||||
if(count==9){gadgetChecks[5]=!gadgetScreen!.Open&&!gadgetScreen.PracticeArmed&&transitionRequest==null;Key(43,false);Click(false);}
|
||||
if(count==11){gadgetChecks[6]=simulation!.Jumps==0&&gadgets?.Ray.Visible!=true
|
||||
&&Vector3.Distance(simulation.ActorRoot,gadgetEntry)<.1f;Key(43,true);Aim(new(200,380));}
|
||||
}
|
||||
if (shrinkSmoke && !headless && count == 0)
|
||||
{
|
||||
var fire = new Sdl.Event {Type=Sdl.KeyDown,Scancode=224,Down=1};
|
||||
if (!Sdl.SDL_PushEvent(ref fire)) throw new InvalidOperationException(Sdl.Error);
|
||||
}
|
||||
if ((walkSmoke || jetpackSmoke) && !headless)
|
||||
{
|
||||
var requested = jetpackSmoke ? LabSimulation.JetpackSmokeInput(simulation!.Steps)
|
||||
@@ -786,9 +917,10 @@ internal static class Program
|
||||
if (e.Type is Sdl.Quit or 0x210) running = false;
|
||||
if (e.Type is Sdl.WindowResized or Sdl.WindowPixelSizeChanged) renderer.Resize();
|
||||
if (e.Type is Sdl.WindowFocusLost or Sdl.WindowMinimized)
|
||||
{ keys.Clear(); debugCapturedKeys.Clear(); mouseJump = false; active = false; stepClock.Reset(); }
|
||||
{ keys.Clear(); debugCapturedKeys.Clear(); gadgetHeldKeys.Clear(); gadgetArrows.Clear(); mouseJump = mouseFire = false; gadgets?.Stop(); active = false; stepClock.Reset(); }
|
||||
if (e.Type is Sdl.WindowFocusGained or Sdl.WindowRestored)
|
||||
{ active = true; stepClock.Reset(); last = clock.Elapsed.TotalSeconds; }
|
||||
if (e.Type == Sdl.KeyUp) { gadgetHeldKeys.Remove(e.Scancode); gadgetArrows.Remove(e.Scancode); }
|
||||
if (e.Type == Sdl.KeyUp && debugCapturedKeys.Remove(e.Scancode)) continue;
|
||||
if (e.Type == Sdl.KeyDown && !debugMenu.Open && debugCapturedKeys.Contains(e.Scancode)) continue;
|
||||
if (e.Type == Sdl.KeyDown && e.Scancode == DebugDiagnostics.ToggleKey)
|
||||
@@ -820,13 +952,36 @@ internal static class Program
|
||||
continue;
|
||||
}
|
||||
if (practice.Active && e.Type == Sdl.MouseButtonDown)
|
||||
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = false; stepClock.Reset(); continue; }
|
||||
{ if (e.MouseButton == 1) practice.Click(Pointer()); keys.Clear(); mouseJump = mouseFire = 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;
|
||||
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
|
||||
}
|
||||
if (e.Type == Sdl.KeyDown && e.Scancode is 43 or 44
|
||||
&& !inspecting && simulation?.Noclip != true && !practice.Active && gadgetScreen != null
|
||||
&& (gadgetScreen.Open || director is { Controlled: true, InventoryEnabled: true }))
|
||||
{
|
||||
var first = gadgetHeldKeys.Count == 0;
|
||||
gadgetHeldKeys.Add(e.Scancode);
|
||||
if (first && e.Repeat == 0) gadgetScreen.Toggle(director is { Controlled: true, InventoryEnabled: true });
|
||||
debugCapturedKeys.UnionWith(keys);
|
||||
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
|
||||
}
|
||||
if (gadgetScreen?.Open == true)
|
||||
{
|
||||
if (e.Type == Sdl.KeyDown && e.Scancode is >= 79 and <= 82) gadgetArrows.Add(e.Scancode);
|
||||
gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
|
||||
if (e.Type == Sdl.KeyDown) debugCapturedKeys.Add(e.Scancode);
|
||||
if (e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode == 41) gadgetScreen.Close();
|
||||
else if (e.Type == Sdl.MouseButtonDown && e.MouseButton is 1 or 3
|
||||
|| e.Type == Sdl.KeyDown && e.Repeat == 0 && e.Scancode is 40 or 88 or 224 or 228 or 225 or 229 or 73 or 98)
|
||||
gadgetScreen.Activate(level.Code,storyTasks.Get("SCENE"));
|
||||
keys.Clear(); mouseJump = mouseFire = false; stepClock.Reset(); continue;
|
||||
}
|
||||
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 1) mouseFire = true;
|
||||
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 1) mouseFire = false;
|
||||
if (e.Type == Sdl.MouseButtonDown && e.MouseButton == 3)
|
||||
{
|
||||
mouseJump = true;
|
||||
@@ -835,6 +990,7 @@ internal static class Program
|
||||
if (e.Type == Sdl.MouseButtonUp && e.MouseButton == 3) mouseJump = false;
|
||||
if (e.Type == Sdl.KeyDown)
|
||||
{
|
||||
if (shrinkSmoke && e.Scancode == 224) sawShrinkKey = true;
|
||||
keys.Add(e.Scancode);
|
||||
if (walkSmoke) sawWalkKeys |= e.Scancode == 82 ? 1 : e.Scancode == 79 ? 2 : e.Scancode == jumpScancode ? 4 : 0;
|
||||
if (jetpackSmoke) sawJetpackKeys |= e.Scancode == 82 ? 1 : e.Scancode == 81 ? 2 : e.Scancode == 80 ? 4 : e.Scancode == jumpScancode ? 8 : 0;
|
||||
@@ -868,24 +1024,41 @@ internal static class Program
|
||||
var elapsed = now - last;
|
||||
var dt = (float)Math.Min(elapsed, 0.1);
|
||||
last = now;
|
||||
if (debugMenu.Open) animationStarted += elapsed;
|
||||
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && (active || headless || walkSmoke || jetpackSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
|
||||
if (gadgetScreen?.Open == true && !headless && !debugMenu.Open)
|
||||
{
|
||||
var steps = headless || walkSmoke || jetpackSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
|
||||
var axis = new Vector2((gadgetArrows.Contains(79) ? 1 : 0) - (gadgetArrows.Contains(80) ? 1 : 0),
|
||||
(gadgetArrows.Contains(81) ? 1 : 0) - (gadgetArrows.Contains(82) ? 1 : 0));
|
||||
var point = Pointer();
|
||||
var moved = gadgetScreen.MovePointer(point,axis,dt);
|
||||
if (moved != point && Sdl.SDL_GetWindowSize(window,out var menuWidth,out var menuHeight))
|
||||
{
|
||||
var viewport = new UiViewport(renderer.Width,renderer.Height);
|
||||
var ndc = viewport.ToNdc(moved + viewport.CenterOffset);
|
||||
Sdl.SDL_WarpMouseInWindow(window,(ndc.X + 1) * menuWidth / 2,(ndc.Y + 1) * menuHeight / 2);
|
||||
}
|
||||
}
|
||||
if (debugMenu.Open) animationStarted += elapsed;
|
||||
if (simulation != null && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true && (active || headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke))
|
||||
{
|
||||
var steps = headless || walkSmoke || jetpackSmoke || shrinkSmoke || gadgetWindowSmoke || practiceWindowSmoke || carlSmoke || controlPhaseSmoke || objectiveWindowSmoke || debugSmoke || diagnosticsSmoke || toolsSmoke ? 1 : stepClock.Advance(elapsed);
|
||||
for (var step = 0; step < steps; step++)
|
||||
{
|
||||
var input = carlSmoke || controlPhaseSmoke ? new PlayerInput(true, false, true, false, true)
|
||||
: shrinkSmoke && headless ? new PlayerInput(false,false,false,false,false,Fire:true)
|
||||
: jetpackSmoke && headless ? LabSimulation.JetpackSmokeInput(simulation.Steps)
|
||||
: walkSmoke && headless ? LabSimulation.SmokeInput(simulation.Steps) : new PlayerInput(
|
||||
keys.Contains(82) || simulation.Noclip && keys.Contains(26), keys.Contains(81) || simulation.Noclip && keys.Contains(22), keys.Contains(80), keys.Contains(79),
|
||||
mouseJump || keys.Contains(225) || keys.Contains(229) || keys.Contains(73) || keys.Contains(98),
|
||||
keys.Contains(44) || keys.Contains(8), keys.Contains(224) || keys.Contains(228) || keys.Contains(20),
|
||||
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229));
|
||||
keys.Contains(4), keys.Contains(7), keys.Contains(225) || keys.Contains(229),
|
||||
mouseFire || keys.Contains(40) || keys.Contains(88) || keys.Contains(224) || keys.Contains(228));
|
||||
gadgets?.StepBodies(FixedStepClock.Step);
|
||||
var before = simulation.Position;
|
||||
var powered = simulation.JetpackEffectVisible && !simulation.Grounded;
|
||||
bool acceptsInput;
|
||||
if (playerBinding != null) acceptsInput = playerBinding.Step(input);
|
||||
else { simulation.Step(input); acceptsInput = true; }
|
||||
gadgets?.StepTimers(FixedStepClock.Step);
|
||||
if (jetpackSmoke && powered)
|
||||
{
|
||||
poweredAirTravel += Vector2.Distance(new(before.X, before.Z), new(simulation.Position.X, simulation.Position.Z));
|
||||
@@ -913,6 +1086,7 @@ internal static class Program
|
||||
if (switched) poseTime = 0;
|
||||
poseTime += FixedStepClock.Step;
|
||||
actorVisuals?.Update(FixedStepClock.Step, mesh);
|
||||
soldierVisuals?.Update(FixedStepClock.Step,mesh);
|
||||
spriteVisuals?.Step(FixedStepClock.Step);
|
||||
}
|
||||
characterModel = simulation.Model;
|
||||
@@ -945,13 +1119,22 @@ internal static class Program
|
||||
renderEye = storyEye; renderTarget = storyTarget;
|
||||
}
|
||||
staticVisuals?.Update(mesh);
|
||||
if (debugMenu.Open || inspecting || practice.Active || director?.Controlled == false) gadgets?.Stop();
|
||||
soldierVisuals?.Update(0,mesh);
|
||||
if (gadgets != null) rayVisuals!.Update(mesh,gadgets.Ray,simulation!.Steps / 60d);
|
||||
if (shrinkSmoke && gadgets!.Ray.Visible) shrinkPhaseMask |= 1 << gadgets.Ray.TexturePhase;
|
||||
jetpackVisuals?.Update(mesh, simulation!);
|
||||
spriteVisuals?.FaceCamera(renderEye, renderTarget, mesh);
|
||||
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active
|
||||
objectivePanel?.Key(keys.Contains(18) && !debugMenu.Open && !inspecting && !practice.Active && gadgetScreen?.Open != true
|
||||
&& director is { Controlled: true, InventoryEnabled: true });
|
||||
objectivePanel?.Step(0, director?.ControlledTag != null, practice.Active);
|
||||
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible,
|
||||
hud?.Update(mesh, interactions!.CurrentObjective, level!.Code == "LV1B" && objectivePanel!.PadVisible && gadgetScreen?.Open != true,
|
||||
practice.Active, objectivePanel!.YOffset, objectivePanel.ContentVisible, renderer.Width, renderer.Height);
|
||||
if (gadgetScreen != null)
|
||||
{
|
||||
if (!headless) gadgetScreen.Point(Pointer(),level!.Code,storyTasks!.Get("SCENE"));
|
||||
gadgetOverlay!.Update(mesh,gadgetScreen.Canvases(level!.Code,storyTasks!.Get("SCENE")),renderer.Width,renderer.Height);
|
||||
}
|
||||
var gameplayProjection = originalCamera || simulation != null && !inspecting;
|
||||
var cameraMode = simulation?.Noclip == true && !inspecting ? "NOCLIP" : !inspecting && director?.CameraEye != null ? "CUTSCENE"
|
||||
: simulation != null && !inspecting ? "GAMEPLAY" : originalCamera ? "STRT" : "ORBIT";
|
||||
@@ -1260,6 +1443,18 @@ internal static class Program
|
||||
if (simulation.Bursts == 0 || simulation.MaximumRise <= 137.62f || !simulation.Grounded
|
||||
|| poweredAirTravel <= 20 || !poweredAirTurn || !headless && (sawJetpackKeys != 15 || !didResize)) return 2;
|
||||
}
|
||||
if (shrinkSmoke)
|
||||
{
|
||||
var renderedHeight = soldierVisuals!.RenderedHeight(shrinkVictim!.Actor.Tag,mesh);
|
||||
Console.WriteLine($"Shrink ray: target={shrinkVictim.Actor.Tag}, hits={gadgets!.ShrinkHits}, shrunk={shrinkVictim.Shrunk}, height={renderedHeight:F3}, remaining={shrinkVictim.Remaining:F3}, beam={gadgets.Ray.Visible}, phases={shrinkPhaseMask}, energy={simulation!.Energy:F3}, SDL fire={sawShrinkKey}.");
|
||||
if (!shrinkVictim.Shrunk || gadgets.ShrinkHits < 1 || renderedHeight > 60 || !gadgets.Ray.Visible || shrinkPhaseMask != 7
|
||||
|| simulation.Energy != 20 || !headless && !sawShrinkKey) return 2;
|
||||
}
|
||||
if (gadgetWindowSmoke)
|
||||
{
|
||||
Console.WriteLine($"Gadget menu SDL: shared-edge={gadgetChecks[0]}, pause={gadgetChecks[1]}, Escape={gadgetChecks[2]}, selection/fire-capture={gadgetChecks[3]}, practice={gadgetChecks[4]}, Return={gadgetChecks[5]}, stable-root={gadgetChecks[6]}.");
|
||||
if (!gadgetChecks.All(c=>c)) 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}.");
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
layout(location=0) in vec2 texCoord;
|
||||
layout(location=1) in vec3 vertexColor;
|
||||
layout(binding=0) uniform sampler2D diffuseMap;
|
||||
layout(push_constant) uniform Material {
|
||||
layout(offset=64) float opacity;
|
||||
} material;
|
||||
layout(location=0) out vec4 outColor;
|
||||
void main() {
|
||||
vec4 diffuse = texture(diffuseMap, texCoord);
|
||||
if (diffuse.a < 0.5) discard;
|
||||
outColor = vec4(diffuse.rgb * vertexColor, diffuse.a);
|
||||
outColor = vec4(diffuse.rgb * vertexColor, diffuse.a * material.opacity);
|
||||
}
|
||||
Binary file not shown.
@@ -29,7 +29,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
private ImageView colorView,depthView;
|
||||
private RenderPass renderPass;
|
||||
private Framebuffer framebuffer;
|
||||
private Pipeline pipeline,overlayPipeline;
|
||||
private Pipeline pipeline,overlayPipeline,alphaPipeline,additivePipeline,overlayAlphaPipeline,overlayAdditivePipeline;
|
||||
private PipelineLayout pipelineLayout;
|
||||
private DescriptorSetLayout descriptorLayout;
|
||||
private DescriptorPool descriptorPool;
|
||||
@@ -130,6 +130,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
throw new ArgumentException("Scene requires nonempty, bounded triangle geometry.",nameof(mesh));
|
||||
if(mesh.Draws.Any(d=>(ulong)d.FirstIndex+d.IndexCount>(ulong)mesh.Indices.Length))
|
||||
throw new ArgumentException("Scene draw exceeds index buffer.",nameof(mesh));
|
||||
ValidateDrawMaterials(mesh.Draws);
|
||||
ValidateTexture(fallback);
|
||||
foreach(var image in mesh.Textures.Values)ValidateTexture(image);
|
||||
|
||||
@@ -142,6 +143,17 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateDrawMaterials(MeshDraw[] draws)
|
||||
{
|
||||
foreach(var draw in draws)
|
||||
{
|
||||
if(!float.IsFinite(draw.Opacity) || draw.Opacity<0 || draw.Opacity>1)
|
||||
throw new ArgumentException("Draw opacity must be finite and between zero and one.",nameof(draws));
|
||||
if(draw.Blend is not (MeshBlend.Opaque or MeshBlend.Alpha or MeshBlend.Additive))
|
||||
throw new ArgumentException("Draw blend mode is invalid.",nameof(draws));
|
||||
}
|
||||
}
|
||||
|
||||
private SceneResources DetachScene()
|
||||
{
|
||||
var scene=new SceneResources(mesh,vertexBuffer,vertexMemory,indexBuffer,indexMemory,
|
||||
@@ -425,7 +437,7 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
|
||||
try
|
||||
{
|
||||
var push=new PushConstantRange(ShaderStageFlags.VertexBit,0,64);var dl=descriptorLayout;
|
||||
var push=new PushConstantRange(ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit,0,68);var dl=descriptorLayout;
|
||||
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
|
||||
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
|
||||
var stages=stackalloc PipelineShaderStageCreateInfo[2];
|
||||
@@ -450,6 +462,23 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
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");
|
||||
// Blended world geometry tests opaque depth but does not write it.
|
||||
// Preserve draw order; general transparent-surface sorting is separate work.
|
||||
blendAttachment.BlendEnable=true;
|
||||
blendAttachment.SrcColorBlendFactor=BlendFactor.SrcAlpha;
|
||||
blendAttachment.DstColorBlendFactor=BlendFactor.OneMinusSrcAlpha;
|
||||
blendAttachment.ColorBlendOp=BlendOp.Add;
|
||||
blendAttachment.SrcAlphaBlendFactor=BlendFactor.SrcAlpha;
|
||||
blendAttachment.DstAlphaBlendFactor=BlendFactor.OneMinusSrcAlpha;
|
||||
blendAttachment.AlphaBlendOp=BlendOp.Add;
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAlphaPipeline),"CreateOverlayAlphaPipeline");
|
||||
ds.DepthTestEnable=true;
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out alphaPipeline),"CreateAlphaPipeline");
|
||||
blendAttachment.DstColorBlendFactor=BlendFactor.One;
|
||||
blendAttachment.DstAlphaBlendFactor=BlendFactor.One;
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out additivePipeline),"CreateAdditivePipeline");
|
||||
ds.DepthTestEnable=false;
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out overlayAdditivePipeline),"CreateOverlayAdditivePipeline");
|
||||
}
|
||||
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
|
||||
}
|
||||
@@ -502,6 +531,9 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
}
|
||||
public void Render(Matrix4x4 mvp)
|
||||
{
|
||||
// Draw materials are mutable between frames. Reject invalid state before
|
||||
// acquiring an image or beginning a command buffer, even on hidden draws.
|
||||
ValidateDrawMaterials(mesh.Draws);
|
||||
uint imageIndex=0;
|
||||
if(window!=0)
|
||||
{
|
||||
@@ -517,14 +549,30 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
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);
|
||||
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
|
||||
foreach(var screenSpace in new[]{false,true})
|
||||
// Opaque world first, blended world second, UI last. Within each pass,
|
||||
// retain source order so existing UI composition remains unchanged.
|
||||
for(var pass=0;pass<3;pass++)
|
||||
{
|
||||
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,screenSpace?overlayPipeline:pipeline);
|
||||
var screenSpace=pass==2;
|
||||
var transform=screenSpace?Matrix4x4.Identity:mvp;
|
||||
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&transform);
|
||||
var stages=ShaderStageFlags.VertexBit|ShaderStageFlags.FragmentBit;
|
||||
vk.CmdPushConstants(command,pipelineLayout,stages,0,64,&transform);
|
||||
foreach(var draw in draws)
|
||||
{
|
||||
if (!draw.Visible || draw.ScreenSpace!=screenSpace) continue;
|
||||
if(!screenSpace && (draw.Blend==MeshBlend.Opaque)!=(pass==0))continue;
|
||||
var selectedPipeline=(screenSpace,draw.Blend) switch
|
||||
{
|
||||
(false,MeshBlend.Alpha)=>alphaPipeline,
|
||||
(false,MeshBlend.Additive)=>additivePipeline,
|
||||
(true,MeshBlend.Alpha)=>overlayAlphaPipeline,
|
||||
(true,MeshBlend.Additive)=>overlayAdditivePipeline,
|
||||
(true,_)=>overlayPipeline,
|
||||
_=>pipeline
|
||||
};
|
||||
vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,selectedPipeline);
|
||||
var opacity=draw.Opacity;
|
||||
vk.CmdPushConstants(command,pipelineLayout,stages,64,4,&opacity);
|
||||
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);
|
||||
@@ -565,6 +613,10 @@ public sealed unsafe class VulkanRenderer : IDisposable
|
||||
DestroyTarget();
|
||||
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
|
||||
if(overlayPipeline.Handle!=0)vk.DestroyPipeline(device,overlayPipeline,null);
|
||||
if(alphaPipeline.Handle!=0)vk.DestroyPipeline(device,alphaPipeline,null);
|
||||
if(additivePipeline.Handle!=0)vk.DestroyPipeline(device,additivePipeline,null);
|
||||
if(overlayAlphaPipeline.Handle!=0)vk.DestroyPipeline(device,overlayAlphaPipeline,null);
|
||||
if(overlayAdditivePipeline.Handle!=0)vk.DestroyPipeline(device,overlayAdditivePipeline,null);
|
||||
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
|
||||
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
|
||||
DestroySceneResources();
|
||||
|
||||
Reference in new issue
Block a user