acdream/tools/MosswartArt/Export.cs
Erik a1ffe77af4 feat: mosswart client icon and Asheron's Call-inspired launcher icon
acdream had no application icon on either executable. Two marks now ship,
built from the game's own material rather than drawn freehand:

* Client - the retail mosswart head. Not an illustration of one: the actual
  creature mesh (Setup 0x02000B4F part 14, skin atlas 0x05001E11,
  ClothingBase 0x10000344) read out of client_portal.dat through acdream's
  own GfxObjMesh/SetupMesh port, then smoothed, lit and graded. Palette
  values are sampled from that texture, including the mustard belly the
  Mosswart lore calls a "foul yellow".

* Launcher - a forged ring enclosing a barbed crescent, rebuilt from
  measurements of the retail wordmark and the acclient.exe icon resource.
  An original construction in the same visual language, not a copy of the
  trademarked logo. Its warm field matches the retail client icon.

Three techniques carry the render quality, all in tools/IconForge:

* PN-triangle tessellation (smooth.py). The retail head is 104 triangles
  and renders faceted. Each triangle becomes a cubic Bezier patch built
  from its own corner positions and normals, so the silhouette genuinely
  rounds rather than merely shading smoothly - and it needs no mesh
  connectivity, which matters because UV seams would otherwise pull apart.
  Normals are welded across coincident positions first, but only within a
  crease angle, so ear fins and tusk edges stay sharp.

* Matcaps (ring.py). A Lambert rasterizer cannot produce chrome, because
  chrome is almost entirely reflection and there is nothing here to
  reflect. Sampling a lit-sphere image by the camera-space normal is the
  standard stand-in for an environment map.

* Distance-transform bevelling (chisel.py). Flat shapes become chiselled
  metal by treating distance-to-edge as height. The height field is
  blurred before differentiating; without that the medial axis of each
  stroke shows through as a hatched ridge.

Two facts worth recording, both discovered the hard way. Creature Setups
define no upright pose in PlacementFrames, so the exporter must be handed
the weenie's MotionTable id or all 17 parts stack on the origin. And a
mosswart's eyes sit on the sides of the skull like a frog's, so a dead-on
frontal turns them edge-on and the face stops reading as a mosswart at all;
the hero angle is az 266 / el 32.

Wiring: <ApplicationIcon> gives each executable its PE icon. The client's
runtime window icon is embedded rather than copied beside the binary - a
window icon has no sensible fallback if the file goes missing, and
embedding survives single-file publish. WindowIconLoaderTests guards the
resource names, which are coupled to LogicalName in the csproj by string
alone and would otherwise fail only as a silently icon-less window.

Both halves of the pipeline are deterministic and reproduce the committed
PNGs byte-for-byte, so an accidental edit shows up as a diff.

Solution builds clean; 14,378 tests pass on the standard hermetic lane
filter, 0 failures.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 14:42:10 +02:00

143 lines
6.6 KiB
C#

// Export a creature Setup's geometry (per part, with UVs + normals + the
// ClothingBase texture substitutions applied) to JSON so an offline rasterizer
// can render it. Uses acdream's own tested GfxObjMesh/SetupMesh port rather than
// re-deriving the dat mesh format.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using AcDream.Core.Content;
using AcDream.Core.Meshing;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Lib.IO;
namespace MosswartArt;
internal sealed class DatSource(DatCollection dats) : IDatObjectSource
{
[return: MaybeNull]
public T Get<T>(uint fileId) where T : IDBObj
=> dats.TryGet<T>(fileId, out var v) ? v : default;
public bool TryGet<T>(uint fileId, [MaybeNullWhen(false)] out T value) where T : IDBObj
=> dats.TryGet(fileId, out value!);
}
internal sealed class AnimLoader(DatCollection dats) : AcDream.Core.Physics.IAnimationLoader
{
public Animation? LoadAnimation(uint id)
=> dats.TryGet<Animation>(id, out var a) ? a : null;
}
internal static class Export
{
private static string F(float v) => v.ToString("R", CultureInfo.InvariantCulture);
public static int Run(DatCollection dats, uint setupId, uint clothingId, string outPath, uint motionTableId = 0)
{
if (!dats.TryGet<Setup>(setupId, out var setup) || setup is null)
{
Console.Error.WriteLine($"Setup 0x{setupId:X8} not found");
return 1;
}
// ClothingBase substitution map, at SurfaceTexture (0x05) level.
var texSwap = new Dictionary<uint, uint>();
if (clothingId != 0 && dats.TryGet<ClothingTable>(clothingId, out var ct) && ct is not null)
{
foreach (var baseEffect in ct.ClothingBaseEffects.Values)
foreach (var objEffect in baseEffect.CloObjectEffects)
foreach (var te in objEffect.CloTextureEffects)
texSwap[(uint)te.OldTexture] = (uint)te.NewTexture;
}
var referencedTextures = new HashSet<uint>();
var src = new DatSource(dats);
// Creatures do not define an upright pose in Setup.PlacementFrames --
// the idle frame has to come from the MotionTable, or every part lands
// stacked on the origin.
var idle = MotionResolver.GetIdleFrame(setup, src, new AnimLoader(dats),
motionTableId == 0 ? null : motionTableId);
Console.WriteLine(idle is null ? "idle frame: NONE (falling back to placement frame)"
: $"idle frame: {idle.Frames.Count} part frames");
var refs = SetupMesh.Flatten(setup, idle);
var sb = new StringBuilder();
sb.Append("{\"setup\":\"0x").Append(setupId.ToString("X8")).Append("\",\"parts\":[");
for (int i = 0; i < refs.Count; i++)
{
var mr = refs[i];
if (!dats.TryGet<GfxObj>(mr.GfxObjId, out var gfx) || gfx is null) continue;
var subs = GfxObjMesh.Build(gfx, src);
var m = mr.PartTransform;
if (i > 0) sb.Append(',');
sb.Append("{\"index\":").Append(i)
.Append(",\"gfx\":\"0x").Append(mr.GfxObjId.ToString("X8")).Append('"')
.Append(",\"m\":[")
.Append(F(m.M11)).Append(',').Append(F(m.M12)).Append(',').Append(F(m.M13)).Append(',').Append(F(m.M14)).Append(',')
.Append(F(m.M21)).Append(',').Append(F(m.M22)).Append(',').Append(F(m.M23)).Append(',').Append(F(m.M24)).Append(',')
.Append(F(m.M31)).Append(',').Append(F(m.M32)).Append(',').Append(F(m.M33)).Append(',').Append(F(m.M34)).Append(',')
.Append(F(m.M41)).Append(',').Append(F(m.M42)).Append(',').Append(F(m.M43)).Append(',').Append(F(m.M44))
.Append("],\"sub\":[");
for (int s = 0; s < subs.Count; s++)
{
var sm = subs[s];
// Surface (0x08) -> OrigTextureId (0x05) -> ClothingBase swap.
uint texId = sm.SurfaceId;
if ((texId >> 24) == 0x08 && dats.TryGet<Surface>(texId, out var surf) && surf is not null)
texId = (uint)surf.OrigTextureId;
if (texSwap.TryGetValue(texId, out var swapped)) texId = swapped;
referencedTextures.Add(texId);
if (s > 0) sb.Append(',');
sb.Append("{\"surface\":\"0x").Append(sm.SurfaceId.ToString("X8")).Append('"')
.Append(",\"tex\":\"0x").Append(texId.ToString("X8")).Append('"')
.Append(",\"v\":[");
for (int v = 0; v < sm.Vertices.Length; v++)
{
var vert = sm.Vertices[v];
if (v > 0) sb.Append(',');
sb.Append('[').Append(F(vert.Position.X)).Append(',').Append(F(vert.Position.Y)).Append(',').Append(F(vert.Position.Z))
.Append(',').Append(F(vert.Normal.X)).Append(',').Append(F(vert.Normal.Y)).Append(',').Append(F(vert.Normal.Z))
.Append(',').Append(F(vert.TexCoord.X)).Append(',').Append(F(vert.TexCoord.Y)).Append(']');
}
sb.Append("],\"i\":[");
for (int k = 0; k < sm.Indices.Length; k++)
{
if (k > 0) sb.Append(',');
sb.Append(sm.Indices[k]);
}
sb.Append("]}");
}
sb.Append("]}");
}
sb.Append("]}");
// The documented destination (tools/IconForge/work/) does not exist in a
// fresh checkout, so create it rather than making the caller mkdir first.
string outFull = Path.GetFullPath(outPath);
Directory.CreateDirectory(Path.GetDirectoryName(outFull) ?? ".");
File.WriteAllText(outFull, sb.ToString());
Console.WriteLine($"wrote {outPath} ({new FileInfo(outFull).Length / 1024} KB), {refs.Count} parts");
// Dump the surfaces alongside the geometry. Keeping both halves in one
// command means the render pipeline has a single documented input step
// and cannot be handed geometry whose textures were never extracted.
string textureDir = Path.Combine(Path.GetDirectoryName(outFull) ?? ".", "textures");
Console.WriteLine($"dumping {referencedTextures.Count} referenced surfaces -> {textureDir}");
int written = Textures.Dump(dats, referencedTextures, textureDir);
if (written != referencedTextures.Count)
{
Console.Error.WriteLine(
$"WARNING: {referencedTextures.Count - written} surface(s) did not resolve; "
+ "the render will fall back to flat grey for those.");
}
return 0;
}
}