Implement timed Invisible gadget and shared energy warnings

This commit is contained in:
UnixNight committed 2026-11-02 09:21:56 -05:00
1 parent 3527d33810
commit 1897dd2b90
44 files changed
+2466 -39

No files matched your search

+9
View File
@@ -66,6 +66,15 @@ Require(menu.Page == 0, "Tab cycles all three pages");
Require(menu.FindScene("VR04")?.LevelFile == "VR04.gam" && menu.FindScene("MISSING") == null, "Checkpoint resolution only uses prepared catalog");
Console.WriteLine("PASS paged player/systems tools, noclip, staged settings and bounded overlay views");
menu.Key(43);
for(var i=0;i<10;i++)menu.Key(81);
Require(menu.Key(40)==DebugAction.GiveInvisible,"Player tools can grant/select implemented Invisible device");
menu.Key(81);Require(menu.Key(40)==DebugAction.UnequipGadget,"Explicit gadget unequip");
var invisibleView=menu.View(new("LV1B","STARTEXP",Vector3.Zero,0,0,true,20,0,30,"NONE",true,0,10000,false,
Systems:new(){InvisibleRemaining=4.5f,InvisibleRecharge=0,Targetable=false}));
Require(invisibleView.Lines.Length<=32 && invisibleView.Lines.Any(s=>s.Contains("INVISIBLE 4.5")),"Bounded Invisible timer/target diagnostics");
Console.WriteLine("PASS Invisible debug commands and live phase diagnostics");
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
var catalog = DebugMenu.AvailableScenes(original, Path.GetFullPath("artifacts/extracted"));
Require(catalog.Length == 33 && catalog.All(s => s.Starts.Length > 0), "Only33 supplied scenes with prepared geometry are offered");
@@ -16,6 +16,8 @@
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
@@ -0,0 +1,12 @@
<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/PlayerGadgetMaterial.cs" />
<Compile Include="../../src/GamePort/Application/InvisibleMeterOverlay.cs" />
<Compile Include="../../src/GamePort/Application/UiViewport.cs" />
</ItemGroup>
</Project>
+179
View File
@@ -0,0 +1,179 @@
using System.Numerics;
using System.Buffers.Binary;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
void Check(bool value, string message) { if (!value) throw new Exception(message); }
var count = 0;
void Test(string name, Action action) { action(); count++; Console.WriteLine($"PASS {name}"); }
void Charge(InvisibleGadget gadget, float energy = 20, bool exemption = false)
{
for (var i = 0; i < 450 && gadget.Recharge != 7; i++)
gadget.Step(1f / 60, true, false, false, energy, exemption, _ => throw new Exception("Recharge spends no energy"));
Check(gadget.Recharge == 7, "ready clamp must reach exact7");
}
InvisibleGadget Ready(float energy = 20, bool exemption = false)
{
var gadget = new InvisibleGadget(); Check(gadget.Equip(energy, exemption), "equip"); Charge(gadget, energy, exemption); return gadget;
}
Test("energy low warning uses19/20 hysteresis and preserves callback order", () => {
var energy = new PlayerEnergy(); var sounds = new List<int>();
energy.Adjust(-1, "LV1B", sounds.Add); Check(energy.Value == 19 && sounds.Count == 0, "exact19 is not low");
energy.Adjust(-.5f, "LV1B", id => { Check(energy.Value == 18.5f && !energy.LowWarning, "low callback after scalar/before latch"); sounds.Add(id); });
energy.Adjust(-1, "LV1B", sounds.Add); Check(sounds.SequenceEqual(new[] {182}), "warn once per low episode");
energy.Value = 20; energy.Adjust(0, "LV1B"); Check(energy.LowWarning, "exact20 keeps latch");
energy.Value = MathF.BitIncrement(20); energy.Adjust(0, "LV1B"); Check(!energy.LowWarning, "above20 clears");
energy.Adjust(-2, "LV1B", sounds.Add); Check(sounds.SequenceEqual(new[] {182,182}), "renewed episode warns");
});
Test("empty crossing sounds before write, then low warning; continuing empty does not repeat", () => {
var energy = new PlayerEnergy { Value = 1 }; var seen = new List<int>();
energy.Adjust(-2, "LEV1", id => { seen.Add(id); Check(id == 80 ? energy.Value == 1 : energy.Value == 0, "source write order"); });
Check(seen.SequenceEqual(new[] {80,182}) && energy.Value == 0, "crossing then low sound");
energy.Adjust(-2, "LEV1", seen.Add); Check(seen.Count == 2, "empty is not another crossing");
energy.Value = 200; energy.Adjust(0, "LEV1"); Check(energy.Value == 100 && !energy.LowWarning, "upper clamp clears latch");
});
Test("tutorial energy helper bypasses scalar, sounds and warning latch", () => {
var energy = new PlayerEnergy { Value = 1 }; energy.Adjust(0, "LV1B");
for (var i = 1; i <= 8; i++) {
energy.Adjust(-100, $"VR0{i}", _ => throw new Exception("tutorial sound"));
Check(energy.Value == 1 && energy.LowWarning, "tutorial must not clear retained low latch");
}
Check(!PlayerEnergy.IsTutorial("VR09") && !PlayerEnergy.IsTutorial("vr03"), "exact numeric FourCC range");
});
Test("energy latch is retained separately from original saved scalar", () => {
var state = new PlayerEnergy { Value = 1 }; state.Adjust(0, "LV1B");
var world = new Mesh([new(new(-1000,0,-1000),Vector2.Zero,Vector3.One),new(new(1000,0,-1000),Vector2.Zero,Vector3.One),
new(new(1000,0,1000),Vector2.Zero,Vector3.One),new(new(-1000,0,1000),Vector2.Zero,Vector3.One)],[0,2,1,0,3,2]);
var standing = AseMesh.Load("../Original/ASE/jimstop.ase");
var first = new LabSimulation(new SceneCollision(world),standing,new(0,80,0),0,energy:state);
var second = new LabSimulation(new SceneCollision(world),standing,new(0,80,0),0,energy:state) {LevelCode="LEV1"};
var sounds = 0; second.EnergySound += _ => sounds++;
second.Energy = 2; second.AdjustEnergy(-.5f);
Check(first.Energy == 1.5f && second.LowEnergyWarning && sounds == 0, "ordinary load shares scalar/latch owner");
second.Energy = 100; Check(second.LowEnergyWarning, "raw save/debug scalar assignment is not helper rearm");
});
Test("Invisible equip gates zero energy but tutorial override permits it", () => {
var device = new InvisibleGadget();
Check(!device.Equip(0,false) && !device.Equipped, "ordinary empty equip fails");
Check(device.Equip(0,true) && device.Recharge == 0 && device.Remaining == 0 && device.Targetable, "VR override equips with fresh clocks");
});
Test("held fire cannot activate on same invocation that recharge clamps7", () => {
var device = new InvisibleGadget(); device.Equip(20,false); var spends=0;
while (device.Recharge != 7) device.Step(.5f,true,true,false,20,false,_=>spends++);
Check(spends == 0 && device.Targetable && device.MeterReady, "first charge before first activation");
device.Step(.5f,true,true,false,20,false,delta=>{Check(delta==-2,"fixed cost");spends++;});
Check(spends==1 && device.Remaining==6.5f && device.Recharge==0 && !device.Targetable && device.Opacity==.7f,
"activation decrements remaining in same invocation, not a new-frame7");
});
Test("activation needs strictly more than2; primary with jump does not activate", () => {
var device=Ready(2); var spends=0;
device.Step(.1f,true,true,false,2,false,_=>spends++);
Check(!device.Active && device.Recharge==7 && spends==0,"exact2 rejected");
device.Step(.1f,true,true,true,3,false,_=>spends++); Check(!device.Active,"jump blocks activation only");
device.Step(.1f,true,true,false,MathF.BitIncrement(2),false,_=>spends++); Check(device.Active && spends==1,"strict threshold");
device.Step(.1f,true,false,true,0,false,_=>spends++); Check(device.Remaining<6.9f,"active continues during jump/empty energy");
});
Test("raw NULL ownership and primary suppressor freeze timers independently", () => {
var device=Ready(); device.Step(.1f,true,true,false,20,false,_=>{}); var before=device.Remaining;
device.Step(.25f,false,false,false,20,false,_=>{}); Check(device.Remaining==before && !device.MeterVisible && device.Active,"null freezes, no cleanup");
device.Step(.25f,true,true,false,20,false,_=>{},suppressed:true); Check(device.Remaining==before && device.MeterVisible,"suppressed primary returns");
device.Step(.25f,true,true,true,20,false,_=>{},suppressed:true); Check(device.Remaining<before,"held jump bypasses primary suppressor branch");
});
Test("last3seconds flashes original material blend; expiry restores opaque and waits to recharge", () => {
var device=Ready(); device.Step(0,true,true,false,20,false,_=>{});
for(var i=0;i<8;i++) device.Step(.5f,true,false,false,18,false,_=>{});
Check(device.Remaining==3 && device.ConventionalBlend,"trunc(3*5) odd conventionalalpha");
device.Step(.25f,true,false,false,18,false,_=>{}); Check(device.Remaining==2.75f && device.ConventionalBlend,"odd13");
device.Step(.25f,true,false,false,18,false,_=>{}); Check(device.Remaining==2.5f && !device.ConventionalBlend,"even12 additive");
for(var i=0;i<5;i++) device.Step(.5f,true,false,false,18,false,_=>{});
Check(!device.Active && device.Targetable && device.Opacity==1 && device.Recharge==0 && !device.MeterReady,"expiry invocation does not recharge");
device.Step(.1f,true,false,false,18,false,_=>{}); Check(device.Recharge==.1f,"next invocation starts recharge");
});
Test("held primary reactivates after recharge without adding edge latch", () => {
var device=Ready(); var spends=0;
for(var i=0;i<35;i++) device.Step(.5f,true,true,false,20,false,_=>spends++);
Check(spends==2 && device.Activations==2,"repeat held activation after active+recharge");
});
Test("release and reset own material/target/meter cleanup", () => {
var device=Ready(); device.Step(.1f,true,true,false,20,false,_=>{}); device.Release();
Check(!device.Equipped && !device.Active && device.Remaining==7 && device.Recharge==0 && device.Targetable && !device.MeterVisible && device.Opacity==1,
"source release stores7, not active restart");
device.Reset(); Check(device.Remaining==0 && device.Activations==0,"modern reset starts clean");
});
Test("original atlas material changes leave geometry and authored visibility intact", () => {
var device=Ready(); var draw=new MeshDraw(0,3,1) {Visible=false};
device.Step(0,true,true,false,20,false,_=>{}); PlayerGadgetMaterial.Apply(draw,device);
Check(draw.Opacity==.7f && draw.Blend==MeshBlend.Additive && !draw.Visible,"source alpha.7, additive branch, no show/hide invention");
for(var i=0;i<8;i++)device.Step(.5f,true,false,false,18,false,_=>{});
PlayerGadgetMaterial.Apply(draw,device); Check(draw.Blend==MeshBlend.Alpha,"flash routes indexed material alpha");
device.Release(); PlayerGadgetMaterial.Apply(draw,device); Check(draw.Opacity==1 && draw.Blend==MeshBlend.Opaque,"cleanup restores opaque");
});
Test("binding distinguishes another control owner, AI NULL freeze and named camera cleanup", () => {
var jim=Entity("3JIM","JIM1"); var dog=Entity("3DOG","C3DGODDARD",("AIState",1));
var other=Entity("3AIT","other",("PlayerControlled","C3DGODDARD"));
var freeze=Entity("3AIT","freeze",("PlayerControlled","NULL"));
var keep=Entity("3CAM","keep",("DeactivateInv",0),("CameraTarget","JIM1"),("SoundIndex",1));
var cleanup=Entity("3MCA","cleanup",("CameraTarget0","none"));
var director=new SceneDirector(new("LV1B",[jim,dog,other,freeze,keep,cleanup]),new TaskStates([]),(_,_)=>1);
var body=Body(); var bag=new SceneInventory(new int[19]); bag.SetState(0,2,1);
using var binding=new PlayerSceneBinding(director,body,bag,"JIM1");
bag.SelectGadget(2); var companion=director.FindActor("C3DGODDARD")!;
Check(!companion.Visible&&!companion.BodyEnabled&&!companion.MovementEnabled&&companion.Active,"equip hides/disables body, not AI activation");
var integrations=0;
var patrol=new ActorPatrol(companion,director.FindActor,(state,_)=>{integrations++;return state with{Position=state.Position+Vector3.UnitX};});
patrol.Step(.1f); Check(integrations==0,"disabled body does not consume provisional integration");
Charge(body.Invisible); director.Trigger("other");
var controllers=body.ControllerSteps;
binding.Step(new(false,false,false,false,false,Fire:true));
Check(body.Invisible.Active && body.ControllerSteps==controllers && body.Energy==18,"nonnull other owner permits wrapper activation without Jimmy input");
director.Trigger("freeze"); var remaining=body.Invisible.Remaining;
binding.Step(new(false,false,false,false,false));
Check(body.Invisible.Active && body.Invisible.Remaining==remaining && !body.Invisible.MeterVisible,"AI NULL freezes without cleanup");
director.Trigger("keep"); Check(body.Invisible.Active,"explicit DeactivateInv0 and absent raw owner preserve effect");
director.Skip(); director.Trigger("cleanup");
Check(!body.Invisible.Active && body.GadgetMode==-1 && bag.SelectedGadget==-1 && companion.Visible
&& companion.BodyEnabled && companion.MovementEnabled,"default named-Jimmy cleanup even when raw owner NULL/first MCA target none");
patrol.Step(.1f); Check(integrations==1,"companion body resumes");
});
Test("failed ordinary equip retains display2 with raw mode-1", () => {
var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1")]),new TaskStates([]),(_,_)=>1);
var body=Body(); body.Energy=0; var bag=new SceneInventory(new int[19]); bag.SetState(0,2,1);
using var binding=new PlayerSceneBinding(director,body,bag,"JIM1"); bag.SelectGadget(2);
Check(bag.SelectedGadget==2 && body.GadgetMode==-1 && !body.Invisible.Equipped,"display callback precedes failed equip");
});
Test("original meter resources stretch and tint with uniform widescreen placement", () => {
var world=new Mesh([new(new(1,2,3),Vector2.Zero,Vector3.One)],[0,0,0]){HasCollisionMaterialIds=true};
var overlay=new InvisibleMeterOverlay(world,"artifacts/extracted/invisible-meter/meter.json");
var device=Ready();
foreach(var (width,height) in new[]{(640u,480u),(1920u,1080u),(3440u,1440u)}) {
overlay.Update(overlay.Mesh,device,width,height);
var a=overlay.Mesh.Vertices[5];var b=overlay.Mesh.Vertices[7];
var view=new UiViewport(width,height);
Check(MathF.Abs((b.Position.X-a.Position.X)*width/2/view.Scale-27)<.0002f,"source fill width27");
Check(device.MeterPercent>=100 && device.MeterPercent<101,"source percentage precedes recharge clamp");
Check(Math.Abs((b.Position.Y-a.Position.Y)*height/2/view.Scale-device.MeterPercent*1.04)<.0005,"source fill percent times1.04");
Check(a.Color==Vector3.One && a.Uv==Vector2.Zero && b.Uv==new Vector2(.9999f,.9999f),"white ready tint and full image stretch");
Check(overlay.Mesh.Vertices[0].Position==new Vector3(1,2,3)&&overlay.Mesh.HasCollisionMaterialIds,"preserve world and collision identities");
}
device.Release();overlay.Update(overlay.Mesh,device,1920,1080);
Check(overlay.Mesh.Draws.Skip(1).All(d=>!d.Visible),"unequip hides both original sprites");
});
Console.WriteLine($"Invisible/energy:{count} groups passed; full enemy AI, original runtime and native Windows comparison remain separate.");
LabSimulation Body()
{
var world=new Mesh([new(new(-1000,0,-1000),Vector2.Zero,Vector3.One),new(new(1000,0,-1000),Vector2.Zero,Vector3.One),
new(new(1000,0,1000),Vector2.Zero,Vector3.One),new(new(-1000,0,1000),Vector2.Zero,Vector3.One)],[0,2,1,0,3,2]);
return new(new SceneCollision(world),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0);
}
GamEntity Entity(string kind,string tag,params (string Name,object Value)[] values)
{
var properties=new Dictionary<string,GamProperty>(StringComparer.Ordinal);
foreach(var (name,value) in new[]{("ObjectTag",(object)tag)}.Concat(values)) {
if(value is string text)properties[name]=new(name,1,Encoding.Latin1.GetBytes(text));
else {var raw=new byte[4];BinaryPrimitives.WriteInt32BigEndian(raw,(int)value);properties[name]=new(name,6,raw);}
}
return new(kind,properties.Count,properties,[]);
}
@@ -20,6 +20,8 @@
<Compile Include="../../src/GamePort/Game/PlayerLevelState.cs"/>
<Compile Include="../../src/GamePort/Game/AirSteering.cs"/>
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
+85
View File
@@ -0,0 +1,85 @@
"""Guarded original Bubble branches; projections are not gameplay verification."""
from dataclasses import replace
from pathlib import Path
import math
import sys
import unittest
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tools/binary'))
from bubble import BubbleVisual, collect, energy_delta, equip_result, f32, start, stop, visual_step
class BubbleSourceTests(unittest.TestCase):
def test_original_identity_spans_sites_and_virtuals(self):
report=collect(ROOT.parent/'Original')
self.assertEqual(len(report['bodies']),12)
self.assertGreaterEqual(len(report['sites']),35)
self.assertEqual(len(report['vtables']),6)
self.assertTrue(all(int(b['va'],16)-int(b['file_offset'],16)==0x400000 for b in report['bodies']))
self.assertEqual((report['archive'],report['canvas']),('RetainedSprites.omt',1))
self.assertEqual(report['equip']['radius'],160)
self.assertEqual(report['equip']['factor'],f32(.415))
self.assertEqual(report['cleanup']['max_speed'],650)
self.assertEqual(report['cleanup']['factor'],f32(1.265))
def test_equip_order_and_transition_flags(self):
self.assertEqual(equip_result(0,exists=False,practice=True),'no_effect')
self.assertEqual(equip_result(0,practice=True),'practice_VR01')
self.assertEqual(equip_result(0),'mode_minus1')
self.assertEqual(equip_result(-1),'mode_minus1')
self.assertEqual(equip_result(0,exempt=True),'equip_mode0_movement2')
self.assertEqual(equip_result(.001),'equip_mode0_movement2')
for flags in ({'active':True},{'expanding':True},{'collapsing':True}):
self.assertEqual(equip_result(1,**flags),'unchanged')
with self.assertRaises(ValueError):equip_result(math.nan)
def test_controlled_movement2_drain_is_half_dt(self):
self.assertEqual(energy_delta(2,.25),-.125)
self.assertEqual(energy_delta(0,.25),0)
self.assertEqual(energy_delta(1,.25),0)
self.assertEqual(energy_delta(3,.25),0)
for seconds in (-1,1,math.inf,math.nan):
with self.assertRaises(ValueError):energy_delta(2,seconds)
def test_expand_changes_color_not_dimensions_and_crosses_strict_one(self):
state=start(BubbleVisual())
self.assertFalse(state.hidden)
state=visual_step(state,.5)
self.assertEqual(state.rgba,(.5,)*4)
self.assertEqual((state.width,state.height),(200,200))
state=visual_step(state,.5)
self.assertEqual(state.rgba,(1.,)*4)
self.assertTrue(state.expanding)
self.assertFalse(state.active)
state=visual_step(state,.125)
self.assertFalse(state.expanding)
self.assertTrue(state.active)
def test_active_width_pulse_and_graphics_alpha_branch(self):
state=BubbleVisual(active=True,hidden=False,rgba=(.9,)*4)
default=visual_step(state,.125)
alpha=visual_step(state,.125,graphics_alpha=True)
self.assertEqual(default.width,240)
self.assertAlmostEqual(default.height,240+math.sin(1.25)*30,places=4)
self.assertEqual(default.rgba,(.9,)*4)
self.assertEqual(alpha.rgba,(1.,1.,1.,.5))
self.assertEqual(alpha.height,default.height)
def test_cleanup_separately_clears_expand_and_fades_until_strict_negative(self):
initial=start(BubbleVisual())
direct=stop(initial,through_jimmy_cleanup=False)
self.assertTrue(direct.expanding and direct.collapsing)
state=stop(initial)
self.assertFalse(state.expanding or state.active)
self.assertTrue(state.collapsing)
state=visual_step(visual_step(state,.5),.5)
self.assertEqual(state.rgba,(0.,)*4)
self.assertTrue(state.collapsing)
self.assertFalse(state.hidden)
state=visual_step(state,.125)
self.assertTrue(state.hidden)
self.assertFalse(state.collapsing)
if __name__=='__main__':unittest.main()
+105
View File
@@ -0,0 +1,105 @@
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 gadget_followup_assets import export_meter, inspect, write_report
from omt import FormatError
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class GadgetFollowupAssetTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = inspect(ORIGINAL)
def test_existing_jimmy_family_has_opaque_atlas_and_compatible_morph_counts(self):
atlas = self.report['jimmyTexture']
self.assertEqual((atlas['width'], atlas['height']), (256, 256))
self.assertEqual(atlas['alphaCounts'], {255: 65536})
for clip in self.report['jimmyClips']:
self.assertEqual(len(clip['nodes']), 1)
node = clip['nodes'][0]
self.assertEqual((node['vertices'], node['faces']), (426, 814))
if clip['source'].casefold() == 'jimstop.ase':
self.assertEqual((node['uvs'], node['textureFaces']), (3551, 814))
self.assertEqual(clip['sha256'], 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0')
else:
self.assertEqual((node['uvs'], node['textureFaces']), (0, 0))
def test_vr03_preserves_intro_wire_offsets_and_distinct_duplicate_tag_actors(self):
level = next(l for l in self.report['levels'] if l['level'] == 'VR03')
self.assertEqual(level['sha256'], '8acc4d3b8c416c41c1900ac0b1f895ab5819781e5dd87d19a1f177414660d5b2')
self.assertEqual(level['counts']['3SOL'], 8)
soldiers = [e for e in level['entities'] if e['kind'] == '3SOL']
self.assertEqual(len({e['offset'] for e in soldiers}), 8)
self.assertEqual({e['tag'] for e in soldiers}, {'C3DYOKIANSOLDIER'})
intro = next(e for e in level['entities'] if e['offset'] == 0x8EEE)
sounds = [p for p in intro['properties'] if p['name'] in ('SoundIndex0', 'SoundIndex1', 'SoundIndex2')]
self.assertEqual([(p['offset'], p['value']) for p in sounds], [(0x90F7, 21), (0x9176, 20), (0x91F5, 37)])
self.assertEqual((level['meshes'][0]['vertices'], level['meshes'][0]['triangles']), (280, 424))
def test_bubble_billboard_and_vr01_are_exact_serialized_resources(self):
sprite = next(r for r in self.report['resources'] if r['archive'] == 'RetainedSprites.omt')
self.assertEqual((sprite['id'], sprite['name'], sprite['offset'], sprite['size']), (1, 'orangebubble', 0x17FCE, 66322))
self.assertEqual((sprite['canvas']['width'], sprite['canvas']['height']), (146, 146))
self.assertEqual(sprite['rgbaSha256'], 'a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4')
self.assertEqual(sprite['alphaCounts'], {0: 5492, 255: 15824})
level = next(l for l in self.report['levels'] if l['level'] == 'VR01')
self.assertEqual(level['sha256'], '7938214fb62784fcb34245491342a5f33e3615bdc178e4883a9e285e6869904f')
self.assertEqual(level['counts'].get('3SOL', 0), 0)
self.assertEqual(sum(level['counts'].values()), 16)
self.assertEqual((level['meshes'][0]['vertices'], level['meshes'][0]['triangles']), (60, 80))
def test_report_rejects_original_tree_before_writing(self):
for output in (ORIGINAL/'followup.json', ORIGINAL/'ASE/followup.json', ORIGINAL/'omt/followup.json'):
with self.subTest(output=output), self.assertRaises(ValueError):
write_report(ORIGINAL, output)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'report.json'
report = write_report(ORIGINAL, output)
self.assertTrue(output.is_file())
self.assertEqual(report['schema'], 1)
def test_meter_export_preserves_exact_source_pixels_and_bounded_resources(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'meter'
manifest = export_meter(ORIGINAL, output)
self.assertEqual(manifest, json.loads((output/'meter.json').read_text()))
self.assertEqual([t['id'] for t in manifest['textures']], [21, 22])
self.assertEqual([(t['sourceOffset'], t['sourceBytes']) for t in manifest['textures']],
[(0x88E18, 8118), (0x8C5D8, 9138)])
for texture in manifest['textures']:
expected = next(r for r in self.report['resources'] if r['archive'] == 'screens.omt' and r['id'] == texture['id'])
rgba = (output/texture['path']).read_bytes()
self.assertEqual(len(rgba), 30*110*4)
self.assertEqual(hashlib.sha256(rgba).hexdigest(), expected['rgbaSha256'])
self.assertTrue((output/texture['png']).is_file())
for output in (ORIGINAL/'generated-meter', ORIGINAL/'ASE/generated-meter', ORIGINAL/'omt/generated-meter'):
with self.subTest(output=output), self.assertRaises(ValueError):
export_meter(ORIGINAL, output)
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'meter'
with patch('gadget_followup_assets.read_canvas', return_value=dict(width=1, height=1, rgba=b'\0'*4)):
with self.assertRaises(FormatError):
export_meter(ORIGINAL, output)
self.assertFalse(output.exists())
def test_rea_meter_code_spans_and_double_height_multiplier_remain_guarded(self):
contract = self.report['meterCode']
self.assertEqual(len(contract['guardedSpans']), 8)
self.assertEqual(contract['heightMultiplier'], 1.04)
self.assertEqual((contract['backgroundCanvas'], contract['fillCanvas']), (21, 22))
self.assertEqual([s['fileOffset'] for s in contract['guardedSpans'][:4]], [0x174D, 0x2D70, 0x3730, 0x37F0])
self.assertEqual(contract['rawBackgroundPosition'], [320, 7])
self.assertEqual(contract['rawFillPosition'], [322, 4])
if __name__ == '__main__':
unittest.main()
+87
View File
@@ -0,0 +1,87 @@
import math
from pathlib import Path
import sys
import unittest
from dataclasses import replace
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/binary'))
from invisible import State, cleanup, collect, equip, f32, step
ORIGINAL = Path(__file__).resolve().parents[2] / 'Original'
class InvisibleSourceTests(unittest.TestCase):
def test_original_identity_spans_sites_virtuals_and_constants(self):
source = collect(ORIGINAL)
self.assertEqual(len(source['bodies']), 7)
self.assertEqual(len(source['sites']), 50)
self.assertEqual(len(source['vtables']), 8)
for body in source['bodies']:
self.assertEqual(int(body['va'], 16)-0x400000, int(body['file_offset'], 16))
def test_equip_energy_gate_is_distinct_from_activation_and_display(self):
self.assertEqual(equip(State(mode=-1), 0).mode, -1)
self.assertEqual(equip(State(mode=-1), .25).mode, 2)
self.assertEqual(equip(State(mode=-1), 0, True).mode, 2)
self.assertEqual((equip(State(), 20).remaining, equip(State(), 20).recharge), (0, 0))
def test_first_recharge_clamp_activates_only_on_next_call(self):
state = State()
for _ in range(14):
state, delta = step(state, .5, 20, primary=True)
self.assertEqual(delta, 0)
self.assertEqual((state.recharge, state.remaining, state.meter_red), (7, 0, False))
state, delta = step(state, .5, 20, primary=True)
self.assertEqual((delta, state.remaining, state.recharge), (-2, 6.5, 0))
self.assertEqual((state.alpha, state.blend, state.targetable), (f32(.7), 'additive', False))
def test_activation_strict_two_and_jump_exclusion(self):
ready = State(recharge=7, meter_red=False)
for energy in (0, 1.5, 2):
state, delta = step(ready, .25, energy, primary=True)
self.assertEqual((state.remaining, delta), (0, 0))
state, delta = step(ready, .25, 2.01, primary=True)
self.assertEqual((state.remaining, delta), (6.75, -2))
state, delta = step(ready, .25, 0, primary=True, override=True)
self.assertEqual((state.remaining, delta), (6.75, -2))
self.assertEqual(step(ready, .25, 20, primary=True, jump=True)[1], 0)
def test_control_and_suppressor_freeze_only_the_proven_branches(self):
active = State(remaining=5, recharge=0, alpha=f32(.7), blend='additive', targetable=False)
state, _ = step(active, .25, 20, control_present=False)
self.assertEqual((state.remaining, state.meter_visible), (5, False))
state, _ = step(active, .25, 20, primary=True, suppressed=True)
self.assertEqual(state.remaining, 5)
for primary, jump in [(False, False), (True, True)]:
self.assertEqual(step(active, .25, 20, primary=primary, jump=jump, suppressed=True)[0].remaining, 4.75)
def test_zero_energy_stops_recharge_but_not_active_duration(self):
self.assertEqual(step(State(recharge=1), .5, 0)[0].recharge, 1)
self.assertEqual(step(State(recharge=1), .5, 0, override=True)[0].recharge, 1.5)
self.assertEqual(step(State(remaining=4), .5, 0)[0].remaining, 3.5)
def test_last_three_flash_and_exact_zero_expiry(self):
active = State(remaining=3, alpha=f32(.7), blend='additive', targetable=False)
self.assertEqual(step(active, .25, 20)[0].blend, 'alpha') # trunc(2.75*5)=13
self.assertEqual(step(active, .5, 20)[0].blend, 'additive') # trunc(2.5*5)=12
ended, delta = step(replace(active, remaining=.5), .5, 20, primary=True)
self.assertEqual((ended.remaining, ended.recharge, delta), (0, 0, 0))
self.assertEqual((ended.alpha, ended.blend, ended.targetable, ended.meter_red), (1, 'opaque', True, True))
self.assertEqual(step(ended, .5, 20)[0].recharge, .5)
def test_cleanup_preserves_source_inactive_timer_value_and_resets_presentation(self):
ended = cleanup(State(remaining=4, alpha=f32(.7), blend='additive', targetable=False))
self.assertEqual((ended.mode, ended.remaining, ended.recharge), (-1, 7, 0))
self.assertEqual((ended.alpha, ended.blend, ended.targetable, ended.meter_visible), (1, 'opaque', True, False))
self.assertEqual(step(ended, .5, 20)[0], ended)
self.assertEqual((equip(ended, 20).remaining, equip(ended, 20).recharge), (0, 0))
def test_source_graphics_branch_and_invalid_modern_projection_time(self):
self.assertEqual(step(State(recharge=7), .25, 20, primary=True, graphics_alpha=True)[0].blend, 'alpha')
for seconds in (-1, 1, math.inf, math.nan):
with self.assertRaises(ValueError):
step(State(), seconds, 20)
if __name__ == '__main__':
unittest.main()
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from player_energy import collect
class PlayerEnergySourceTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.report = collect(ROOT.parent/'Original')
def test_exact_shared_body_and_warning_constants(self):
self.assertEqual(self.report['body']['size'], 0xF3)
self.assertEqual(self.report['constants'], dict(zero=0, maximum=100, low=19, rearm=20))
def test_sound_and_scalar_order_have_guarded_sites(self):
sites = {site['name']: int(site['va'], 16) for site in self.report['sites']}
self.assertLess(sites['empty_sound_before_scalar'], sites['scalar_store_before_extended_upper_test'])
self.assertLess(sites['low_sound_before_latch'], sites['strict_rearm'])
self.assertEqual(self.report['globals']['warning'], '0x4f83dc')
def test_constructor_and_both_new_consumers_are_bound(self):
sites = {site['name'] for site in self.report['sites']}
self.assertTrue({'ctor_zero_register', 'ctor_clear_warning', 'ray_adjust_caller',
'invisible_adjust_caller'}.issubset(sites))
def test_every_site_has_pe_mapped_offset(self):
for site in self.report['sites']:
self.assertEqual(int(site['file_offset'], 16), int(site['va'], 16)-0x400000)
if __name__ == '__main__':
unittest.main()