diff --git a/Assets/Scripts/Editor/ShipModPlaySmoke.cs b/Assets/Scripts/Editor/ShipModPlaySmoke.cs index a4fb708b5..f0753e4e6 100644 --- a/Assets/Scripts/Editor/ShipModPlaySmoke.cs +++ b/Assets/Scripts/Editor/ShipModPlaySmoke.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using GameCult.Caching; using UnityEditor; using UnityEngine; @@ -9,6 +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. +// // Unity -batchmode -nographics -projectPath -executeMethod ShipModPlaySmoke.Run // -shipModPath //ship.cc [-shippedCatalog GameData/Aetheria.cc] -logFile // @@ -24,22 +29,32 @@ public static class ShipModPlaySmoke return at >= 0 && at + 1 < args.Length ? args[at + 1] : fallback; } var packagePath = Option("-shipModPath"); - var derived = Path.Combine(Path.GetTempPath(), $"ship-mod-play-smoke-{Guid.NewGuid():N}.cc"); + var work = Path.Combine(Path.GetTempPath(), $"ship-mod-play-smoke-{Guid.NewGuid():N}"); + var derived = Path.Combine(work, "Aetheria.modded.cc"); + var modsRoot = Path.Combine(work, "Mods"); GameObject zone = null; try { if (packagePath == null) throw new InvalidOperationException("-shipModPath is required"); var package = ShipModCatalog.ReadPackage(packagePath); - var modsRoot = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(packagePath))); + var broken = InstallWithBrokenSibling(packagePath, package, modsRoot); var composition = ShipModCatalog.Compose(Path.GetFullPath(Option("-shippedCatalog", "GameData/Aetheria.cc")), derived, modsRoot); - if (!composition.Included.Contains(package.Visual.Id)) - throw new InvalidOperationException($"{package.Visual.Id} was not composed into the catalog: " + - string.Join("; ", composition.Excluded.Select(excluded => $"{excluded.Package}: {excluded.Reason}"))); + 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}"))); using (var catalog = AetheriaStores.Open(derived)) { await ShipModShips.Preload(catalog, modsRoot); - var hull = catalog.GetAll().Single(candidate => candidate.Visual.IsSet() && candidate.Name == package.Hull.Name); + HullData Hull(string name) => catalog.GetAll().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(); @@ -56,16 +71,51 @@ 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"); + Debug.Log($"SHIP_MOD_PLAY_SMOKE thrusters={thrusters} weapons={weapons} collider=ok mapicon=ok skipped={broken.Visual.Id}"); } - if (zone != null) UnityEngine.Object.DestroyImmediate(zone); + Clean(zone, work); EditorApplication.Exit(0); } catch (Exception exception) { Debug.LogException(exception); - if (zone != null) UnityEngine.Object.DestroyImmediate(zone); + Clean(zone, work); EditorApplication.Exit(1); } } + + // 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)); + + var (hull, ship) = ShipAuthoringStore.Read(Path.Combine(modsRoot, package.Visual.Id, "ship.cc")); + ship.Id += ".broken"; + hull.Name += " Broken"; + hull.Visual = new CultRecordRef(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); + using (var cache = ShipAuthoringStore.Open(Path.Combine(modsRoot, ship.Id, "ship.cc"), writable: true)) + { + ShipAuthoringStore.Write(cache, hull, ship); + cache.FlushAsync().GetAwaiter().GetResult(); + } + return (hull, ship); + } + + private static void Clean(GameObject zone, string work) + { + if (zone != null) UnityEngine.Object.DestroyImmediate(zone); + try { if (Directory.Exists(work)) Directory.Delete(work, true); } + catch (Exception error) { Debug.LogWarning($"Play smoke left {work}: {error.Message}"); } + } } diff --git a/Assets/Scripts/Editor/ShipModPreview.cs b/Assets/Scripts/Editor/ShipModPreview.cs index 64f9ea6b7..9ed4fcec4 100644 --- a/Assets/Scripts/Editor/ShipModPreview.cs +++ b/Assets/Scripts/Editor/ShipModPreview.cs @@ -51,9 +51,9 @@ public static class ShipModPreview // Instantiate clones the assembled root, and Unity must remap every array reference into the clone. var clone = UnityEngine.Object.Instantiate(ship.gameObject).GetComponent(); - try { CheckShip(clone, plan, "clone"); } + try { CheckShip(clone, plan, "clone"); CheckExhaust(clone); } finally { UnityEngine.Object.DestroyImmediate(clone.gameObject); } - Debug.Log($"SHIP_MOD_ASSEMBLY_SMOKE thrusters={plan.Thrusters.Length} " + + Debug.Log($"SHIP_MOD_ASSEMBLY_SMOKE thrusters={plan.Thrusters.Length} exhaust=ok collider=hidden " + $"weapons={plan.Weapons.Length} radiators={plan.Radiators.Length}"); } @@ -63,6 +63,9 @@ public static class ShipModPreview bool Inside(Component part) => part != null && part.transform.IsChildOf(ship.transform); Require(ship.HullColliders.Length == 1 && Inside(ship.HullColliders[0]) && ship.HullColliders[0].GetComponent() != null, "one hull collider with a MeshCollider"); + Require(ship.HullColliders[0].GetComponentsInChildren(true).All(renderer => + renderer.sharedMaterials.All(material => material == ship.InvisibleMaterial)), + "a hull collider that draws nothing"); Require(Inside(ship.MapIcon) && Inside(ship.Shield) && Inside(ship.TractorBeam), "map icon, shield and tractor inside the ship"); Require(ship.ThrusterHardpoints.Select(node => node.name).SequenceEqual(plan.Thrusters) && ship.ThrusterHardpoints.All(node => Inside(node) && Inside(node.Emitter) && @@ -76,6 +79,42 @@ public static class ShipModPreview node.FiringPoint.All(Inside)).All(ok => ok), "weapon hardpoints with their muzzles in order"); } + // Exhaust from each hidden emitter, wired as ShipInstance wires it, from a particle system left at Unity's defaults + // (Use Mesh Colors on). The emitter's invisible material has alpha 0, so mesh colours would make every particle + // transparent; the wiring must turn them off. + private static void CheckExhaust(ShipInstance ship) + { + const int count = 200; + foreach (var hardpoint in ship.ThrusterHardpoints) + { + var exhaust = new GameObject("Smoke Exhaust").AddComponent(); + try + { + exhaust.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear); + var main = exhaust.main; + main.playOnAwake = false; + main.startSpeed = 0; + main.startLifetime = 10; + main.maxParticles = count * 2; + var emission = exhaust.emission; + emission.enabled = false; + var shape = exhaust.shape; + shape.enabled = true; + shape.shapeType = ParticleSystemShapeType.MeshRenderer; + if (!shape.useMeshColors) throw new InvalidOperationException("Unity's default Use Mesh Colors is off; the exhaust check proves nothing."); + ThrusterHardpoint.WireExhaust(exhaust, hardpoint); + exhaust.Emit(count); + if (exhaust.particleCount != count) + throw new InvalidOperationException($"clone: exhaust from {hardpoint.name} emitted {exhaust.particleCount} of {count} particles."); + var alive = new ParticleSystem.Particle[count]; + exhaust.GetParticles(alive); + if (alive.Any(particle => particle.GetCurrentColor(exhaust).a == 0)) + throw new InvalidOperationException($"clone: exhaust from {hardpoint.name} has transparent particles."); + } + finally { UnityEngine.Object.DestroyImmediate(exhaust.gameObject); } + } + } + [MenuItem("Aetheria/Preview Mod Ship Package")] private static async void Open() { diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs index 8a419c6e0..5d5b7352c 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoring.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoring.cs @@ -160,7 +160,8 @@ public static class ShipPrefabAuthoring mapIcon.gameObject.layer = minimapLayer; hull.gameObject.layer = combatLayer; var hullRenderer = hull.GetComponent(); - if (hullRenderer != null) hullRenderer.forceRenderingOff = true; + // Serialized, so it survives SaveAsPrefabAsset and every clone; forceRenderingOff survives neither. + if (hullRenderer != null) ShipModShips.Hide(hullRenderer, invisible); var collider = AddOrGet(hull.gameObject); collider.sharedMesh = hullMesh; collider.convex = true; diff --git a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs index 34f5abf83..9f740f557 100644 --- a/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs +++ b/Assets/Scripts/Editor/ShipPrefabAuthoringSmoke.cs @@ -33,6 +33,8 @@ public static class ShipPrefabAuthoringSmoke Require(ship.RadiatorHardpoints.Length == 1 && ship.RadiatorHardpoints[0].Mesh != null, "radiator mesh"); Require(ship.ArticulationPoints.Length == 1 && ship.ArticulationPoints[0].Group == 2, "articulation"); Require(ship.HullColliders.Length == 1 && ship.HullColliders[0].GetComponent().convex, "hull collision"); + Require(Array.TrueForAll(ship.HullColliders[0].GetComponent().sharedMaterials, + material => material == ship.InvisibleMaterial), "hull collider drawn with the invisible material only"); Require(ship.Shield != null && ship.Shield.GetComponent() != null, "shield envelope"); Require(ship.TractorBeam != null && ship.PingPrefab != null && ship.DestroyEffect != null, "shared assets"); Require(ship.MapIcon != null && ship.MapIcon.gameObject.layer == LayerMask.NameToLayer("Minimap"), "map icon"); diff --git a/Assets/Scripts/Gameplay/ShipInstance.cs b/Assets/Scripts/Gameplay/ShipInstance.cs index a81668af4..8f4fe40bf 100644 --- a/Assets/Scripts/Gameplay/ShipInstance.cs +++ b/Assets/Scripts/Gameplay/ShipInstance.cs @@ -65,10 +65,9 @@ public class ShipInstance : EntityInstance { var effectData = (ThrusterData) thruster.Data; var particles = Instantiate(EngineAssets.Load(effectData.ParticlesPrefab), transform, false); - var particlesShape = particles.shape; var thrusterHardpoint = ThrusterHardpoints .FirstOrDefault(t => t.name == thruster.Item.Hardpoint.Transform); - particlesShape.meshRenderer = thrusterHardpoint?.Emitter; + ThrusterHardpoint.WireExhaust(particles, thrusterHardpoint); // if (!string.IsNullOrEmpty(thruster.Item.Data.SoundEffectTrigger) && thrusterHardpoint != null) // { // AkSoundEngine.RegisterGameObj(thrusterHardpoint.gameObject); diff --git a/Assets/Scripts/Gameplay/ShipModShips.cs b/Assets/Scripts/Gameplay/ShipModShips.cs index 354a1e4a6..94177e0a5 100644 --- a/Assets/Scripts/Gameplay/ShipModShips.cs +++ b/Assets/Scripts/Gameplay/ShipModShips.cs @@ -14,7 +14,9 @@ public static class ShipModShips private static readonly Dictionary Prototypes = new Dictionary(); private static CultCache _catalog; - // Set by Preload; complete when every prototype is ready, faulted when any mod ship failed to import or assemble. + // 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. public static Task Loading { get; private set; } = Task.CompletedTask; public static Task Preload(CultCache catalog, string modsRoot) @@ -39,18 +41,19 @@ public static class ShipModShips if (Application.isPlaying) Object.DontDestroyOnLoad(root); foreach (var hull in hulls) { - var package = ShipModCatalog.PackageOf(catalog, hull, modsRoot); - var visual = await ShipModVisual.LoadAsync(package, root.transform); + ShipModVisual.Instance visual = null; try { + var package = ShipModCatalog.PackageOf(catalog, hull, modsRoot); + visual = await ShipModVisual.LoadAsync(package, root.transform); visual.Root.SetActive(false); Assemble(visual, package.Hull, package.Visual, template); Prototypes[catalog.RefOf(hull).Key] = visual.Root; } - catch + catch (Exception error) { - visual.Destroy(); - throw; + visual?.Destroy(); + Debug.LogError($"Mod ship {hull.Name} skipped: {error.Message}"); } } } @@ -103,8 +106,10 @@ public static class ShipModShips if (!hullMesh.isReadable) throw new InvalidOperationException($"{ship.Id}: the hull-collider mesh imported unreadable, so it cannot back a MeshCollider."); hullNode.gameObject.layer = combat; + // The collision hull is never drawn. Its renderer takes the invisible material, which is serialized and so survives + // the prototype's clone; forceRenderingOff would not survive Instantiate. var hullRenderer = hullNode.GetComponent(); - if (hullRenderer != null) hullRenderer.forceRenderingOff = true; + if (hullRenderer != null) Hide(hullRenderer, template.Invisible); var collider = AddOrGet(hullNode.gameObject); collider.sharedMesh = hullMesh; collider.convex = true; @@ -127,7 +132,7 @@ public static class ShipModShips // this renderer's visible material; forceRenderingOff would not survive Instantiate. var hardpoint = AddOrGet(Node(id).gameObject); hardpoint.Emitter = Renderer(id); - hardpoint.Emitter.sharedMaterials = Enumerable.Repeat(template.Invisible, hardpoint.Emitter.sharedMaterials.Length).ToArray(); + Hide(hardpoint.Emitter, template.Invisible); return hardpoint; }).ToArray(); var radiators = plan.Radiators.Select(id => @@ -162,6 +167,10 @@ public static class ShipModShips return instance; } + // Every material slot takes the invisible material, so the renderer draws nothing on the prototype and on every clone. + public static void Hide(Renderer renderer, Material invisible) => + renderer.sharedMaterials = Enumerable.Repeat(invisible, renderer.sharedMaterials.Length).ToArray(); + private static void Reset(Transform transform) { transform.localPosition = Vector3.zero; diff --git a/Assets/Scripts/Gameplay/ThrusterHardpoint.cs b/Assets/Scripts/Gameplay/ThrusterHardpoint.cs index d3c3dbb98..b0b1d0f26 100644 --- a/Assets/Scripts/Gameplay/ThrusterHardpoint.cs +++ b/Assets/Scripts/Gameplay/ThrusterHardpoint.cs @@ -1,8 +1,16 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; +using UnityEngine; public class ThrusterHardpoint : MonoBehaviour { public MeshRenderer Emitter; + + // Points an exhaust's shape at a hardpoint's emitter, or at nothing when the ship has no such hardpoint. The emitter + // carries the invisible material (alpha 0), so the particles never take their colour from its mesh: with Use Mesh + // Colors on, Unity's default, they would all be born transparent. + public static void WireExhaust(ParticleSystem exhaust, ThrusterHardpoint hardpoint) + { + var shape = exhaust.shape; + shape.useMeshColors = false; + shape.meshRenderer = hardpoint != null ? hardpoint.Emitter : null; + } } diff --git a/Assets/Scripts/UI/MainMenu.cs b/Assets/Scripts/UI/MainMenu.cs index 9d17af138..859d17c95 100644 --- a/Assets/Scripts/UI/MainMenu.cs +++ b/Assets/Scripts/UI/MainMenu.cs @@ -193,7 +193,7 @@ public class MainMenu : MonoBehaviour } // The one way into the game scene. Mod ship prototypes import asynchronously at boot, so the scene waits for them, - // and a failed import stops here with its reason rather than in the first zone. + // and a preload that could not run at all stops here with its reason rather than in the first zone. private void EnterGame() => StartCoroutine(EnterGameWhenModShipsAreReady()); private IEnumerator EnterGameWhenModShipsAreReady()