Merge branch 'feat-alfar-nexus'

This commit is contained in:
kanym 2026-10-30 23:42:50 +01:00
commit 4cf95fa8c7
22 changed files with 1009 additions and 12 deletions

View file

@ -0,0 +1,79 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The light on the two Alfar chests, which says whether the drones have work there: the fire
/// chest's grate burns while it holds wood they may burn, the entry chest's inlay shines while it
/// holds anything but the sigil. Every client asks its own copy of the inventory, which Container
/// keeps in step with the ZDO, so nothing travels over the network for it.
/// </summary>
public class AlfarChestGlow : MonoBehaviour
{
public Renderer[] Glows;
public ParticleSystem Embers;
public Color GlowColor;
public bool WoodOnly;
private Container m_container;
private Material m_lit;
private Material m_cold;
private bool? m_shown;
private float m_nextCheck;
private void Awake()
{
m_container = GetComponent<Container>();
if (Glows == null || Glows.Length == 0 || Glows[0] == null) return;
m_cold = Glows[0].sharedMaterial;
m_lit = new Material(m_cold) { name = m_cold.name + "_lit" };
m_lit.color = Color.black;
m_lit.EnableKeyword("_EMISSION");
m_lit.SetColor("_EmissionColor", GlowColor);
}
private void Update()
{
if (Time.time < m_nextCheck) return;
m_nextCheck = Time.time + 1f;
bool lit = HasWork();
if (m_shown == lit) return;
m_shown = lit;
if (m_lit != null)
{
foreach (Renderer glow in Glows)
{
if (glow != null) glow.sharedMaterial = lit ? m_lit : m_cold;
}
}
if (Embers != null)
{
if (lit) Embers.Play(true);
else Embers.Stop(true, ParticleSystemStopBehavior.StopEmitting);
}
}
private bool HasWork()
{
Inventory inventory = m_container != null ? m_container.GetInventory() : null;
if (inventory == null) return false;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item == null || item.m_dropPrefab == null) continue;
string name = item.m_dropPrefab.name;
if (WoodOnly ? AlfarDroneAI.IsWood(name) : name != AlfarSigil.PrefabName) return true;
}
return false;
}
private void OnDestroy()
{
if (m_lit != null) Destroy(m_lit);
}
}
}

View file

@ -61,12 +61,15 @@ namespace RacesOfValheim
public static void Register() public static void Register()
{ {
RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc",
new Color(0.62f, 0.80f, 1f, 1f)); "$rov_hover_alfar_inngangskista", new Color(0.62f, 0.80f, 1f, 1f),
AlfarInputChest.Build, "AlfarInputChest_icon.png");
RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc",
new Color(0.85f, 0.62f, 0.36f, 1f)); "$rov_hover_alfar_eldividarkista", new Color(0.85f, 0.62f, 0.36f, 1f),
AlfarFireChest.Build, "AlfarFireChest_icon.png");
} }
private static void RegisterOne(string pieceName, string display, string description, Color tint) private static void RegisterOne(string pieceName, string display, string description, string hoverName, Color tint,
System.Func<GameObject, bool> build, string iconResource)
{ {
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood"); GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_chest_wood");
if (source == null) if (source == null)
@ -91,15 +94,19 @@ namespace RacesOfValheim
} }
requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true));
// The hover and the chest window say what the chest is for, not only its name.
Container container = prefab.GetComponent<Container>(); Container container = prefab.GetComponent<Container>();
if (container != null) container.m_name = display; if (container != null) container.m_name = hoverName;
Piece piece = prefab.GetComponent<Piece>(); Piece piece = prefab.GetComponent<Piece>();
if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; }
piece.m_name = display; piece.m_name = display;
piece.m_description = description; piece.m_description = description;
AlfarConstructs.Tint(prefab, tint); // Each chest has a body of its own; the tint stays as the fallback if it cannot be built.
Sprite icon = piece.m_icon;
if (!build(prefab)) AlfarConstructs.Tint(prefab, tint);
else icon = IconFrom(iconResource) ?? icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{ {
@ -107,7 +114,7 @@ namespace RacesOfValheim
Description = description, Description = description,
PieceTable = PieceTables.Hammer, PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting, Category = PieceCategories.Crafting,
Icon = piece.m_icon, Icon = icon,
Requirements = requirements.ToArray(), Requirements = requirements.ToArray(),
})); }));
@ -130,5 +137,12 @@ namespace RacesOfValheim
AlfarPieces.Extra.Add(pieceName); AlfarPieces.Extra.Add(pieceName);
} }
internal static Sprite IconFrom(string resource)
{
Texture2D texture = PieceLook.LoadTexture(resource);
if (texture == null) return null;
return Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
} }
} }

View file

@ -1878,7 +1878,7 @@ namespace RacesOfValheim
"Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood",
}; };
private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); internal static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
/// <summary> /// <summary>
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest

View file

@ -0,0 +1,166 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Eldividarkista's own body. Players kept mistaking a plain "Wood chest" for it, so it must
/// not look like any chest they can build: the box and lid are the Mistlands dvergr crate (a prop
/// nobody can place), repainted as blackened iron with an aged-bronze frame
/// (scripts/paint_fire_chest.py), with an iron grate on the front.
///
/// Behind the grate the fire shows only while the chest holds wood the drones may burn: a dark
/// grate means empty. No light source, on purpose - a base full of chests must not glow.
/// </summary>
public static class AlfarFireChest
{
private const string CrateName = "dvergrprops_crate";
private const string EmbersSource = "fx_Torch_Carried";
// The crate is a 1.02 m cube, stretched into a chest about the size of the vanilla one:
// 1.6 m wide, 0.8 m deep. Its front face (+z, away from the lid's hinge) ends up here.
private static readonly Vector3 Stretch = new Vector3(1.6f, 1f, 0.8f);
private const float FrontZ = 0.515f * 0.8f;
private const float LidY = 0.81f;
private const float GrateWidth = 0.62f * 1.6f;
private const int GrateGaps = 10;
private const float GrateHeight = 0.36f;
private const float GrateY = 0.42f;
private static readonly Color Ember = new Color(1f, 0.42f, 0.1f);
/// <summary>Swaps the cloned wood chest's meshes for the fire chest. False leaves the wood
/// chest's look in place, with a warning, rather than an invisible chest.</summary>
public static bool Build(GameObject prefab)
{
GameObject crate = PrefabManager.Cache.GetPrefab<GameObject>(CrateName);
Transform crateNew = crate != null ? crate.transform.Find("new") : null;
Transform visual = prefab.transform.Find("New");
if (crateNew == null || crateNew.childCount < 3 || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr crate to build the Eldividarkista from; it keeps the wood chest's look.");
return false;
}
// The wood chest's box, lids and LOD group go; "New" itself stays, because WearNTear
// switches it as the piece's healthy look.
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
// The crate's high meshes, in the order the prefab keeps them: box, contents, lid. The
// contents are the glowing dvergr cargo and stay behind.
GameObject body = Object.Instantiate(crateNew.GetChild(0).gameObject, visual, false);
body.name = "body";
body.transform.localScale = Vector3.Scale(body.transform.localScale, Stretch);
GameObject lidClosed = Object.Instantiate(crateNew.GetChild(2).gameObject, visual, false);
lidClosed.name = "lid_closed";
lidClosed.transform.localScale = Vector3.Scale(lidClosed.transform.localScale, Stretch);
// The open lid: the closed one turned up 100 degrees about its back edge.
GameObject lidOpen = Object.Instantiate(lidClosed, visual, false);
lidOpen.name = "lid_open";
foreach (Collider collider in lidOpen.GetComponentsInChildren<Collider>(true)) Object.DestroyImmediate(collider);
Vector3 hinge = new Vector3(0f, LidY, -FrontZ);
Quaternion turn = Quaternion.Euler(-100f, 0f, 0f);
lidOpen.transform.localPosition = hinge + turn * (lidClosed.transform.localPosition - hinge);
lidOpen.transform.localRotation = turn * lidClosed.transform.localRotation;
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
// Only a retextured material is a copy; without the paint, writing to it would change every
// dvergr crate in the Mistlands too.
Texture2D paint = PieceLook.LoadTexture("AlfarFireChest_d.png");
if (paint != null) PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "Crate_d", paint } });
Material iron = paint != null ? body.GetComponent<MeshRenderer>()?.sharedMaterial : null;
if (iron != null)
{
// The crate's normal map is wood planks; on plates it would draw seams that are not there.
if (iron.HasProperty("_BumpMap")) iron.SetTexture("_BumpMap", null);
if (iron.HasProperty("_Metallic")) iron.SetFloat("_Metallic", 0.6f);
if (iron.HasProperty("_Glossiness")) iron.SetFloat("_Glossiness", 0.45f);
}
Transform grate = BuildGrate(visual, iron, out Renderer glow);
ParticleSystem embers = AddEmbers(grate);
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = new[] { glow };
look.Embers = embers;
look.GlowColor = Ember * 2f;
look.WoodOnly = true;
return true;
}
/// <summary>The grate: a glowing plate just off the front face, a frame and bars in front of it.</summary>
private static Transform BuildGrate(Transform visual, Material iron, out Renderer glow)
{
Transform grate = new GameObject("grate").transform;
grate.SetParent(visual, false);
grate.gameObject.layer = visual.gameObject.layer;
Material bars = iron != null ? new Material(iron) { name = "AlfarFireChest_bars" } : null;
if (bars != null)
{
bars.SetTexture("_MainTex", null);
bars.color = new Color(0.16f, 0.15f, 0.15f);
}
glow = Block(grate, "glow", new Vector3(0f, GrateY, FrontZ + 0.005f), new Vector3(GrateWidth, GrateHeight, 0.01f), bars).GetComponent<Renderer>();
const float frame = 0.035f;
foreach (float x in new[] { -GrateWidth / 2f, GrateWidth / 2f })
Block(grate, "frame", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(frame, GrateHeight + frame, 0.04f), bars);
foreach (float y in new[] { GrateY - GrateHeight / 2f, GrateY + GrateHeight / 2f })
Block(grate, "frame", new Vector3(0f, y, FrontZ + 0.02f), new Vector3(GrateWidth + frame, frame, 0.04f), bars);
for (int i = 1; i < GrateGaps; i++)
{
float x = -GrateWidth / 2f + GrateWidth * i / GrateGaps;
Block(grate, "bar", new Vector3(x, GrateY, FrontZ + 0.02f), new Vector3(0.022f, GrateHeight, 0.03f), bars);
}
Block(grate, "bar", new Vector3(0f, GrateY, FrontZ + 0.022f), new Vector3(GrateWidth, 0.022f, 0.03f), bars);
return grate;
}
/// <summary>A plain box with no collider, for trim the borrowed meshes do not have.</summary>
internal static GameObject Block(Transform parent, string name, Vector3 position, Vector3 size, Material material)
{
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
Object.DestroyImmediate(block.GetComponent<Collider>());
block.name = name;
block.layer = parent.gameObject.layer;
block.transform.SetParent(parent, false);
block.transform.localPosition = position;
block.transform.localScale = size;
if (material != null) block.GetComponent<Renderer>().sharedMaterial = material;
return block;
}
/// <summary>The carried torch's embers, rising off the top of the grate.</summary>
private static ParticleSystem AddEmbers(Transform grate)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No torch embers for the Eldividarkista; its grate glows without sparks.");
return null;
}
GameObject embers = Object.Instantiate(source.gameObject, grate, false);
embers.name = "embers";
embers.transform.localPosition = new Vector3(0f, GrateY + GrateHeight / 2f, FrontZ + 0.05f);
embers.transform.localRotation = Quaternion.identity;
return embers.GetComponent<ParticleSystem>();
}
}
}

View file

@ -0,0 +1,137 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Inngangskista's own body, the cold twin of <see cref="AlfarFireChest"/>: the dvergr loot
/// chest of the Mistlands towns (seen, never built), its panels repainted navy steel
/// (scripts/paint_input_chest.py) and its copper trim turned silver. A cyan line set into the
/// lid shines while the chest holds anything for the drones, and goes dark once they have
/// emptied it.
/// </summary>
public static class AlfarInputChest
{
private const string SourceName = "TreasureChest_dvergrtown";
// The town chest is placed at 1.2 and its meshes at 1.5 on top: 1.66 m wide, a vanilla chest's size.
private const float SourceScale = 1.2f;
private const float MeshScale = 1.5f * SourceScale;
private const float LidTop = 0.48f * MeshScale;
private const float LidHalfX = 0.42f * MeshScale;
private const float LidHalfZ = 0.24f * MeshScale;
private const float InlayInset = 0.10f;
private const float InlayWidth = 0.03f;
private static readonly Color Trim = new Color(0.9f, 0.95f, 1f);
private static readonly Color Inlay = new Color(0.35f, 0.9f, 1f);
/// <summary>Swaps the cloned wood chest's meshes for the input chest. False leaves the wood
/// chest's look in place, with a warning.</summary>
public static bool Build(GameObject prefab)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourceName);
Transform sourceNew = source != null ? source.transform.Find("New") : null;
Transform box = sourceNew != null ? sourceNew.Find("stonechest") : null;
Transform closed = sourceNew != null ? sourceNew.Find("stonechesttop_closed") : null;
Transform open = sourceNew != null ? sourceNew.Find("stonechesttop_open") : null;
Transform visual = prefab.transform.Find("New");
if (box == null || closed == null || open == null || visual == null)
{
Jotunn.Logger.LogWarning("[Alfar] No dvergr chest to build the Inngangskista from; it keeps the wood chest's look.");
return false;
}
for (int i = visual.childCount - 1; i >= 0; i--) Object.DestroyImmediate(visual.GetChild(i).gameObject);
LODGroup lod = visual.GetComponent<LODGroup>();
if (lod != null) Object.DestroyImmediate(lod);
GameObject body = Copy(box, visual, "body");
GameObject lidClosed = Copy(closed, visual, "lid_closed");
GameObject lidOpen = Copy(open, visual, "lid_open");
lidOpen.SetActive(false);
Container container = prefab.GetComponent<Container>();
if (container != null)
{
container.m_open = lidOpen;
container.m_closed = lidClosed;
}
Texture2D paint = PieceLook.LoadTexture("AlfarInputChest_d.png");
if (paint == null) return true; // the dvergr chest as it is: still not a vanilla chest
PieceLook.Retexture(visual, new Dictionary<string, Texture> { { "dvergrchestWorn_d", paint } });
// The trim shares the anvil's texture, so it is recoloured on a copy instead; the panels'
// material is already a copy from Retexture.
var copies = new Dictionary<Material, Material>();
Material panel = null;
foreach (Renderer renderer in visual.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
Material material = materials[i];
if (material == null) continue;
if (material.name.EndsWith("_rov")) { panel = panel ?? material; continue; }
if (!material.name.StartsWith("dvergr_metal_furnmiture")) continue;
if (!copies.TryGetValue(material, out Material trim))
{
trim = new Material(material) { name = material.name + "_rov" };
trim.color = Trim;
if (trim.HasProperty("_MetalColor")) trim.SetColor("_MetalColor", Trim);
copies[material] = trim;
}
materials[i] = trim;
}
renderer.sharedMaterials = materials;
}
AlfarChestGlow look = prefab.AddComponent<AlfarChestGlow>();
look.Glows = BuildInlay(lidClosed.transform, panel);
look.GlowColor = Inlay * 1.6f;
look.WoodOnly = false;
return true;
}
/// <summary>A copy of one of the town chest's parts, at the town chest's size and on the piece layer.</summary>
private static GameObject Copy(Transform part, Transform parent, string name)
{
GameObject copy = Object.Instantiate(part.gameObject, parent, false);
copy.name = name;
copy.transform.localPosition = part.localPosition * SourceScale;
copy.transform.localScale = part.localScale * SourceScale;
foreach (Transform t in copy.GetComponentsInChildren<Transform>(true)) t.gameObject.layer = parent.gameObject.layer;
return copy;
}
/// <summary>The cyan line on the lid: four thin strips just above it, inset from the edge. They
/// hang off the closed lid, so they go with it when the chest opens. The lid is scaled, so the
/// sizes are divided back out of it.</summary>
private static Renderer[] BuildInlay(Transform lid, Material panel)
{
Material cold = panel != null ? new Material(panel) { name = "AlfarInputChest_inlay" } : null;
if (cold != null)
{
cold.SetTexture("_MainTex", null);
cold.color = new Color(0.08f, 0.12f, 0.16f);
}
float k = 1f / lid.localScale.x;
float x = LidHalfX - InlayInset, z = LidHalfZ - InlayInset, y = LidTop + 0.004f;
var strips = new List<Renderer>();
foreach (float side in new[] { -z, z })
strips.Add(Strip(lid, new Vector3(0f, y, side) * k, new Vector3(2f * x + InlayWidth, 0.01f, InlayWidth) * k, cold));
foreach (float side in new[] { -x, x })
strips.Add(Strip(lid, new Vector3(side, y, 0f) * k, new Vector3(InlayWidth, 0.01f, 2f * z) * k, cold));
return strips.ToArray();
}
private static Renderer Strip(Transform lid, Vector3 position, Vector3 size, Material material)
{
return AlfarFireChest.Block(lid, "inlay", position, size, material).GetComponent<Renderer>();
}
}
}

View file

@ -46,7 +46,9 @@ namespace RacesOfValheim
Object.DestroyImmediate(behaviour); Object.DestroyImmediate(behaviour);
} }
AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); // The floating pyramid; the blue table stays as the fallback if it cannot be built.
bool pyramid = AlfarNexusLook.Build(prefab);
if (!pyramid) AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f));
AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>(); AlfarNexusBehaviour nexus = prefab.AddComponent<AlfarNexusBehaviour>();
nexus.m_switch = prefab.AddComponent<Switch>(); nexus.m_switch = prefab.AddComponent<Switch>();
@ -71,7 +73,7 @@ namespace RacesOfValheim
trader.m_randomUseItemAlreadyRecieved = new List<string>(); trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>(); trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); Sprite icon = (pyramid ? AlfarChests.IconFrom("AlfarNexus_icon.png") : null) ?? BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>(); Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null; piece.m_craftingStation = null;

View file

@ -0,0 +1,217 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Ljoskjarne's body: a stone pyramid, 2 m to a side and 2 m tall, floating 0.8 m above the
/// ground. Dark steel carved with Valheim's own runes (the Ashlands rune tile's glyphs, laid out by
/// scripts/paint_nexus.py), and a cyan seam down the middle of each face.
///
/// The seam is painted into the faces' glow map, not built. Bars standing on the faces, lit or
/// unlit, lost part of their length to the face on whichever side looked one way in the world,
/// as the pyramid turned; a line in the face's own pixels has nothing to hide behind.
///
/// Only the look moves. The piece keeps one still collider from the ground up, so building on it,
/// support, hovering and the E key behave as before; the pyramid bobs and turns on each client by
/// itself, nothing over the network. The seam breathes, and burns brighter while crystals wait.
/// </summary>
public static class AlfarNexusLook
{
private const float Height = 2f;
private const float HalfBase = 1f;
private const float Lift = 0.8f;
private const string SourceMaterialPrefab = "piece_cartographytable";
private const string EmbersSource = "fx_Torch_Carried";
private static readonly Color Seam = new Color(0.35f, 0.75f, 1f);
/// <summary>Strips the cartography table's body and puts the pyramid in its place. False leaves
/// the table, with a warning, so the Nexus is never invisible.</summary>
public static bool Build(GameObject prefab)
{
Texture2D face = PieceLook.LoadTexture("AlfarNexus_face.png");
Texture2D glow = PieceLook.LoadTexture("AlfarNexus_glow.png");
Texture2D bumps = PieceLook.LoadTexture("AlfarNexus_n.png", true);
Renderer tableRenderer = prefab.transform.Find("new/high")?.GetComponent<Renderer>();
if (face == null || glow == null || tableRenderer == null || tableRenderer.sharedMaterial == null)
{
Jotunn.Logger.LogWarning("[Alfar] Could not build the Ljoskjarne's pyramid; it keeps the cartography table's look.");
return false;
}
Material stone = new Material(tableRenderer.sharedMaterial) { name = "AlfarNexus_stone" };
stone.color = Color.white;
stone.SetTexture("_MainTex", face);
// Forged, not polished: the plate's own grain in the normal map, and a dull sheen.
stone.SetTexture("_BumpMap", bumps);
if (bumps != null) stone.EnableKeyword("_NORMALMAP");
else stone.DisableKeyword("_NORMALMAP");
if (stone.HasProperty("_MetallicGlossMap")) stone.SetTexture("_MetallicGlossMap", null);
if (stone.HasProperty("_Metallic")) stone.SetFloat("_Metallic", 0.6f);
if (stone.HasProperty("_Glossiness")) stone.SetFloat("_Glossiness", 0.3f);
// Custom/Piece samples its noise in world space unless told the object moves, as boats and
// carts do; on a turning pyramid the blotches would slide across the faces.
stone.EnableKeyword("_MOVEABLEOBJECT_ON");
if (stone.HasProperty("_MoveableObject")) stone.SetFloat("_MoveableObject", 1f);
stone.SetTexture("_EmissionMap", glow);
stone.EnableKeyword("_EMISSION");
stone.SetColor("_EmissionColor", Seam);
// The table goes whole: its meshes, its damage states, its fragments and its four colliders.
for (int i = prefab.transform.childCount - 1; i >= 0; i--)
Object.DestroyImmediate(prefab.transform.GetChild(i).gameObject);
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_new = null;
wear.m_worn = null;
wear.m_broken = null;
wear.m_fragmentRoots = new GameObject[0];
}
// One still collider, from the ground to the tip, a little inside the faces.
GameObject solid = new GameObject("collider") { layer = prefab.layer };
solid.transform.SetParent(prefab.transform, false);
BoxCollider box = solid.AddComponent<BoxCollider>();
box.center = new Vector3(0f, (Lift + Height) / 2f, 0f);
box.size = new Vector3(HalfBase * 1.4f, Lift + Height, HalfBase * 1.4f);
Transform floating = new GameObject("float").transform;
floating.SetParent(prefab.transform, false);
floating.gameObject.layer = prefab.layer;
MeshRenderer pyramid = Part(floating, "pyramid", PyramidMesh(), stone).GetComponent<MeshRenderer>();
NexusLook look = prefab.AddComponent<NexusLook>();
look.Float = floating;
look.SeamRenderer = pyramid;
look.Motes = AddMotes(prefab.transform);
return true;
}
private static GameObject Part(Transform parent, string name, Mesh mesh, Material material)
{
GameObject part = new GameObject(name) { layer = parent.gameObject.layer };
part.transform.SetParent(parent, false);
part.AddComponent<MeshFilter>().sharedMesh = mesh;
part.AddComponent<MeshRenderer>().sharedMaterial = material;
return part;
}
private static Vector3 Apex => new Vector3(0f, Lift + Height, 0f);
private static Vector3[] BaseCorners => new[]
{
new Vector3(-HalfBase, Lift, -HalfBase), new Vector3(HalfBase, Lift, -HalfBase),
new Vector3(HalfBase, Lift, HalfBase), new Vector3(-HalfBase, Lift, HalfBase),
};
/// <summary>Four faces, each with its own three corners so the shading stays flat and every face
/// shows the whole carving (u along the base, v = 1 at the tip), and the underside.</summary>
private static Mesh PyramidMesh()
{
Vector3[] c = BaseCorners;
var vertices = new Vector3[16];
var uvs = new Vector2[16];
var triangles = new int[18];
for (int i = 0; i < 4; i++)
{
// Wound clockwise seen from outside, which is Unity's front face.
vertices[i * 3] = c[(i + 1) % 4];
vertices[i * 3 + 1] = c[i];
vertices[i * 3 + 2] = Apex;
uvs[i * 3] = new Vector2(1f, 0f);
uvs[i * 3 + 1] = new Vector2(0f, 0f);
uvs[i * 3 + 2] = new Vector2(0.5f, 1f);
triangles[i * 3] = i * 3;
triangles[i * 3 + 1] = i * 3 + 1;
triangles[i * 3 + 2] = i * 3 + 2;
}
for (int i = 0; i < 4; i++) { vertices[12 + i] = c[i]; uvs[12 + i] = new Vector2(0.1f, 0.02f); }
int[] under = { 12, 13, 14, 12, 14, 15 };
System.Array.Copy(under, 0, triangles, 12, 6);
Mesh mesh = new Mesh { name = "AlfarNexus_pyramid", vertices = vertices, uv = uvs, triangles = triangles };
mesh.RecalculateNormals();
mesh.RecalculateBounds();
return mesh;
}
/// <summary>A few cyan motes drifting up from the ground under it: the torch's embers, recoloured,
/// spread over the pyramid's shadow and slowed down.</summary>
private static ParticleSystem AddMotes(Transform root)
{
GameObject torch = PrefabManager.Cache.GetPrefab<GameObject>(EmbersSource);
Transform source = torch != null ? torch.transform.Find("Embers") : null;
if (source == null) return null;
GameObject motes = Object.Instantiate(source.gameObject, root, false);
motes.name = "motes";
motes.transform.localPosition = new Vector3(0f, 0.05f, 0f);
motes.transform.localRotation = Quaternion.identity;
PieceLook.Rehue(motes.transform, Seam * 2f);
ParticleSystem particles = motes.GetComponent<ParticleSystem>();
if (particles != null)
{
ParticleSystem.ShapeModule shape = particles.shape;
shape.enabled = true;
shape.shapeType = ParticleSystemShapeType.Circle;
shape.radius = HalfBase;
shape.rotation = new Vector3(-90f, 0f, 0f);
ParticleSystem.MainModule main = particles.main;
main.simulationSpeed = 0.5f;
}
return particles;
}
/// <summary>The motion and the seam's light, per client.</summary>
public class NexusLook : MonoBehaviour
{
public Transform Float;
public Renderer SeamRenderer;
public ParticleSystem Motes;
private const float BobHeight = 0.08f;
private const float BobSeconds = 4.5f;
private const float TurnSeconds = 40f;
private const float BreathSeconds = 3.5f;
private AlfarNexusBehaviour m_nexus;
private Material m_seam;
private float m_phase;
private float m_ready; // eases between 0 (no crystals) and 1, so the brightening is not a jump
private void Awake()
{
m_nexus = GetComponent<AlfarNexusBehaviour>();
if (SeamRenderer != null) m_seam = SeamRenderer.material; // this one's own copy, to animate
// Two Nexuses side by side must not bob in step.
m_phase = (Mathf.Abs(transform.position.x * 0.37f + transform.position.z * 0.71f)) % 10f;
}
private void Update()
{
float t = Time.time + m_phase;
if (Float != null)
{
Float.localPosition = new Vector3(0f, Mathf.Sin(t * 2f * Mathf.PI / BobSeconds) * BobHeight, 0f);
Float.localRotation = Quaternion.Euler(0f, t * 360f / TurnSeconds, 0f);
}
if (m_seam == null) return;
bool ready = m_nexus != null && m_nexus.Crystals > 0;
m_ready = Mathf.MoveTowards(m_ready, ready ? 1f : 0f, Time.deltaTime * 0.5f);
float breath = 0.75f + 0.25f * Mathf.Sin(t * 2f * Mathf.PI / BreathSeconds);
Color glow = Seam * breath * Mathf.Lerp(1f, 2.2f, m_ready);
m_seam.SetColor("_EmissionColor", glow);
}
private void OnDestroy()
{
if (m_seam != null) Destroy(m_seam);
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic",
"rov_hover_ward_world": "World", "rov_hover_ward_world": "World",
"rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", "rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7",
"rov_hover_boneship_bone_hand": "\nbone in hand to buy a place" "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place",
"rov_hover_alfar_inngangskista": "Inngangskista (input)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (fuel)"
} }

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss",
"rov_hover_ward_world": "del mondo", "rov_hover_ward_world": "del mondo",
"rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7", "rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7",
"rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto" "rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto",
"rov_hover_alfar_inngangskista": "Inngangskista (ingresso)",
"rov_hover_alfar_eldividarkista": "Eldividarkista (combustibile)"
} }

View file

@ -52,5 +52,7 @@
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Открыть\n[<color=yellow><b>Использовать предмет</b></color>] Пожертвовать реликвию босса",
"rov_hover_ward_world": "Общий", "rov_hover_ward_world": "Общий",
"rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7", "rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7",
"rov_hover_boneship_bone_hand": "\nкость в руке — купить место" "rov_hover_boneship_bone_hand": "\nкость в руке — купить место",
"rov_hover_alfar_inngangskista": "Инганг-киста (вход)",
"rov_hover_alfar_eldividarkista": "Эльдивидар-киста (топливо)"
} }

View file

@ -0,0 +1,89 @@
"""Paint the Eldividarkista (Alfar fire chest) and render its preview and hammer icon.
Usage: py -3.14 -I paint_fire_chest.py <pylib> <scripts dir> <work dir>
<work dir> must hold tex/Crate_d.png and crate_0.obj / crate_2.obj (body, lid) exported from
dvergrprops_crate in bundle c4210710 (see extract_carto.py for the export). Writes
AlfarFireChest_d.png and AlfarFireChest_icon.png there; copy both to
JotunnModStub/Assets/AlfarFireChest/."""
import sys, os, math
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter
from render_obj import render
d = sys.argv[3]
src = Image.open(os.path.join(d,"tex","Crate_d.png")).convert("RGB")
S = 256
up = np.asarray(src.resize((S,S), Image.BICUBIC), dtype=np.float32)/255
lum = up @ np.array([0.3,0.59,0.11])
# normalise the wood's shading into 0..1 so the brace and frame keep their relief
lo, hi = np.percentile(lum, 3), np.percentile(lum, 97)
t = np.clip((lum-lo)/(hi-lo), 0, 1)
rng = np.random.default_rng(7)
grain = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.8)), dtype=np.float32)/255
# the panels: plain brushed plates, the wood's planks and X-brace flattened away
brushed = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).resize((S//32,S), Image.BICUBIC).resize((S,S), Image.BICUBIC), dtype=np.float32)/255
iron = np.array([0.17,0.18,0.20])[None,None,:] * (0.85 + 0.3*brushed)[...,None] * (0.92 + 0.16*t)[...,None]
# the raised frame and brace become copper: every triangle lying on the outer shell of the body
# or lid (|x|, |z| or y at the extreme) paints its UV area into the copper mask
from PIL import ImageDraw
from render_obj import load_obj
mask = Image.new("L", (S,S), 0); md = ImageDraw.Draw(mask)
for name in ("crate_0.obj","crate_2.obj"):
v, vt, faces = load_obj(os.path.join(d,name))
mn, mx = v.min(0), v.max(0)
for f in faces:
pv = np.array([v[i] for i,_ in f]); c = pv.mean(0)
n = np.cross(pv[1]-pv[0], pv[2]-pv[0]); nl = np.linalg.norm(n)
if nl == 0: continue
n = n/nl; ax = int(np.argmax(np.abs(n)))
outer = (abs(c[ax]-mx[ax]) < 0.012) or (abs(c[ax]-mn[ax]) < 0.012)
if ax != 1 and not outer: continue
if ax == 1 and name == "crate_0.obj": continue # body top/bottom: skip
if ax == 1 and not outer: continue
uv = [(vt[j][0]*S, (1-vt[j][1])*S) for _,j in f]
md.polygon(uv, fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(0.6))
mask.save(os.path.join(d,"copper_mask.png"))
cu = (np.asarray(mask, dtype=np.float32)/255)[...,None]
copper = np.array([0.30,0.17,0.10]) * (0.8 + 0.4*t[...,None])
iron = iron*(1-cu) + copper*cu
iron *= (0.9 + 0.2*grain)[...,None]
# soot: a warm brown tint creeping into the darkest texels
soot = np.clip(0.35 - t, 0, 0.35)/0.35
iron = iron*(1-0.25*soot[...,None]) + np.array([0.12,0.06,0.03])*0.25*soot[...,None]
out = np.clip(iron,0,1)
Image.fromarray((out*255).astype(np.uint8)).save(os.path.join(d,"AlfarFireChest_d.png"))
# a unit cube OBJ for the grate bars and the glow plate
cube = """v -0.5 -0.5 -0.5\nv 0.5 -0.5 -0.5\nv 0.5 0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 -0.5 0.5\nv 0.5 -0.5 0.5\nv 0.5 0.5 0.5\nv -0.5 0.5 0.5\nvt 0 0\nf 1/1 2/1 3/1 4/1\nf 5/1 8/1 7/1 6/1\nf 1/1 5/1 6/1 2/1\nf 2/1 6/1 7/1 3/1\nf 3/1 7/1 8/1 4/1\nf 4/1 8/1 5/1 1/1\n"""
open(os.path.join(d,"cube.obj"),"w").write(cube)
tex = Image.open(os.path.join(d,"AlfarFireChest_d.png"))
# the crate stretched into a chest: 1.6x as wide, 0.8x as deep (AlfarFireChest.Stretch)
SX, SZ = 1.6, 0.8
parts=[{'obj':os.path.join(d,'crate_0.obj'),'tex':tex,'scale':(1.5*SX,1.5,1.5*SZ)},
{'obj':os.path.join(d,'crate_2.obj'),'tex':tex,'scale':(1.5*SX,1.5,1.5*SZ),'offset':(0,0.81,0)}]
# grate on the +z face: glow plate, frame, bars (sizes in metres, mirrored like the OBJ x)
FZ = 0.515*SZ; GW, GH, GY = 0.62*SX, 0.36, 0.42
glow = (1.0, 0.45, 0.12)
bar = (0.16,0.15,0.15)
parts.append({'obj':os.path.join(d,'cube.obj'),'color':glow,'emissive':True,'scale':(GW,GH,0.01),'offset':(0,GY,FZ+0.005)})
T = 0.035
for x in (-GW/2, GW/2):
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(T,GH+T,0.04),'offset':(x,GY,FZ+0.02)})
for y in (GY-GH/2, GY+GH/2):
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(GW+T,T,0.04),'offset':(0,y,FZ+0.02)})
n = 10
for i in range(1,n):
x = -GW/2 + GW*i/n
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(0.022,GH,0.03),'offset':(x,GY,FZ+0.02)})
parts.append({'obj':os.path.join(d,'cube.obj'),'color':bar,'scale':(GW,0.022,0.03),'offset':(0,GY,FZ+0.022)})
render(parts, os.path.join(d,'prev_fire.png'), yaw=-30, pitch=-20, light=(0.4,0.8,0.6))
render(parts, os.path.join(d,'prev_fire_side.png'), yaw=-80, pitch=-15, light=(0.4,0.8,0.6))
from PIL import Image as I
tiles=[]
for k,yw in enumerate((-30,60,150,240)):
p=os.path.join(d,f'_q{k}.png'); render(parts,p,size=256,yaw=yw,pitch=-20,light=(0.4,0.8,0.6)); tiles.append(I.open(p))
sheet=I.new('RGBA',(1024,256))
for k,tl in enumerate(tiles): sheet.paste(tl,(k*256,0))
sheet.save(os.path.join(d,'prev_sheet.png'))
render(parts, os.path.join(d,'AlfarFireChest_icon.png'), size=128, yaw=160, pitch=-22, bg=(0,0,0,0), light=(0.3,0.8,0.7))

View file

@ -0,0 +1,45 @@
"""Paint the Inngangskista (Alfar input chest) and render its preview and hammer icon.
Usage: py -3.14 -I paint_input_chest.py <pylib> <scripts dir> <work dir>
<work dir> must hold tex/dvergrchestWorn_d.png, tex/anvil.png and
TreasureChest_dvergrtown__stonechest.obj / __stonechesttop_closed.obj, exported from bundle c4210710.
Writes AlfarInputChest_d.png and AlfarInputChest_icon.png; copy both to
JotunnModStub/Assets/AlfarInputChest/. The trim is recoloured in code (AlfarInputChest.Trim)."""
import sys, os
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter
from render_obj import render
d = sys.argv[3]
S = 128
src = Image.open(os.path.join(d,"tex","dvergrchestWorn_d.png")).convert("RGB")
up = np.asarray(src.resize((S,S), Image.BICUBIC), dtype=np.float32)/255
lum = up @ np.array([0.3,0.59,0.11])
lo, hi = np.percentile(lum, 3), np.percentile(lum, 97)
t = np.clip((lum-lo)/(hi-lo), 0, 1)
rng = np.random.default_rng(11)
brushed = np.asarray(Image.fromarray((rng.random((S,S))*255).astype(np.uint8)).resize((S,S//16), Image.BICUBIC).resize((S,S), Image.BICUBIC), dtype=np.float32)/255
# steel-blue plates: the planks' seams survive as faint plate joints
steel = np.array([0.12,0.17,0.24])[None,None,:] * (0.85 + 0.25*brushed)[...,None] * (0.8 + 0.35*t)[...,None]
Image.fromarray((np.clip(steel,0,1)*255).astype(np.uint8)).save(os.path.join(d,"AlfarInputChest_d.png"))
TRIM = (1.25,1.3,1.35) # AlfarInputChest.Trim
K = 1.5*1.2 # the mesh scale times the chest's 1.2
LIDTOP, HX, HZ = 0.48*K, 0.42*K, 0.24*K
INSET, W = 0.10, 0.03 # AlfarInputChest inlay
cyan = (0.35,0.9,1.0)
panel = Image.open(os.path.join(d,"AlfarInputChest_d.png")); metal = Image.open(os.path.join(d,"tex","anvil.png"))
parts = [{'obj':os.path.join(d,'TreasureChest_dvergrtown__'+n+'.obj'),'texs':[metal,panel],'colors':[TRIM,(1,1,1)],'scale':(K,K,K)}
for n in ('stonechest','stonechesttop_closed')]
cube = os.path.join(d,'cube.obj')
ix, iz = HX-INSET, HZ-INSET
for z in (-iz, iz): parts.append({'obj':cube,'color':cyan,'emissive':True,'scale':(2*ix+W,0.01,W),'offset':(0,LIDTOP+0.004,z)})
for x in (-ix, ix): parts.append({'obj':cube,'color':cyan,'emissive':True,'scale':(W,0.01,2*iz),'offset':(x,LIDTOP+0.004,0)})
tiles = []
for k,yw in enumerate((-30,60,150,240)):
p = os.path.join(d,f'_i{k}.png'); render(parts,p,size=256,yaw=yw,pitch=-30,light=(0.4,0.8,0.6)); tiles.append(Image.open(p))
sheet = Image.new('RGBA',(1024,256))
for k,tl in enumerate(tiles): sheet.paste(tl,(k*256,0))
sheet.save(os.path.join(d,'prev_input.png'))
render(parts, os.path.join(d,'AlfarInputChest_icon.png'), size=128, yaw=160, pitch=-28, bg=(0,0,0,0), light=(0.3,0.8,0.7))

154
scripts/paint_nexus.py Normal file
View file

@ -0,0 +1,154 @@
"""Paint the Ljoskjarne's pyramid face (Alfar Nexus) and render a preview.
Usage: py -3.14 -I paint_nexus.py <pylib> <scripts dir> <work dir>
<work dir> must hold runes/RuneTile_e.png (Valheim's glyphs, the Ashlands rune tile's glow mask),
metal/Ironbeam_d.png, both from bundle c4210710. Writes
AlfarNexus_face.png (one face, u 0..1 along the base, v 1 at the apex), AlfarNexus_glow.png (its glow
map: the cyan seam down the middle), AlfarNexus_n.png (its normal map), AlfarNexus_icon.png and
prev_nexus.png; copy the face, glow, normal map and icon to
JotunnModStub/Assets/AlfarNexus/."""
import sys, os, math
sys.path.insert(0, sys.argv[1]); sys.path.insert(0, sys.argv[2])
import numpy as np
from PIL import Image, ImageFilter, ImageChops
from render_obj import render
d = sys.argv[3]
S = 512
# --- the glyphs: every blob of the rune tile's glow mask, cut out with its bounding box
mask = np.asarray(Image.open(os.path.join(d,"runes","RuneTile_e.png")).convert("L"), dtype=np.float32)/255
grown = np.asarray(Image.fromarray((mask>0.15).astype(np.uint8)*255).filter(ImageFilter.MaxFilter(15)))>0
seen = np.zeros_like(grown); blobs = []
H, W = grown.shape
for y in range(H):
for x in range(W):
if grown[y,x] and not seen[y,x]:
stack=[(y,x)]; seen[y,x]=True; ys=[];xs=[]
while stack:
cy,cx=stack.pop(); ys.append(cy); xs.append(cx)
for ny,nx in ((cy+1,cx),(cy-1,cx),(cy,cx+1),(cy,cx-1)):
if 0<=ny<H and 0<=nx<W and grown[ny,nx] and not seen[ny,nx]: seen[ny,nx]=True; stack.append((ny,nx))
y0,y1,x0,x1=min(ys)+7,max(ys)-7,min(xs)+7,max(xs)-7
if (y1-y0)*(x1-x0) > 150: blobs.append((x0,y0,x1+1,y1+1))
tall = [b for b in blobs if (b[3]-b[1]) > 2.5*(b[2]-b[0])]
wide = [b for b in blobs if b not in tall and (b[2]-b[0]) < 200]
glyph = lambda b: Image.fromarray((mask[b[1]:b[3], b[0]:b[2]]*255).astype(np.uint8))
print("glyphs: tall", len(tall), "short", len(wide))
# --- the plate: three riveted steel panels per face, split by two straight seams and framed by a
# seam along the sloping edges, each brushed in its own streaks toward the apex. Straight lines and
# streaks read as metal; the iron beam's blotches stay only as a faint hint of wear.
def norm(a): return (a - a.mean())/(a.std() + 1e-6)
Y, X = np.mgrid[0:S, 0:S].astype(np.float32) # Y from the apex down
edge = Y/2 - np.abs(X - (S-1)/2) # pixels inside the sloping edges
SEAMS_Y = (int(S*0.31), int(S*0.635)) # above the tall runes, between them and the rows
FRAME = 12 # the edge seam, this far inside the edge
band = (Y >= SEAMS_Y[0]).astype(int) + (Y >= SEAMS_Y[1]).astype(int)
def brushed(seed):
n = np.random.default_rng(seed).normal(size=(S + 120, S)).astype(np.float32)
c = np.cumsum(n, axis=0); n = (c[120:] - c[:-120])/120 # long streaks down the face
return norm(n + 0.5*np.roll(n, 1, axis=1))
streaks = np.choose(band, [brushed(1), brushed(2), brushed(3)])
iron = Image.open(os.path.join(d,"metal","Ironbeam_d.png")).convert("L").crop((176,90,256,250))
mottle = norm(np.asarray(iron.resize((S,S), Image.BICUBIC).filter(ImageFilter.GaussianBlur(10)), dtype=np.float32))
seam_lines = np.zeros((S,S), np.float32) # 1 in the groove, soft at its sides
for y in SEAMS_Y: seam_lines = np.maximum(seam_lines, np.clip(2 - np.abs(Y - y), 0, 1))
seam_lines = np.maximum(seam_lines, np.clip(2 - np.abs(edge - FRAME), 0, 1)*(Y > FRAME*2))
rivets = np.zeros((S,S), np.float32) # domes, 2 cm across
def rivet(cx, cy, r=5):
if edge[int(cy), int(cx)] < FRAME + 2 or abs(cx - (S-1)/2) < 30: return
rivets[:] = np.maximum(rivets, np.sqrt(np.clip(1 - ((X-cx)**2 + (Y-cy)**2)/r**2, 0, 1)))
for y, below in zip(SEAMS_Y, (True, False)): # the rune rows start just under the second seam
for cy in ((y - 8, y + 8) if below else (y - 8,)):
for cx in np.arange(S/2 % 30, S, 30): rivet(cx, cy)
for cy in np.arange(FRAME*2 + 20, S - 12, 30): # down both sloping edges
for side in (-1, 1): rivet((S-1)/2 + side*(cy/2 - FRAME - 9), cy)
tone = 0.30 + np.choose(band, [0.015, -0.01, 0.005]) + 0.022*streaks + 0.012*mottle
tone = tone*(1 - 0.5*seam_lines) + 0.08*rivets
stone = tone[...,None]*np.array([0.95,1.0,1.08])
# --- lay the glyphs out inside the face's triangle (in image space the apex is at the top middle)
ink = Image.new("L", (S,S), 0)
inside = lambda x, y: abs(x - S/2) < (y/S)*S/2 - 14 # y measured from the apex
GAP = 26 # half-width kept clear for the seam
# the tall columns flank the seam
for i, b in enumerate(tall[:3]):
g = glyph(b); h = int(S*0.28); w = max(1, int(g.width*h/g.height))
g = g.resize((w,h), Image.LANCZOS)
for side in (-1, 1):
x = int(S/2 + side*(GAP + 8 + i*(w+10)) - (w if side < 0 else 0)); y = int(S*0.34)
if inside(x, y) and inside(x+w, y): ink.paste(g, (x,y), g)
# short clusters in rows toward the base
k = 0
for row, y in enumerate(range(int(S*0.66), S-40, 48)):
half = (y/S)*S/2 - 36 # clear of the edge rivets
x = S/2 - half
while x < S/2 + half:
g = glyph(wide[k % len(wide)]); k += 1
h = 34; w = max(1, int(g.width*h/g.height)); w = min(w, 80)
g = g.resize((w,h), Image.LANCZOS)
if abs(x + w/2 - S/2) < GAP + w/2: x = S/2 + GAP; continue
if inside(x, y) and inside(x+w, y+h): ink.paste(g, (int(x), int(y)), g)
x += w + 14
ink = ink.filter(ImageFilter.MaxFilter(3)) # thicker strokes: they are read from metres away
inkf = np.clip(np.asarray(ink, dtype=np.float32)/255*1.4, 0, 1)
# carved: a dark rim just below each line, the line itself light grey
shadow = np.asarray(ink.filter(ImageFilter.GaussianBlur(2)).transform((S,S), Image.AFFINE, (1,0,-1,0,1,-2)), dtype=np.float32)/255
face = stone*(1 - 0.45*shadow[...,None])
face = face*(1 - inkf[...,None]) + np.array([0.72,0.73,0.76])*inkf[...,None]
out = Image.fromarray((np.clip(face,0,1)*255).astype(np.uint8)) # top row is v = 1, the apex, as Unity reads a PNG
out.save(os.path.join(d,"AlfarNexus_face.png"))
# --- the glow map: one line down the middle. u runs 0.5 per metre at every height, so a band of
# constant width in u is 9 cm wide on the pyramid from base to tip.
SEAM_HALF = 11 # pixels; GAP keeps the runes clear of it
xs = np.abs(np.arange(S) - (S-1)/2)
line = np.clip((SEAM_HALF + 1 - xs)/2, 0, 1) # two pixels of soft edge
glow = np.tile(line, (S,1))
Image.fromarray((glow*255).astype(np.uint8)).convert("RGB").save(os.path.join(d,"AlfarNexus_glow.png"))
# --- the normal map, from a height field: faint streaks and wear, the panel seams, runes and the
# glowing seam's channel cut in, the rivets raised. DXT5nm, as Valheim packs it: X in alpha, Y in
# green and blue, red 255.
height = 0.12*streaks + 0.25*mottle - 1.6*seam_lines + 2.5*rivets \
- 2.2*np.asarray(ink.filter(ImageFilter.GaussianBlur(1)), dtype=np.float32)/255 \
- 1.5*np.clip((SEAM_HALF + 4 - xs)/3, 0, 1)[None,:]
gx = np.zeros_like(height); gy = np.zeros_like(height)
gx[:,1:-1] = height[:,2:] - height[:,:-2]; gy[1:-1,:] = height[2:,:] - height[:-2,:]
K = 0.35
nm = np.stack([-gx*K, gy*K, np.ones_like(height)], -1) # image y runs down, texture v up
nm /= np.linalg.norm(nm, axis=-1, keepdims=True)
packed = np.zeros((S,S,4), np.float32)
packed[...,0] = 1; packed[...,1] = packed[...,2] = nm[...,1]*0.5 + 0.5; packed[...,3] = nm[...,0]*0.5 + 0.5
Image.fromarray((packed*255).astype(np.uint8), "RGBA").save(os.path.join(d,"AlfarNexus_n.png"))
# a lit check of the normal map, light from the upper left
shade = np.clip(nm @ np.array([-0.5,0.5,0.7])/np.linalg.norm([-0.5,0.5,0.7]), 0, 1)
Image.fromarray((np.clip(face*shade[...,None]*1.6,0,1)*255).astype(np.uint8)).save(os.path.join(d,"prev_nexus_bump.png"))
# --- preview: the pyramid as AlfarNexus builds it
HGT, B, LIFT = 2.0, 1.0, 0.8 # AlfarNexusLook: 2 m tall, 2 m base, floating 0.8 m up
apex = np.array([0, LIFT+HGT, 0]); c = [np.array(p) for p in [(-B,LIFT,-B),(B,LIFT,-B),(B,LIFT,B),(-B,LIFT,B)]]
lit = np.asarray(out, dtype=np.float32)/255
lit = lit*(1-glow[...,None]) + np.array([0.35,0.75,1.0])*glow[...,None]
shown = Image.fromarray((lit*255).astype(np.uint8))
L = []; vi = 1
for i in range(4):
a, b = c[i], c[(i+1)%4]
for p in (a, b, apex): L.append("v %f %f %f" % (-p[0], p[1], p[2]))
L += ["vt 0 0", "vt 1 0", "vt 0.5 1", f"f {vi}/{vi} {vi+1}/{vi+1} {vi+2}/{vi+2}"]; vi += 3
for p in c: L.append("v %f %f %f" % (-p[0], p[1], p[2]))
L += ["vt 0 0", f"f {vi}/{3*4+1} {vi+3}/{3*4+1} {vi+2}/{3*4+1} {vi+1}/{3*4+1}"]
open(os.path.join(d,"pyramid.obj"),"w").write("\n".join(L)+"\n")
open(os.path.join(d,"ground.obj"),"w").write("v -2 0 -2\nv 2 0 -2\nv 2 0 2\nv -2 0 2\nvt 0 0\nf 1/1 2/1 3/1 4/1\n")
sh = B*0.85
open(os.path.join(d,"shadow.obj"),"w").write(
f"v {-sh} 0.005 {-sh}\nv {sh} 0.005 {-sh}\nv {sh} 0.005 {sh}\nv {-sh} 0.005 {sh}\nvt 0 0\nf 1/1 2/1 3/1 4/1\n")
parts = [{'obj':os.path.join(d,'pyramid.obj'),'tex':shown},
{'obj':os.path.join(d,'ground.obj'),'color':(0.33,0.36,0.3)},
{'obj':os.path.join(d,'shadow.obj'),'color':(0.18,0.2,0.17)}]
render(parts, os.path.join(d,'prev_nexus.png'), size=640, yaw=25, pitch=-12, light=(0.4,0.8,0.6), fit=(np.array([0,1.4,0]), 2.5))
# the hammer icon: the pyramid alone, nearly side-on so two faces show
render(parts[:1], os.path.join(d,'AlfarNexus_icon.png'), size=128, yaw=35, pitch=-12, bg=(0,0,0,0), light=(0.3,0.8,0.7))

88
scripts/render_obj.py Normal file
View file

@ -0,0 +1,88 @@
"""Tiny software renderer: render(parts, out, size, yaw, pitch, bg)
parts: list of dicts {obj: path, tex: PIL image or None, color:(r,g,b), offset:(x,y,z), scale:(sx,sy,sz), emissive:bool}
OBJ x is mirrored vs Unity: we flip x back."""
import numpy as np
from PIL import Image
import math
def load_obj(path, groups=False):
v=[];vt=[];vn=[];faces=[];gid=[];g=0;gn=0;ids={}
for l in open(path):
p=l.split()
if not p: continue
if p[0]=='g': gn+=1; g=gn
elif p[0]=='v': v.append([float(x) for x in p[1:4]])
elif p[0]=='vt': vt.append([float(x) for x in p[1:3]])
elif p[0]=='f':
idx=[]
for k in p[1:]:
a=k.split('/'); idx.append((int(a[0])-1, int(a[1])-1 if len(a)>1 and a[1] else -1))
# a group counts as a submesh only once it has faces (the export starts with an empty one)
if g not in ids: ids[g]=len(ids)
for i in range(1,len(idx)-1): faces.append((idx[0],idx[i],idx[i+1])); gid.append(ids[g])
v=np.array(v); v[:,0]*=-1
if groups: return v, np.array(vt) if vt else None, faces, gid
return v, np.array(vt) if vt else None, faces
def render(parts, out, size=512, yaw=35, pitch=25, bg=(40,44,52,255), fit=None, light=(0.4,0.8,-0.5)):
tris=[]
for P in parts:
v,vt,faces,gid=load_obj(P['obj'],groups=True)
if 'rotx' in P:
a=math.radians(P['rotx']); c,s=math.cos(a),math.sin(a)
v=v@np.array([[1,0,0],[0,c,-s],[0,s,c]]).T
v=v*np.array(P.get('scale',(1,1,1)))+np.array(P.get('offset',(0,0,0)))
# 'texs'/'colors'/'emissives' per OBJ group (submesh) override 'tex'/'color'/'emissive'
def arr(t): return np.asarray(t.convert('RGBA'),dtype=np.float32)/255 if t is not None else None
texs=[arr(t) for t in P['texs']] if 'texs' in P else None
ta0=arr(P.get('tex'))
for f,gi in zip(faces,gid):
pv=np.array([v[i] for i,_ in f]); puv=np.array([vt[j] if (vt is not None and j>=0) else (0,0) for _,j in f])
ta=texs[min(gi,len(texs)-1)] if texs is not None else ta0
col=P['colors'][min(gi,len(P['colors'])-1)] if 'colors' in P else P.get('color',(1,1,1))
em=P['emissives'][min(gi,len(P['emissives'])-1)] if 'emissives' in P else P.get('emissive',False)
tris.append((pv,puv,ta,col,em))
ay=math.radians(yaw); ap=math.radians(pitch)
Ry=np.array([[math.cos(ay),0,math.sin(ay)],[0,1,0],[-math.sin(ay),0,math.cos(ay)]])
Rx=np.array([[1,0,0],[0,math.cos(ap),-math.sin(ap)],[0,math.sin(ap),math.cos(ap)]])
R=Rx@Ry
allv=np.concatenate([t[0] for t in tris])@R.T
if fit is None:
mn=allv.min(0); mx=allv.max(0); c=(mn+mx)/2; ext=max(mx[0]-mn[0],mx[1]-mn[1])*0.55
else: c,ext=fit
img=np.zeros((size,size,4),np.float32); img[:]=np.array(bg)/255
zb=np.full((size,size),-1e9)
L=np.array(light);L=L/np.linalg.norm(L)
for pv,puv,ta,col,em in tris:
q=pv@R.T
n=np.cross(pv[1]-pv[0],pv[2]-pv[0]); nl=np.linalg.norm(n)
if nl==0: continue
n=n/nl
nv=n@R.T
shade=1.0 if em else 0.35+0.65*abs(float(n@L))
sx=(q[:,0]-c[0])/ext*size/2+size/2; sy=size/2-(q[:,1]-c[1])/ext*size/2
x0=max(int(sx.min()),0);x1=min(int(sx.max())+1,size);y0=max(int(sy.min()),0);y1=min(int(sy.max())+1,size)
if x0>=x1 or y0>=y1: continue
xs,ys=np.meshgrid(np.arange(x0,x1)+0.5,np.arange(y0,y1)+0.5)
d=(sy[1]-sy[2])*(sx[0]-sx[2])+(sx[2]-sx[1])*(sy[0]-sy[2])
if abs(d)<1e-9: continue
w0=((sy[1]-sy[2])*(xs-sx[2])+(sx[2]-sx[1])*(ys-sy[2]))/d
w1=((sy[2]-sy[0])*(xs-sx[2])+(sx[0]-sx[2])*(ys-sy[2]))/d
w2=1-w0-w1
m=(w0>=0)&(w1>=0)&(w2>=0)
if not m.any(): continue
z=w0*q[0,2]+w1*q[1,2]+w2*q[2,2]
z=-z
sub=zb[y0:y1,x0:x1]; m&=z>sub
if not m.any(): continue
if ta is not None:
u=(w0*puv[0,0]+w1*puv[1,0]+w2*puv[2,0])%1; vv=(w0*puv[0,1]+w1*puv[1,1]+w2*puv[2,1])%1
th,tw=ta.shape[:2]
px=np.clip((u*tw).astype(int),0,tw-1); py=np.clip(((1-vv)*th).astype(int),0,th-1)
rgb=ta[py,px,:3]
else: rgb=np.ones(xs.shape+(3,))
rgb=rgb*np.array(col)*shade
sub[m]=z[m]
reg=img[y0:y1,x0:x1]
reg[m,:3]=np.clip(rgb[m],0,1); reg[m,3]=1
Image.fromarray((img*255).astype(np.uint8)).save(out)