Merge branch 'feat-scale-hammer'

# Conflicts:
#	JotunnModStub/Translations/English/messages.json
#	JotunnModStub/Translations/Italian/messages.json
#	JotunnModStub/Translations/Russian/messages.json
This commit is contained in:
kanym 2026-10-30 23:42:58 +01:00
commit 106dc22bc1
17 changed files with 417 additions and 14 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View file

@ -47,6 +47,7 @@ namespace RacesOfValheim
// Not a race either: a tool any race can craft, so it sits beside the vulture rather
// than inside the alphabetical run above.
TrolsHammerConfig.Bind(Config);
ShrinkHammerConfig.Bind(Config);
// Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they
// bind here rather than inside either race's run.
ButlerConfig.Bind(Config);
@ -306,6 +307,7 @@ namespace RacesOfValheim
AlfarRace.CreateModAssets();
WarVultureItem.Register();
TrolsHammerItem.Register();
ShrinkHammerItem.Register();
BoneServant.Register();
}
// --- RACE SELECTION UI ---

View file

@ -0,0 +1,211 @@
using BepInEx.Configuration;
using HarmonyLib;
using TMPro;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What both sizing hammers share: which size the hammer in hand builds at, Alt + scroll to
/// change it, the size floating over the ghost, and the "Alt: Size" row in the bottom bar.
///
/// Trol's Hammer builds 1 to 3 times the vanilla size, the Shrink Hammer a quarter to 1. Each
/// keeps its size in its own config entry, and the wheel writes that entry, so Configuration
/// Manager and the wheel never disagree. The entries are not synced: each player picks their own.
/// Alt is free in build mode: vanilla's own placing modifier ("AltPlace") is Left Shift.
/// </summary>
public static class BuildScale
{
public const float Step = 0.05f;
/// <summary>The config entry behind the hammer in hand, or null for any other tool.</summary>
public static ConfigEntry<float> EntryFor(ItemDrop.ItemData item)
{
if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ScaleFactor;
if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ScaleFactor;
return null;
}
/// <summary>The multiplier a placement with this item in hand gets: 1 for any other tool.</summary>
public static float For(ItemDrop.ItemData item)
{
if (TrolsHammerItem.IsTrolsHammer(item)) return TrolsHammerConfig.ActiveFactor();
if (ShrinkHammerItem.IsShrinkHammer(item)) return ShrinkHammerConfig.ActiveFactor();
return 1f;
}
public static bool AltHeld() => Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);
/// <summary>Moves the entry by whole steps, kept on the 0.05 grid and inside its range.</summary>
public static void Nudge(ConfigEntry<float> entry, int steps)
{
AcceptableValueRange<float> range = entry.Description.AcceptableValues as AcceptableValueRange<float>;
float min = range != null ? range.MinValue : 0.25f, max = range != null ? range.MaxValue : 3f;
float value = Mathf.Round((entry.Value + steps * Step) / Step) * Step;
entry.Value = Mathf.Clamp(value, min, max);
}
// --- the size over the ghost ---
private static GameObject s_labelled;
private static float s_shown;
/// <summary>
/// The size in Valheim's own floating NPC text, with one of the two hammers in hand:
/// - over the ghost, while the hammer's size differs from its default (1.2 for Trol's
/// Hammer, 1 for the Shrink Hammer);
/// - with the repair tool selected, over the piece aimed at, always: the size it was built
/// at, 1 for a piece no sizing hammer built.
/// The text has no timeout, so it is set again only when its piece or the size changes:
/// setting it replays its fade-in.
/// </summary>
public static void UpdateLabel(Player player, GameObject ghost)
{
if (Chat.instance == null) return;
ConfigEntry<float> entry = player != null && player.InPlaceMode() ? EntryFor(player.RightItem) : null;
if (entry == null)
{
ClearLabel();
return;
}
Piece tool = player.GetSelectedPiece();
if (tool != null && tool.m_repairPiece)
{
Piece aimed = player.GetHoveringPiece();
if (aimed != null) Show(aimed.gameObject, BuiltSize(aimed));
else ClearLabel();
return;
}
float value = For(player.RightItem);
if (ghost != null && ghost.activeInHierarchy && !Mathf.Approximately(value, (float)entry.DefaultValue))
Show(ghost, value);
else
ClearLabel();
}
/// <summary>The size a placed piece was built at, from its ZDO; 1 when no sizing hammer built it.</summary>
private static float BuiltSize(Piece piece)
{
ZDO zdo = piece.GetComponent<ZNetView>()?.GetZDO();
float saved = zdo != null ? zdo.GetFloat(TrolsHammerScaling.ScaleKey, 0f) : 0f;
return saved > 0f ? saved : 1f;
}
private static void Show(GameObject target, float value)
{
if (target == s_labelled && Mathf.Approximately(value, s_shown)) return;
ClearLabel();
Chat.instance.SetNpcText(target, Vector3.up * (TopOf(target) + 0.3f), 30f, 0f, "",
ModText.Get("rov_msg_build_scale", value.ToString("0.00")), false);
s_labelled = target;
s_shown = value;
}
private static void ClearLabel()
{
if (s_labelled != null && Chat.instance != null) Chat.instance.ClearNpcText(s_labelled);
s_labelled = null;
}
/// <summary>How far above its pivot the ghost reaches, from its renderers.</summary>
private static float TopOf(GameObject ghost)
{
float top = 0.5f;
foreach (Renderer renderer in ghost.GetComponentsInChildren<Renderer>())
top = Mathf.Max(top, renderer.bounds.max.y - ghost.transform.position.y);
return top;
}
}
/// <summary>
/// Alt + scroll in build mode. Vanilla turns the piece with the same wheel in the same method,
/// whatever key is held, so the prefix reads the wheel for the size and the postfix puts the
/// rotation back as it was.
/// </summary>
[HarmonyPatch(typeof(Player), "UpdatePlacement")]
public static class BuildScaleScrollPatch
{
private static float s_scroll;
private static void Prefix(Player __instance, bool takeInput, int ___m_placeRotation, out int __state)
{
__state = ___m_placeRotation;
if (!takeInput || __instance != Player.m_localPlayer || !__instance.InPlaceMode()) return;
if (!BuildScale.AltHeld()) return;
ConfigEntry<float> entry = BuildScale.EntryFor(__instance.RightItem);
if (entry == null) return;
s_scroll += ZInput.GetMouseScrollWheel();
if (s_scroll > __instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, 1); }
if (s_scroll < -__instance.m_scrollAmountThreshold) { s_scroll = 0f; BuildScale.Nudge(entry, -1); }
}
private static void Postfix(Player __instance, int __state, ref int ___m_placeRotation,
ref float ___m_scrollCurrAmount, GameObject ___m_placementGhost)
{
if (__instance != Player.m_localPlayer) return;
if (BuildScale.AltHeld() && BuildScale.EntryFor(__instance.RightItem) != null)
{
___m_placeRotation = __state;
___m_scrollCurrAmount = 0f;
}
BuildScale.UpdateLabel(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The "Alt: Size" row in the build hints, next to vanilla's "Rotate": a copy of that row (the
/// wheel icon and its text), shown only while one of the two hammers is in hand. Added beside the
/// vanilla rows rather than through Jotunn's key hints, which replace the whole bar for an item.
/// </summary>
[HarmonyPatch(typeof(KeyHints), "UpdateHints")]
public static class BuildScaleKeyHintPatch
{
private static GameObject s_row;
private static bool s_failed;
private static void Postfix(KeyHints __instance)
{
if (s_row == null && !s_failed) s_row = MakeRow(__instance);
if (s_row == null) return;
Player player = Player.m_localPlayer;
bool show = player != null && BuildScale.EntryFor(player.RightItem) != null;
if (s_row.activeSelf != show) s_row.SetActive(show);
}
private static GameObject MakeRow(KeyHints hints)
{
Transform rotate = hints.m_buildHints != null ? FindDeep(hints.m_buildHints.transform, "rotate") : null;
TMP_Text source = rotate != null ? rotate.Find("Text")?.GetComponent<TMP_Text>() : null;
if (source == null)
{
s_failed = true;
Jotunn.Logger.LogWarning("[BuildScale] No rotate row in the build hints; the Alt: Size hint is not shown.");
return null;
}
GameObject row = Object.Instantiate(rotate.gameObject, rotate.parent, false);
row.name = "RoV_scale";
row.transform.SetSiblingIndex(rotate.GetSiblingIndex() + 1);
row.transform.Find("Text").GetComponent<TMP_Text>().text = ModText.Get("rov_hint_build_scale");
return row;
}
private static Transform FindDeep(Transform parent, string name)
{
foreach (Transform child in parent)
{
if (child.name == name) return child;
Transform found = FindDeep(child, name);
if (found != null) return found;
}
return null;
}
}
}

View file

@ -0,0 +1,33 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The Shrink Hammer's one number: the size it builds at, from a quarter of the vanilla piece up
/// to the vanilla size. Bigger than vanilla is Trol's Hammer's job. Alt + scroll with the hammer
/// in hand writes this same entry (BuildScale), so the slider in Configuration Manager and the
/// wheel always agree, and the size survives a restart.
/// </summary>
public static class ShrinkHammerConfig
{
public static ConfigEntry<float> ScaleFactor;
public static void Bind(ConfigFile config)
{
ScaleFactor = config.Bind("Shrink Hammer", "Scale factor", 1f,
new ConfigDescription("The size of the pieces the Shrink Hammer builds, against the " +
"vanilla piece: 1 is vanilla size, 0.25 a quarter. Hold Alt and " +
"scroll in build mode to change it in steps of 0.05. Cost and " +
"drop never change. A ship keeps its physics at any size.",
new AcceptableValueRange<float>(0.25f, 1f)));
}
/// <summary>The multiplier a new placement should use; 1 for a value typed into the .cfg
/// file that would make a piece too small to see, hit or remove.</summary>
public static float ActiveFactor()
{
if (ScaleFactor == null) return 1f;
return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
}
}
}

View file

@ -0,0 +1,77 @@
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Shrink Hammer: the builder's hammer for small work, down to a quarter of the vanilla size.
/// Any race can craft it. Built the same way as <see cref="TrolsHammerItem"/>: a clone of the
/// vanilla Hammer that keeps the vanilla piece table, so every piece, including those other mods
/// add, is in its menu at the same cost. The size lives on the placement (TrolsHammerPatches,
/// BuildScale), never on the piece prefabs.
/// </summary>
public static class ShrinkHammerItem
{
public const string PrefabName = "ShrinkHammer";
public const string DisplayName = "$rov_item_shrinkhammer_name";
private const string SourcePrefab = "Hammer";
private const string Label = "ShrinkHammer";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "$rov_item_shrinkhammer_desc";
Sprite icon = HammerIcon.Load("ShrinkHammer_icon.png");
if (icon != null) shared.m_icons = new[] { icon };
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Workbench,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig("FineWood", 2, 0, true),
new RequirementConfig("Resin", 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
}
/// <summary>Whether an item in hand is this hammer; the display name is the fallback for an
/// ItemData built before ObjectDB finished, as in TrolsHammerItem.</summary>
public static bool IsShrinkHammer(ItemDrop.ItemData item)
{
if (item == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
return item.m_shared != null && item.m_shared.m_name == DisplayName;
}
}
/// <summary>The two hammers' own icons, painted offline (scripts/paint_hammer_icons.py) and
/// embedded in the DLL.</summary>
internal static class HammerIcon
{
public static Sprite Load(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

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Rot Seed",
"rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.",
"rov_item_trol_giantslog_name": "Giant's Log",
"rov_item_trolshammer_desc": "A hammer swung by something that never had to duck through a doorway. It builds everything the ordinary one builds, out of the same materials, and simply builds it bigger.",
"rov_item_trolshammer_desc": "A hammer swung by something that never had to duck through a doorway. It builds everything the ordinary one builds, out of the same materials, and simply builds it bigger. Hold Alt and scroll to choose how much bigger.",
"rov_item_trolshammer_name": "Trol's Hammer",
"rov_item_shrinkhammer_name": "Shrink Hammer",
"rov_item_shrinkhammer_desc": "A fine hammer for small work. It builds everything the ordinary one builds, out of the same materials, down to a quarter of the size. Hold Alt and scroll to choose the size.",
"rov_item_warvulture_desc": "A vulture's head, kept. Raise it and the bird comes back under you, and it will carry you as long as you care to stay up - though it only has so much haste in it before it settles into a glide.",
"rov_item_warvulture_name": "War Vulture",
"rov_piece_aswid_bloodrefinery_desc": "Flesh goes in, bone goes in, and what is left of both comes out red.",

View file

@ -241,5 +241,7 @@
"rov_msg_alfar_nexus_no_store": "The nucleus has nothing to offer right now.",
"rov_msg_alfar_drone_sort_nowhere": "I have nowhere to put $1. Give me an empty chest, or one that already holds $1.",
"rov_msg_alfar_drone_sort_keep": "I leave $1 in the $2: a station here works with it.",
"rov_msg_alfar_drone_kiln_wood": "The $4 is idle. I only burn wood from the $3, and the $1 is in another chest."
"rov_msg_alfar_drone_kiln_wood": "The $4 is idle. I only burn wood from the $3, and the $1 is in another chest.",
"rov_msg_build_scale": "Size $1",
"rov_hint_build_scale": "Alt: Size"
}

View file

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Seme marcio",
"rov_item_trol_giantslog_desc": "Un enorme tronco d'albero brandito come arma.",
"rov_item_trol_giantslog_name": "Tronco del gigante",
"rov_item_trolshammer_desc": "Un martello brandito da qualcosa che non ha mai dovuto chinarsi sotto una porta. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, e lo fa semplicemente più grande.",
"rov_item_trolshammer_desc": "Un martello brandito da qualcosa che non ha mai dovuto chinarsi sotto una porta. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, e lo fa semplicemente più grande. Tieni premuto Alt e usa la rotellina per scegliere quanto.",
"rov_item_trolshammer_name": "Martello del Trol",
"rov_item_shrinkhammer_name": "Martello Riduttore",
"rov_item_shrinkhammer_desc": "Un martello fine per i lavori piccoli. Costruisce tutto ciò che costruisce quello normale, con gli stessi materiali, fino a un quarto della grandezza. Tieni premuto Alt e usa la rotellina per sceglierla.",
"rov_item_warvulture_desc": "La testa di un avvoltoio, conservata. Sollevala e l'uccello torna sotto di te, e ti porterà finché vorrai restare in aria, anche se ha solo un po' di slancio prima di mettersi a planare.",
"rov_item_warvulture_name": "Avvoltoio da guerra",
"rov_piece_aswid_bloodrefinery_desc": "Entra carne, entra osso, e quel che resta di entrambi esce rosso.",

View file

@ -241,5 +241,7 @@
"rov_msg_alfar_nexus_no_store": "Il nucleo non ha niente da offrire adesso.",
"rov_msg_alfar_drone_sort_nowhere": "Non so dove mettere $1. Dammi una cassa vuota, o una che contenga già $1.",
"rov_msg_alfar_drone_sort_keep": "Lascio $1 nella $2: una stazione qui lo usa.",
"rov_msg_alfar_drone_kiln_wood": "$4 è fermo. Brucio solo la legna della $3, e $1 è in un'altra cassa."
"rov_msg_alfar_drone_kiln_wood": "$4 è fermo. Brucio solo la legna della $3, e $1 è in un'altra cassa.",
"rov_msg_build_scale": "Grandezza $1",
"rov_hint_build_scale": "Alt: Grandezza"
}

View file

@ -81,8 +81,10 @@
"rov_item_trenta_rotseed_name": "Семя гнили",
"rov_item_trol_giantslog_desc": "Исполинский ствол векового дерева, используемый как сокрушительное оружие.",
"rov_item_trol_giantslog_name": "Бревно великана",
"rov_item_trolshammer_desc": "Молот, которым размахивает тот, кому никогда не приходилось пригибаться в дверях. Возводит те же постройки, что и обычный молот, из тех же материалов, но с истинным тролльим размахом.",
"rov_item_trolshammer_desc": "Молот, которым размахивает тот, кому никогда не приходилось пригибаться в дверях. Возводит те же постройки, что и обычный молот, из тех же материалов, но с истинным тролльим размахом. Зажмите Alt и крутите колесо мыши, чтобы выбрать, насколько.",
"rov_item_trolshammer_name": "Молот тролля",
"rov_item_shrinkhammer_name": "Молот-уменьшитель",
"rov_item_shrinkhammer_desc": "Тонкий молот для мелкой работы. Возводит те же постройки, что и обычный молот, из тех же материалов, вплоть до четверти размера. Зажмите Alt и крутите колесо мыши, чтобы выбрать размер.",
"rov_item_warvulture_desc": "Высушенная голова стервятника. Поднимите ее — и птица опустится вам под ноги, неся вас вперед, пока вам не надоест (хотя силы для рывка у нее быстро сменяются плавным парением).",
"rov_item_warvulture_name": "Боевой стервятник",
"rov_piece_aswid_bloodrefinery_desc": "Загрузите плоть, бросьте кости — и то, что от них останется, выйдет алым соком.",

View file

@ -241,5 +241,7 @@
"rov_msg_alfar_nexus_no_store": "У ядра сейчас нечего предложить.",
"rov_msg_alfar_drone_sort_nowhere": "Мне некуда положить $1. Дай мне пустой сундук или тот, где уже лежит $1.",
"rov_msg_alfar_drone_sort_keep": "Оставляю $1 в «$2»: с этим работает станция здесь.",
"rov_msg_alfar_drone_kiln_wood": "«$4» простаивает. Я жгу только дрова из «$3», а $1 лежит в другом сундуке."
"rov_msg_alfar_drone_kiln_wood": "«$4» простаивает. Я жгу только дрова из «$3», а $1 лежит в другом сундуке.",
"rov_msg_build_scale": "Размер $1",
"rov_hint_build_scale": "Alt: размер"
}

View file

@ -28,9 +28,11 @@ namespace RacesOfValheim
"Switching this off leaves every piece already built at the size " +
"it was built at; only new placements are affected."));
// Smaller than vanilla is the Shrink Hammer's job, so this one starts at 1.
ScaleFactor = config.Bind(section, "Scale factor", 1.2f,
new ConfigDescription("How much bigger than the vanilla piece. 1.2 is the +20% the " +
"hammer exists for. Cost and drop never change - this is size " +
"hammer exists for. Hold Alt and scroll in build mode to change " +
"it in steps of 0.05. Cost and drop never change - this is size " +
"only.", new AcceptableValueRange<float>(1f, 3f)));
}

View file

@ -52,6 +52,9 @@ namespace RacesOfValheim
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "$rov_item_trolshammer_desc";
// A blue-steel head and a troll's trophy, so it cannot pass for the vanilla hammer.
Sprite icon = HammerIcon.Load("TrolsHammer_icon.png");
if (icon != null) shared.m_icons = new[] { icon };
if (shared.m_buildPieces == null)
{

View file

@ -110,9 +110,7 @@ namespace RacesOfValheim
if (ghost != m_tracked) Adopt(ghost);
float desired = TrolsHammerItem.IsTrolsHammer(player.RightItem)
? TrolsHammerConfig.ActiveFactor()
: 1f;
float desired = BuildScale.For(player.RightItem);
if (Mathf.Approximately(desired, m_applied)) return;
@ -158,9 +156,8 @@ namespace RacesOfValheim
private static void Prefix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
float factor = TrolsHammerConfig.ActiveFactor();
// Trol's Hammer or the Shrink Hammer; any other tool builds at 1 and leaves here.
float factor = BuildScale.For(__instance.RightItem);
if (Mathf.Approximately(factor, 1f)) return;
TrolsHammerScaling.Placing = true;

View file

@ -435,7 +435,19 @@ A builder's hammer swung by something that never had to duck through a doorway.
- **Both hammers work in the same house.** The ordinary hammer still builds at normal size, and either one repairs or removes anything. Big pieces snap to big pieces, since their snap points grow with them.
- **It sticks.** The size is saved with the piece, so it survives a reload, and other players see the same building you do (they need the mod installed).
The size is a slider in Configuration Manager under `Trols Hammer`. Turning the hammer off there only stops new placements from growing — anything already standing keeps the size it was built at.
**Choosing the size:** hold **Alt** and scroll in build mode, in steps of 0.05, from 1 to 3. The bottom bar shows the hint, and the size floats over the preview whenever it is not the usual 1.2. The same size is a slider in Configuration Manager under `Trols Hammer`. Turning the hammer off there only stops new placements from growing — anything already standing keeps the size it was built at.
---
## Shrink Hammer (Building, Down to a Quarter)
A fine hammer for small work: a little drakkar on a shelf, a table for the shelf.
- **Craft:** 2 Fine Wood, 2 Resin, at a Workbench. Any race may make one.
- **Builds exactly what the ordinary hammer builds**, from the same build menu, at the same cost, with the same drop.
- **From a quarter of the size up to vanilla size.** Hold **Alt** and scroll in build mode to change it in steps of 0.05; the size floats over the preview whenever it is not 1. The same size is a slider in Configuration Manager under `Shrink Hammer`.
- **It sticks**, like Trol's Hammer's: the size is saved with the piece. A ship built small keeps its boat physics.
- **Reading a size:** with either sizing hammer, select the repair tool and aim at a piece; the size it was built at floats over it.
---

View file

@ -0,0 +1,54 @@
"""Paint the two sizing hammers' icons from the vanilla hammer's, so neither can pass for it in a
hotbar: Trol's Hammer gets a blue-steel head and a troll trophy, the Shrink Hammer a brass head and a
shrink badge (four arrows pointing in at a small square, the usual sign for making smaller).
Usage: py -3.14 -I paint_hammer_icons.py <pylib> <icons dir>
<icons dir> holds hammer.png and TrophyForestTroll.png (Sprites "hammer" and "TrophyForestTroll"
from bundle 6a33a62). Writes TrolsHammer_icon.png and ShrinkHammer_icon.png there; copy them to
JotunnModStub/Assets/Hammers/."""
import sys, os, math
sys.path.insert(0, sys.argv[1])
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
d = sys.argv[2]
S = 128 # twice the vanilla icon, for sharper badges
def hammer_with_head(tint, lift):
hammer = Image.open(os.path.join(d, "hammer.png")).convert("RGBA").resize((S, S), Image.LANCZOS)
a = np.asarray(hammer, dtype=np.float32)/255
# the head: a rotated block in the upper part, its corners read off the 64 px sprite
head = Image.new("L", (S, S), 0)
ImageDraw.Draw(head).polygon([(x*2, y*2) for x, y in [(21,1), (57,13), (52,31), (16,19)]], fill=255)
head = np.asarray(head.filter(ImageFilter.GaussianBlur(1)), dtype=np.float32)/255
lum = a[...,:3] @ np.array([0.3, 0.55, 0.15])
metal = np.clip(lum[...,None]*np.array(tint) + np.array(lift), 0, 1)
a[...,:3] = a[...,:3]*(1 - head[...,None]) + metal*head[...,None]
return Image.fromarray((a*255).astype(np.uint8), "RGBA")
def with_rim(badge):
"""A dark rim around a badge, so it reads on any slot colour."""
rim = Image.new("RGBA", badge.size, (10, 10, 10, 0))
rim.putalpha(badge.split()[3].filter(ImageFilter.MaxFilter(5)).point(lambda v: min(v, 200)))
rim.alpha_composite(badge)
return rim
# Trol's Hammer
icon = hammer_with_head((1.05, 1.35, 1.9), (0.02, 0.05, 0.1))
trophy = Image.open(os.path.join(d, "TrophyForestTroll.png")).convert("RGBA").resize((60, 60), Image.LANCZOS)
icon.alpha_composite(with_rim(trophy), (S - 62, S - 62))
icon.save(os.path.join(d, "TrolsHammer_icon.png"))
# the Shrink Hammer
icon = hammer_with_head((1.9, 1.5, 0.75), (0.06, 0.04, 0.0))
B = 56
badge = Image.new("RGBA", (B, B), (0, 0, 0, 0))
g = ImageDraw.Draw(badge)
white = (240, 240, 235, 255)
c = B // 2
g.rectangle([c - 7, c - 7, c + 7, c + 7], fill=white) # the piece, made small
for dx, dy in ((-1, -1), (1, -1), (-1, 1), (1, 1)): # and the arrows closing in on it
start, tip = (c + dx*25, c + dy*25), (c + dx*11, c + dy*11)
g.line([start, tip], fill=white, width=3)
a = math.atan2(tip[1] - start[1], tip[0] - start[0])
g.polygon([tip] + [(tip[0] - 10*math.cos(a + s), tip[1] - 10*math.sin(a + s)) for s in (-0.5, 0.5)], fill=white)
icon.alpha_composite(with_rim(badge), (S - B - 4, S - B - 4))
icon.save(os.path.join(d, "ShrinkHammer_icon.png"))