Merge branch 'localisation' into localisation-turkish

This commit is contained in:
kanym 2026-10-28 13:57:24 +01:00
commit fcdea70ee1
24 changed files with 942 additions and 13 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 340 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 441 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

View file

@ -218,6 +218,7 @@ namespace RacesOfValheim
}
prefab.transform.localScale = Vector3.one * TableScale;
Dress(prefab, family);
ServantTableBehaviour table = prefab.AddComponent<ServantTableBehaviour>();
table.m_switch = prefab.AddComponent<Switch>();
@ -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;
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
private static void LayCover(GameObject prefab, string set, bool metal)
{
var cover = new System.Collections.Generic.Dictionary<string, Texture>();
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<string, Texture> 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;

View file

@ -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;
}
/// <summary>

View file

@ -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<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))

View file

@ -36,10 +36,13 @@ namespace RacesOfValheim
/// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes.
/// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres,
/// measured AFTER <paramref name="localRotation"/> has been applied.
/// <paramref name="activeOnly"/> 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.
/// </summary>
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<GameObject>(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);
}
/// <summary>
@ -66,7 +69,7 @@ namespace RacesOfValheim
/// </summary>
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<Transform>(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);

View file

@ -1,7 +1,7 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds eleven custom playable races (Alfar, Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.",
"version_number": "1.6.2",
"version_number": "1.6.3",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",

197
JotunnModStub/PieceLook.cs Normal file
View file

@ -0,0 +1,197 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class PieceLook
{
/// <summary>
/// Multiplies the base colour of every mesh under <paramref name="root"/>, inactive ones included
/// (a piece's worn and broken meshes are switched off until it takes damage). Particles are left
/// alone: that is what <see cref="Rehue"/> is for.
/// </summary>
public static void Tint(Transform root, Color tint)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(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;
}
}
/// <summary>
/// Swaps the hue of everything under <paramref name="root"/> that GLOWS - lights, particles and
/// any material with emission - for <paramref name="glow"/>, 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.
/// </summary>
public static void Rehue(Transform root, Color glow)
{
if (root == null) return;
foreach (Light light in root.GetComponentsInChildren<Light>(true))
{
if (light != null) light.color = glow;
}
foreach (ParticleSystem ps in root.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps == null) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(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;
}
}
/// <summary>
/// Swaps textures by the name of the texture they replace: every material under
/// <paramref name="root"/> that uses "Cartographer_d" gets <paramref name="replacements"/>'s
/// "Cartographer_d" instead, whichever slot it sits in. Materials are copied as in Tint.
/// </summary>
public static void Retexture(Transform root, IDictionary<string, Texture> replacements)
{
if (root == null) return;
var copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(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;
}
}
/// <summary>
/// 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.
/// </summary>
private static readonly System.Reflection.MethodInfo LoadImage =
System.Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")
?.GetMethod("LoadImage", new[] { typeof(Texture2D), typeof(byte[]), typeof(bool) });
/// <summary>
/// A PNG embedded in the DLL (see the csproj's EmbeddedResource), or null with a warning.
/// <paramref name="linear"/> for anything that is data rather than colour - a normal map read
/// as sRGB comes out bent.
/// </summary>
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<Material, Material> 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;
}
}
}

View file

@ -44,6 +44,8 @@ namespace RacesOfValheim
prefab.AddComponent<RaceMenuWardBehavior>();
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
/// <summary>Seidr blue in place of the Ward's hearth orange: every race builds this, so no race's colour.</summary>
private static readonly Color Glow = new Color(0.55f, 0.62f, 1f, 1f);
/// <summary>A colder stone, so it reads as a different thing from the vanilla Ward across a base.</summary>
private static readonly Color StoneTint = new Color(0.78f, 0.82f, 0.92f, 1f);
/// <summary>Narrower and taller than the Ward, on a plinth: a statue rather than a waystone.</summary>
private static readonly Vector3 StatueShape = new Vector3(0.9f, 1.12f, 0.9f);
private const float PlinthWidth = 1.3f;
/// <summary>
/// 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.
/// </summary>
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";

View file

@ -16,7 +16,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.6.2";
public const string PluginVersion = "1.6.3";
private readonly Harmony harmony = new Harmony(PluginGUID);
@ -89,6 +89,7 @@ namespace RacesOfValheim
CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand());
CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand());
CommandManager.Instance.AddConsoleCommand(new TrolPoseCommand());
CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand());
}

View file

@ -53,6 +53,12 @@
<Reference Include="System.Xml" />
</ItemGroup>
<!-- Textures painted offline (scripts/paint_cook_cloth.py), carried inside the DLL so a mod
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
<ItemGroup>
<EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />

View file

@ -0,0 +1,112 @@
using System.Globalization;
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// [DEBUG] Tries troll states as the True Form guard and roll, live, until the right frame is
/// found and baked into TrolTrueFormModel. Nothing is saved: a restart goes back to the defaults.
/// </summary>
public class TrolPoseCommand : ConsoleCommand
{
// Off troll_animator with scripts/dump_controller.py. Wakeup? and the AnyState entries left
// out: an entry check and transitions, not poses.
private static readonly string[] States =
{
"Movement", "attack", "jump", "punch", "throw", "swing log V", "swing log H",
"Stagger", "Summon", "Sleeping", "Wakeup", "In Water",
};
public override string Name => "trolpose";
public override string Help =>
"[DEBUG] trolpose guard <state> [0-1] - the frame True Form holds while blocking. " +
"trolpose play <state> - plays a state whole on your troll. " +
"trolpose dodge <state|off> [speed] - the state played when you roll, and how fast. trolpose - lists states and current values.";
public override void Run(string[] args)
{
if (args.Length == 0)
{
Print($"guard: '{TrolTrueFormModel.GuardState}' at {TrolTrueFormModel.GuardTime:0.00}, " +
$"dodge: '{TrolTrueFormModel.DodgeState ?? "off"}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}");
Print("states: " + string.Join(", ", States));
return;
}
string verb = args[0].ToLowerInvariant();
float time = -1f;
int nameEnd = args.Length;
// The trailing number: the frame for guard, the speed for dodge.
if ((verb == "guard" || verb == "dodge") && args.Length > 2 &&
float.TryParse(args[args.Length - 1], NumberStyles.Float, CultureInfo.InvariantCulture, out float number))
{
time = number;
nameEnd--;
}
string typed = string.Join(" ", args, 1, Mathf.Max(0, nameEnd - 1));
if (verb == "dodge" && typed.ToLowerInvariant() == "off")
{
TrolTrueFormModel.DodgeState = null;
Print("dodge: off");
return;
}
string state = Match(typed);
if (state == null)
{
Print($"unknown state '{typed}'. states: " + string.Join(", ", States));
return;
}
switch (verb)
{
case "guard":
TrolTrueFormModel.GuardState = state;
if (time >= 0f) TrolTrueFormModel.GuardTime = Mathf.Clamp01(time);
Print($"guard: '{state}' at {TrolTrueFormModel.GuardTime:0.00}. Hold right click in True Form to see it.");
break;
case "dodge":
TrolTrueFormModel.DodgeState = state;
if (time > 0f) TrolTrueFormModel.DodgeSpeed = Mathf.Clamp(time, 0.25f, 5f);
Print($"dodge: '{state}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}. Block and jump in True Form to roll.");
break;
case "play":
Animator anim = TrolTrueFormModel.LocalAnimator;
if (anim == null)
{
Print("play needs True Form on (not Legacy).");
return;
}
anim.speed = 1f;
anim.CrossFadeInFixedTime("Base Layer." + state, 0.1f, 0, 0f);
Print($"playing '{state}'.");
break;
default:
Print(Help);
break;
}
}
private static string Match(string typed)
{
foreach (string s in States)
{
if (string.Equals(s, typed, System.StringComparison.OrdinalIgnoreCase)) return s;
}
return null;
}
private static void Print(string line)
{
Jotunn.Logger.LogInfo("[Trol] trolpose " + line);
if (Console.instance != null) Console.instance.Print(line);
}
}
}

View file

@ -27,6 +27,9 @@ namespace RacesOfValheim
private bool isAttacking;
private float busySince = -1f;
private bool guarding;
private bool dodging;
private readonly TrolGuardPose guardPose = new TrolGuardPose();
private GameObject heldLog;
private string heldLogName;
@ -42,6 +45,8 @@ namespace RacesOfValheim
private void OnDestroy()
{
TrolTrueFormModel.LocalAttacking = false;
TrolTrueFormModel.EndDodge();
if (guarding && Player.m_localPlayer != null) TrolTrueFormModel.PublishGuard(Player.m_localPlayer, false);
}
private void Start()
@ -84,22 +89,60 @@ namespace RacesOfValheim
SetAttacking(false);
}
// The guard: right click blocks, as it does for the human underneath, and the troll
// holds a pose for it. A roll out of the guard drops it, so the roll is not hidden
// behind a frozen troll.
bool guard = !isAttacking && !player.IsDead() && player.IsBlocking() && !player.InDodge();
TrolTrueFormModel.TickDodge();
if (guard) TrolTrueFormModel.EndDodge();
Guard(player, guard);
if (isAttacking || player.IsDead()) return;
bool grounded = locomotion.Mirror(anim, playerAnim, player);
if (guard) return;
if (player.InDodge())
{
if (!dodging) TrolTrueFormModel.PlayDodge(anim);
dodging = true;
return;
}
dodging = false;
if (!grounded || !RaceInput.Allowed) return;
// Left punches, middle slams: the vanilla primary and secondary attack. Right click is
// the block, so the slam no longer goes off every time the troll raises its guard.
bool log = heldLogName != null;
if (RaceInput.AttackDown(0))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch);
}
else if (RaceInput.AttackDown(1))
else if (RaceInput.AttackDown(2))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam);
}
}
/// <summary>Holds the guard pose while blocking and lets go after, and tells every other
/// client which pose to hold.</summary>
private void Guard(Player player, bool on)
{
if (on)
{
guardPose.Hold(anim, TrolTrueFormModel.GuardState, TrolTrueFormModel.GuardTime);
TrolTrueFormModel.PublishGuard(player, true);
guarding = true;
}
else if (guarding)
{
guardPose.Release(anim);
TrolTrueFormModel.PublishGuard(player, false);
guarding = false;
}
}
private void Play(TrolTrueFormModel.AttackKind kind)
{
TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind);
@ -406,6 +449,8 @@ namespace RacesOfValheim
private Animator playerAnim;
private ZNetView nview;
private string lastAttack;
private bool guarding;
private readonly TrolGuardPose guardPose = new TrolGuardPose();
private readonly FormLocomotion locomotion = new FormLocomotion();
private GameObject heldLog;
@ -438,6 +483,17 @@ namespace RacesOfValheim
ReplayAttack();
locomotion.Mirror(anim, playerAnim, player);
if (TrolTrueFormModel.ReadGuard(nview.GetZDO(), out string guardState, out float guardTime))
{
guardPose.Hold(anim, guardState, guardTime);
guarding = true;
}
else if (guarding)
{
guardPose.Release(anim);
guarding = false;
}
}
private void ReplayAttack()

View file

@ -79,6 +79,8 @@ namespace RacesOfValheim
public static bool LocalActive => localModel != null;
public static Animator LocalAnimator => localModel != null ? localModel.GetComponentInChildren<Animator>() : null;
/// <summary>True while the local troll is in the middle of a swing, a slam or a throw.
/// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long.</summary>
public static bool LocalAttacking { get; set; }
@ -434,6 +436,105 @@ namespace RacesOfValheim
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq);
}
// ─── Guard and roll poses ────────────────────────────────────────────
// The troll has no block or roll of its own, so the guard is one frame of another state held
// still. State names are read off troll_animator with scripts/dump_controller.py: Movement,
// attack, jump, punch, throw, swing log V, swing log H, Stagger, Summon, Sleeping, Wakeup,
// In Water. Both are settable live with the trolpose command until the right frame is found.
public const string MovementState = "Movement";
// Picked in game with trolpose: the troll half risen out of its Wakeup, arms up.
public static string GuardState = "Wakeup";
public static float GuardTime = 0.13f;
/// <summary>The state played whole when the player rolls; null plays nothing and the troll
/// slides along with the roll.</summary>
public static string DodgeState = "jump";
/// <summary>How fast the roll state plays: the troll's jump runs longer than a roll, so at 1
/// the troll was still leaping after the roll had ended.</summary>
public static float DodgeSpeed = 2f;
// The local troll's Animator while its roll state plays, null otherwise.
// Trol_TrueFormDodgeSpeed_Patch keeps its speed up through every FixedUpdate.
private static Animator dodgeAnimator;
private static float dodgeStarted;
/// <summary>Set while the owner's troll holds its guard, to "state|time", so every other
/// client's copy holds the same frame. Empty when it is not guarding.</summary>
public const string GuardKey = "RacesOfValheim_TrolTrueFormGuard";
public static bool HasState(Animator anim, string state)
{
return anim != null && !string.IsNullOrEmpty(state) && anim.HasState(0, Animator.StringToHash("Base Layer." + state));
}
public static void PlayDodge(Animator anim)
{
if (!HasState(anim, DodgeState)) return;
anim.speed = DodgeSpeed;
anim.CrossFadeInFixedTime("Base Layer." + DodgeState, 0.1f, 0, 0f);
dodgeAnimator = anim;
dodgeStarted = Time.time;
}
/// <summary>
/// Called every frame: keeps the roll state at DodgeSpeed while it plays, and puts the speed
/// back once the troll has left it. The first moments are skipped, because the cross-fade
/// into the state only starts on the Animator's next update.
/// </summary>
public static void TickDodge()
{
if (dodgeAnimator == null) return;
int hash = Animator.StringToHash("Base Layer." + DodgeState);
bool inState = dodgeAnimator.GetCurrentAnimatorStateInfo(0).fullPathHash == hash ||
(dodgeAnimator.IsInTransition(0) && dodgeAnimator.GetNextAnimatorStateInfo(0).fullPathHash == hash);
if (inState || Time.time - dodgeStarted < 0.15f) dodgeAnimator.speed = DodgeSpeed;
else EndDodge();
}
public static void EndDodge()
{
if (dodgeAnimator != null) dodgeAnimator.speed = 1f;
dodgeAnimator = null;
}
/// <summary>The troll's CharacterAnimEvent sets its Animator back to speed 1 in every
/// FixedUpdate; this sets the roll's speed again right after.</summary>
[HarmonyPatch(typeof(CharacterAnimEvent), nameof(CharacterAnimEvent.CustomFixedUpdate))]
public static class Trol_TrueFormDodgeSpeed_Patch
{
public static void Postfix(CharacterAnimEvent __instance)
{
if (dodgeAnimator != null && __instance.gameObject == dodgeAnimator.gameObject) dodgeAnimator.speed = DodgeSpeed;
}
}
public static void PublishGuard(Player player, bool on)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
string value = on ? GuardState + "|" + GuardTime.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
if (nview.GetZDO().GetString(GuardKey, "") != value) nview.GetZDO().Set(GuardKey, value);
}
/// <summary>The pose another client's troll should hold, read back off the owner's ZDO.</summary>
public static bool ReadGuard(ZDO zdo, out string state, out float time)
{
state = null;
time = 0f;
string value = zdo.GetString(GuardKey, "");
int bar = value.LastIndexOf('|');
if (bar <= 0) return false;
state = value.Substring(0, bar);
return float.TryParse(value.Substring(bar + 1), System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out time);
}
/// <summary>
/// The damage a troll attack deals for this player right now: the troll's own numbers, times
/// Troll Attack Damage, times the same random Clubs factor a club would get.
@ -465,6 +566,35 @@ namespace RacesOfValheim
crouch = false;
dodge = false;
}
/// <summary>
/// Rooted while guarding, so the held pose cannot slide across the ground. Cleared after
/// SetControls, not before: the block-and-jump roll takes its direction from the move
/// input inside SetControls, and an input zeroed first sent every roll backwards.
/// </summary>
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer || !LocalActive || LocalAttacking) return;
if (__instance.IsBlocking() && !__instance.InDodge()) MoveDir(__instance) = Vector3.zero;
}
private static readonly AccessTools.FieldRef<Character, Vector3> MoveDir =
AccessTools.FieldRefAccess<Character, Vector3>("m_moveDir");
}
// Share of a normal roll's distance the troll covers. The roll moves by root motion, and
// under True Form two animators feed it: the hidden human's dodge and the troll's jump.
private const float RollDistance = 0.5f;
/// <summary>A shorter roll for the troll: every bit of root motion that reaches the player
/// during a True Form roll is scaled, whichever of the two clips it came from.</summary>
[HarmonyPatch(typeof(Character), nameof(Character.AddRootMotion))]
public static class Trol_TrueFormRollDistance_Patch
{
public static void Prefix(Character __instance, ref Vector3 vel)
{
if (__instance == Player.m_localPlayer && LocalActive && __instance.InDodge()) vel *= RollDistance;
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
@ -502,4 +632,86 @@ namespace RacesOfValheim
}
}
}
/// <summary>
/// Holds one troll at one frame of a state, for the True Form guard. It blends in the way it
/// blends out: a cross-fade into the frame first, then the frame pinned once the fade is over.
/// Pinned again every frame it holds: the troll's own CharacterAnimEvent puts the Animator back
/// to speed 1 in every FixedUpdate, so a speed of 0 set once would not stay.
/// </summary>
internal class TrolGuardPose
{
private const float Fade = 0.2f;
// Each state's length, learned the first time it is held: the fade starts that far ahead of
// the frame, so the state lands on it when the fade ends instead of running past it.
private static readonly Dictionary<int, float> lengths = new Dictionary<int, float>();
private int state;
private float target;
private float fadeStarted;
private bool fading;
private float pinned;
public void Hold(Animator anim, string name, float time)
{
if (!TrolTrueFormModel.HasState(anim, name)) return;
int hash = Animator.StringToHash("Base Layer." + name);
time = Mathf.Clamp01(time);
if (hash != state || time != target)
{
state = hash;
target = time;
StartFade(anim);
}
if (fading)
{
anim.speed = 1f;
if (Time.time - fadeStarted < Fade || anim.IsInTransition(0)) return;
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
if (info.fullPathHash == state && info.length > 0f)
{
lengths[state] = info.length;
pinned = info.normalizedTime < 1f ? info.normalizedTime : target;
}
else
{
pinned = target;
}
fading = false;
}
anim.Play(state, 0, pinned);
anim.speed = 0f;
}
private void StartFade(Animator anim)
{
// CrossFade takes its duration as a share of the state being left, so turn the seconds
// into that share.
float from = anim.GetCurrentAnimatorStateInfo(0).length;
float lead = lengths.TryGetValue(state, out float length) && length > 0f ? Fade / length : 0f;
anim.speed = 1f;
anim.CrossFade(state, from > 0f ? Fade / from : Fade, 0, Mathf.Max(0f, target - lead));
fadeStarted = Time.time;
fading = true;
}
public void Release(Animator anim)
{
state = 0;
fading = false;
if (anim == null) return;
anim.speed = 1f;
if (TrolTrueFormModel.HasState(anim, TrolTrueFormModel.MovementState))
{
anim.CrossFadeInFixedTime("Base Layer." + TrolTrueFormModel.MovementState, Fade, 0);
}
}
}
}