diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_d.png new file mode 100644 index 0000000..905ec99 Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_d.png differ diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_n.png b/JotunnModStub/Assets/CookCloth/CookCloth_n.png new file mode 100644 index 0000000..7603df9 Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_n.png differ diff --git a/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png b/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png new file mode 100644 index 0000000..d36ee7c Binary files /dev/null and b/JotunnModStub/Assets/CookCloth/CookCloth_worn_d.png differ diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_d.png new file mode 100644 index 0000000..5ecb47d Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_d.png differ diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_m.png b/JotunnModStub/Assets/SmithMail/SmithMail_m.png new file mode 100644 index 0000000..0227d0f Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_m.png differ diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_n.png b/JotunnModStub/Assets/SmithMail/SmithMail_n.png new file mode 100644 index 0000000..9198ee1 Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_n.png differ diff --git a/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png b/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png new file mode 100644 index 0000000..a90bd1c Binary files /dev/null and b/JotunnModStub/Assets/SmithMail/SmithMail_worn_d.png differ diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index 714016f..59ef5d7 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -218,6 +218,7 @@ namespace RacesOfValheim } prefab.transform.localScale = Vector3.one * TableScale; + Dress(prefab, family); ServantTableBehaviour table = prefab.AddComponent(); table.m_switch = prefab.AddComponent(); @@ -255,6 +256,65 @@ namespace RacesOfValheim })); } + // The look, in the table's own space BEFORE TableScale, so sizes are divided by it to come out + // in real metres. The cover lies where the map was: x -2.06 to 0.62, read off the mesh. Its top + // is the Dvergar bank's PileHeight, on the same vanilla mesh; the mesh's own height is no use + // here, since the writing desk stands taller than the map. + private const float CoverTop = 1.05f; + private static readonly Vector3 TradeSpot = new Vector3(-0.75f, CoverTop, 0.2f); + private static readonly Vector3 SkullSpot = new Vector3(-1.55f, CoverTop, 0.35f); + private const float AnvilSize = 0.75f; + private const float MealSize = 0.6f; + private const float SkullSize = 0.45f; + + /// + /// The map painted over - a sheet of chainmail for the smith, a red and white tablecloth for the + /// cook - with the trade's own work on it (an anvil, a meal) and a skeleton's skull beside it. + /// + private static void Dress(GameObject prefab, ButlerFamily family) + { + bool forge = family == ButlerFamily.Forge; + LayCover(prefab, forge ? "SmithMail" : "CookCloth", metal: forge); + + float metres = 1f / TableScale; + if (forge) + { + ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2", + TradeSpot, Quaternion.identity, AnvilSize * metres, "Butler", activeOnly: true); + } + else + { + ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter", + TradeSpot, Quaternion.identity, MealSize * metres, "Butler", activeOnly: true); + } + ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton", + SkullSpot, Quaternion.Euler(0f, -150f, 0f), SkullSize * metres, "Butler", activeOnly: true); + } + + /// + /// The cartography table's own textures with the map painted over, offline: + /// scripts/paint_cook_cloth.py (CookCloth) and scripts/paint_smith_mail.py (SmithMail). Each set + /// has its own worn texture for a damaged table (a stained cloth, rusted mail) and its own normal + /// map, so the coastline's relief does not show through. The mail also brings a metallic map, + /// which is what makes the rings shine; the cloth keeps vanilla's, which is metal nowhere. + /// + private static void LayCover(GameObject prefab, string set, bool metal) + { + var cover = new System.Collections.Generic.Dictionary(); + AddCover(cover, "Cartographer_d", set + "_d.png", false); + AddCover(cover, "Cartographer_worn_d", set + "_worn_d.png", false); + AddCover(cover, "Cartographer_n", set + "_n.png", true); + if (metal) AddCover(cover, "Cartographer_m", set + "_m.png", true); + PieceLook.Retexture(prefab.transform, cover); + } + + private static void AddCover(System.Collections.Generic.Dictionary cover, + string vanilla, string resource, bool linear) + { + Texture2D texture = PieceLook.LoadTexture(resource, linear); + if (texture != null) cover[vanilla] = texture; + } + public static void EnsureKnown(Player player) { if (player == null) return; diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs index e4964e6..44346b0 100644 --- a/JotunnModStub/Butler/ServantTableBehaviour.cs +++ b/JotunnModStub/Butler/ServantTableBehaviour.cs @@ -143,7 +143,8 @@ namespace RacesOfValheim string status = servant.Status; if (string.IsNullOrEmpty(status)) status = ModText.Get("rov_hover_butler_waiting"); - return m_title + "\n" + status; + // m_title is a $token, and a hover text goes to the HUD as it is: nothing localizes it later. + return Localization.instance.Localize(m_title) + "\n" + status; } /// diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index a912a2d..8f24220 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -76,6 +76,12 @@ namespace RacesOfValheim private const float PileHeight = 1.05f; private const float PileSize = 0.45f; + // The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the + // tankard stands just clear of it, on the near side. + private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f); + private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f); + private const float TankardSize = 0.38f; + public class Troop { public string Id; @@ -276,6 +282,12 @@ namespace RacesOfValheim prefab.transform.localScale = Vector3.one * TableScale; + // A counting table, not a map table: darker wood and a dvergr tankard beside the coin. + // Tinted BEFORE the tankard goes on, or it would be darkened too. + PieceLook.Tint(prefab.transform, BankWoodTint); + ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr", + TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true); + DvergarBancoBehaviour bank = prefab.AddComponent(); foreach (Switch existing in prefab.GetComponentsInChildren(true)) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 08a777b..19a6ced 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -36,10 +36,13 @@ namespace RacesOfValheim /// is where the model's BOTTOM CENTRE goes. /// is how big its largest dimension should end up, in metres, /// measured AFTER has been applied. + /// drops every child the source keeps switched off before measuring. + /// A build piece carries its snow cover, its fire, its worn and broken meshes that way, and they + /// count towards the size: the cauldron's hidden tripod legs are two metres long. /// public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, Vector3 localPosition, Quaternion localRotation, float targetSize, - string label) + string label, bool activeOnly = false) { GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab); if (source == null) @@ -52,7 +55,7 @@ namespace RacesOfValheim return empty; } - return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label); + return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label, activeOnly); } /// @@ -66,7 +69,7 @@ namespace RacesOfValheim /// public static GameObject Attach(Transform parent, string holderName, GameObject source, Vector3 localPosition, Quaternion localRotation, float targetSize, - string label) + string label, bool activeOnly = false) { GameObject holder = new GameObject(holderName); holder.transform.SetParent(parent, false); @@ -110,6 +113,16 @@ namespace RacesOfValheim if (nview != null) Object.DestroyImmediate(nview); } + if (activeOnly) + { + foreach (Transform child in copy.GetComponentsInChildren(true)) + { + // Null once an inactive parent above it has already gone. + if (child == null || child == copy.transform || child.gameObject.activeSelf) continue; + Object.DestroyImmediate(child.gameObject); + } + } + FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label); holder.SetActive(true); diff --git a/JotunnModStub/PieceLook.cs b/JotunnModStub/PieceLook.cs new file mode 100644 index 0000000..ce521ad --- /dev/null +++ b/JotunnModStub/PieceLook.cs @@ -0,0 +1,197 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Recolouring a cloned vanilla piece without touching the original. + /// + /// A clone made by CreateClonedPrefab shares its MATERIALS with the vanilla prefab, so writing a + /// colour onto renderer.sharedMaterial would repaint every Ward or cartography table in the world. + /// Each material is copied once and the copy is written; renderers that shared one material before + /// share the one copy after, so the LOD, worn and broken meshes stay matched. + /// + public static class PieceLook + { + /// + /// Multiplies the base colour of every mesh under , inactive ones included + /// (a piece's worn and broken meshes are switched off until it takes damage). Particles are left + /// alone: that is what is for. + /// + public static void Tint(Transform root, Color tint) + { + if (root == null) return; + + var copies = new Dictionary(); + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + Material[] materials = renderer.sharedMaterials; + for (int i = 0; i < materials.Length; i++) + { + Material copy = CopyOf(materials[i], copies); + if (copy == null) continue; + if (copy.HasProperty("_Color")) copy.SetColor("_Color", copy.GetColor("_Color") * tint); + materials[i] = copy; + } + renderer.sharedMaterials = materials; + } + } + + /// + /// Swaps the hue of everything under that GLOWS - lights, particles and + /// any material with emission - for , keeping each one's brightness. + /// + /// Brightness is kept rather than overwritten because these values are not 0 to 1: the Ward's + /// sparks are authored at a colour of 2.0, and painting them a flat 1.0 blue would dim them by + /// half. A material whose emission is black does not glow and is skipped, so the Ward's stone + /// stays stone. + /// + public static void Rehue(Transform root, Color glow) + { + if (root == null) return; + + foreach (Light light in root.GetComponentsInChildren(true)) + { + if (light != null) light.color = glow; + } + + foreach (ParticleSystem ps in root.GetComponentsInChildren(true)) + { + if (ps == null) continue; + ParticleSystem.MainModule main = ps.main; + main.startColor = new ParticleSystem.MinMaxGradient(glow); + } + + var copies = new Dictionary(); + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + bool particles = renderer is ParticleSystemRenderer; + + Material[] materials = renderer.sharedMaterials; + bool changed = false; + for (int i = 0; i < materials.Length; i++) + { + Material source = materials[i]; + if (source == null) continue; + + bool emits = source.HasProperty("_EmissionColor") && Brightness(source.GetColor("_EmissionColor")) > 0.01f; + if (!emits && !particles) continue; + + Material copy = CopyOf(source, copies); + if (emits) Recolour(copy, "_EmissionColor", glow); + if (particles) + { + Recolour(copy, "_Color", glow); + Recolour(copy, "_TintColor", glow); + } + materials[i] = copy; + changed = true; + } + if (changed) renderer.sharedMaterials = materials; + } + } + + /// + /// Swaps textures by the name of the texture they replace: every material under + /// that uses "Cartographer_d" gets 's + /// "Cartographer_d" instead, whichever slot it sits in. Materials are copied as in Tint. + /// + public static void Retexture(Transform root, IDictionary replacements) + { + if (root == null) return; + + var copies = new Dictionary(); + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + Material[] materials = renderer.sharedMaterials; + bool changed = false; + for (int i = 0; i < materials.Length; i++) + { + Material source = materials[i]; + if (source == null) continue; + + foreach (string property in source.GetTexturePropertyNames()) + { + Texture current = source.GetTexture(property); + if (current == null || !replacements.TryGetValue(current.name, out Texture replacement)) continue; + + Material copy = CopyOf(source, copies); + copy.SetTexture(property, replacement); + materials[i] = copy; + changed = true; + } + } + if (changed) renderer.sharedMaterials = materials; + } + } + + /// + /// ImageConversion.LoadImage, found at run time. Its module is built against netstandard 2.1 and + /// this project targets net48, so referencing it at compile time fails the build (CS1705); the + /// game has the module loaded either way. + /// + private static readonly System.Reflection.MethodInfo LoadImage = + System.Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule") + ?.GetMethod("LoadImage", new[] { typeof(Texture2D), typeof(byte[]), typeof(bool) }); + + /// + /// A PNG embedded in the DLL (see the csproj's EmbeddedResource), or null with a warning. + /// for anything that is data rather than colour - a normal map read + /// as sRGB comes out bent. + /// + public static Texture2D LoadTexture(string resource, bool linear = false) + { + using (System.IO.Stream stream = typeof(PieceLook).Assembly.GetManifestResourceStream(resource)) + { + if (stream == null) + { + Jotunn.Logger.LogWarning($"No embedded texture '{resource}'."); + return null; + } + + byte[] bytes = new byte[stream.Length]; + int read = 0; + while (read < bytes.Length) read += stream.Read(bytes, read, bytes.Length - read); + + Texture2D texture = new Texture2D(2, 2, TextureFormat.RGBA32, true, linear) + { + name = System.IO.Path.GetFileNameWithoutExtension(resource), + anisoLevel = 4, + }; + if (LoadImage == null || !(bool)LoadImage.Invoke(null, new object[] { texture, bytes, true })) + { + Jotunn.Logger.LogWarning($"Embedded texture '{resource}' would not decode."); + return null; + } + return texture; + } + } + + private static void Recolour(Material material, string property, Color glow) + { + if (!material.HasProperty(property)) return; + Color old = material.GetColor(property); + Color hue = glow * Brightness(old); + hue.a = old.a; + material.SetColor(property, hue); + } + + private static float Brightness(Color colour) => Mathf.Max(colour.r, Mathf.Max(colour.g, colour.b)); + + private static Material CopyOf(Material source, Dictionary copies) + { + if (source == null) return null; + if (!copies.TryGetValue(source, out Material copy)) + { + copy = new Material(source) { name = source.name + "_rov" }; + copies[source] = copy; + } + return copy; + } + } +} diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs index e59b237..4ed4c37 100644 --- a/JotunnModStub/RaceMenuWard.cs +++ b/JotunnModStub/RaceMenuWard.cs @@ -44,6 +44,8 @@ namespace RacesOfValheim prefab.AddComponent(); + Restyle(prefab); + PieceConfig config = new PieceConfig { Name = "$rov_piece_racemenuward_name", @@ -60,6 +62,44 @@ namespace RacesOfValheim PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); } + // ---------------------------------------------------------------- the look + /// Seidr blue in place of the Ward's hearth orange: every race builds this, so no race's colour. + private static readonly Color Glow = new Color(0.55f, 0.62f, 1f, 1f); + /// A colder stone, so it reads as a different thing from the vanilla Ward across a base. + private static readonly Color StoneTint = new Color(0.78f, 0.82f, 0.92f, 1f); + /// Narrower and taller than the Ward, on a plinth: a statue rather than a waystone. + private static readonly Vector3 StatueShape = new Vector3(0.9f, 1.12f, 0.9f); + private const float PlinthWidth = 1.3f; + + /// + /// Odin's stone on a plinth, glowing blue. The statue, its light and its sparks are lifted by the + /// plinth's MEASURED height, so a different plinth model needs no new offset. + /// + private static void Restyle(GameObject prefab) + { + Transform statue = prefab.transform.Find("new"); + if (statue == null) + { + Jotunn.Logger.LogWarning("guard_stone has no 'new' model; the Race Menu Ward keeps the vanilla look."); + return; + } + + PieceLook.Tint(statue, StoneTint); + PieceLook.Rehue(prefab.transform, Glow); + statue.localScale = Vector3.Scale(statue.localScale, StatueShape); + + GameObject plinth = ModelBorrow.Attach(prefab.transform, "WardPlinth", "stone_floor_2x2", + Vector3.zero, Quaternion.identity, PlinthWidth, + "RaceMenuWard", activeOnly: true); + float lift = ModelBorrow.HeightOf(plinth); + + foreach (string child in new[] { "new", "WayEffect", "GuidePoint" }) + { + Transform part = prefab.transform.Find(child); + if (part != null) part.localPosition += Vector3.up * lift; + } + } + // Marks a world as already having its starter ward, so it is placed exactly once rather // than every time someone loads in. private const string PlacedKey = "RacesOfValheim_StarterWardPlaced"; diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj index 7ddf073..66294a4 100644 --- a/JotunnModStub/RacesOfValheim.csproj +++ b/JotunnModStub/RacesOfValheim.csproj @@ -53,6 +53,12 @@ + + + + + diff --git a/scripts/extract_carto.py b/scripts/extract_carto.py new file mode 100644 index 0000000..6e9ba7c --- /dev/null +++ b/scripts/extract_carto.py @@ -0,0 +1,39 @@ +"""Export the cartography table's textures (PNG) and its high mesh (OBJ) from Valheim's bundle. +Usage: py -3.14 -I extract_carto.py """ +import os, sys +sys.path.insert(0, sys.argv[1]) +import UnityPy + +bundle, out = sys.argv[2], sys.argv[3] +os.makedirs(out, exist_ok=True) +env = UnityPy.load(bundle) + +want_tex = {"Cartographer_d", "Cartographer_worn_d", "Cartographer_n", "Cartographer_m"} +for obj in env.objects: + if obj.type.name == "Texture2D": + t = obj.read() + if t.m_Name in want_tex: + img = t.image + img.save(os.path.join(out, t.m_Name + ".png")) + print("tex", t.m_Name, img.size, t.m_TextureFormat) + +for path, ptr in env.container.items(): + if path.endswith("/piece_cartographytable.prefab"): + go = ptr.read() + def walk(tr, prefix): + g = tr.m_GameObject.read() + name = prefix + "/" + g.m_Name + for c in g.m_Component: + o = (c.component if hasattr(c, 'component') else c[1]).read() + if o.object_reader.type.name == "MeshFilter": + m = o.m_Mesh.read() + fn = name.strip("/").replace("/", "__") + ".obj" + open(os.path.join(out, fn), "w").write(m.export()) + print("mesh", name, m.m_Name, "->", fn) + for ch in tr.m_Children: + walk(ch.read(), name) + for c in go.m_Component: + o = (c.component if hasattr(c, 'component') else c[1]).read() + if o.object_reader.type.name == "Transform": + walk(o, "") + break diff --git a/scripts/paint_cook_cloth.py b/scripts/paint_cook_cloth.py new file mode 100644 index 0000000..c63f63a --- /dev/null +++ b/scripts/paint_cook_cloth.py @@ -0,0 +1,55 @@ +"""Paint a red and white gingham tablecloth over the cartography table's map. +Usage: py -3.14 -I paint_cloth.py """ +import os, sys +sys.path.insert(0, sys.argv[1]) +from PIL import Image, ImageFilter + +src, out = sys.argv[2], sys.argv[3] +os.makedirs(out, exist_ok=True) + +# The parchment's UV island spans x 10-133, y 11-90 (read off the mesh). A margin either side, +# stopping short of the next island (the red disc starts at y 96, the stone at x 150). +X0, Y0, X1, Y1 = 4, 4, 141, 95 +SQUARE = 6 # pixels; the island is ~45 px per metre, so about 13 cm squares + +WHITE = (236, 231, 219) +MID = (204, 92, 86) +DARK = (158, 28, 32) + + +def gingham(x, y): + a = ((x - X0) // SQUARE) % 2 == 0 + b = ((y - Y0) // SQUARE) % 2 == 0 + return DARK if a and b else MID if a or b else WHITE + + +def paint(name, fade=0.0, dirt=1.0): + img = Image.open(os.path.join(src, name + ".png")).convert("RGBA") + # Keep the parchment's broad light and shadow (the folds, the dark rolled edges) but not + # its ink: a heavy blur of its brightness, around 1.0. + lum = img.convert("L").filter(ImageFilter.GaussianBlur(5)) + region = [lum.getpixel((x, y)) for y in range(Y0, Y1) for x in range(X0, X1)] + mean = sum(region) / len(region) + px = img.load() + for y in range(Y0, Y1): + for x in range(X0, X1): + shade = max(0.7, min(1.15, lum.getpixel((x, y)) / mean)) * dirt + r, g, b = gingham(x, y) + o = px[x, y] + c = [int(min(255, v * shade)) for v in (r, g, b)] + c = [int(cv * (1 - fade) + ov * fade) for cv, ov in zip(c, o[:3])] + px[x, y] = (c[0], c[1], c[2], o[3]) + img.save(os.path.join(out, name.replace("Cartographer", "CookCloth") + ".png")) + + +def smooth_normal(name): + img = Image.open(os.path.join(src, name + ".png")).convert("RGBA") + box = (X0, Y0, X1, Y1) + img.paste(img.crop(box).filter(ImageFilter.GaussianBlur(4)), box) + img.save(os.path.join(out, name.replace("Cartographer", "CookCloth") + ".png")) + + +paint("Cartographer_d") +paint("Cartographer_worn_d", fade=0.3, dirt=0.85) # the damaged table: a stained, faded cloth +smooth_normal("Cartographer_n") +print("done") diff --git a/scripts/paint_smith_mail.py b/scripts/paint_smith_mail.py new file mode 100644 index 0000000..cad2bfa --- /dev/null +++ b/scripts/paint_smith_mail.py @@ -0,0 +1,118 @@ +"""Paint a sheet of chainmail over the cartography table's map: colour, worn (rusted) colour, +normal map and metallic map, at twice the vanilla resolution so the rings keep their shape. +Usage: py -3.14 -I paint_mail.py """ +import os, sys +sys.path.insert(0, sys.argv[1]) +import numpy as np +from PIL import Image, ImageFilter + +src, out = sys.argv[2], sys.argv[3] +os.makedirs(out, exist_ok=True) + +SCALE = 2 +# The parchment's UV island (x 10-133, y 11-90 at 256 px) plus a margin, as in paint_cook_cloth.py. +X0, Y0, X1, Y1 = 4 * SCALE, 4 * SCALE, 141 * SCALE, 95 * SCALE +W, H = X1 - X0, Y1 - Y0 + +RING = 7.0 # ring radius to the middle of the wire, px at 512 (about 15 cm across in game) +WIRE = 1.5 # half the wire's thickness +SX, SY = RING * 2.3, RING * 1.3 # 4-in-1: each row offset by half, linking the rows above and below +rng = np.random.default_rng(7) + +# ---------------------------------------------------------------- the rings, as a height field +ys, xs = np.mgrid[0:H, 0:W].astype(np.float32) +height = np.zeros((H, W), np.float32) +tone = np.ones((H, W), np.float32) +rows = int(H / SY) + 3 +cols = int(W / SX) + 3 +for row in range(-1, rows): + tilt = 0.45 if row % 2 else -0.45 # alternate rows lean opposite ways, like real mail + lift = 0.25 if row % 2 else 0.0 # and one set lies over the other + for col in range(-1, cols): + cx = col * SX + (SX / 2 if row % 2 else 0) + cy = row * SY + x0, x1 = int(max(0, cx - RING - WIRE - 2)), int(min(W, cx + RING + WIRE + 3)) + y0, y1 = int(max(0, cy - RING - WIRE - 2)), int(min(H, cy + RING + WIRE + 3)) + if x0 >= x1 or y0 >= y1: + continue + dx = xs[y0:y1, x0:x1] - cx + dy = ys[y0:y1, x0:x1] - cy + # a tilted ring seen from above is an ellipse, squashed along its lean + u = dx * np.cos(tilt) + dy * np.sin(tilt) + v = (-dx * np.sin(tilt) + dy * np.cos(tilt)) / 0.78 + t = (np.sqrt(u * u + v * v) - RING) / WIRE + h = np.where(np.abs(t) < 1, np.sqrt(np.clip(1 - t * t, 0, 1)) * 0.75 + lift, 0) + win = h > height[y0:y1, x0:x1] + height[y0:y1, x0:x1] = np.where(win, h, height[y0:y1, x0:x1]) + tone[y0:y1, x0:x1] = np.where(win, 0.92 + rng.random() * 0.16, tone[y0:y1, x0:x1]) + +ring = height > 0 + +# ---------------------------------------------------------------- lighting from the height field +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 = 1.6 +n = np.stack([-gx * K, gy * K, np.ones_like(height)], -1) # image y runs down, texture v up +n /= np.linalg.norm(n, axis=-1, keepdims=True) +light = np.array([-0.45, 0.55, 0.70]); light /= np.linalg.norm(light) +diffuse = np.clip((n * light).sum(-1), 0, 1) +half = light + np.array([0, 0, 1.0]); half /= np.linalg.norm(half) +spec = np.clip((n * half).sum(-1), 0, 1) ** 24 + + +def broad_shade(img): + """The parchment's folds and rolled edges, without its ink: a heavy blur of its brightness.""" + lum = np.asarray(img.convert("L").filter(ImageFilter.GaussianBlur(5 * SCALE)), np.float32)[Y0:Y1, X0:X1] + return np.clip(lum / lum.mean(), 0.7, 1.15) + + +def upscale(name): + img = Image.open(os.path.join(src, name + ".png")).convert("RGBA") + return img.resize((img.width * SCALE, img.height * SCALE), Image.BICUBIC) + + +def colour(name, rust): + img = upscale(name) + a = np.asarray(img, np.float32).copy() + shade = broad_shade(img) + steel = np.array([150, 156, 164], np.float32) + # Through the holes, the table's own planks in the mail's shadow: tiled from the wood island. + wood = a[130 * SCALE:240 * SCALE, 60 * SCALE:240 * SCALE, :3] + reps = (H // wood.shape[0] + 1, W // wood.shape[1] + 1, 1) + gap = np.tile(wood, reps)[:H, :W] * 0.5 + lit = steel * (0.30 + 0.75 * diffuse[..., None]) * tone[..., None] + 120 * spec[..., None] + if rust: + blotch = np.asarray(Image.fromarray((rng.random((H // 6 + 1, W // 6 + 1)) * 255).astype(np.uint8)) + .resize((W, H), Image.BICUBIC).filter(ImageFilter.GaussianBlur(3)), np.float32) / 255 + amount = np.clip((blotch - 0.35) * 2.2, 0, 0.85)[..., None] + rusty = np.array([118, 62, 32], np.float32) * (0.45 + 0.6 * diffuse[..., None]) + lit = lit * (1 - amount) + rusty * amount + lit *= 0.85 + rgb = np.where(ring[..., None], lit, gap) * shade[..., None] + a[Y0:Y1, X0:X1, :3] = np.clip(rgb, 0, 255) + return Image.fromarray(a.astype(np.uint8), "RGBA") + + +def normal(): + a = np.asarray(upscale("Cartographer_n"), np.float32).copy() + # DXT5nm, as Valheim packs it: X in alpha, Y in green (blue repeats it), red pinned to 255. + a[Y0:Y1, X0:X1, 0] = 255 + a[Y0:Y1, X0:X1, 1] = (n[..., 1] * 0.5 + 0.5) * 255 + a[Y0:Y1, X0:X1, 2] = (n[..., 1] * 0.5 + 0.5) * 255 + a[Y0:Y1, X0:X1, 3] = (n[..., 0] * 0.5 + 0.5) * 255 + return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8), "RGBA") + + +def metallic(): + a = np.asarray(upscale("Cartographer_m"), np.float32).copy() + a[Y0:Y1, X0:X1, 0] = np.where(ring, 210, 0) # red is metallic; the rest of the table stays 0 + return Image.fromarray(a.astype(np.uint8), "RGBA") + + +colour("Cartographer_d", rust=False).save(os.path.join(out, "SmithMail_d.png")) +colour("Cartographer_worn_d", rust=True).save(os.path.join(out, "SmithMail_worn_d.png")) +normal().save(os.path.join(out, "SmithMail_n.png")) +metallic().save(os.path.join(out, "SmithMail_m.png")) +print("done") +