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
150 changes: 150 additions & 0 deletions Test/NaniteRepairFixture/Data/Scripts/NaniteRepair/Probe.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
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 NaniteRepairFixture
{
[MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)]
public class Probe : MySessionComponentBase
{
private class Rig
{
public IMyFunctionalBlock Factory;
public IMySlimBlock Target;
}

private Rig enabled,
disabled;
private int frames;
private bool done;

private static Rig Create(bool treatment)
{
var grid = new MyObjectBuilder_CubeGrid
{
GridSizeEnum = MyCubeSize.Large,
IsStatic = true,
DisplayName = treatment ? "Enabled nanite repair" : "Disabled nanite control",
PersistentFlags = MyPersistentEntityFlags2.InScene,
PositionAndOrientation = new MyPositionAndOrientation(
new Vector3D(treatment ? 110 : 2110, 140, 100),
Vector3.Forward,
Vector3.Up
),
};
grid.CubeBlocks.Add(
new MyObjectBuilder_ShipWelder
{
SubtypeName = "LargeNaniteControlFacility",
Min = Vector3I.Zero,
Enabled = false,
}
);
// A continuous armor beam puts the target far beyond the factory block's 4 m vanilla welder.
for (int x = 3; x <= 16; x++)
grid.CubeBlocks.Add(
new MyObjectBuilder_CubeBlock
{
SubtypeName = "LargeBlockArmorBlock",
Min = new Vector3I(x, 0, 0),
}
);
for (int x = 3; x < 15; x++)
grid.CubeBlocks.Add(
new MyObjectBuilder_BatteryBlock
{
SubtypeName = "LargeBlockBatteryBlock",
Min = new Vector3I(x, 1, 0),
CurrentStoredPower = 3f,
}
);
// The mod obtains a grid's resource distributor from a ship controller.
grid.CubeBlocks.Add(
new MyObjectBuilder_RemoteControl
{
SubtypeName = "LargeBlockRemoteControl",
Min = new Vector3I(15, 1, 0),
}
);
var live = (IMyCubeGrid)MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(grid);
var factory = (IMyFunctionalBlock)live.GetCubeBlock(Vector3I.Zero).FatBlock;
factory
.GetInventory()
.AddItems(100, new MyObjectBuilder_Component { SubtypeName = "SteelPlate" });
return new Rig
{
Factory = factory,
Target = live.GetCubeBlock(new Vector3I(16, 0, 0)),
};
}

private void Observe(string phase)
{
MyLog.Default.WriteLineAndConsole(
"nanite_repair "
+ phase
+ " frame="
+ frames
+ " enabled="
+ enabled.Factory.Enabled
+ " working="
+ enabled.Factory.IsWorking
+ " disabled="
+ disabled.Factory.Enabled
+ " creative="
+ MyAPIGateway.Session.CreativeMode
+ " max="
+ enabled.Target.MaxIntegrity.ToString("R", CultureInfo.InvariantCulture)
+ " test="
+ enabled.Target.Integrity.ToString("R", CultureInfo.InvariantCulture)
+ " control="
+ disabled.Target.Integrity.ToString("R", CultureInfo.InvariantCulture)
);
}

public override void UpdateAfterSimulation()
{
if (done || ++frames % 30 != 0)
return;
if (enabled == null)
{
if (
!MyAPIGateway.Utilities.FileExistsInModLocation("start.txt", ModContext.ModItem)
)
return;
enabled = Create(true);
disabled = Create(false);
frames = 0;
return;
}
if (frames == 120)
{
Observe("pristine");
var type = MyStringHash.GetOrCompute("Bullet");
enabled.Target.DoDamage(300f, type, true);
disabled.Target.DoDamage(300f, type, true);
}
if (frames == 240)
{
Observe("damaged");
enabled.Factory.Enabled = true;
}
if (frames > 240 && (enabled.Target.IsFullIntegrity || frames >= 4800))
{
Observe("settled");
enabled.Factory.RefreshCustomInfo();
MyLog.Default.WriteLineAndConsole(
"nanite_factory "
+ enabled.Factory.CustomInfo.Replace("\r", "").Replace("\n", " | ")
);
done = true;
}
}
}
}
1 change: 1 addition & 0 deletions Test/NaniteRepairFixture/cluster-mod-compat.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
D everywhere
13 changes: 13 additions & 0 deletions Test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,16 @@ IDs on one of the original grids, consume both pads and leave no duplicate on
the other cluster roles. The raw role snapshots are saved in
`MOD-WELD-PADS/observations.json`. This scenario exercises pad welding. Detaching
a block with a player's hand grinder requires a separate case.

### Nanite Control Facility v2.2 repair

Run `python nanite_repair_differential.py /path/to/corpus /path/to/new-results`.
Workshop item 219757726 uses its construction nanites to repair damaged armor.
The fixture creates two powered, static grids 2 km apart. Their armor targets
are at least 35 m from the factory, outside the block's 4 m native welder
radius. Each grid carries a remote control so the mod can find its power
distributor. Both factories start disabled, receive 100 steel plates and have
the same damage applied to their targets. Only the treatment facility is enabled.
A pass requires full repair on that grid while the disabled grid retains its
measured damage. The test world shortens nanite travel using the mod's config.
This case covers same-grid repair in creative mode.
93 changes: 93 additions & 0 deletions Test/nanite_repair_differential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Compare actual integrity restored by the Workshop Nanite Control Facility to a disabled control."""

import argparse
import re
from pathlib import Path

from staged_mod_differential import run_staged

MOD = "219757726"
PROBE = "9991845004"


def configure(world):
# Keen scopes world files by the staged script assembly name.
storage = world / "Storage" / (MOD + ".sbm_NaniteConstructionSystem")
storage.mkdir(parents=True)
(storage / "Config.xml").write_text(
"<NaniteSettings><ConstructionMinTravelTime>1</ConstructionMinTravelTime>"
"<ConstructionDistanceDivisor>50</ConstructionDistanceDivisor>"
"</NaniteSettings>"
)


def measure(bench, roles, issuer):
(bench.cluster.config.root / f"{issuer}-data/Mods/{PROBE}.sbm/start.txt").touch(
exist_ok=False
)
rows = {}
for phase in ("pristine", "damaged", "settled"):
pattern = rf"nanite_repair {phase} frame=(\d+) enabled=(True|False) working=(True|False) disabled=(True|False) creative=(True|False) max=([\d.E+-]+) test=([\d.E+-]+) control=([\d.E+-]+)"
match = re.search(
pattern,
bench.cluster.wait_node_log(
issuer, pattern, 135 if phase == "settled" else 35
),
)
frame, enabled, working, disabled, creative, max_hp, test_hp, control_hp = (
match.groups()
)
rows[phase] = dict(
frame=int(frame),
enabled=enabled == "True",
working=working == "True",
disabled=disabled == "True",
creative=creative == "True",
max_hp=float(max_hp),
test_hp=float(test_hp),
control_hp=float(control_hp),
)
fresh, damaged, end = rows.values()
usable = (
fresh["test_hp"] == fresh["control_hp"] == fresh["max_hp"]
and fresh["max_hp"] > 0
and 0 < damaged["test_hp"] == damaged["control_hp"] < fresh["max_hp"]
and not damaged["enabled"]
and not any(row["disabled"] for row in rows.values())
and end["enabled"]
and end["working"]
and end["control_hp"] == damaged["control_hp"]
)
return dict(
issuer=issuer,
measurements=rows,
terminal_status=bench.cluster.wait_node_log(
issuer, "nanite_factory ", 10
).partition("nanite_factory ")[2],
result=(
"INCONCLUSIVE"
if not usable
else "PASS" if end["test_hp"] == fresh["max_hp"] else "DIFF"
),
)


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_staged(
args.corpus,
args.results,
scenario="MOD-NANITE-REPAIR",
title="Nanite Control Facility armor repair",
mod=MOD,
probe=PROBE,
fixture="NaniteRepairFixture",
measure=measure,
configure=configure,
)
print(result["result"])
raise SystemExit(0 if result["result"] == "PASS" else 1)
99 changes: 99 additions & 0 deletions Test/staged_mod_differential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Run the same Workshop and observer fixtures on standalone and two cluster nodes."""

import hashlib
import json
import os
import shutil
import subprocess
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

NODES = ("wa-1", "node-1", "node-2")


def run_staged(
corpus,
results,
*,
scenario,
title,
mod,
probe,
fixture,
measure,
world_name="ModWorld",
configure=None,
):
os.environ["CLUSTER_TEST_PLUGIN"] = "0"
bench = Bench(scenario, title, "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 / fixture, mods / f"{probe}.sbm")
world = work / world_name
world_with_mods(
HOST.package / "examples/Cluster-Simple", world, [mod, probe]
)
if configure is not None:
configure(world)
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"], "stock")
finally:
stock.stop()
if reference["result"] != "PASS":
return report
for role in NODES:
shutil.copytree(
mods, config.root / f"{role}-data/Mods", dirs_exist_ok=True
)
bench.cluster.start()
bench.cluster.wait_ready(timeout=240, serving=True)
bench.cluster.post("/automatic/pause")
actual = report["cluster"] = measure(bench, NODES, "node-1")
report["result"] = actual["result"]
except (
OSError,
ValueError,
TimeoutError,
ClusterError,
subprocess.CalledProcessError,
) as exc:
report["error"] = str(exc)
finally:
report["seconds"] = round(time.monotonic() - started, 1)
bench.record("observations", report)
bench.close()
return report
Loading