Implement Baseball aiming, pooled projectiles and VR07 targets

This commit is contained in:
UnixNight committed 2026-11-02 22:54:19 -05:00
1 parent 50fcb87d90
commit d6ca417e9e
50 files changed
+3149 -32

No files matched your search

@@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs"/><Compile Include="../../src/GamePort/Assets/*.cs"/>
<Compile Include="../../src/GamePort/Game/*.cs"/></ItemGroup>
</Project>
+141
View File
@@ -0,0 +1,141 @@
using System.Numerics;
using System.Text;
using System.Buffers.Binary;
using GamePort.Game;
using GamePort.Assets;
var count=0;
void Check(bool value,string message){if(!value)throw new Exception(message);}
void Near(float a,float b,string message)=>Check(MathF.Abs(a-b)<.02f,$"{message}: {a} != {b}");
void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");}
void Hold(BaseballGadget device,bool down=false,bool up=false,float energy=20,bool supported=true)
{
var input=new PlayerInput(down,up,false,false,false,Fire:true);
device.StepCameraInput(input);
device.StepInput(input,Vector3.Zero,Vector3.Zero,supported,energy,false,()=>{},_=>{},_=>{});
}
void Release(BaseballGadget device,Action<float>? cost=null)=>device.StepInput(default,Vector3.Zero,Vector3.Zero,false,0,false,()=>{},_=>{},cost??(_=>{}));
Mesh Floor()=>new([new(new(-4000,0,-4000),Vector2.Zero,Vector3.One),new(new(4000,0,-4000),Vector2.Zero,Vector3.One),
new(new(4000,0,4000),Vector2.Zero,Vector3.One),new(new(-4000,0,4000),Vector2.Zero,Vector3.One)], [0,1,2,0,2,3])
{HasCollisionMaterialIds=true,CollisionPolygons=[new(0,0,Vector3.UnitY,"floor","floor",0),new(0,1,Vector3.UnitY,"floor","floor",0)]};
Test("first hold arms, next captures pitch, label retains prior capture",()=>{
var g=new BaseballGadget();g.Equip();Hold(g,true);
Check(g.PendingThrow&&g.AimVisible&&g.SavedPitch==0,"first hold arms only");
Hold(g,true);Near(g.SavedPitch,10+2f/3,"camera pitch");Check(g.DisplayPitch==0,"first numeric label precedes capture");
var old=g.SavedPitch;Hold(g,true);Check(g.DisplayPitch==old&&g.SavedPitch>old,"stored label order");
for(var i=0;i<200;i++)Hold(g,true);Check(g.SavedPitch==45,"upper clamp");
for(var i=0;i<200;i++)Hold(g,up:true);Check(g.SavedPitch==0,"lower clamp");
});
Test("release launches once with sound before fixed energy debit",()=>{
var g=new BaseballGadget();g.Equip();Hold(g);Hold(g);var order=new List<string>();g.Thrown+=()=>{
Check(g.PendingThrow&&!g.Projectiles[0].Visible,"sound callback precedes launch and pending clear");order.Add("sound");};
Release(g,cost=>{Check(cost==-1,"fixed cost");order.Add("cost");});Release(g);
Check(order.SequenceEqual(new[]{"sound","cost"})&&g.Throws==1&&!g.PendingThrow,"one release transaction");
Check(g.Projectiles[0].Visible&&g.NextSlot==1,"first owned pool slot");
});
Test("pending throw survives cleanup and can release at zero energy",()=>{
var g=new BaseballGadget();g.Equip();Hold(g);Hold(g,true);var saved=g.SavedPitch;g.Release();
Check(g.PendingThrow&&!g.AimVisible&&g.CameraPitch==0&&g.SavedPitch==saved,"source cleanup scalar ownership");
Release(g);Check(g.Throws==1&&g.Projectiles[0].Visible,"release predicate has no fresh energy or raw-mode gate");
});
Test("twenty reused slots, no invented ammo or lifetime",()=>{
var g=new BaseballGadget();g.Equip();
for(var i=0;i<23;i++){Hold(g);Release(g);}
Check(g.Throws==23&&g.NextSlot==3&&g.Projectiles.Count==20&&g.Projectiles.All(b=>b.Visible),"fixed wraparound pool");
g.Release();Check(g.Projectiles.All(b=>b.Visible),"unequip retains helper bodies");
g.Reset();Check(g.Throws==0&&g.Projectiles.All(b=>!b.Visible),"modern new scene clears port-owned pool");
});
Test("upright launch offset, quick-normalized speed and45-degree slope",()=>{
var ball=new BaseballProjectile();ball.Launch(new(100,200,300),Vector3.Zero,45);
Check(ball.Position==new Vector3(100,280,350),"local80/50 offset");Near(ball.Velocity.Y/ball.Velocity.Z,1,"slope45/45");
Near(OriginalBodySupport.QuickMagnitude(ball.Velocity),1800,"published speed");
ball.Launch(Vector3.Zero,new(0,90,0),0);Near(ball.Position.X,-50,"rotated offset");Near(ball.Velocity.X,-1800,"yaw90 velocity");
});
Test("landing queues old horizontal velocity and-.65Y before support clearsY",()=>{
var physics=new OriginalBodyPhysics(OriginalStaticCollision.FromRouteScene(Floor(),"VR07"));
var result=physics.Step(new(new(0,16,0),new(60,-120,0),Vector3.Zero,Vector3.Zero),1f/60,
radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball);
Check(result.Landing!=null&&result.Body.Supported&&result.Body.Velocity.Y==0,"landing and liveY reset");
Near(result.Body.Impulse.X,60,"queued oldX");Near(result.Body.Impulse.Y,(120+800f/60)*.65f,"queued bounce");
Near(result.Body.Velocity.X,59.54f,"source .46 floor friction follows landing callback");
var next=physics.Step(result.Body,1f/60,radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball);
Check(next.Body.Impulse==Vector3.Zero,"one consumption");Check(next.Body.Velocity.X>result.Body.Velocity.X,"horizontal impulse is added, not replaced");
});
Test("ball wall callback reflects and damps horizontal velocity while preserving falling Y",()=>{
var wall=new CameraRayPolygon(new(new(-1000,-1000,0),new(-1000,1000,0),new(1000,1000,0)),Vector3.UnitZ);
var physics=new OriginalBodyPhysics(new([wall]));
var result=physics.Step(new(new(0,100,30),new(0,-10,-1800),Vector3.Zero,Vector3.Zero),1f/60,
radius:15,factor:1,friction:.46f,profile:BodyResponseProfile.Baseball);
Check(result.Contact==wall,"source static dispatcher finds the actual wall");
Near(result.Body.Velocity.Z,972,"horizontal reflection and1-.46 damping");
Near(result.Body.Velocity.Y,-10-800f/60,"wall callback keeps liveY");
Check(result.Body.Impulse==Vector3.Zero&&!result.Body.Supported,"wall is not a landing callback");
});
Test("target cooldown runs while hidden and end arrival teleports to Start",()=>{
var actor=new SceneDirector(new("VR07",[Entity("3TAR","target",("StartPosX",-500f),("DestPosX",500f),("RespawnTime",1f))]),new TaskStates([]),(_,_)=>1).Actors[0];
var t=new MovingBaseballTarget(actor);Check(t.Hit()&&!t.Hit()&&!actor.Visible,"one callback per respawn");
t.StepFrame(.5f);Check(!actor.Visible,"still hidden");t.StepFrame(.5f);Check(actor.Visible&&t.Remaining==0,"exact zero expires");
actor.Position=new(450,0,0);t.StepFrame(0);Check(actor.Position==t.Start&&t.Velocity.X>0,"source teleports without swapping endpoints");
});
Test("VR07 keeps six duplicate-tag targets by source instance",()=>{
var level=GamLevel.Load("../Original/gam/VR07.gam");var d=new SceneDirector(level,new TaskStates([]),(_,_)=>1);
var mesh=Mesh.LoadSceneJson("artifacts/extracted/VR07/scene.json");var collision=OriginalStaticCollision.FromRouteScene(mesh,"VR07");
Check(!collision.HasSpecialPlayerContacts&&collision.PolygonCount>0,"ordinary source wall profile");
var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),level.Entities.First(e=>e.Kind=="STRT").Position,0){LevelCode="VR07"};
var scene=new SceneBaseballs(d,p,mesh);Check(scene.Targets.Count==6,"all source records");
Check(scene.Targets.Select(t=>t.Actor.SourceGam!.Offset).Distinct().Count()==6,"instances are never resolved by duplicate tag");
var first=scene.Targets[0];var second=scene.Targets[1];first.Hit();Check(!first.Actor.Visible&&second.Actor.Visible,"per-instance state");
});
Test("named-Jimmy cutscene restores companion while retaining pending throw",()=>{
var mesh=Floor();var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0){LevelCode="LV1B"};
var d=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1"),Entity("3DOG","C3DGODDARD"),Entity("3MCA","cleanup",("CameraTarget0","none"))]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,6,1);using var binding=new PlayerSceneBinding(d,p,bag,"JIM1");
bag.SelectGadget(6);binding.Step(new(false,false,false,false,false,Fire:true));
Check(!d.FindActor("C3DGODDARD")!.Visible&&p.Baseball.PendingThrow,"equip hides companion and arms");
d.Trigger("cleanup");Check(p.GadgetMode==-1&&p.Baseball.PendingThrow&&d.FindActor("C3DGODDARD")!.Visible,"named cleanup preserves source latch");
});
Test("Baseball cleanup restores companion even in Invisible's blocked levels",()=>{
foreach(var code in new[]{"LEV6","LEV7","LV1C","LV1D","LV4A","LV6A"})
{
var p=new LabSimulation(new SceneCollision(Floor()),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0){LevelCode=code};
var d=new SceneDirector(new(code,[Entity("3JIM","JIM1"),Entity("3DOG","C3DGODDARD")]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,6,1);using var binding=new PlayerSceneBinding(d,p,bag,"JIM1");
bag.SelectGadget(6);bag.SelectGadget(-1);var companion=d.FindActor("C3DGODDARD")!;
Check(companion.Visible&&companion.BodyEnabled&&companion.MovementEnabled,"raw6 unconditional restoration "+code);
}
});
Test("actual contact activates trophy only after strict fourth hit and honors HasCollision",()=>{
foreach(var hasCollision in new[]{0,-1})
{
var mesh=Floor();var p=new LabSimulation(new SceneCollision(mesh),AseMesh.Load("../Original/ASE/jimstop.ase"),new(1000,80,0),0){LevelCode="VR07"};
var d=new SceneDirector(new("VR07",[Entity("3TAR","target",("PositionY",100f),("PositionZ",100f),
("StartPosY",100f),("StartPosZ",100f),("DestPosX",1000f),("RespawnTime",.25f),("ActivateObject","trophy"),("HitsRequired",3)),
Entity("3TRO","trophy",("InitiallyVisible",0),("HasCollision",hasCollision))]),new TaskStates([]),(_,_)=>1);
var scene=new SceneBaseballs(d,p,mesh);var trophy=d.FindActor("trophy")!;
Check(!trophy.Visible&&!trophy.BodyEnabled,"initial hidden trophy contact disabled");
var score=0;var sounds=new List<int>();scene.ScoreAwarded+=x=>score+=x;scene.Sound+=sounds.Add;
for(var i=0;i<4;i++)
{
p.Baseball.Projectiles[i].Launch(new(0,20,0),Vector3.Zero,0);
scene.StepBodies(1f/60);
foreach(var ball in p.Baseball.Projectiles)ball.Hide();
if(i<3)Check(!trophy.Visible,"strict threshold must not activate at "+(i+1));
scene.StepTargets(.5f);
}
Check(scene.Hits==4&&score==40&&trophy.Visible&&trophy.BodyEnabled==(hasCollision!=0),"source contact and conditional enable");
Check(sounds.SequenceEqual(new[]{199})&&!d.Blocked,"parent428 does not invoke trigger interpreter");
}
});
Console.WriteLine($"Baseball:{count} groups passed; pair scheduling/full enemy combat remain separate.");
GamEntity Entity(string kind,string tag,params(string Name,object Value)[] values)
{
var props=new Dictionary<string,GamProperty>(StringComparer.Ordinal);
foreach(var(name,value) in new[]{("ObjectTag",(object)tag)}.Concat(values))
{
if(value is string text)props[name]=new(name,1,Encoding.Latin1.GetBytes(text));
else{var raw=new byte[4];if(value is float f)BinaryPrimitives.WriteInt32BigEndian(raw,BitConverter.SingleToInt32Bits(f));
else BinaryPrimitives.WriteInt32BigEndian(raw,(int)value);props[name]=new(name,value is float?3u:6u,raw);}
}
return new(kind,props.Count,props,[]);
}
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
<ItemGroup><Compile Include="Program.cs" />
<Compile Include="../../src/GamePort/Assets/*.cs" />
<Compile Include="../../src/GamePort/Game/*.cs" />
<Compile Include="../../src/GamePort/Application/UiViewport.cs" />
<Compile Include="../../src/GamePort/Application/BaseballVisuals.cs" />
<Compile Include="../../src/GamePort/Application/BaseballAimOverlay.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,153 @@
using System.Numerics;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
var prepared=args.Length==0?"artifacts/extracted":args[0];
var count=0;
void Check(bool condition,string message){if(!condition)throw new Exception(message);}
void Near(float actual,float expected,string message)=>Check(MathF.Abs(actual-expected)<.001f,$"{message}: {actual} != {expected}");
void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");}
void Invalid(Action action)
{
try{action();}catch(Exception e)when(e is ArgumentException or InvalidDataException){return;}
throw new Exception("Invalid visual input accepted");
}
BaseballGadget Aim(float pitch,bool visible=true)
{
var device=new BaseballGadget();
//Visual contract fixtures set published state directly, independently of
//input/timing tests owned by BaseballGadget's separate test project.
typeof(BaseballGadget).GetProperty("DisplayPitch")!.SetValue(device,pitch);
typeof(BaseballGadget).GetProperty("AimVisible")!.SetValue(device,visible);
return device;
}
Vector2 Pixels(MeshVertex vertex,uint width,uint height)=>new((vertex.Position.X+1)*width/2,(vertex.Position.Y+1)*height/2);
Test("twenty exact source balls append hidden alpha quads and preserve scene metadata",()=>
{
var source=new Mesh([new(new(1,2,3),Vector2.Zero,Vector3.One)],[0,0,0])
{
CollisionPolygons=[new(1,2,Vector3.UnitY,"floor")],HasCollisionMaterialIds=true,
Textures=new(){[int.MinValue+17000]=PngImage.White}
};
var visual=new BaseballVisuals(source,prepared);
Check(visual.Mesh.Vertices.Length==81&&visual.Mesh.Indices.Length==123,"append20 quads");
Check(visual.Mesh.Draws.Length==21&&!visual.Mesh.Draws[0].ScreenSpace,"preserve implicit scene draw");
Check(visual.Mesh.Vertices[0].Position==new Vector3(1,2,3),"original vertex retained");
Check(ReferenceEquals(visual.Mesh.CollisionPolygons,source.CollisionPolygons)&&visual.Mesh.HasCollisionMaterialIds,"collision metadata retained");
Check(visual.Mesh.Draws.Skip(1).All(d=>!d.Visible&&!d.ScreenSpace&&d.Blend==MeshBlend.Alpha),"hidden alpha world sprites");
var image=visual.Mesh.Textures[visual.Mesh.Draws[^1].TextureId];
Check(image.Width==32&&image.Height==32,"source32x32 canvas");
Check(Convert.ToHexStringLower(SHA256.HashData(image.Rgba))=="68904b758e69139de0b01329b2a9844ecd2a466f31598c24324affaccfa2cab9","exact ball0000 pixels");
Check(visual.Mesh.Draws[^1].TextureId!=int.MinValue+17000,"texture collision avoided");
});
Test("source25-unit ball corners face camera with finite degenerate bases and full UVs",()=>
{
var visual=new BaseballVisuals(new([],[]),prepared);
var ball=new BaseballProjectile();ball.Launch(new(5,10,15),Vector3.Zero,0);
foreach(var target in new[]{Vector3.Zero,Vector3.UnitY,-Vector3.UnitY,new Vector3(2,3,4)})
{
visual.Update(visual.Mesh,[ball],Vector3.Zero,target);
var v=visual.Mesh.Vertices.Take(4).ToArray();
Check(v.All(c=>float.IsFinite(c.Position.X+c.Position.Y+c.Position.Z)),"finite basis");
Near(Vector3.Distance(v[0].Position,v[1].Position),25,"source width");
Near(Vector3.Distance(v[1].Position,v[2].Position),25,"source height");
Check(Vector3.Distance(v.Aggregate(Vector3.Zero,(a,b)=>a+b.Position)/4,ball.Position)<.0001f,"source published position is center");
Check(v.Select(c=>c.Uv).SequenceEqual(new Vector2[]{new(0,1),new(1,1),new(1,0),new(0,0)}),"full source UV");
Check(visual.Mesh.Draws.Count(d=>d.Visible)==1,"unused19 slots remain hidden");
}
ball.Hide();visual.Update(visual.Mesh,[ball],Vector3.Zero,Vector3.UnitZ);
Check(visual.Mesh.Draws.All(d=>!d.Visible),"hide removes stale draw");
Invalid(()=>visual.Update(new([],[]),[ball],Vector3.Zero,Vector3.UnitZ));
Invalid(()=>visual.Update(visual.Mesh,[ball],new(float.NaN),Vector3.UnitZ));
Invalid(()=>visual.Update(visual.Mesh,Enumerable.Range(0,21).Select(_=>ball).ToArray(),Vector3.Zero,Vector3.UnitZ));
});
Test("aim uses stationary original strip, prior-capture pitch and source integer truncation",()=>
{
var overlay=new BaseballAimOverlay(new([],[]),prepared);
foreach(var pitch in new[]{0f,9.9f,17.5f,44.99f,45f})
{
overlay.Update(overlay.Mesh,Aim(pitch),640,480);
Check(overlay.Mesh.Draws.Count(d=>d.Visible)==3,"one strip and two digits");
var visible=overlay.Mesh.Draws.Where(d=>d.Visible).ToArray();
var strip=visible.Single(d=>overlay.Mesh.Textures[d.TextureId].Height==210);
var start=overlay.Mesh.Indices[strip.FirstIndex];
Near(Pixels(overlay.Mesh.Vertices[start],640,480).X,315,"strip x stationary");
Near(Pixels(overlay.Mesh.Vertices[start],640,480).Y,100,"strip y stationary");
var digits=visible.Where(d=>d!=strip).OrderBy(d=>Pixels(overlay.Mesh.Vertices[overlay.Mesh.Indices[d.FirstIndex]],640,480).X).ToArray();
for(var place=0;place<2;place++)
{
var point=Pixels(overlay.Mesh.Vertices[overlay.Mesh.Indices[digits[place].FirstIndex]],640,480);
Near(point.X,286+place*16,"null TIME space has zero advance");
Near(point.Y,(int)((45-(double)pitch)*4.3+100),"label integer y");
var digit=place==0?(int)pitch/10:(int)pitch%10;
Check(overlay.Mesh.Textures[digits[place].TextureId].Rgba.SequenceEqual(
File.ReadAllBytes(Path.Combine(prepared,$"baseball/aim_{new[]{118,127,120,121,122,123,124,125,126,119}[digit]}.rgba"))),"exact selected source digit pixels");
}
Check(strip.Blend==MeshBlend.Alpha&&strip.ScreenSpace,"screen alpha path");
}
overlay.Update(overlay.Mesh,Aim(0,false),640,480);
Check(overlay.Mesh.Draws.All(d=>!d.Visible),"unequip hides all owned aim draws");
Invalid(()=>overlay.Update(overlay.Mesh,Aim(float.NaN),640,480));
Invalid(()=>overlay.Update(overlay.Mesh,Aim(46),640,480));
Invalid(()=>overlay.Update(overlay.Mesh,Aim(0),0,480));
Invalid(()=>overlay.Update(new([],[]),Aim(0),640,480));
});
Test("widescreen preserves aim pixel proportions and centered640x480 placement",()=>
{
var overlay=new BaseballAimOverlay(new([],[]),prepared);
foreach(var size in new[]{(640u,480u),(1920u,1080u),(3440u,1440u),(480u,800u)})
{
var(w,h)=size;var scale=MathF.Min(w/640f,h/480f);
overlay.Update(overlay.Mesh,Aim(45),w,h);
var strip=overlay.Mesh.Draws.Single(d=>d.Visible&&overlay.Mesh.Textures[d.TextureId].Height==210);
var start=overlay.Mesh.Indices[strip.FirstIndex];
var a=Pixels(overlay.Mesh.Vertices[start],w,h);var b=Pixels(overlay.Mesh.Vertices[start+2],w,h);
Near(a.X,w/2f-5*scale,"centered strip x");
Near(a.Y,(h-480*scale)/2+100*scale,"centered strip y");
Near(b.X-a.X,15*scale,"uniform source width");Near(b.Y-a.Y,210*scale,"uniform source height");
}
});
Test("world plus overlay updates retain each other's vertices and draws",()=>
{
var balls=new BaseballVisuals(new([],[]),prepared);var overlay=new BaseballAimOverlay(balls.Mesh,prepared);
var ball=new BaseballProjectile();ball.Launch(Vector3.Zero,Vector3.Zero,0);
balls.Update(overlay.Mesh,[ball],Vector3.Zero,Vector3.UnitZ);
var position=overlay.Mesh.Vertices[0].Position;
overlay.Update(overlay.Mesh,Aim(12),1920,1080);
Check(overlay.Mesh.Vertices[0].Position==position&&overlay.Mesh.Draws[0].Visible,"overlay retains world state");
Check(overlay.Mesh.Draws.Count(d=>d.Visible)==4,"one world and three overlay draws");
});
Test("altered pixels, dimensions and manifest traversal are rejected",()=>
{
var directory=Path.Combine(Path.GetTempPath(),"neutron-baseball-visual-"+Guid.NewGuid());
var output=Path.Combine(directory,"baseball");Directory.CreateDirectory(output);
try
{
var source=Path.Combine(prepared,"baseball");
foreach(var path in Directory.EnumerateFiles(source,"*.rgba"))File.Copy(path,Path.Combine(output,Path.GetFileName(path)));
var original=File.ReadAllText(Path.Combine(source,"baseball.json"));
var root=JsonNode.Parse(original)!;
void Save()=>File.WriteAllText(Path.Combine(output,"baseball.json"),root.ToJsonString());
root["textures"]![0]!["path"]="../outside.rgba";Save();
File.Copy(Path.Combine(source,"canvas_2.rgba"),Path.Combine(directory,"outside.rgba"));
Invalid(()=>new BaseballVisuals(new([],[]),directory));
root=JsonNode.Parse(original)!;root["aimTextures"]![0]!["width"]=16;Save();
Invalid(()=>new BaseballAimOverlay(new([],[]),directory));
root=JsonNode.Parse(original)!;Save();
File.WriteAllBytes(Path.Combine(output,"canvas_2.rgba"),new byte[4096]);
Invalid(()=>new BaseballVisuals(new([],[]),directory));
File.WriteAllBytes(Path.Combine(output,"aim_253.rgba"),new byte[15*210*4]);
Invalid(()=>new BaseballAimOverlay(new([],[]),directory));
}
finally{Directory.Delete(directory,true);}
});
Console.WriteLine($"Baseball visual checks passed: {count}");
@@ -19,6 +19,7 @@
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BaseballGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
@@ -23,6 +23,7 @@
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BaseballGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
+61
View File
@@ -0,0 +1,61 @@
"""Source guard/projection checks; these do not execute original gameplay."""
from pathlib import Path
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from baseball import Aim, aim_hold, aim_label, cleanup, collect, landing_impulse, launch_yaw_only, next_slot, release, f32
class BaseballSourceTests(unittest.TestCase):
def test_identity_ranges_and_virtuals(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),15)
self.assertEqual(len(report['vtables']),13)
self.assertEqual(report['wall_damping'],f32(.46))
self.assertEqual(report['pool_size'],20)
self.assertTrue(all(int(b['va'],16)-int(b['file_offset'],16)==0x400000 for b in report['bodies']))
def test_first_hold_does_not_capture_then_clamps_and_displays_previous(self):
state=aim_hold(Aim(saved_pitch=12),30)
self.assertEqual(state,Aim(True,12))
self.assertEqual(aim_label(state.saved_pitch),(286,241,12))
self.assertEqual(aim_hold(state,80),Aim(True,45))
self.assertEqual(aim_hold(state,-3),Aim(True,0))
for flags in ({'mode':0},{'mode':2},{'supported':False},{'energy':0},{'modal':True},{'busy':True}):
self.assertEqual(aim_hold(state,42,**flags),state)
self.assertEqual(aim_hold(Aim(),20,energy=0,exempt=True),Aim(True,0))
def test_release_survives_cleanup_without_fresh_energy_or_mode_gate(self):
state=Aim(True,30)
self.assertEqual(cleanup(state),state)
self.assertEqual(release(state,primary=True),(state,None))
after,event=release(cleanup(state))
self.assertEqual(after,Aim(False,30))
self.assertEqual(event,dict(pitch=30,sound=10,energy=-1.))
self.assertEqual(release(after),(after,None))
def test_ring_is_capacity_not_ammo_and_null_slot_does_not_advance(self):
self.assertEqual(next_slot(19),0)
self.assertEqual(next_slot(19,exists=False),19)
for index in (-1,20):
with self.assertRaises(ValueError): next_slot(index)
def test_launch_origin_and_aim_slope(self):
root,velocity=launch_yaw_only((1,2,3),0,0)
self.assertEqual(root,(1.,82.,53.))
self.assertEqual(velocity,(-0.,0.,1800.))
root,v=launch_yaw_only((0,0,0),90,45)
self.assertAlmostEqual(root[0],-50)
self.assertAlmostEqual(v[0],-v[1],places=4)
self.assertAlmostEqual(sum(x*x for x in v),1800**2,places=5)
def test_landing_queues_full_vector_before_velocity_y_is_zeroed(self):
impulse=landing_impulse((100,-200,50))
self.assertEqual(impulse,(100.,130.,50.))
# Source support then stores velocity(100,0,50); next body adds impulse.
self.assertEqual(tuple(a+b for a,b in zip((100.,0.,50.),impulse)),(200.,130.,100.))
if __name__=='__main__': unittest.main()
+94
View File
@@ -0,0 +1,94 @@
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from baseball_resources import ARCHIVE_SHA256, VR07_SHA256, CANVASES, AIM_CANVASES, AIM_ARCHIVES, export_baseball
from omt import FormatError
from png import read_png
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class BaseballResourceTests(unittest.TestCase):
def test_exact_original_pixels_and_provenance(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'baseball'
manifest = export_baseball(ORIGINAL, output)
self.assertEqual(manifest, json.loads((output/'baseball.json').read_text()))
self.assertEqual((manifest['schema'], manifest['sourceSha256']), (1, ARCHIVE_SHA256))
self.assertEqual([e['id'] for e in manifest['textures']], [2, 3, 4, 5, 8])
for entry, expected in zip(manifest['textures'], CANVASES):
self.assertEqual((entry['id'], entry['name'], entry['sourceOffset'], entry['sourceBytes'],
entry['width'], entry['height'], entry['rgbaSha256']), expected)
rgba = (output/entry['path']).read_bytes()
self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256'])
self.assertEqual(read_png(output/entry['png'])['rgba'], rgba)
def test_aim_strip_and_original_gameplay_glyphs_are_not_substituted(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'baseball'
manifest = export_baseball(ORIGINAL, output)
self.assertEqual(manifest['aimArchiveSha256'], AIM_ARCHIVES)
for entry, expected in zip(manifest['aimTextures'], AIM_CANVASES):
self.assertEqual((entry['database'], entry['id'], entry['width'], entry['height'], entry['rgbaSha256']), expected)
rgba = (output/entry['path']).read_bytes()
self.assertEqual(hashlib.sha256(rgba).hexdigest(), entry['rgbaSha256'])
self.assertEqual(read_png(output/entry['png'])['rgba'], rgba)
def test_tutorial_retains_six_duplicate_tags_and_exact_properties(self):
with tempfile.TemporaryDirectory() as directory:
manifest = export_baseball(ORIGINAL, Path(directory)/'baseball')
tutorial = manifest['tutorial']
self.assertEqual(tutorial['sha256'], VR07_SHA256)
targets = [e for e in tutorial['entities'] if e['kind'] == '3TAR']
self.assertEqual([e['offset'] for e in targets], [0x885, 0xAD6, 0xD27, 0xF78, 0x11C9, 0x141C])
for target in targets:
values = {p['name']: p['value'] for p in target['properties']}
self.assertEqual((values['ObjectTag'], values['SpriteDatabase'], values['SpriteIndex']),
('C3DMOVINGTARGET', 'sprites.omt', 135))
self.assertEqual((values['HitsRequired'], values['Speed'], values['NumPoints'], values['RespawnTime']),
(3, 100.0, 10, 15.0))
source = next(p for p in target['properties'] if p['name'] == 'SpriteIndex')
self.assertEqual(source['raw'], '00000087')
self.assertGreater(source['offset'], target['offset'])
def test_source_outputs_and_descendant_symlinks_rejected(self):
for output in (ORIGINAL, ORIGINAL/'omt/baseball-generated', ORIGINAL.parent):
with self.subTest(output=output), self.assertRaises(ValueError):
export_baseball(ORIGINAL, output)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'baseball'
output.mkdir()
target = Path(directory)/'unchanged'
target.write_bytes(b'unchanged')
(output/'canvas_2.rgba').symlink_to(target)
with self.assertRaises(ValueError):
export_baseball(ORIGINAL, output)
self.assertEqual(target.read_bytes(), b'unchanged')
def test_bad_pixels_rejected_before_output(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'baseball'
with patch('baseball_resources.read_canvas', return_value=dict(width=32, height=32, rgba=b'\0'*4096)), \
self.assertRaises(FormatError):
export_baseball(ORIGINAL, output)
self.assertFalse(output.exists())
def test_bad_source_identity_rejected_before_decode(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'baseball'
with patch('baseball_resources.digest', return_value='0'*64), \
patch('baseball_resources.read_canvas') as decoder, self.assertRaises(FormatError):
export_baseball(ORIGINAL, output)
decoder.assert_not_called()
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()
+33
View File
@@ -0,0 +1,33 @@
import sys
from pathlib import Path
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/binary'))
import baseball_targets as source
class BaseballTargetTests(unittest.TestCase):
def test_original_guards_and_six_distinct_records(self):
report = source.collect(Path(__file__).resolve().parents[2] / 'Original')
self.assertEqual(len(report['targets']), 6)
self.assertEqual(len({e['offset'] for e in report['targets']}), 6)
self.assertEqual({e['properties']['ObjectTag'] for e in report['targets']}, {'C3DMOVINGTARGET'})
self.assertTrue(all(e['properties']['SpriteIndex'] == 135 for e in report['targets']))
def test_hit_respawn_gate_and_score(self):
self.assertEqual(source.hit_target(0, 10, 15), dict(accepted=True, hidden=True, timer=15, points=10))
self.assertFalse(source.hit_target(.0001, 10, 15)['accepted'])
self.assertTrue(source.hit_target(-1, 10, 15)['accepted'])
def test_expiry_uses_stored_subtraction(self):
self.assertEqual(source.step_respawn(1, 1), (0, True))
self.assertEqual(source.step_respawn(0, .5), (0, False))
self.assertEqual(source.step_respawn(.75, .5), (.25, False))
def test_parent_threshold_is_strict(self):
self.assertEqual(source.parent_hits(2, 3), (3, False))
self.assertEqual(source.parent_hits(3, 3), (0, True))
if __name__ == '__main__':
unittest.main()
+90
View File
@@ -0,0 +1,90 @@
"""Static source guards/projections, not original runtime Scooter tests."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
import scooter as s
class ScooterTests(unittest.TestCase):
def test_identity_and_source_guards(self):
source = ROOT.parent/'Original'
if not source.exists():
self.skipTest('Original source directory unavailable')
result = s.collect(source)
self.assertEqual(17, len(result['bodies']))
self.assertEqual(150, result['radius'])
self.assertEqual(4, result['wheel_construction_count'])
self.assertFalse(result['runtime_implemented'])
def test_spawn_does_not_mount(self):
self.assertEqual('raw4_vehicle_visible_unmounted', s.equip_result())
self.assertEqual('unchanged', s.equip_result(companion_enabled=False))
self.assertEqual('unchanged', s.equip_result(companion_exists=False))
self.assertEqual('practice_VR05', s.equip_result(practice=True))
def test_actual_child_support_required(self):
self.assertFalse(s.drive_eligible(True, (None,)*6)['drive'])
state = s.drive_eligible(True, (True, False, True, False, None, None))
self.assertEqual(dict(front=1, rear=1, total=2, drive=True), state)
self.assertFalse(s.drive_eligible(False, (True,)*6)['drive'])
self.assertFalse(s.drive_eligible(True, (True, False, None, None, None, None))['drive'])
with self.assertRaises(ValueError):
s.drive_eligible(True, (True, True))
def test_steering_keyboard_priority_cap_and_release(self):
state = s.keyboard_input(s.Steering(), .1, left=True, right=True)
self.assertAlmostEqual(20, state.turn, places=5)
state = s.keyboard_input(state, .2, left=True)
self.assertEqual(45, state.turn)
self.assertEqual(0, s.keyboard_input(state, .3).turn)
self.assertEqual(-45, s.keyboard_input(state, .5, right=True).turn)
def test_forward_requires_rear_support_and_uses_dt(self):
self.assertEqual(0, s.keyboard_input(s.Steering(), .1, forward=True).speed)
state = s.keyboard_input(s.Steering(), .1, forward=True, rear_supports=1)
self.assertAlmostEqual(70, state.speed, places=4)
for _ in range(30):
state = s.keyboard_input(state, .1, forward=True, rear_supports=2)
self.assertEqual(s.f32(2250*s.f32(.66)), state.speed)
self.assertEqual(state.speed, s.keyboard_input(state, .1).speed)
def test_reverse_first_call_brakes_then_reverses(self):
state = s.keyboard_input(s.Steering(speed=100), .1, backward=True, rear_supports=2)
self.assertEqual(0, state.speed)
self.assertTrue(state.braking)
state = s.keyboard_input(state, .1, backward=True, rear_supports=2)
self.assertAlmostEqual(-120, state.speed, places=4)
for _ in range(10):
state = s.keyboard_input(state, .1, backward=True, rear_supports=2)
self.assertEqual(s.f32(-s.f32(2250*s.f32(.66))*s.f32(.4)), state.speed)
state = s.keyboard_input(state, .1)
self.assertFalse(state.reverse_latch)
self.assertFalse(state.braking)
def test_jump_edge_and_support_gates(self):
self.assertEqual((False, None), s.jump_pending(mounted=True, grounded=False, held=True, latched=False))
self.assertEqual((True, (0.,700.,0.)), s.jump_pending(mounted=True, grounded=True, held=True, latched=False))
self.assertEqual((True, None), s.jump_pending(mounted=True, grounded=True, held=True, latched=True))
self.assertEqual((False, None), s.jump_pending(mounted=True, grounded=True, held=False, latched=True))
self.assertEqual((True, None), s.jump_pending(mounted=False, grounded=True, held=False, latched=True))
def test_animation_strict_timer_and_signed_speed(self):
self.assertEqual((0., 'SCOOTSTOP'), s.animation_step(0., .31, -100))
self.assertEqual((0., 'SCOOT'), s.animation_step(0., .31, 10))
self.assertIsNone(s.animation_step(0., .29, 100)[1])
# float32(.3) is greater than the source double.3 comparison operand.
self.assertEqual((0., 'SCOOT'), s.animation_step(0., .3, 10))
def test_bounded_projection(self):
for value in [-1, 1, float('nan'), float('inf')]:
with self.assertRaises(ValueError):
s.keyboard_input(s.Steering(), value)
with self.assertRaises(ValueError):
s.keyboard_input(s.Steering(), .1, rear_supports=5)
if __name__ == '__main__':
unittest.main()
+98
View File
@@ -0,0 +1,98 @@
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from ase import expand_mesh, read_ase
from entities import resolve_asset
from omt import FormatError
from png import read_png
from scooter_resources import SOURCES, export_scooter
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class ScooterResourceTests(unittest.TestCase):
def test_original_shape_material_links_and_pixels(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'scooter'
manifest = export_scooter(ORIGINAL, output)
self.assertEqual(manifest, json.loads((output/'scooter.json').read_text()))
self.assertEqual(manifest['sources'], SOURCES)
self.assertEqual([s['triangles'] for s in manifest['shapes']], [176, 56])
for identity, expected_canvas in ((0, 1), (1, 0)):
scene = json.loads((output/f'shape_{identity}/scene.json').read_text())
self.assertEqual(len(scene['materials']), 1)
self.assertEqual(scene['materials'][0]['texture'], dict(type='Canv', id=expected_canvas))
texture = scene['textures'][0]
self.assertEqual(texture['id'], expected_canvas)
image = read_png(output/f'shape_{identity}'/texture['png'])
self.assertEqual(image['rgba'], (output/f'shape_{identity}'/texture['path']).read_bytes())
wheel = json.loads((output/'shape_1/scene.json').read_text())
self.assertIn(-1, [m['material'] for m in wheel['meshes']])
self.assertEqual((output/'jimycarl.rgba').read_bytes(),
read_png(resolve_asset(ORIGINAL, 'png/jimycarl.png'))['rgba'])
def test_jimmy_exact_base_topology_and_morph_positions(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'scooter'
export_scooter(ORIGINAL, output)
base = read_ase(resolve_asset(ORIGINAL, 'ASE/jimstop.ASE'))['objects'][0]['samples'][0]
for stem in ('jimscooter', 'jimscooterstop'):
source = read_ase(resolve_asset(ORIGINAL, f'ASE/{stem}.ASE'))
animation = json.loads((output/stem/'animation.json').read_text())
self.assertEqual((animation['framesPerSecond'], animation['ticksPerFrame']), (10, 480))
self.assertEqual([f['time'] for f in animation['frames']], [0, 480])
self.assertEqual(animation['sha256'], source['sha256'])
for index, sample in enumerate(source['objects'][0]['samples']):
expected = expand_mesh(dict(sample, faces=base['faces'], uvs=base['uvs'],
textureFaces=base['textureFaces']))
actual = json.loads((output/stem/animation['frames'][index]['path']).read_text())
self.assertEqual(actual['vertices'], [list(v) for v in expected['vertices']])
self.assertEqual(actual['uvs'], [list(v) for v in expected['uvs']])
def test_unbound_morphs_retain_source_161_ticks_and_no_guessed_uvs(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'scooter'
manifest = export_scooter(ORIGINAL, output)
for entry in manifest['unboundMorphs']:
morph = json.loads((output/entry['path']).read_text())
self.assertEqual((morph['framesPerSecond'], morph['ticksPerFrame']), (30, 160))
samples = morph['objects'][0]['samples']
self.assertEqual([s['time'] for s in samples], [0, 161])
self.assertEqual([len(s['vertices']) for s in samples], [195, 195])
self.assertTrue(all(not s['uvs'] and not s['textureFaces'] for s in samples))
self.assertEqual(morph['sha256'], hashlib.sha256(
resolve_asset(ORIGINAL, 'ASE/'+entry['source']).read_bytes()).hexdigest())
def test_original_subtrees_ancestors_and_symlinks_rejected(self):
for output in (ORIGINAL, ORIGINAL/'png/generated-scooter', ORIGINAL.parent):
with self.subTest(output=output), self.assertRaises(ValueError):
export_scooter(ORIGINAL, output)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'scooter'
output.mkdir()
outside = Path(directory)/'unchanged'
outside.write_text('unchanged')
for relative in ('scooter.json', 'shape_0', 'jimscooter', 'jimycarl.rgba'):
(output/relative).symlink_to(outside)
with self.subTest(relative=relative), self.assertRaises(ValueError):
export_scooter(ORIGINAL, output)
self.assertEqual(outside.read_text(), 'unchanged')
(output/relative).unlink()
def test_changed_source_identity_rejected_before_writes(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'scooter'
with patch.dict(SOURCES, {'omt/scooter.omt': '0'*64}), self.assertRaises(FormatError):
export_scooter(ORIGINAL, output)
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()