feat: Shrink Hammer, and Alt + scroll to size pieces with both hammers

A player asked to build below vanilla size for small details. The new
Shrink Hammer, craftable by any race, builds from 0.25 to 1; Trol's Hammer
keeps 1 to 3. With either hammer, Alt + scroll in build mode changes the
size in steps of 0.05, an Alt: Size row joins the build hints, and the size
floats over the ghost when it is not the default. With the repair tool, the
aimed piece shows the size it was built at. Both hammers get icons of their
own.
This commit is contained in:
kanym 2026-10-30 22:49:27 +01:00
commit 0d1f655598
17 changed files with 414 additions and 14 deletions

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));
}
}
}