Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,15 @@ on each receiving node. Each transfer must have a sole owner, a clean handover
gate and the original grid ID, terminal custom data and NPC identity. The
report includes the storage size and SHA-256 for investigating differences.
MES also writes a timestamp into this record.

### Energy Shields damage absorption

From `Test/`, run `python shield_damage_differential.py /path/to/corpus /path/to/new-results`
with the bench environment and a claimed slot. The fixture creates two powered
armor grids and adds the Workshop shield generator to one of them. After five
simulation seconds it applies the same 20-point hit to each grid. It records the
damage reported after the mod's handler and the resulting integrity loss,
including damage still queued for application. The standalone control must
show damage to the bare grid and full absorption on the shielded grid. The
cluster repeats the test on node 1. Other damage types, upgrades, handover, and
client effects need separate cases.
138 changes: 138 additions & 0 deletions Test/ShieldDamageFixture/Data/Scripts/ShieldDamage/Probe.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
using System.Globalization;
using Sandbox.Common.ObjectBuilders;
using Sandbox.ModAPI;
using VRage.Game;
using VRage.Game.Components;
using VRage.Game.ModAPI;
using VRage.ObjectBuilders;
using VRage.Utils;
using VRageMath;

namespace ShieldDamageFixture
{
[MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
public class Probe : MySessionComponentBase
{
private IMySlimBlock control,
shielded;
private int elapsed;
private float controlHit = -1,
shieldHit = -1,
controlStart,
shieldStart;

private void AfterDamage(object target, MyDamageInformation info)
{
if (info.Type != MyStringHash.GetOrCompute("Bullet"))
return;
if (target == control)
controlHit = info.Amount;
if (target == shielded)
shieldHit = info.Amount;
}

private static IMySlimBlock CreateTarget(bool addShield)
{
var grid = new MyObjectBuilder_CubeGrid
{
DisplayName = addShield ? "Shielded control target" : "Unshielded control target",
GridSizeEnum = MyCubeSize.Large,
IsStatic = true,
PersistentFlags = MyPersistentEntityFlags2.InScene,
PositionAndOrientation = new MyPositionAndOrientation(
new Vector3D(addShield ? 135 : 110, 250, 120),
Vector3.Forward,
Vector3.Up
),
};
grid.CubeBlocks.Add(
new MyObjectBuilder_CubeBlock
{
SubtypeName = "LargeBlockArmorBlock",
Min = Vector3I.Zero,
}
);
grid.CubeBlocks.Add(
new MyObjectBuilder_BatteryBlock
{
SubtypeName = "LargeBlockBatteryBlock",
Min = new Vector3I(1, 0, 0),
CurrentStoredPower = 3f,
}
);
if (addShield)
grid.CubeBlocks.Add(
new MyObjectBuilder_Refinery
{
SubtypeName = "LargeShipSmallShieldGeneratorBase",
Min = new Vector3I(-1, 0, 0),
}
);
var live = (IMyCubeGrid)MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(grid);
return live.GetCubeBlock(Vector3I.Zero);
}

public override void UpdateAfterSimulation()
{
if (++elapsed % 30 != 0)
return;
if (control == null)
{
if (
!MyAPIGateway.Utilities.FileExistsInModLocation("start.txt", ModContext.ModItem)
)
return;
control = CreateTarget(false);
shielded = CreateTarget(true);
MyAPIGateway.Session.DamageSystem.RegisterAfterDamageHandler(1000, AfterDamage);
elapsed = 0;
return;
}
if (elapsed == 300)
{
var generator =
shielded.CubeGrid.GetCubeBlock(new Vector3I(-1, 0, 0))?.FatBlock
as IMyTerminalBlock;
if (generator != null)
generator.RefreshCustomInfo();
var battery =
shielded.CubeGrid.GetCubeBlock(new Vector3I(1, 0, 0))?.FatBlock
as IMyBatteryBlock;
MyLog.Default.WriteLineAndConsole(
"shield_fixture generator="
+ (generator?.CustomInfo ?? "missing").Replace("\r", "").Replace("\n", " ")
+ " functional="
+ generator?.IsFunctional
+ " working="
+ generator?.IsWorking
+ " battery="
+ battery?.CurrentStoredPower
+ " output="
+ battery?.CurrentOutput
);
var damage = MyStringHash.GetOrCompute("Bullet");
controlStart = control.Integrity;
shieldStart = shielded.Integrity;
control.DoDamage(20, damage, true);
shielded.DoDamage(20, damage, true);
}
if (elapsed == 360)
{
MyLog.Default.WriteLineAndConsole(
"shield_damage_probe control="
+ controlHit.ToString(CultureInfo.InvariantCulture)
+ " shielded="
+ shieldHit.ToString(CultureInfo.InvariantCulture)
+ " controlLoss="
+ (controlStart - control.Integrity + control.AccumulatedDamage).ToString(
CultureInfo.InvariantCulture
)
+ " shieldLoss="
+ (shieldStart - shielded.Integrity + shielded.AccumulatedDamage).ToString(
CultureInfo.InvariantCulture
)
);
}
}
}
}
118 changes: 118 additions & 0 deletions Test/shield_damage_differential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""Compare actual armor damage with and without an Energy Shields generator."""

import argparse
import hashlib
import json
import os
import re
import shutil
import tempfile
import time
from pathlib import Path

from bench import Bench, HOST
from cluster import ClusterError
from mod_definition_differential import build_observer, stage, world_with_mods
from scenarios_planet import start_standalone

MOD = "484504816"
PROBE = "9991845002"
PATTERN = r"shield_damage_probe control=([\d.E+-]+) shielded=([\d.E+-]+) controlLoss=([\d.E+-]+) shieldLoss=([\d.E+-]+)"


def measure(bench, role):
mods = bench.cluster.config.root / f"{role}-data/Mods"
(mods / f"{PROBE}.sbm/start.txt").touch(exist_ok=False)
match = re.search(PATTERN, bench.cluster.wait_node_log(role, PATTERN, 60))
return dict(
zip(
("unshielded", "shielded", "unshielded_loss", "shielded_loss"),
map(float, match.groups()),
strict=True,
)
)


def run(corpus: Path, results: Path):
os.environ["CLUSTER_TEST_PLUGIN"] = "0"
bench = Bench("SHIELD-DAMAGE", "Energy Shields damage absorption", "2", results)
started = time.monotonic()
report = {
"mod": MOD,
"result": "INCONCLUSIVE",
"package": json.loads((HOST.package / "manifest.json").read_text()),
}
with tempfile.TemporaryDirectory(dir=results) as temp:
work = Path(temp)
try:
mods = work / "Mods"
stage(corpus / "244850" / MOD, mods)
sources = (mods / f"{MOD}.sbm" / "Data/Scripts").rglob("*.cs")
report["script_sha256"] = {
p.relative_to(mods)
.as_posix(): hashlib.sha256(p.read_bytes())
.hexdigest()
for p in sorted(sources)
}
shutil.copytree(
Path(__file__).parent / "ShieldDamageFixture", mods / f"{PROBE}.sbm"
)
world = work / "ShieldWorld"
world_with_mods(
HOST.package / "examples/Cluster-Simple", world, [MOD, PROBE]
)
config = bench.cluster.config
config.world_template = world
bench.cluster.prepare(wipe=True)
observer = build_observer(work)
stock = start_standalone(
bench,
world,
ready=("Game ready",),
local_plugins=[observer],
staged_mods=mods,
extra_env={"MOD_DEFINITION_STAGE_STOCK": "1"},
)
try:
reference = report["standalone"] = measure(bench, "stock")
finally:
stock.stop()
if (
reference["unshielded"] <= 0
or reference["shielded"] != 0
or reference["unshielded_loss"] <= 0
or reference["shielded_loss"] != 0
):
return report
for role in ("wa-1", "node-1", "node-2"):
shutil.copytree(
mods, config.root / f"{role}-data/Mods", dirs_exist_ok=True
)
bench.cluster.start()
bench.cluster.wait_ready(timeout=240, serving=True)
actual = report["node-1"] = measure(bench, "node-1")
report["result"] = (
"INCONCLUSIVE"
if actual["unshielded"] <= 0
or actual["unshielded_loss"] <= 0
or actual["shielded"] < 0
else "PASS" if actual == reference else "DIFF"
)
except (OSError, ValueError, TimeoutError, ClusterError) as exc:
report["error"] = str(exc)
finally:
report["seconds"] = round(time.monotonic() - started, 1)
bench.record("observations", report)
bench.close()
return report


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("corpus", type=Path)
parser.add_argument("results", type=Path)
args = parser.parse_args()
args.results.mkdir(parents=True, exist_ok=False)
result = run(args.corpus, args.results)
print(result["result"])
raise SystemExit(0 if result["result"] == "PASS" else 1)