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/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index 344b9d3..2376bfa 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -62,6 +62,8 @@ namespace RacesOfValheim public const float TableSpacing = 40f; private const string TableSource = "piece_blackmarble_table"; + private const string ClothTableSource = "piece_cartographytable"; + private const float ClothTableScale = 0.8f; /// /// One skull, one wishbone, eight stone - the same price for both tables. @@ -197,20 +199,22 @@ namespace RacesOfValheim private static void RegisterTable(string pieceName, string displayName, string servantPrefab, ButlerFamily family, string description, string iconSource) { - // The black marble table: "a slab of bone and slate". It was the cartography table once, - // whose map is baked into its own texture and could not be taken off. - GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, TableSource); + // The smith works at the black marble table, "a slab of bone and slate". The cook keeps the + // cartography table, with a tablecloth painted over its map (Dress). + bool kitchen = family == ButlerFamily.Kitchen; + string source = kitchen ? ClothTableSource : TableSource; + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source); if (prefab == null) { - Jotunn.Logger.LogWarning($"[Butler] Could not clone {TableSource}; " + + Jotunn.Logger.LogWarning($"[Butler] Could not clone {source}; " + $"the {displayName} is not registered."); return; } - // A blanket sweep by capability rather than a named DestroyImmediate. The cartography table - // taught it: its MapTable is Interactable AND Hoverable, so it took the E key before our own - // Switch ever saw it. The marble table carries nothing of the kind today, and the sweep - // keeps a future patch from adding one behind our back. + // The MapTable trap, and it is the reason this is a blanket sweep by capability rather than + // a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key + // before our own Switch ever sees it and opens the shared map instead. The marble table + // carries nothing of the kind today, and the sweep keeps a future patch from adding one. foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) { if (behaviour == null) continue; @@ -218,6 +222,7 @@ namespace RacesOfValheim Object.DestroyImmediate(behaviour); } + if (kitchen) prefab.transform.localScale = Vector3.one * ClothTableScale; Dress(prefab, family); ServantTableBehaviour table = prefab.AddComponent(); @@ -256,8 +261,8 @@ namespace RacesOfValheim })); } - // The look. The marble table is 2.6 m by 1.5 m; both props sit either side of its centre, the - // trade's tool the bigger of the two. X and Z only: the height is the table's, measured. + // The smith's look. The marble table is 2.6 m by 1.5 m; both props sit either side of its + // centre, the anvil the bigger of the two. X and Z only: the height is the table's, measured. private const float MarbleTableTop = 0.82f; private static readonly Vector3 TradeSpot = new Vector3(-0.35f, 0f, 0f); private static readonly Vector3 SkullSpot = new Vector3(0.6f, 0f, 0.1f); @@ -265,12 +270,32 @@ namespace RacesOfValheim private const float MealSize = 0.6f; private const float SkullSize = 0.45f; + // The cook's cartography table, in its own space BEFORE ClothTableScale (so sizes are divided by + // it to come out the same as the smith's). The cloth covers what was the map: 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 cloth. + private const float ClothTop = 1.05f; + private static readonly Vector3 MealOnCloth = new Vector3(-0.75f, ClothTop, 0.2f); + private static readonly Vector3 SkullOnCloth = new Vector3(-1.55f, ClothTop, 0.35f); + /// - /// "A slab of bone and slate": the black marble table, with the trade's own work in the middle - - /// an anvil for the smith, a meal for the cook - and a skeleton's skull beside it. + /// The trade's own work in the middle - an anvil for the smith, a meal for the cook - and a + /// skeleton's skull beside it. The smith's on the black marble, the cook's on a red and white + /// cloth painted over the cartography table's map. /// private static void Dress(GameObject prefab, ButlerFamily family) { + if (family == ButlerFamily.Kitchen) + { + LayCloth(prefab); + float size = 1f / ClothTableScale; + ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter", + MealOnCloth, Quaternion.identity, MealSize * size, "Butler", activeOnly: true); + ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton", + SkullOnCloth, Quaternion.Euler(0f, -150f, 0f), SkullSize * size, "Butler", activeOnly: true); + return; + } + // The table's own height off its own mesh, with vanilla's 0.82 m as the fallback. The mesh // stands on the piece's origin, so its height IS the height of the top. Transform model = prefab.transform.Find("new"); @@ -278,19 +303,32 @@ namespace RacesOfValheim if (top <= 0f) top = MarbleTableTop; Vector3 up = Vector3.up * top; + ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2", + TradeSpot + up, Quaternion.identity, AnvilSize, "Butler", activeOnly: true); ModelBorrow.Attach(prefab.transform, "TableSkull", "TrophySkeleton", SkullSpot + up, Quaternion.Euler(0f, -150f, 0f), SkullSize, "Butler", activeOnly: true); + } - if (family == ButlerFamily.Forge) - { - ModelBorrow.Attach(prefab.transform, "TableAnvil", "forge_ext2", - TradeSpot + up, Quaternion.identity, AnvilSize, "Butler", activeOnly: true); - } - else - { - ModelBorrow.Attach(prefab.transform, "TableMeal", "MeatPlatter", - TradeSpot + up, Quaternion.identity, MealSize, "Butler", activeOnly: true); - } + /// + /// The tablecloth: the cartography table's own textures with the map painted over in red and + /// white squares, by scripts/paint_cook_cloth.py. The worn texture (a damaged table) has a + /// faded, stained cloth of its own, and the normal map is smoothed there so the coastline's + /// relief does not show through. + /// + private static void LayCloth(GameObject prefab) + { + var cloth = new System.Collections.Generic.Dictionary(); + AddCloth(cloth, "Cartographer_d", "CookCloth_d.png", false); + AddCloth(cloth, "Cartographer_worn_d", "CookCloth_worn_d.png", false); + AddCloth(cloth, "Cartographer_n", "CookCloth_n.png", true); + PieceLook.Retexture(prefab.transform, cloth); + } + + private static void AddCloth(System.Collections.Generic.Dictionary cloth, + string vanilla, string resource, bool linear) + { + Texture2D texture = PieceLook.LoadTexture(resource, linear); + if (texture != null) cloth[vanilla] = texture; } public static void EnsureKnown(Player player) diff --git a/JotunnModStub/PieceLook.cs b/JotunnModStub/PieceLook.cs index 402d96d..ce521ad 100644 --- a/JotunnModStub/PieceLook.cs +++ b/JotunnModStub/PieceLook.cs @@ -94,6 +94,84 @@ namespace RacesOfValheim } } + /// + /// 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; 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")