RacesOfValheim/JotunnModStub/Alfar/AlfarConstructs.cs
Ferdinando 3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00

397 lines
19 KiB
C#

using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5):
///
/// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower
/// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus
/// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s
///
/// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks:
/// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings,
/// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them
/// the follow and stay orders every other race's troops already have.
///
/// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's
/// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own
/// slow vanilla regeneration is switched off too.
/// </summary>
public static class AlfarConstructs
{
public const string Neistvordr = "AlfarNeistvordr";
public const string Steinvordr = "AlfarSteinvordr";
public const string Eldingvordr = "AlfarEldingvordr";
public const string SphereProjectile = "AlfarLightningSphere";
public const string SphereWeapon = "AlfarSphereAttack";
public class Kind
{
public string PrefabName;
public string Display;
public string Source;
public float Health; // 0 = keep the vanilla creature's
public float HealthFactor; // applied after Health when Health is 0
public float Scale; // 1 = the vanilla size
}
public static readonly Kind[] Roster =
{
new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f },
new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f },
new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f },
};
public static Kind Find(string prefabName)
{
foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind;
return null;
}
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
// The sphere first: the Eldingvordr's weapon needs it.
bool sphere = RegisterSphere();
foreach (Kind kind in Roster)
{
if (kind.PrefabName == Eldingvordr && !sphere)
{
Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee.");
}
RegisterOne(kind, sphere);
}
}
private static void RegisterOne(Kind kind, bool sphere)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(kind.Source);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = kind.Display;
character.m_faction = Character.Faction.Players;
if (kind.Health > 0f) character.m_health = kind.Health;
else character.m_health *= kind.HealthFactor;
// The damage to the body is permanent: no slow regeneration either.
character.m_regenAllHPTime = 0f;
}
if (!Mathf.Approximately(kind.Scale, 1f))
{
prefab.transform.localScale = Vector3.one * kind.Scale;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value;
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
// The vanilla creatures attack player-built objects. Ours never touch a building.
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value;
}
// A construct that dropped Coal, a Surtling core or a trophy would be a loot farm.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab);
if (kind.PrefabName == Neistvordr) BlueFlames(prefab);
else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "construct";
// What a destroyed construct gives back: the METAL it was built from, and nothing else - the
// crystals and the refined eitr are spent for good (design sec. 8.5).
AlfarRefund refund = prefab.AddComponent<AlfarRefund>();
refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal";
refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value
: kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value
: AlfarNexusConfig.SteinMetal.Value;
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = character != null ? character.m_health : 0f;
shield.Shield = shield.MaxShield;
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind.PrefabName;
thrall.m_commandingRace = AlfarConfig.RaceId;
thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus
thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value;
thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value;
thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar";
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'.");
}
// ─── The lightning sphere ────────────────────────────────────────────
/// <summary>
/// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never
/// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the
/// clean base the probe found: an area burst and NO lingering effect spawned on impact (the
/// fire one drops a fire field and also spawns on buildings).
/// </summary>
private static bool RegisterSphere()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("DvergerStaffIce_projectile");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere.");
return false;
}
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source);
if (projectile == null) return false;
Projectile settings = projectile.GetComponent<Projectile>();
if (settings == null) return false;
settings.m_gravity = 0f;
settings.m_ttl = 4f;
settings.m_aoe = 3f;
settings.m_aoeSkipWearNTear = true;
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_hitOwner = false;
settings.m_statusEffect = "";
Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f));
PrefabManager.Instance.AddPrefab(projectile);
// The weapon that fires it: the Surtling's own fireball weapon, because a creature that
// shoots needs an item with a projectile attack, and that is the one that exists.
GameObject surtling = PrefabManager.Cache.GetPrefab<GameObject>("Surtling");
Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent<Humanoid>() : null;
GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null &&
surtlingHumanoid.m_defaultItems.Length > 0
? surtlingHumanoid.m_defaultItems[0]
: null;
if (fireball == null)
{
Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon.");
return false;
}
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_sphere_name";
// One shot every eight seconds (design): the AI waits this long between uses.
shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value;
shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value;
shared.m_aiAttackRangeMin = 4f;
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.SphereDamage.Value;
shared.m_damages = damage;
if (shared.m_attack != null)
{
shared.m_attack.m_attackProjectile = projectile;
// The Abomination's right hand: where the sphere leaves from.
shared.m_attack.m_attackOriginJoint = "r.hand";
}
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void GiveSphereWeapon(GameObject prefab)
{
Humanoid humanoid = prefab.GetComponent<Humanoid>();
GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon);
if (humanoid == null || weapon == null) return;
humanoid.m_defaultItems = new[] { weapon };
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
// ─── Colour ──────────────────────────────────────────────────────────
/// <summary>
/// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or
/// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5).
/// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is
/// still to do (test file, phase 6).
/// </summary>
public static void Tint(GameObject prefab, Color color)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue;
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = color;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", color * 0.08f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = color;
}
/// <summary>
/// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY
/// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn
/// the red ones off, and recolour the glow of the body and the point light.
/// </summary>
private static void BlueFlames(GameObject prefab)
{
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true);
else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple")
{
child.gameObject.SetActive(false);
}
}
Color blue = new Color(0.25f, 0.55f, 1f, 1f);
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = blue;
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material != null && material.HasProperty("_EmissionColor"))
{
// The vanilla emission is white-hot (73): keep the strength, change the hue.
material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f);
}
}
renderer.materials = materials;
}
}
// ─── Counting and spawning (called by the Nexus) ─────────────────────
/// <summary>
/// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH:
/// a zone unloading destroys the object too and must not pay anyone (the same rule as the
/// Butler's payload).
/// </summary>
public class AlfarRefund : MonoBehaviour
{
public string Item = "";
public int Amount;
}
[HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")]
public static class Alfar_Refund_Patch
{
public static void Postfix(Character __instance)
{
AlfarRefund refund = __instance != null ? __instance.GetComponent<AlfarRefund>() : null;
if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item);
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (template == null || template.m_itemData == null) return;
int left = refund.Amount;
int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize);
Vector3 at = __instance.transform.position + Vector3.up * 0.5f;
while (left > 0)
{
int stack = Mathf.Min(left, max);
ItemDrop.ItemData clone = template.m_itemData.Clone();
clone.m_dropPrefab = prefab;
ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
left -= stack;
}
refund.Amount = 0; // once only
}
}
public static int CountAlive(Vector3 anchor, string prefabName)
{
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor))
{
if (thrall != null && thrall.Kind == prefabName) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor, string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built.");
return false;
}
Vector3 where = SpawnSpot(anchor);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
RaisedThrall thrall = spawned != null ? spawned.GetComponent<RaisedThrall>() : null;
if (thrall != null) thrall.Bind(anchor);
return spawned != null;
}
/// <summary>A free spot on a ring around the Nexus, on the ground, or due south as a last resort.</summary>
public static Vector3 SpawnSpot(Vector3 centre)
{
const float radius = 3.5f;
int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle");
float start = Random.Range(0f, 360f);
for (int i = 0; i < 12; i++)
{
float angle = (start + i * 30f) * Mathf.Deg2Rad;
Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate);
if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue;
return candidate + Vector3.up * 0.3f;
}
Vector3 fallback = centre + new Vector3(0f, 0f, -radius);
if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback);
return fallback + Vector3.up * 0.3f;
}
}
}