Preview typed mod ship visuals and captured LineArt in Unity

This commit is contained in:
Meta Vens 2026-09-26 19:10:44 +02:00
commit 24c2964046
10 changed files with 314 additions and 45 deletions

View file

@ -0,0 +1,51 @@
using System;
using UnityEditor;
using UnityEngine;
public static class ShipModPreview
{
// Batch proof: -executeMethod ShipModPreview.Smoke -shipModPath <package/ship.cc>
public static async void Smoke()
{
var args = Environment.GetCommandLineArgs();
var option = Array.IndexOf(args, "-shipModPath");
if (option < 0 || option + 1 >= args.Length)
{
Debug.LogError("-shipModPath <package/ship.cc> is required");
EditorApplication.Exit(1);
return;
}
ShipModVisual.Instance visual = null;
try
{
visual = await ShipModVisual.LoadAsync(args[option + 1], null);
if (visual.Anchors.Count == 0 || visual.LineMesh == null || visual.LineMesh.vertexCount == 0)
throw new InvalidOperationException("Mod visual did not import anchors and line points.");
Debug.Log($"SHIP_MOD_VISUAL_SMOKE anchors={visual.Anchors.Count} points={visual.LineMesh.vertexCount} segments={visual.LineMesh.GetIndexCount(0) / 2}");
visual.Destroy();
EditorApplication.Exit(0);
}
catch (Exception exception)
{
Debug.LogException(exception);
visual?.Destroy();
EditorApplication.Exit(1);
}
}
[MenuItem("Aetheria/Preview Mod Ship Package")]
private static async void Open()
{
var path = EditorUtility.OpenFilePanel("Ship authoring record", "GameData/Mods", "cc");
if (string.IsNullOrEmpty(path)) return;
try
{
var visual = await ShipModVisual.LoadAsync(path, null);
Undo.RegisterCreatedObjectUndo(visual.Root, "Preview mod ship");
Selection.activeGameObject = visual.Root;
SceneView.FrameLastActiveSceneView();
Debug.Log($"Previewed {path}: {visual.Anchors.Count} anchors, {visual.LineMesh?.vertexCount ?? 0} line points.");
}
catch (Exception exception) { Debug.LogException(exception); }
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4d32248a66f6454a9be20458fa43f3ef

View file

@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GLTFast;
using UnityEngine;
using Object = UnityEngine.Object;
// A mod package's visual assembly. It does not decide hull cells or hardpoint roles.
public static class ShipModVisual
{
public sealed class Instance
{
public GameObject Root;
public IReadOnlyDictionary<string, Transform> Anchors;
public Mesh LineMesh;
public Material LineMaterial;
public void Destroy()
{
DestroyObject(Root);
DestroyObject(LineMesh);
DestroyObject(LineMaterial);
}
}
private sealed class Nodes : GameObjectInstantiator
{
public Nodes(IGltfReadable gltf, Transform parent) : base(gltf, parent) { }
public Transform Get(uint index) => m_Nodes.TryGetValue(index, out var node) ? node.transform : null;
}
public static async Task<Instance> LoadAsync(string shipPath, Transform parent)
{
var package = ShipModCatalog.ReadPackage(shipPath);
var ship = package.Ship;
var root = new GameObject("mod-ship:" + ship.Id);
root.SetActive(false);
root.transform.SetParent(parent, false);
var result = new Instance { Root = root };
try
{
// glTFast's default defer agent creates a DontDestroyOnLoad object, which is
// unavailable in edit-mode previews. Play mode keeps its frame-budgeted agent.
var gltf = new GltfImport(deferAgent: Application.isPlaying ? null : new UninterruptedDeferAgent());
if (!await gltf.LoadFile(package.ModelPath))
throw new InvalidOperationException($"{ship.Id}: GLB import failed.");
var nodes = new Nodes(gltf, root.transform);
if (!await gltf.InstantiateMainSceneAsync(nodes))
throw new InvalidOperationException($"{ship.Id}: GLB scene instantiation failed.");
result.Anchors = ship.Anchors.ToDictionary(anchor => anchor.Id, anchor =>
nodes.Get(package.NodeIndices[anchor.ModelNodeId]) ??
throw new InvalidOperationException($"{ship.Id}: GLB scene omitted node {anchor.ModelNodeId}."),
StringComparer.Ordinal);
result.LineMesh = BuildLineMesh(ship.SchematicLines);
if (result.LineMesh != null)
{
var lines = new GameObject("Schematic Lines");
lines.transform.SetParent(root.transform, false);
lines.AddComponent<MeshFilter>().sharedMesh = result.LineMesh;
var shader = Shader.Find("Sprites/Default") ??
throw new InvalidOperationException("Sprites/Default shader is unavailable for ship lines.");
result.LineMaterial = new Material(shader) { name = "Ship Lines" };
lines.AddComponent<MeshRenderer>().sharedMaterial = result.LineMaterial;
}
root.SetActive(true);
return result;
}
catch
{
result.Destroy();
throw;
}
}
private static void DestroyObject(Object target)
{
if (target == null) return;
if (Application.isPlaying) Object.Destroy(target);
else Object.DestroyImmediate(target);
}
// Blender Z-up to Unity Y-up through Blender's glTF export and glTFast's handedness conversion.
// Segment topology preserves every authored point; display width is currently one screen pixel.
public static Mesh BuildLineMesh(IReadOnlyList<ShipPolyline> lines)
{
if (lines == null || lines.Count == 0) return null;
var vertices = new List<Vector3>();
var colors = new List<Color>();
var segments = new List<int>();
foreach (var line in lines)
{
var count = line.Points.Length / 3;
var start = vertices.Count;
for (var i = 0; i < count; i++)
{
var offset = i * 3;
vertices.Add(new Vector3(-line.Points[offset], line.Points[offset + 2], -line.Points[offset + 1]));
var rgba = line.Color;
colors.Add(new Color(rgba?[0] ?? 1, rgba?[1] ?? 1, rgba?[2] ?? 1,
(rgba?[3] ?? 1) * (line.Opacities?[i] ?? 1)));
if (i > 0) { segments.Add(start + i - 1); segments.Add(start + i); }
}
if (line.Cyclic && count > 2) { segments.Add(start + count - 1); segments.Add(start); }
}
var mesh = new Mesh { name = "Captured Ship Lines", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
mesh.SetVertices(vertices);
mesh.SetColors(colors);
mesh.SetIndices(segments, MeshTopology.Lines, 0);
mesh.RecalculateBounds();
return mesh;
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a8a4f72a22b44819a71e43e21c7db894

View file

@ -10,6 +10,13 @@ using System.Text;
// mod-owned ship.cc; this output is disposable and never becomes an authoring surface.
public static class ShipModCatalog
{
public sealed class Package
{
public ShipAuthoring Ship;
public string ModelPath;
public Dictionary<string, uint> NodeIndices;
}
public static CultRecordKey HullKey(string id) => new CultRecordKey("mod-hull:" + id);
public static CultRecordKey AuthoringKey(string id) => new CultRecordKey("mod-ship:" + id);
@ -31,20 +38,10 @@ public static class ShipModCatalog
{
var path = Path.Combine(directory, "ship.cc");
if (!File.Exists(path)) continue;
var ship = ShipAuthoringStore.Read(path);
if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal) ||
!ids.Add(ship.Id))
throw new InvalidOperationException($"{path}: ship ID must uniquely match its package directory name.");
var modelPath = Path.GetFullPath(Path.Combine(directory, ship.ModelAsset));
if (!modelPath.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(modelPath) || !string.Equals(Path.GetExtension(modelPath), ".glb", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"{ship.Id}: model asset must name an existing GLB inside its package.");
var modelNodes = ReadNodeIds(modelPath);
foreach (var anchor in ship.Anchors)
if (!modelNodes.Contains(anchor.ModelNodeId))
throw new InvalidOperationException($"{ship.Id}: model has no node with aetheria.id={anchor.ModelNodeId} for anchor {anchor.Id}.");
CultRecordRefs.Validate(ship.Hull);
ships.Add(ship);
var package = ReadPackage(path);
if (!ids.Add(package.Ship.Id))
throw new InvalidOperationException($"{path}: duplicate ship ID {package.Ship.Id}.");
ships.Add(package.Ship);
}
Directory.CreateDirectory(Path.GetDirectoryName(output));
@ -75,8 +72,27 @@ public static class ShipModCatalog
}
}
public static Package ReadPackage(string shipPath)
{
var path = Path.GetFullPath(shipPath);
var directory = Path.GetDirectoryName(path);
var ship = ShipAuthoringStore.Read(path);
if (!string.Equals(Path.GetFileName(directory), ship.Id, StringComparison.Ordinal))
throw new InvalidOperationException($"{path}: ship ID must match its package directory name.");
var modelPath = Path.GetFullPath(Path.Combine(directory, ship.ModelAsset));
if (!modelPath.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(modelPath) || !string.Equals(Path.GetExtension(modelPath), ".glb", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"{ship.Id}: model asset must name an existing GLB inside its package.");
var modelNodes = ReadNodeIds(modelPath);
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}.");
CultRecordRefs.Validate(ship.Hull);
return new Package { Ship = ship, ModelPath = modelPath, NodeIndices = modelNodes };
}
// GLB is the xenos asset boundary. Only its node extras are read here; geometry belongs to the runtime importer.
public static HashSet<string> ReadNodeIds(string path)
public static Dictionary<string, uint> ReadNodeIds(string path)
{
using var stream = File.OpenRead(path);
using var reader = new BinaryReader(stream);
@ -87,13 +103,16 @@ 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 HashSet<string>(StringComparer.Ordinal);
foreach (var node in json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>())
var ids = new Dictionary<string, uint>(StringComparer.Ordinal);
var nodes = json["nodes"]?.OfType<JObject>() ?? Enumerable.Empty<JObject>();
uint index = 0;
foreach (var node in nodes)
{
var id = (string)node["extras"]?["aetheria.id"];
if (string.IsNullOrEmpty(id)) continue;
if (!ids.Add(id))
if (string.IsNullOrEmpty(id)) { index++; continue; }
if (!ids.TryAdd(id, index))
throw new InvalidOperationException($"{path}: duplicate GLB node aetheria.id={id}.");
index++;
}
return ids;
}

View file

@ -3,7 +3,6 @@ using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using TMPro;
using UnityEngine;
using UnityEngine.UI;