Merge eureka/aetheria-release-ship-render-fixes-r3 (cut cut-ship-render-fixes, verdicts s2 and s3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-17 00:53:39 +02:00
commit 0e0afda03d
8 changed files with 327 additions and 53 deletions

1
.gitignore vendored
View file

@ -94,6 +94,7 @@ crashlytics-build.properties
Packages/packages-lock.json
GameData/run.cc
GameData/player.cc
GameData/RemovedMods/
Vault/Aetheria/.obsidian/plugins/copilot/data.json
# Agent scratch, sandboxed toolchain caches, and throwaway checkouts. These had

View file

@ -10,9 +10,10 @@ using UnityEngine;
// Body() calls for a hull with a Visual. A plain parent transform stands in for ZoneRoot; nothing else in LoadEntity
// touches the body before it takes its ShipInstance.
//
// The package is installed beside a broken sibling: the same ship under another id, with its map-icon anchor moved onto
// its first muzzle's meshless node. The sibling composes, because no compose-time check reads meshes, and then fails
// assembly. The smoke proves the preload skips it and the good package still spawns.
// The package is installed beside two siblings. The .broken one has its map-icon anchor moved onto a meshless node:
// Compose excludes it, naming the anchor. The .unimportable one has its GLB's BIN chunk dropped: the headless reader
// accepts it, so it composes, and the importer cannot build it, so Preload faults Loading with ImportFault naming it.
// RemovePackage then moves it aside and the next Compose leaves it out.
//
// Unity -batchmode -nographics -projectPath <project> -executeMethod ShipModPlaySmoke.Run
// -shipModPath <mods>/<id>/ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile <log>
@ -37,12 +38,20 @@ public static class ShipModPlaySmoke
{
if (packagePath == null) throw new InvalidOperationException("-shipModPath <package/ship.cc> is required");
var package = ShipModCatalog.ReadPackage(packagePath);
var broken = InstallWithBrokenSibling(packagePath, package, modsRoot);
var composition = ShipModCatalog.Compose(Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc")), derived, modsRoot);
foreach (var id in new[] { package.Visual.Id, broken.Visual.Id })
if (!composition.Included.Contains(id))
throw new InvalidOperationException($"{id} was not composed into the catalog: " +
string.Join("; ", composition.Excluded.Select(excluded => $"{excluded.Package}: {excluded.Reason}")));
Install(package.Visual.Id, package, modsRoot, Path.GetFullPath(packagePath));
var broken = InstallSibling(package, modsRoot, ".broken", ship =>
{
var mapIcon = ship.Anchors.Single(anchor => anchor.Role == "map-icon");
var muzzle = ship.Anchors.First(anchor => anchor.Role == "weapon-muzzle");
(mapIcon.ModelNodeId, muzzle.ModelNodeId) = (muzzle.ModelNodeId, mapIcon.ModelNodeId);
}, null);
var shipped = Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc"));
var composition = ShipModCatalog.Compose(shipped, derived, modsRoot);
if (!composition.Included.Contains(package.Visual.Id))
throw new InvalidOperationException($"{package.Visual.Id} was not composed into the catalog: " + Reasons(composition));
var excluded = composition.Excluded.SingleOrDefault(entry => entry.Package == broken.Visual.Id);
if (composition.Included.Contains(broken.Visual.Id) || excluded == null || !excluded.Reason.Contains("map-icon anchor"))
throw new InvalidOperationException($"{broken.Visual.Id} was not excluded for its map-icon anchor: " + Reasons(composition));
using (var catalog = AetheriaStores.Open(derived))
{
@ -50,12 +59,6 @@ public static class ShipModPlaySmoke
HullData Hull(string name) => catalog.GetAll<HullData>().Single(candidate => candidate.Visual.IsSet() && candidate.Name == name);
var hull = Hull(package.Hull.Name);
// The broken sibling has no prototype, and Loading did not fault for it (await would have thrown).
var refused = false;
try { ShipModShips.Instantiate(Hull(broken.Hull.Name), null); }
catch (InvalidOperationException error) { refused = error.Message.Contains("no mod ship prototype"); }
if (!refused) throw new InvalidOperationException($"{broken.Visual.Id} assembled, or was refused for the wrong reason.");
zone = new GameObject("Play Smoke Zone");
var ship = ShipModShips.Instantiate(hull, zone.transform).GetComponent<ShipInstance>();
if (ship == null) throw new InvalidOperationException("The mod ship body has no ShipInstance.");
@ -71,7 +74,33 @@ public static class ShipModPlaySmoke
throw new InvalidOperationException("The hull collider is not a MeshCollider over a readable mesh.");
if (ship.MapIcon == null || ship.MapIcon.sharedMaterial == null || ship.MapIcon.gameObject.layer != LayerMask.NameToLayer("Minimap"))
throw new InvalidOperationException("The map icon is missing its renderer, material or Minimap layer.");
Debug.Log($"SHIP_MOD_PLAY_SMOKE thrusters={thrusters} weapons={weapons} collider=ok mapicon=ok skipped={broken.Visual.Id}");
// Phase 2: an unimportable sibling composes, then faults the preload with ImportFault naming exactly it.
var unimportable = InstallSibling(package, modsRoot, ".unimportable", null, DropBinChunk);
var derivedTwo = Path.Combine(work, "Derived2", "Aetheria.modded.cc");
var second = ShipModCatalog.Compose(shipped, derivedTwo, modsRoot);
if (!second.Included.Contains(unimportable.Visual.Id))
throw new InvalidOperationException($"{unimportable.Visual.Id} was not composed: " + Reasons(second));
ShipModShips.ImportFault fault = null;
using (var catalogTwo = AetheriaStores.Open(derivedTwo))
{
try { await ShipModShips.Preload(catalogTwo, modsRoot); }
catch (ShipModShips.ImportFault caught) { fault = caught; }
}
if (fault == null || fault.Faults.Length != 1 || fault.Faults[0].Package != unimportable.Visual.Id ||
!fault.Faults[0].Reason.StartsWith(unimportable.Hull.Name))
throw new InvalidOperationException("Loading did not fault with ImportFault naming exactly " + unimportable.Visual.Id + ".");
// Phase 3: removal moves it aside, and the next compose leaves it out.
var destination = ShipModCatalog.RemovePackage(modsRoot, unimportable.Visual.Id);
if (Directory.Exists(Path.Combine(modsRoot, unimportable.Visual.Id)) ||
destination != Path.Combine(work, "RemovedMods", unimportable.Visual.Id) || !File.Exists(Path.Combine(destination, "ship.cc")))
throw new InvalidOperationException("RemovePackage did not move the package to RemovedMods.");
var third = ShipModCatalog.Compose(shipped, Path.Combine(work, "Derived3", "Aetheria.modded.cc"), modsRoot);
if (third.Included.Contains(unimportable.Visual.Id) || !third.Included.Contains(package.Visual.Id))
throw new InvalidOperationException("The compose after removal still includes the removed package, or lost the good one.");
Debug.Log($"SHIP_MOD_PLAY_SMOKE thrusters={thrusters} weapons={weapons} collider=ok mapicon=ok excluded={broken.Visual.Id} " +
$"faulted={unimportable.Visual.Id} removed={Path.GetFileName(destination)}");
}
Clean(zone, work);
EditorApplication.Exit(0);
@ -84,26 +113,29 @@ public static class ShipModPlaySmoke
}
}
// Copies the package into modsRoot and writes its broken sibling beside it. Returns the sibling's records.
private static (HullData Hull, ShipAuthoring Visual) InstallWithBrokenSibling(string packagePath, ShipModCatalog.Package package, string modsRoot)
{
void Install(string id, string shipFile)
{
var model = Path.Combine(modsRoot, id, package.Visual.ModelAsset);
Directory.CreateDirectory(Path.GetDirectoryName(model));
File.Copy(package.ModelPath, model);
if (shipFile != null) File.Copy(shipFile, Path.Combine(modsRoot, id, "ship.cc"));
}
Install(package.Visual.Id, Path.GetFullPath(packagePath));
private static string Reasons(ShipModCatalog.Composition composition) =>
string.Join("; ", composition.Excluded.Select(excluded => $"{excluded.Package}: {excluded.Reason}"));
private static void Install(string id, ShipModCatalog.Package package, string modsRoot, string shipFile)
{
var model = Path.Combine(modsRoot, id, package.Visual.ModelAsset);
Directory.CreateDirectory(Path.GetDirectoryName(model));
File.Copy(package.ModelPath, model);
if (shipFile != null) File.Copy(shipFile, Path.Combine(modsRoot, id, "ship.cc"));
}
// The package's ship under the id plus suffix, its records changed by tweak and its GLB rewritten in place by glb.
// Returns the sibling's records.
private static (HullData Hull, ShipAuthoring Visual) InstallSibling(ShipModCatalog.Package package, string modsRoot, string suffix,
Action<ShipAuthoring> tweak, Action<string> glb)
{
var (hull, ship, _) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc"));
ship.Id += ".broken";
hull.Name += " Broken";
ship.Id += suffix;
hull.Name += suffix;
hull.Visual = new CultRecordRef<ShipAuthoring>(ShipModCatalog.AuthoringKey(ship.Id));
var mapIcon = ship.Anchors.Single(anchor => anchor.Role == "map-icon");
var muzzle = ship.Anchors.First(anchor => anchor.Role == "weapon-muzzle");
(mapIcon.ModelNodeId, muzzle.ModelNodeId) = (muzzle.ModelNodeId, mapIcon.ModelNodeId);
Install(ship.Id, null);
tweak?.Invoke(ship);
Install(ship.Id, package, modsRoot, null);
glb?.Invoke(Path.Combine(modsRoot, ship.Id, package.Visual.ModelAsset));
using (var cache = ShipAuthoringStore.Open(Path.Combine(modsRoot, ship.Id, "ship.cc"), writable: true))
{
ShipAuthoringStore.Write(cache, hull, ship);
@ -112,6 +144,17 @@ public static class ShipModPlaySmoke
return (hull, ship);
}
// Keeps the 12-byte GLB header and the JSON chunk, drops the BIN chunk and rewrites the header's total length: the
// headless reader needs only the JSON, the importer needs the buffer.
private static void DropBinChunk(string path)
{
var bytes = File.ReadAllBytes(path);
var end = 20 + (int)BitConverter.ToUInt32(bytes, 12);
var kept = bytes.Take(end).ToArray();
BitConverter.GetBytes((uint)kept.Length).CopyTo(kept, 8);
File.WriteAllBytes(path, kept);
}
private static void Clean(GameObject zone, string work)
{
if (zone != null) UnityEngine.Object.DestroyImmediate(zone);

View file

@ -46,7 +46,7 @@ public class ActionGameManager : MonoBehaviour
public static ShipModCatalog.Exclusion[] ModExclusions { get; private set; } = Array.Empty<ShipModCatalog.Exclusion>();
private static string CatalogPath => Path.Combine(GameDataDirectory.FullName, "Aetheria.cc");
private static string ModsPath => Path.Combine(GameDataDirectory.FullName, "Mods");
public static string ModsPath => Path.Combine(GameDataDirectory.FullName, "Mods");
// Disposable: composed at every boot from the shipped catalog and the mod packages, never authored.
private static string DerivedCatalogPath => Path.Combine(Application.persistentDataPath, "Aetheria.modded.cc");

View file

@ -6,17 +6,29 @@ using GameCult.Caching;
using UnityEngine;
using Object = UnityEngine.Object;
// Mod ships in the running game. Preload imports each catalog hull's GLB once, at boot, into an inactive assembled
// prototype keyed by the hull's record key; Instantiate then clones it synchronously, so LoadEntity never loads async.
// Mod ships in the running game. Compose decides which mod hulls exist; Preload builds a prototype for each, keyed by the
// hull's record key, into an inactive assembled copy that Instantiate clones synchronously, so LoadEntity never loads async.
// A composed hull Preload cannot build is an import fault: Loading faults with ImportFault, naming every such hull's package.
// The prototypes are cache-only: rebuilt every boot from the catalog, the mod GLBs and the template.
public static class ShipModShips
{
// Thrown by Loading when composed hulls could not be imported. It names the packages and changes no catalog.
public sealed class ImportFault : Exception
{
public ShipModCatalog.Exclusion[] Faults { get; }
public ImportFault(ShipModCatalog.Exclusion[] faults) :
base("Mod ships the game could not import: " + string.Join("; ", faults.Select(fault => fault.ToString())))
{
Faults = faults;
}
}
private static readonly Dictionary<CultRecordKey, GameObject> Prototypes = new Dictionary<CultRecordKey, GameObject>();
private static CultCache _catalog;
// Set by Preload; complete when every hull that could be built has its prototype. A mod ship that fails to import or
// assemble is skipped and logged, as Compose skips a bad package, so it never stops the rest; Loading faults only
// when the preload itself cannot run.
// Set by Preload; complete when every hull has its prototype, and faulted when any could not be built (ImportFault)
// or the preload itself cannot run.
public static Task Loading { get; private set; } = Task.CompletedTask;
public static Task Preload(CultCache catalog, string modsRoot)
@ -39,6 +51,7 @@ public static class ShipModShips
// DontDestroyOnLoad is play-mode only; the edit-mode play smoke builds the same prototypes
// without it, and nothing there loads scenes.
if (Application.isPlaying) Object.DontDestroyOnLoad(root);
var faults = new List<ShipModCatalog.Exclusion>();
foreach (var hull in hulls)
{
ShipModVisual.Instance visual = null;
@ -53,9 +66,10 @@ public static class ShipModShips
catch (Exception error)
{
visual?.Destroy();
Debug.LogError($"Mod ship {hull.Name} skipped: {error.Message}");
faults.Add(new ShipModCatalog.Exclusion { Package = catalog.Get(hull.Visual)?.Id ?? "(all mods)", Reason = $"{hull.Name}: {error.Message}" });
}
}
if (faults.Count > 0) throw new ImportFault(faults.ToArray());
}
// A live ship body for a mod hull. Refuses loudly when the prototype is missing: nothing is loaded here.

View file

@ -189,6 +189,54 @@ public static class ShipModCatalog
return (composition.Included.Length == 0 ? shippedCatalog : derivedCatalog, composition.Excluded);
}
// The one uninstall: presence under Mods is the only enablement (MR1), so a package leaves by moving, never by deletion,
// to <parent of modsRoot>/RemovedMods/<package> ('<package> (2)' and on when taken). Moving it back reinstalls it.
// Returns the destination. Compose and ResolveCatalog never read RemovedMods.
public static string RemovePackage(string modsRoot, string package)
{
var root = Path.GetFullPath(modsRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Containment, not a blacklist: the package must resolve to a strict child of the mods folder whose final name is
// the name given. A name the filesystem rewrites ('...', 'a.', 'a ', 'CON', 'a:b') resolves to something else.
if (!IsPackageName(package)) throw new ArgumentException("Not a mod package name.", nameof(package));
var source = ChildOf(root, package) ?? throw new ArgumentException("Not a mod package name.", nameof(package));
var info = new DirectoryInfo(source);
if (!info.Exists) throw new DirectoryNotFoundException("The package is not a directory under the mods folder.");
if (info.Attributes.HasFlag(FileAttributes.ReparsePoint))
throw new ArgumentException("A package that is a link is not removed.", nameof(package));
var removed = RemovedRoot(modsRoot);
Directory.CreateDirectory(removed);
var destination = ChildOf(removed, package);
for (var copy = 2; destination != null && (Directory.Exists(destination) || File.Exists(destination)); copy++)
destination = ChildOf(removed, $"{package} ({copy})");
if (destination == null) throw new ArgumentException("Not a mod package name.", nameof(package));
Directory.Move(source, destination);
return destination;
}
private static readonly string[] ReservedDeviceNames =
{ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
// A name Windows keeps as written: no separator, stream colon or wildcard, no trailing dot or space, and
// not a device name (with or without an extension). Held on every platform so a mod moves the same way everywhere.
private static bool IsPackageName(string name) =>
!string.IsNullOrEmpty(name) && name != "(all mods)" &&
name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && name.IndexOfAny(new[] { ':', '*', '?', '"', '<', '>', '|', '/', '\\' }) < 0 &&
name.All(character => character >= ' ') && !name.EndsWith('.') && !name.EndsWith(' ') &&
!ReservedDeviceNames.Contains(name.Split('.')[0].TrimEnd(' '), StringComparer.OrdinalIgnoreCase);
// The full path of `name` directly under `root`, or null when the filesystem would resolve it anywhere else or under
// another name. The comparison is of resolved path segments, never of a string prefix ('Mods2' is not inside 'Mods').
private static string ChildOf(string root, string name)
{
var full = Path.GetFullPath(Path.Combine(root, name));
return string.Equals(Path.GetDirectoryName(full), root, StringComparison.Ordinal) &&
string.Equals(Path.GetFileName(full), name, StringComparison.Ordinal) ? full : null;
}
private static string RemovedRoot(string modsRoot) =>
Path.Combine(Path.GetDirectoryName(Path.GetFullPath(modsRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), "RemovedMods");
private static Package Bind(HullData hull, ShipAuthoring ship, FactionProductData[] products, string directory, string path)
{
if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal))
@ -201,11 +249,17 @@ public static class ShipModCatalog
foreach (var anchor in ship.Anchors)
if (!modelNodes.ContainsKey(anchor.ModelNodeId))
throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}.");
// A thruster's mesh is its exhaust emission surface and a radiator's mesh is what glows (ruling
// thrusters-radiators-are-meshes), so either on an empty node is refused here, before any catalog sees the ship.
// Assemble reads a renderer or collider mesh from these anchors' nodes and refuses without one, and reads the shield
// node's scale as three positive radii (ruling thrusters-radiators-are-meshes). These refusals stand in for Assemble's
// throws, so a package Compose includes is one the importer's assembler can build; the exhaust emission surface and
// the glowing radiator are meshes by that same ruling. A weapon mount and a tractor may be empties.
foreach (var anchor in ship.Anchors)
if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh") && !modelNodes[anchor.ModelNodeId].HasMesh)
if ((anchor.Role == "thruster-emitter" || anchor.Role == "radiator-mesh" || anchor.Role == "map-icon" || anchor.Role == "hull-collider") &&
!modelNodes[anchor.ModelNodeId].HasMesh)
throw new InvalidOperationException($"{ship.Id}: {anchor.Role} anchor {anchor.Id} needs a mesh, but model node {anchor.ModelNodeId} has none.");
foreach (var anchor in ship.Anchors)
if (anchor.Role == "shield" && !modelNodes[anchor.ModelNodeId].PositiveScale)
throw new InvalidOperationException($"{ship.Id}: shield anchor {anchor.Id} needs three positive scale radii on model node {anchor.ModelNodeId}, with no matrix.");
BindRig(ship, modelNodes);
CultRecordRefs.Validate(hull);
return new Package
@ -218,7 +272,7 @@ public static class ShipModCatalog
// The rig the record states must be the rig the model has: every joint is a node, each joint's Parent and each mount's
// Joint is the nearest joint above its node, ancestors without an id being walked through by ReadNodeIds, and a radiator
// mesh sits under no joint.
private static void BindRig(ShipAuthoring ship, Dictionary<string, (uint Index, bool HasMesh, int Parent)> nodes)
private static void BindRig(ShipAuthoring ship, Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)> nodes)
{
var joints = new HashSet<string>((ship.Joints ?? new List<ShipJoint>()).Select(joint => joint.Id), StringComparer.Ordinal);
var idAt = nodes.ToDictionary(node => (int)node.Value.Index, node => node.Key);
@ -249,9 +303,13 @@ public static class ShipModCatalog
}
}
// No matrix, and every scale component (default 1) above zero: what Assemble's shield radii need.
private static bool PositiveScale(JObject node) =>
node["matrix"] == null && (node["scale"] == null || node["scale"].Select(component => (double)component).All(component => component > 0));
// GLB is the xenos asset boundary. Only its node extras, whether each node names a mesh, and its nearest identified ancestor's node index
// (-1 for none) are read here; geometry belongs to the runtime importer.
public static Dictionary<string, (uint Index, bool HasMesh, int Parent)> ReadNodeIds(string path)
// (-1 for none) are read here, plus whether the node's scale is three positive radii with no matrix; geometry belongs to the runtime importer.
public static Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)> ReadNodeIds(string path)
{
using var stream = File.OpenRead(path);
using var reader = new BinaryReader(stream);
@ -262,7 +320,7 @@ public static class ShipModCatalog
if (reader.ReadUInt32() != 0x4E4F534A || chunkLength > stream.Length - stream.Position)
throw new InvalidOperationException($"{path}: missing GLB JSON chunk.");
var json = JObject.Parse(Encoding.UTF8.GetString(reader.ReadBytes((int)chunkLength)));
var ids = new Dictionary<string, (uint Index, bool HasMesh, int Parent)>(StringComparer.Ordinal);
var ids = new Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)>(StringComparer.Ordinal);
var nodes = (json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>()).ToArray();
var parents = Enumerable.Repeat(-1, nodes.Length).ToArray();
for (var parent = 0; parent < nodes.Length; parent++)
@ -273,7 +331,7 @@ public static class ShipModCatalog
{
var id = (string)node["extras"]?["aetheria.id"];
if (string.IsNullOrEmpty(id)) { index++; continue; }
if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index))))
if (!ids.TryAdd(id, (index, node["mesh"] != null && node["mesh"].Type != JTokenType.Null, IdentifiedAncestor(parents, nodes, (int)index), PositiveScale(node))))
throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}.");
index++;
}

View file

@ -99,7 +99,7 @@ public class MainMenu : MonoBehaviour
if (ActionGameManager.ModExclusions.Length > 0 && !_exclusionsShown)
{
_exclusionsShown = true;
Refuse("Some mods were not loaded", string.Join("\n", ActionGameManager.ModExclusions.Select(exclusion => exclusion.ToString())));
RefuseMods("Some mods were not loaded", ActionGameManager.ModExclusions);
}
var saved = cache.GetGlobal<SavedGame>();
if (saved == null && cache.AllStoredDocuments.Any(stored => RunSave.IsRunRecord(stored.Descriptor.DocumentType)))
@ -210,7 +210,8 @@ public class MainMenu : MonoBehaviour
while (!loading.IsCompleted) yield return null;
if (loading.IsFaulted)
{
Refuse("Mod ships failed to load", loading.Exception.GetBaseException().Message);
if (loading.Exception.GetBaseException() is ShipModShips.ImportFault fault) RefuseMods("Mod ships failed to load", fault.Faults);
else Refuse("Mod ships failed to load", loading.Exception.GetBaseException().Message);
yield break;
}
SceneManager.LoadScene("ARPG");
@ -225,6 +226,42 @@ public class MainMenu : MonoBehaviour
Dialog.Show(onCancel: () => { }, cancelText: "OK");
}
// Refuse for faults that name mod packages: each distinct package gets a Remove button, the one RemovePackage. The catalog
// stays as this boot opened it, so the dialog says that removal takes effect at the next launch.
private readonly HashSet<string> _removedPackages = new();
public void RefuseMods(string title, ShipModCatalog.Exclusion[] faults)
{
// A package moved aside this session stays named but loses its button: this boot's catalog still holds it.
var open = faults.Where(fault => !_removedPackages.Contains(fault.Package)).ToArray();
var reason = string.Join("\n", faults.Select(fault => fault.ToString()));
Debug.LogError($"{title}: {reason}");
Dialog.Clear();
Dialog.Title.text = title;
Dialog.AddProperty(() => reason);
foreach (var package in open.Select(fault => fault.Package).Where(package => package != "(all mods)").Distinct())
Dialog.AddButton($"Remove {package}", () => Remove(title, faults, package));
Dialog.Show(onCancel: () => { }, cancelText: "OK");
}
private void Remove(string title, ShipModCatalog.Exclusion[] faults, string package)
{
string destination;
try { destination = ShipModCatalog.RemovePackage(ActionGameManager.ModsPath, package); }
catch (Exception error)
{
Refuse($"Could not remove {package}", $"{error.Message} Remove it by hand from {ActionGameManager.ModsPath}.");
return;
}
_removedPackages.Add(package);
var done = $"{package} moved to {destination}. Mods load at launch: restart Aetheria to play without it, or move it back into Mods to reinstall.";
Debug.Log(done);
Dialog.Clear();
Dialog.Title.text = $"Removed {package}";
Dialog.AddProperty(() => done);
Dialog.Show(onConfirm: Application.Quit, onCancel: () => { if (faults.Any(fault => fault.Package != "(all mods)" && !_removedPackages.Contains(fault.Package))) RefuseMods(title, faults); }, confirmText: "Quit", cancelText: "OK");
}
private void ShowSettings()
{
_nextMenu.panel.Clear();

View file

@ -383,7 +383,8 @@ public sealed class ShipModCatalogTests : IDisposable
}
// Ruling thrusters-radiators-are-meshes: a thruster's mesh is its emission surface and a radiator's is what glows, so
// either on an empty node is refused before compose; a weapon mount (and shield, tractor) may be an empty.
// either on an empty node is refused before compose, as are the map icon and hull collider Assemble reads a mesh from,
// and a shield whose node does not carry three positive radii; a weapon mount (and shield, tractor) may be an empty.
[Fact]
public void AMeshRoleAnchorOnAnEmptyNodeIsRefused()
{
@ -402,6 +403,24 @@ public sealed class ShipModCatalogTests : IDisposable
Assert.Contains("radiator-mesh anchor thruster.port needs a mesh", Assert.Throws<InvalidOperationException>(() =>
ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message);
foreach (var (dropped, message) in new[] { ("map", "map-icon anchor map needs a mesh"), ("collider", "hull-collider anchor collider needs a mesh") })
{
Directory.Delete(Path.Combine(Mods, "mod.skiff"), true);
WritePackage("mod.skiff", meshNodes: ShipFixture.MeshNodes.Where(node => node != dropped).ToArray());
Assert.Contains(message, Assert.Throws<InvalidOperationException>(() =>
ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message);
}
foreach (var shieldNode in new[] { @"{""name"":""shield"",""scale"":[1,0,1]", @"{""name"":""shield"",""scale"":[1,1,-1]", @"{""name"":""shield"",""matrix"":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]" })
{
Directory.Delete(Path.Combine(Mods, "mod.skiff"), true);
WritePackage("mod.skiff");
var glb = Path.Combine(Mods, "mod.skiff", "skiff.glb");
var json = ShipFixture.GlbJson(FixtureNodes).Replace(@"{""name"":""shield""", shieldNode);
File.WriteAllBytes(glb, ShipFixture.Glb(json, ShipFixture.MeshBytes()));
Assert.Contains("shield anchor shield needs three positive scale radii", Assert.Throws<InvalidOperationException>(() =>
ShipModCatalog.ReadPackage(Path.Combine(Mods, "mod.skiff", "ship.cc"))).Message);
}
// The same radiator on a mesh node, and the weapon mount, shield and tractor on empty nodes, are accepted.
Directory.Delete(Path.Combine(Mods, "mod.skiff"), true);
WritePackage("mod.skiff", tweak: AsRadiator);
@ -488,7 +507,18 @@ public sealed class ShipModCatalogTests : IDisposable
{
var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[
{""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}}]}"));
Assert.Equal(new Dictionary<string, (uint, bool, int)> { ["a"] = (1, false, -1), ["b"] = (4, true, -1) }, ShipModCatalog.ReadNodeIds(path));
Assert.Equal(new Dictionary<string, (uint, bool, int, bool)> { ["a"] = (1, false, -1, true), ["b"] = (4, true, -1, true) }, ShipModCatalog.ReadNodeIds(path));
}
[Fact]
public void PositiveScaleReadsAnAbsentScaleAsPositiveAndANegativeComponentOrAMatrixAsNot()
{
var path = Write("scales.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[
{""extras"":{""aetheria.id"":""none""}},{""scale"":[2,3,4],""extras"":{""aetheria.id"":""pos""}},{""scale"":[1,-1,1],""extras"":{""aetheria.id"":""neg""}},
{""scale"":[1,1,0],""extras"":{""aetheria.id"":""zero""}},{""matrix"":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],""extras"":{""aetheria.id"":""matrix""}}]}"));
var nodes = ShipModCatalog.ReadNodeIds(path);
Assert.Equal(new[] { "none", "pos" }, nodes.Where(node => node.Value.PositiveScale).Select(node => node.Key).OrderBy(key => key));
Assert.Equal(new[] { "matrix", "neg", "zero" }, nodes.Where(node => !node.Value.PositiveScale).Select(node => node.Key).OrderBy(key => key));
}
[Fact]
@ -551,6 +581,97 @@ public sealed class ShipModCatalogTests : IDisposable
Assert.Contains(ShipModCatalog.HullKey("mod.c").Value, Records(Derived).Keys);
}
private string RemovedMods => Path.Combine(_directory.Path, "RemovedMods");
[Fact]
public void RemovePackageMovesItAsideAndTheNextBootDoesNotLoadIt()
{
WritePackage("mod.skiff");
var before = (Ship: Hash(Path.Combine(Mods, "mod.skiff", "ship.cc")), Glb: Hash(Path.Combine(Mods, "mod.skiff", "skiff.glb")));
Assert.Equal(Derived, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog);
var destination = ShipModCatalog.RemovePackage(Mods, "mod.skiff");
Assert.Equal(Path.Combine(RemovedMods, "mod.skiff"), destination);
Assert.False(Directory.Exists(Path.Combine(Mods, "mod.skiff")));
Assert.Equal(before, (Hash(Path.Combine(destination, "ship.cc")), Hash(Path.Combine(destination, "skiff.glb"))));
Assert.Equal(Shipped, ShipModCatalog.ResolveCatalog(Shipped, Derived, Mods).Catalog);
}
[Fact]
public void RemovingAPackageTwiceKeepsBothCopies()
{
WritePackage("mod.skiff");
ShipModCatalog.RemovePackage(Mods, "mod.skiff");
File.WriteAllText(Path.Combine(RemovedMods, "mod.skiff", "marker.txt"), "first");
WritePackage("mod.skiff");
var second = ShipModCatalog.RemovePackage(Mods, "mod.skiff");
Assert.Equal(Path.Combine(RemovedMods, "mod.skiff (2)"), second);
Assert.Equal("first", File.ReadAllText(Path.Combine(RemovedMods, "mod.skiff", "marker.txt")));
Assert.False(File.Exists(Path.Combine(second, "marker.txt")));
}
// Hostile ids: the ones a filesystem rewrites or resolves elsewhere. A directory is created for each where the platform
// allows it, so a refusal that merely finds nothing is not enough. Nothing outside the intended package may move.
[Theory]
[InlineData("")]
[InlineData(".")]
[InlineData("..")]
[InlineData("...")]
[InlineData(".. ")]
[InlineData("a.")]
[InlineData("a ")]
[InlineData("CON")]
[InlineData("con.txt")]
[InlineData("NUL")]
[InlineData("a:b")]
[InlineData("(all mods)")]
[InlineData("a/b")]
[InlineData("a\\b")]
[InlineData("../Mods")]
[InlineData("../Mods2")]
[InlineData("missing")]
public void RemovePackageRefusesWhatIsNotAPackageDirectory(string name)
{
WritePackage("mod.skiff");
File.WriteAllText(Path.Combine(_directory.Path, "outside.txt"), "x");
Directory.CreateDirectory(Path.Combine(_directory.Path, "Mods2"));
if (name != "missing") try { Directory.CreateDirectory(Path.Combine(Mods, name)); } catch (Exception) { }
var before = Directory.GetDirectories(Mods).Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.ThrowsAny<Exception>(() => ShipModCatalog.RemovePackage(Mods, name));
Assert.True(Directory.Exists(Mods));
Assert.True(Directory.Exists(Path.Combine(Mods, "mod.skiff")));
Assert.True(Directory.Exists(Path.Combine(_directory.Path, "Mods2")));
Assert.True(File.Exists(Path.Combine(_directory.Path, "outside.txt")));
Assert.False(Directory.Exists(RemovedMods));
Assert.Equal(before, Directory.GetDirectories(Mods).Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal));
}
[Fact]
public void RemovePackageRefusesAnAbsolutePathAndAnInPackageLinkOutsideMods()
{
WritePackage("mod.skiff");
var outside = Path.Combine(_directory.Path, "Outside");
Directory.CreateDirectory(outside);
File.WriteAllText(Path.Combine(outside, "keep.txt"), "x");
Assert.ThrowsAny<Exception>(() => ShipModCatalog.RemovePackage(Mods, outside));
Assert.True(File.Exists(Path.Combine(outside, "keep.txt")));
var linked = true;
try { Directory.CreateSymbolicLink(Path.Combine(Mods, "link"), outside); } catch (Exception) { linked = false; }
if (linked)
{
Assert.ThrowsAny<Exception>(() => ShipModCatalog.RemovePackage(Mods, "link"));
Assert.True(File.Exists(Path.Combine(outside, "keep.txt")));
Assert.True(Directory.Exists(Path.Combine(Mods, "link")));
}
Assert.False(Directory.Exists(RemovedMods));
Assert.True(Directory.Exists(Path.Combine(Mods, "mod.skiff")));
}
[Fact]
public void TheBootCatalogIsTheShippedOneUntilAModIsInstalled()
{
@ -652,7 +773,7 @@ public sealed class ShipModCatalogTests : IDisposable
private void WritePackage(string id, string hullName = "Skiff", string[] nodes = null, string modelAsset = "skiff.glb",
Action<ShipParts> tweak = null, string[] meshNodes = null) => ShipFixture.WritePackage(Mods, id, hullName, nodes, modelAsset, tweak, meshNodes);
private static Dictionary<string, uint> Indices(Dictionary<string, (uint Index, bool HasMesh, int Parent)> nodes) =>
private static Dictionary<string, uint> Indices(Dictionary<string, (uint Index, bool HasMesh, int Parent, bool PositiveScale)> nodes) =>
nodes.ToDictionary(node => node.Key, node => node.Value.Index);
private static int Occurrences(byte[] haystack, byte[] needle)

View file

@ -201,7 +201,7 @@ public sealed class ShipRigTests : IDisposable
// arm > elbow > wrist > (an untagged bracket) > gun > gun-muzzle, with the fixture's other nodes at the root.
private static readonly Node[] RigNodes =
{
new Node("map", "map", null), new Node("collider", "collider", null), new Node("shield", "shield", null),
new Node("map", "map", null, true), new Node("collider", "collider", null, true), new Node("shield", "shield", null),
new Node("tractor", "tractor", null), new Node("thruster-port", "thruster-port", null, true),
new Node("pod", "pod", null), new Node("arm", "arm", null), new Node("elbow", "elbow", "arm"), new Node("wrist", "wrist", "elbow"),
new Node("bracket", null, "wrist"), new Node("gun", "gun", "bracket"), new Node("gun-muzzle", "gun-muzzle", "gun")