RacesOfValheim/JotunnModStub/Alfar/AlfarTowers.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

239 lines
9.9 KiB
C#

using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The PRISMAVARD, the Alfar's towers (Alfar_Progettazione.txt sec. 8.6): the charred ballista of the
/// Ashlands, smaller and bronze, turned around to defend. Read from the live prefab (doc 16C P5):
///
/// - it is NOT a Piece: it has Turret, WearNTear and DropOnDestroyed and nothing that lets the
/// hammer place it, so a Piece is added here;
/// - it is an ENEMY tower: it targets players and tamed creatures and not enemies, so the three
/// flags are turned round;
/// - m_maxAmmo is 0 and HasAmmo() is true when it is 0 (read in the IL): the vanilla tower has
/// infinite ammunition, so "consumes nothing" is free; what is changed is the AMMO, a bolt that
/// does lightning, so the shot is ours.
///
/// It only works inside a Ljoskjarne's radius (AlfarTower switches the Turret off outside it), has a
/// shield equal to its health that returns by itself, and is repaired with the hammer and by the
/// drones like any building.
/// </summary>
public static class AlfarTowers
{
public const string PieceName = "AlfarPrismavard";
public const string PieceDisplay = "$rov_piece_alfar_prismavard_name";
public const string AmmoName = "AlfarPrismBolt";
public const string ProjectileName = "AlfarPrismProjectile";
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("piece_Charred_Balista");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'piece_Charred_Balista': the Prismavard is not registered.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) return;
Turret turret = prefab.GetComponent<Turret>();
if (turret == null)
{
Jotunn.Logger.LogWarning("[Alfar] The charred ballista has no Turret component: no Prismavard.");
return;
}
// Turned around: it defends the base against enemies and never at players or their tames.
turret.m_targetPlayers = false;
turret.m_targetTamed = false;
turret.m_targetEnemies = true;
turret.m_returnAmmoOnDestroy = false;
// The ammunition: a bolt that does lightning, shot from a projectile that spares friends
// and buildings. m_maxAmmo stays 0, which means infinite.
GameObject ammo = RegisterAmmo(turret);
if (ammo != null)
{
ItemDrop ammoDrop = ammo.GetComponent<ItemDrop>();
turret.m_defaultAmmo = ammoDrop;
if (turret.m_allowedAmmo != null && turret.m_allowedAmmo.Count > 0)
{
var allowed = turret.m_allowedAmmo[0];
allowed.m_ammo = ammoDrop;
turret.m_allowedAmmo[0] = allowed;
}
}
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null) wear.m_health *= AlfarNexusConfig.TowerHealthFactor.Value;
// The loot of an enemy ballista: a tower of ours must not be a way to farm it.
foreach (DropOnDestroyed drop in prefab.GetComponentsInChildren<DropOnDestroyed>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.transform.localScale = Vector3.one * AlfarNexusConfig.TowerScale.Value;
ZNetView nview = prefab.GetComponent<ZNetView>();
if (nview != null) nview.m_syncInitialScale = true;
AlfarConstructs.Tint(prefab, new Color(0.85f, 0.58f, 0.28f, 1f));
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = "tower";
AlfarPieceShield shield = prefab.AddComponent<AlfarPieceShield>();
shield.Max = wear != null ? wear.m_health : 100f;
shield.Shield = shield.Max;
prefab.AddComponent<AlfarTower>();
Sprite icon = AlfarNexus.BorrowIcon("Crystal") ?? AlfarNexus.BorrowIcon("Bronze");
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplay;
piece.m_canBeRemoved = true;
piece.m_icon = icon;
piece.m_groundOnly = false;
piece.m_groundPiece = false;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplay,
Description = "$rov_piece_alfar_prismavard_desc",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
Icon = icon,
Requirements = new[]
{
new RequirementConfig("Bronze", AlfarNexusConfig.TowerBronze.Value, 0, true),
new RequirementConfig("Crystal", AlfarNexusConfig.TowerCrystal.Value, 0, true),
},
}));
// No cap on how many (the user said so), but one rule: inside a Ljoskjarne's radius.
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (!AlfarRace.IsLocalAlfar())
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar"));
return false;
}
if (AlfarNexusBehaviour.Covering(position) == null)
{
if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_tower_needs_nexus"));
return false;
}
return true;
});
AlfarPieces.Extra.Add(PieceName);
}
private static GameObject RegisterAmmo(Turret turret)
{
ItemDrop original = turret.m_defaultAmmo;
if (original == null)
{
Jotunn.Logger.LogWarning("[Alfar] The ballista has no default ammo to copy.");
return null;
}
GameObject ammo = PrefabManager.Instance.CreateClonedPrefab(AmmoName, original.gameObject);
if (ammo == null) return null;
ItemDrop drop = ammo.GetComponent<ItemDrop>();
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_prismbolt_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.TowerDamage.Value;
shared.m_damages = damage;
// The projectile it flies as: a copy that spares friends and buildings.
GameObject originalProjectile = shared.m_attack != null ? shared.m_attack.m_attackProjectile : null;
if (originalProjectile != null)
{
GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(ProjectileName, originalProjectile);
Projectile settings = projectile != null ? projectile.GetComponent<Projectile>() : null;
if (settings != null)
{
settings.m_hitFriendly = false;
settings.m_noDamageFriendly = true;
settings.m_aoeSkipWearNTear = true;
PrefabManager.Instance.AddPrefab(projectile);
shared.m_attack.m_attackProjectile = projectile;
}
}
ItemManager.Instance.AddItem(new CustomItem(ammo, fixReference: false));
return ammo;
}
}
/// <summary>The tower runs only while a Ljoskjarne's radius covers it: outside, the Turret is off.</summary>
public class AlfarTower : MonoBehaviour
{
private Turret turret;
private float nextCheck;
private void Awake() { turret = GetComponent<Turret>(); }
private void Update()
{
if (turret == null || Time.time < nextCheck) return;
nextCheck = Time.time + 2f;
bool powered = AlfarNexusBehaviour.Covering(transform.position) != null;
if (turret.enabled != powered) turret.enabled = powered;
}
}
/// <summary>
/// A building's shield: equal to its health, back at 1% a second after five quiet seconds. Its own
/// absorption on WearNTear.ApplyDamage, the stage every blow on a building ends in; the hammer and
/// the drones repair the HEALTH, the shield returns by itself.
/// </summary>
public class AlfarPieceShield : MonoBehaviour
{
public float Max;
public float Shield;
private float lastHit = -999f;
private void Update()
{
if (Shield >= Max || Time.time - lastHit < 5f) return;
Shield = Mathf.Min(Max, Shield + Max * 0.01f * Time.deltaTime);
}
public float Absorb(float damage)
{
if (damage <= 0f) return damage;
lastHit = Time.time;
float absorbed = Mathf.Min(Shield, damage);
Shield -= absorbed;
return damage - absorbed;
}
[HarmonyPatch(typeof(WearNTear), "ApplyDamage")]
public static class Alfar_PieceShield_Patch
{
public static void Prefix(WearNTear __instance, ref float __0)
{
AlfarPieceShield shield = __instance != null ? __instance.GetComponent<AlfarPieceShield>() : null;
if (shield != null) __0 = shield.Absorb(__0);
}
}
}
}