Merge branch 'fix-ravager-attacks': Ravager attacks follow the Brute's clips, ram lunges, slam digs per claw; War Vulture startup error gone

This commit is contained in:
kanym 2026-10-17 20:28:54 +02:00
commit 7e6d3d0936
6 changed files with 361 additions and 45 deletions

View file

@ -96,10 +96,7 @@ namespace RacesOfValheim
// Everything that is not a Renderer or a Transform. Order matters for the same reason it did
// on the Aswid's lights: behaviours first, then the things they hold references to.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
StripBehaviours(copy, label);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
@ -119,6 +116,67 @@ namespace RacesOfValheim
return holder;
}
/// <summary>
/// Destroys every MonoBehaviour under <paramref name="root"/>, dependents first.
///
/// A single pass in component order is not enough, and the log said so: "Can't remove Humanoid
/// (Script) because CharacterDrop (Script) depends on it". Unity refuses to destroy a component
/// another one still requires through [RequireComponent], so the pass that reached Humanoid
/// before CharacterDrop left a live Humanoid on the Sverm's Ravager costume - on every player
/// wearing it - which is the leftover that once broke the hammer for every piece (see
/// SvermHive.MouthCandidates). Each round here destroys only what nothing remaining requires,
/// and rounds repeat until nothing is left or nothing more can go.
/// </summary>
public static void StripBehaviours(GameObject root, string label)
{
if (root == null) return;
for (int round = 0; round < 16; round++)
{
MonoBehaviour[] left = root.GetComponentsInChildren<MonoBehaviour>(true);
if (left.Length == 0) return;
int destroyed = 0;
foreach (MonoBehaviour behaviour in left)
{
if (behaviour == null || IsRequired(behaviour)) continue;
Object.DestroyImmediate(behaviour);
destroyed++;
}
if (destroyed == 0) break;
}
foreach (MonoBehaviour survivor in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (survivor != null)
{
Jotunn.Logger.LogWarning($"[{label}] '{survivor.GetType().Name}' on '{survivor.name}' could not be stripped from a borrowed model.");
}
}
}
/// <summary>True if another component on the same GameObject names this one's type in a
/// [RequireComponent].</summary>
public static bool IsRequired(Component target)
{
System.Type type = target.GetType();
foreach (Component other in target.GetComponents<Component>())
{
if (other == null || other == target) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent require = (RequireComponent)attribute;
if (Requires(require.m_Type0, type) || Requires(require.m_Type1, type) || Requires(require.m_Type2, type))
{
return true;
}
}
}
return false;
}
private static bool Requires(System.Type required, System.Type type) => required != null && required.IsAssignableFrom(type);
/// <summary>
/// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack
/// one borrowed model on top of another without a magic offset.

View file

@ -125,10 +125,8 @@ namespace RacesOfValheim
// Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour,
// not a MonoBehaviour, so the first loop never touches it.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
// Dependents first, so a Humanoid held down by CharacterDrop cannot survive on the copy.
ModelBorrow.StripBehaviours(copy, "Skeleton");
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);

View file

@ -45,6 +45,7 @@ namespace RacesOfValheim
public static ConfigEntry<float> RavagerScaleMultiplier;
public static ConfigEntry<float> RavagerYawDegrees;
public static ConfigEntry<float> RavagerAttackOffsetValue;
public static ConfigEntry<bool> RavagerSlamCraterValue;
// ─── Colony caps ─────────────────────────────────────────────────────
// Every ceiling on how many things the colony can have alive at once, in one section, so
@ -226,6 +227,10 @@ namespace RacesOfValheim
"Raise it if a swing visibly connects short of the model's mouth/claws; lower it " +
"if it connects well past them.");
RavagerSlamCraterValue = config.Bind(ravager, "Ground Slam Crater", true,
"The middle-click slam digs into the ground where it lands, like a pickaxe blow. " +
"Never inside a ward you have no access to.");
EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength,
"How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " +
"to the chest, the legs and the helmet at once, so it goes a very long way. Settled " +
@ -358,6 +363,7 @@ namespace RacesOfValheim
public static float RavagerScale => RavagerScaleMultiplier?.Value ?? 1f;
public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f;
public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f;
public static bool RavagerSlamCrater => RavagerSlamCraterValue?.Value ?? true;
public static bool Spines => SpinesEnabled?.Value ?? false;
public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall;

View file

@ -28,6 +28,10 @@ namespace RacesOfValheim
{
public static bool IsActive { get; private set; }
/// <summary>True while the local Brute is inside a swing or the roar.
/// Sverm_RavagerHoldStill_Patch holds the player still for exactly that long.</summary>
public static bool LocalAttacking { get; set; }
// Read by Sverm_RavagerRemoteVisuals_Patch (SvermPatches.cs) so every other client can
// tell the form is up at all - without this the whole thing was local-only, exactly like
// DrakeFormBehavior's flight flag and Fenrir's own form key, and other players saw nothing
@ -103,10 +107,9 @@ namespace RacesOfValheim
// Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a
// MonoBehaviour, so it is never touched by the first loop and survives on purpose -
// it is the one live thing this costume is allowed to keep.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
// Dependents first: a single pass left the Brute's Humanoid on the costume, because
// CharacterDrop requires it and came later. See ModelBorrow.StripBehaviours.
ModelBorrow.StripBehaviours(copy, "Sverm");
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
@ -303,6 +306,7 @@ namespace RacesOfValheim
private static void Exit(Player player, bool spendCooldown)
{
IsActive = false;
LocalAttacking = false;
ZNetView exitNview = player.GetComponent<ZNetView>();
if (exitNview != null && exitNview.IsValid()) exitNview.GetZDO().Set(ActiveKey, false);
@ -472,6 +476,61 @@ namespace RacesOfValheim
/// equipped never swings and never deals damage while this is up; RavagerFormBehavior's
/// own coroutines are the only thing that can land a hit.
/// </summary>
/// <summary>
/// Holds the Brute still through its attack clips, the way Fenrir_FormHoldStill_Patch and
/// Trol_TrueFormHoldStill_Patch do for their forms. The hidden player kept walking under the
/// costume, so a bite or a slam slid toward whatever WASD held.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class Sverm_RavagerHoldStill_Patch
{
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
{
if (__instance != Player.m_localPlayer || !LocalAttacking) return;
if (!IsActive)
{
LocalAttacking = false;
return;
}
__0 = Vector3.zero;
jump = false;
crouch = false;
dodge = false;
}
}
/// <summary>The ram clip's own forward motion, collected by RavagerRootMotionRelay and
/// spent by Sverm_RavagerRootMotion_Patch.</summary>
public static Vector3 PendingRootMotion;
/// <summary>
/// Moves the player by the ram clip's root motion, the way vanilla moves a charging Brute.
/// Vanilla's own path (CharacterAnimEvent.OnAnimatorMove into Character.AddRootMotion) only
/// takes motion while Character.InAttack(), and this form never starts a native attack, so
/// the motion comes in here instead and is applied exactly as Character.ApplyRootMotion
/// applies it: delta times 55, used when it is faster than the walk velocity.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyRootMotion")]
public static class Sverm_RavagerRootMotion_Patch
{
public static void Prefix(Character __instance, ref Vector3 vel)
{
if (__instance != Player.m_localPlayer) return;
Vector3 motion = PendingRootMotion;
PendingRootMotion = Vector3.zero;
if (!IsActive || !LocalAttacking) return;
Vector3 push = motion * 55f;
push.y = 0f;
if (push.magnitude > new Vector3(vel.x, 0f, vel.z).magnitude)
{
vel = new Vector3(push.x, vel.y, push.z);
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Sverm_RavagerBlockNativeAttack_Patch
{
@ -518,6 +577,23 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Sits on the costume's Animator object. Unity calls OnAnimatorMove there instead of moving
/// the costume itself; while Active (the ram), the clip's motion is handed to the player
/// through SvermRavagerForm.PendingRootMotion. Otherwise it is dropped, so the costume stays
/// where the player is.
/// </summary>
public class RavagerRootMotionRelay : MonoBehaviour
{
public Animator Animator;
public bool Active;
private void OnAnimatorMove()
{
if (Active && Animator != null) SvermRavagerForm.PendingRootMotion += Animator.deltaPosition;
}
}
/// <summary>
/// Locomotion AND combat, both held on every frame while the form is up - built on the same
/// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations,
@ -546,7 +622,8 @@ namespace RacesOfValheim
// gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the
// animation has to finish before the Brute can move": nothing here can start moving the
// model again, or start a second attack, until the coroutine below clears it.
private bool isAttacking;
private bool isAttacking { get => attacking; set { attacking = value; SvermRavagerForm.LocalAttacking = value; } }
private bool attacking;
// The taunt's own cooldown - short, and tracked separately from the other three, which
// have no cooldown of their own beyond their own lock duration.
@ -556,8 +633,21 @@ namespace RacesOfValheim
// present, so PlayAttack does not pass a name to SetTrigger the controller cannot use.
private readonly System.Collections.Generic.HashSet<string> knownTriggers = new System.Collections.Generic.HashSet<string>();
// The two front claws (bone names read from the SeekerBrute prefab with UnityPy). The slam
// brings one down, then the other; each Hit lands under whichever claw just came down.
private Transform leftClaw;
private Transform rightClaw;
private RavagerRootMotionRelay rootMotion;
private void Start()
{
foreach (Transform bone in GetComponentsInChildren<Transform>(true))
{
if (bone.name == "l.frontfoot") leftClaw = bone;
else if (bone.name == "r.frontfoot") rightClaw = bone;
}
anim = GetComponentInChildren<Animator>();
if (anim == null || anim.runtimeAnimatorController == null) return;
@ -575,6 +665,13 @@ namespace RacesOfValheim
anim.fireEvents = false;
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
// The ram is the exception: its clip's motion moves the PLAYER (see
// Sverm_RavagerRootMotion_Patch). With an OnAnimatorMove receiver on the Animator's
// object, Unity computes the motion and hands it over instead of moving the costume.
rootMotion = anim.gameObject.AddComponent<RavagerRootMotionRelay>();
rootMotion.Animator = anim;
anim.applyRootMotion = true;
foreach (AnimatorControllerParameter param in anim.parameters)
{
if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed")
@ -656,15 +753,15 @@ namespace RacesOfValheim
// be the only reliable option.
if (RaceInput.AttackDown(1))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f));
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false, true));
}
else if (RaceInput.AttackDown(0))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f));
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false, false));
}
else if (RaceInput.AttackDown(2))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f));
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true, false));
}
else if ((SvermConfigManagement.RavagerKey.Value.IsDown() ||
RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt)
@ -675,31 +772,36 @@ namespace RacesOfValheim
}
/// <summary>
/// One swing: play the clip, wait for the moment it should land, hit whatever is there,
/// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in
/// every particular except the damage itself, which here is the Brute's own real numbers
/// (SvermRavagerAttacks) instead of one tuned float.
/// One swing, timed by the clip itself instead of by fixed delays. Each "Hit" animation
/// event in the clip is a hit here, at the same point of the clip (the bite and the ram
/// have one, the slam has two, one per claw). The player is held still until the
/// animator starts blending out of the attack state, which is when the real Brute can
/// move again. With lunge, the clip's own root motion carries the player forward (the ram).
/// </summary>
private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius,
float hitDelay, float lockDuration)
private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName,
float radius, bool slam, bool lunge)
{
isAttacking = true;
bool played = StartAttackState(profile);
if (rootMotion != null) rootMotion.Active = lunge;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
int dropSamples = 0;
float[] leftY = new float[ClawHistory];
float[] rightY = new float[ClawHistory];
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
yield return FollowAttackState(stateName, played, 0f, () =>
{
anim.SetTrigger(profile.Trigger);
SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger);
}
yield return new WaitForSeconds(hitDelay);
ExecuteDamage(profile, radius);
float remaining = lockDuration - hitDelay;
if (remaining > 0f) yield return new WaitForSeconds(remaining);
if (slam) Slam(profile, radius, leftY, rightY, dropSamples);
else ExecuteDamage(profile, radius);
}, () =>
{
if (leftClaw == null || rightClaw == null) return;
leftY[dropSamples % ClawHistory] = leftClaw.position.y;
rightY[dropSamples % ClawHistory] = rightClaw.position.y;
dropSamples++;
});
if (rootMotion != null) rootMotion.Active = false;
isAttacking = false;
}
@ -708,37 +810,159 @@ namespace RacesOfValheim
/// swing - the roar reaches out in every direction, so the sphere is centred on the
/// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately
/// silent: no message, no status effect, nothing in a corner of the screen - just the
/// animation, the sound if one resolves, and the hit.
/// animation, the sound if one resolves, and the hit. The clip has no Hit event, so the
/// roar lands at TauntHitPoint of the clip.
/// </summary>
private System.Collections.IEnumerator TauntRoutine()
{
isAttacking = true;
SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
{
anim.SetTrigger(profile.Trigger);
SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger);
}
bool played = StartAttackState(profile);
PlaySound(SvermConfig.RavagerTauntSoundEffects);
yield return new WaitForSeconds(0.3f);
Player player = Player.m_localPlayer;
if (player != null)
yield return FollowAttackState("Taunt", played, TauntHitPoint, () =>
{
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage);
}
yield return new WaitForSeconds(0.4f);
Player player = Player.m_localPlayer;
if (player != null)
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage);
}, null);
isAttacking = false;
}
// 0.3 s into the 2.67 s taunt clip, where the old fixed delay put the roar's hit.
private const float TauntHitPoint = 0.11f;
// Frames of claw height kept to tell which claw just came down (about 0.2 s at 60 fps).
private const int ClawHistory = 12;
private bool StartAttackState(SvermRavagerAttacks.Profile profile)
{
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false;
anim.SetTrigger(profile.Trigger);
SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger);
return true;
}
/// <summary>
/// Waits out one attack state frame by frame. Calls onHit at every Hit event of the
/// state's clip (or once at fallbackHit, a 0-1 point of the clip, when the clip has
/// none), and returns once the animator starts leaving the state. If the state never
/// starts (trigger missing), it hits once and returns, so the attack still works.
/// </summary>
private System.Collections.IEnumerator FollowAttackState(string stateName, bool played, float fallbackHit,
System.Action onHit, System.Action eachFrame)
{
float startedAt = Time.time;
bool entered = false;
float[] hits = null;
int nextHit = 0;
while (played && Time.time - startedAt < 8f)
{
eachFrame?.Invoke();
AnimatorStateInfo state;
AnimatorClipInfo[] clips;
bool leaving;
if (!TryGetAttackState(stateName, out state, out clips, out leaving))
{
if (entered || Time.time - startedAt > 0.5f) break;
yield return null;
continue;
}
entered = true;
if (hits == null) hits = ReadHitPoints(clips, fallbackHit);
while (nextHit < hits.Length && state.normalizedTime >= hits[nextHit])
{
onHit();
nextHit++;
}
if (leaving) break;
yield return null;
}
if (!entered) onHit();
}
private bool TryGetAttackState(string stateName, out AnimatorStateInfo state, out AnimatorClipInfo[] clips, out bool leaving)
{
state = anim.GetCurrentAnimatorStateInfo(0);
if (state.IsName(stateName))
{
clips = anim.GetCurrentAnimatorClipInfo(0);
leaving = anim.IsInTransition(0);
return true;
}
leaving = false;
if (anim.IsInTransition(0))
{
state = anim.GetNextAnimatorStateInfo(0);
if (state.IsName(stateName))
{
clips = anim.GetNextAnimatorClipInfo(0);
return true;
}
}
clips = null;
return false;
}
private static float[] ReadHitPoints(AnimatorClipInfo[] clips, float fallbackHit)
{
var points = new System.Collections.Generic.List<float>();
if (clips != null && clips.Length > 0 && clips[0].clip != null && clips[0].clip.length > 0f)
{
AnimationClip clip = clips[0].clip;
foreach (AnimationEvent ev in clip.events)
if (ev.functionName == "Hit") points.Add(ev.time / clip.length);
}
if (points.Count == 0) points.Add(fallbackHit);
points.Sort();
return points.ToArray();
}
/// <summary>
/// One claw of the slam landing: the claw that dropped the most over the last few frames
/// is the one that just struck. Damage and crater go under it, not at a fixed point ahead.
/// </summary>
private void Slam(SvermRavagerAttacks.Profile profile, float radius, float[] leftY, float[] rightY, int samples)
{
Transform claw = StrikingClaw(leftY, rightY, samples);
if (claw == null)
{
ExecuteDamage(profile, radius);
Player player = Player.m_localPlayer;
if (player != null)
DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset);
return;
}
ApplyDamageInSphere(claw.position + Vector3.up * 0.5f, radius, profile.Damage);
DigCrater(claw.position);
}
private Transform StrikingClaw(float[] leftY, float[] rightY, int samples)
{
if (leftClaw == null || rightClaw == null || samples == 0) return null;
int oldest = samples < ClawHistory ? 0 : samples % ClawHistory;
float leftDrop = leftY[oldest] - leftClaw.position.y;
float rightDrop = rightY[oldest] - rightClaw.position.y;
return leftDrop >= rightDrop ? leftClaw : rightClaw;
}
/// <summary>Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect.</summary>
private static void PlaySound(string[] candidates)
{
@ -769,6 +993,26 @@ namespace RacesOfValheim
ApplyDamageInSphere(attackPoint, radius, profile.Damage);
}
private const string CraterPrefab = "digg_v3";
private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece");
/// <summary>
/// The slam digs where it lands, the way the True Form troll's does (TrolTrueFormBehavior.Slam):
/// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the
/// ward check is done here.
/// </summary>
private static void DigCrater(Vector3 impact)
{
if (Player.m_localPlayer == null || !SvermConfigManagement.RavagerSlamCrater) return;
if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return;
if (ground.collider == null || ground.collider.GetComponent<Heightmap>() == null) return;
if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return;
GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(CraterPrefab);
if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity);
}
/// <summary>
/// The actual sweep, shared by every attack this form has (the three forward swings and
/// the taunt's own AoE) - only the sphere's centre and radius differ between them.

View file

@ -229,6 +229,7 @@ namespace RacesOfValheim
if (component is MeshFilter) continue;
if (component is MeshRenderer) continue;
if (component is SkinnedMeshRenderer) continue;
if (ModelBorrow.IsRequired(component)) continue; // a later pass, once its dependent is gone
Object.DestroyImmediate(component);

View file

@ -118,6 +118,15 @@ namespace RacesOfValheim
if (component == null) continue;
if (IsKept(component)) continue;
// Not yet if something still requires it: Unity would refuse and log an error
// ("Can't remove Humanoid because CharacterDrop depends on it"). It goes on a
// later pass, once its dependent is gone.
if (ModelBorrow.IsRequired(component))
{
stubborn++;
continue;
}
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;