bugfix 06/10/26 + bone ship
This commit is contained in:
parent
7a863b07a6
commit
553303d0fd
27 changed files with 3206 additions and 226 deletions
368
JotunnModStub/BoneShip/BoneShip.cs
Normal file
368
JotunnModStub/BoneShip/BoneShip.cs
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Configs;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections
|
||||
/// 2, 10 and 11 - every number and node name below was read off the game, not remembered.
|
||||
///
|
||||
/// WHAT THIS STEP DOES
|
||||
/// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone.
|
||||
/// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as
|
||||
/// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's
|
||||
/// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new
|
||||
/// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in
|
||||
/// the prefab or both would show at once.
|
||||
/// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never
|
||||
/// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below.
|
||||
///
|
||||
/// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the
|
||||
/// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs).
|
||||
/// </summary>
|
||||
public static class BoneShip
|
||||
{
|
||||
// Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what
|
||||
// ShipMountTest's post table and the rest of the Bone Ship know them by.
|
||||
public const string KarveName = "BoneKarve";
|
||||
public const string LongshipName = "BoneLongship";
|
||||
public const string AshlandsName = "BoneAshlands";
|
||||
|
||||
/// <summary>The hover name of the altar on the deck, where bone fragments are offered.</summary>
|
||||
public const string AltarName = "$rov_piece_boneship_altar_name";
|
||||
|
||||
/// <summary>
|
||||
/// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is
|
||||
/// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull,
|
||||
/// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call.
|
||||
/// The rowers' seats follow: one per place, half on each side.
|
||||
/// </summary>
|
||||
private const int KarveMelee = 2, KarveRanged = 2;
|
||||
private const int LongshipMelee = 4, LongshipRanged = 4;
|
||||
private const int AshlandsMelee = 6, AshlandsRanged = 6;
|
||||
|
||||
public static int MeleeCapOf(Component ship) =>
|
||||
IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee;
|
||||
|
||||
public static int RangedCapOf(Component ship) =>
|
||||
IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged;
|
||||
|
||||
private static bool IsAshlands(Component ship)
|
||||
{
|
||||
return ship != null && ship.name.StartsWith(AshlandsName);
|
||||
}
|
||||
|
||||
private static bool IsKarve(Component ship)
|
||||
{
|
||||
return ship != null && ship.name.StartsWith(KarveName);
|
||||
}
|
||||
|
||||
public static bool IsKarveShip(Component ship) => IsKarve(ship);
|
||||
|
||||
/// <summary>Half the length of the hull, read from the OnboardTrigger every ship carries.</summary>
|
||||
public static float HalfLengthOf(Component ship)
|
||||
{
|
||||
Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null;
|
||||
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
|
||||
return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f;
|
||||
}
|
||||
|
||||
/// <summary>Our prefab, the vanilla one it is cloned from, and the localisation key stem.</summary>
|
||||
private struct Spec
|
||||
{
|
||||
public string Name;
|
||||
public string Source;
|
||||
public string KeyStem;
|
||||
public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; }
|
||||
}
|
||||
|
||||
private static readonly Spec[] Specs =
|
||||
{
|
||||
new Spec(KarveName, "Karve", "karve"),
|
||||
new Spec(LongshipName, "VikingShip", "longship"),
|
||||
new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"),
|
||||
};
|
||||
|
||||
private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name";
|
||||
private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc";
|
||||
|
||||
/// <summary>
|
||||
/// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength
|
||||
/// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind):
|
||||
/// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured
|
||||
/// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise.
|
||||
/// </summary>
|
||||
public const float SailK = 0.75f;
|
||||
|
||||
/// <summary>The key part of every bone ship's recipe: the swamp's Wishbone. One per ship.</summary>
|
||||
private const string WishbonePrefab = "Wishbone";
|
||||
|
||||
/// <summary>
|
||||
/// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the
|
||||
/// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement
|
||||
/// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the
|
||||
/// pieces, asks who is building.
|
||||
/// </summary>
|
||||
private static RequirementConfig[] CostOf(string name)
|
||||
{
|
||||
switch (name)
|
||||
{
|
||||
case KarveName:
|
||||
return new[]
|
||||
{
|
||||
new RequirementConfig(WishbonePrefab, 1, 0, true),
|
||||
new RequirementConfig("Wood", 30, 0, true),
|
||||
new RequirementConfig("BoneFragments", 60, 0, true),
|
||||
new RequirementConfig("Resin", 10, 0, true),
|
||||
};
|
||||
|
||||
case LongshipName:
|
||||
return new[]
|
||||
{
|
||||
new RequirementConfig(WishbonePrefab, 1, 0, true),
|
||||
new RequirementConfig("Wood", 60, 0, true),
|
||||
new RequirementConfig("BoneFragments", 120, 0, true),
|
||||
new RequirementConfig("Resin", 20, 0, true),
|
||||
};
|
||||
|
||||
default: // the Ashlands one
|
||||
return new[]
|
||||
{
|
||||
new RequirementConfig(WishbonePrefab, 1, 0, true),
|
||||
new RequirementConfig("FineWood", 60, 0, true),
|
||||
new RequirementConfig("BoneFragments", 200, 0, true),
|
||||
new RequirementConfig("Resin", 30, 0, true),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one.</summary>
|
||||
private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f);
|
||||
|
||||
public static bool IsBoneShip(Ship ship)
|
||||
{
|
||||
return ship != null && ship.GetComponent<BoneShipMarker>() != null;
|
||||
}
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
BoneShipArcher.Register();
|
||||
|
||||
foreach (Spec spec in Specs)
|
||||
{
|
||||
RegisterShip(spec);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RegisterShip(Spec spec)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered.");
|
||||
return;
|
||||
}
|
||||
|
||||
prefab.AddComponent<BoneShipMarker>();
|
||||
RotHull(prefab, spec.Name);
|
||||
BoneShipSail.Apply(prefab, spec.Name);
|
||||
|
||||
// The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar
|
||||
// itself, built when the ship is in the world). The roster registers its RPC in Awake.
|
||||
prefab.AddComponent<BoneShipRoster>();
|
||||
prefab.AddComponent<BoneShipFittings>();
|
||||
prefab.AddComponent<BoneShipRowers>(); // the oarsmen; how many show is the roster's count
|
||||
|
||||
Piece piece = prefab.GetComponent<Piece>();
|
||||
if (piece == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered.");
|
||||
return;
|
||||
}
|
||||
|
||||
piece.m_name = DisplayKey(spec);
|
||||
piece.m_description = DescriptionKey(spec);
|
||||
Sprite icon = BorrowIcon("TrophySkeleton");
|
||||
if (icon != null) piece.m_icon = icon;
|
||||
|
||||
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
|
||||
{
|
||||
Name = DisplayKey(spec),
|
||||
Description = DescriptionKey(spec),
|
||||
PieceTable = PieceTables.Hammer,
|
||||
Category = PieceCategories.Misc,
|
||||
CraftingStation = CraftingStations.Workbench,
|
||||
Icon = icon,
|
||||
Requirements = CostOf(spec.Name),
|
||||
}));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can
|
||||
/// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new,
|
||||
/// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a
|
||||
/// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show.
|
||||
/// </summary>
|
||||
private static void RotHull(GameObject prefab, string name)
|
||||
{
|
||||
WearNTear wear = prefab.GetComponent<WearNTear>();
|
||||
if (wear == null || wear.m_new == null || wear.m_worn == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is.");
|
||||
return;
|
||||
}
|
||||
|
||||
GameObject fresh = wear.m_new;
|
||||
GameObject worn = wear.m_worn;
|
||||
if (fresh == worn) return;
|
||||
|
||||
wear.m_new = worn;
|
||||
fresh.SetActive(false);
|
||||
|
||||
Tint(worn, RotTint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the
|
||||
/// asset keeps its colour; the water mask and anything without a plain colour are left alone.
|
||||
/// </summary>
|
||||
private static void Tint(GameObject root, Color tint)
|
||||
{
|
||||
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
|
||||
|
||||
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (renderer == null || renderer is ParticleSystemRenderer) continue;
|
||||
|
||||
Material[] shared = renderer.sharedMaterials;
|
||||
bool changed = false;
|
||||
|
||||
for (int i = 0; i < shared.Length; i++)
|
||||
{
|
||||
Material source = shared[i];
|
||||
if (source == null || source.shader == null) continue;
|
||||
if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue;
|
||||
|
||||
Material copy;
|
||||
if (!copies.TryGetValue(source, out copy))
|
||||
{
|
||||
copy = new Material(source) { name = source.name + "_bone" };
|
||||
copy.SetColor("_Color", source.GetColor("_Color") * tint);
|
||||
copies[source] = copy;
|
||||
}
|
||||
|
||||
shared[i] = copy;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) renderer.sharedMaterials = shared;
|
||||
}
|
||||
}
|
||||
|
||||
public static void EnsureKnown(Player player)
|
||||
{
|
||||
if (player == null) return;
|
||||
|
||||
Traverse traverse = Traverse.Create(player);
|
||||
bool any = false;
|
||||
|
||||
foreach (Spec spec in Specs)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name);
|
||||
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
|
||||
if (piece == null) continue;
|
||||
|
||||
traverse.Method("AddKnownPiece", piece).GetValue();
|
||||
any = true;
|
||||
}
|
||||
|
||||
if (any) traverse.Method("UpdateAvailablePiecesList").GetValue();
|
||||
}
|
||||
|
||||
private static Sprite BorrowIcon(string prefabName)
|
||||
{
|
||||
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
|
||||
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
|
||||
? drop.m_itemData.m_shared.m_icons
|
||||
: null;
|
||||
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
|
||||
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks a ship as one of ours. No logic: the patches below and the archers look for it.</summary>
|
||||
public class BoneShipMarker : MonoBehaviour
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The oarsmen's push, in place of the wind's.
|
||||
///
|
||||
/// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1,
|
||||
/// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle
|
||||
/// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone
|
||||
/// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with
|
||||
/// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of
|
||||
/// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push.
|
||||
///
|
||||
/// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were
|
||||
/// never the wind's.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Ship), "GetSailForce")]
|
||||
public static class BoneShipSailForcePatch
|
||||
{
|
||||
private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce");
|
||||
private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity");
|
||||
|
||||
public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result)
|
||||
{
|
||||
if (!BoneShip.IsBoneShip(__instance)) return true;
|
||||
if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla
|
||||
|
||||
Vector3 current = (Vector3)SailForce.GetValue(__instance);
|
||||
Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance);
|
||||
|
||||
Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK);
|
||||
current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f);
|
||||
|
||||
SailForce.SetValue(__instance, current);
|
||||
WindChangeVelocity.SetValue(__instance, velocity);
|
||||
|
||||
__result = current;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and
|
||||
/// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs
|
||||
/// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both.
|
||||
/// What the sail looks like left alone is for the game to show: the prefab's own pose.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Ship), "UpdateSail")]
|
||||
public static class BoneShipSailPatch
|
||||
{
|
||||
public static bool Prefix(Ship __instance)
|
||||
{
|
||||
return !BoneShip.IsBoneShip(__instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Makes the piece buildable without having to craft its parts first, like the bone pile.</summary>
|
||||
[HarmonyPatch(typeof(Player), "OnSpawned")]
|
||||
public static class BoneShipKnownPatch
|
||||
{
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
BoneShip.EnsureKnown(__instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
54
JotunnModStub/BoneShip/BoneShipArcher.cs
Normal file
54
JotunnModStub/BoneShip/BoneShipArcher.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
using UnityEngine;
|
||||
using Jotunn.Managers;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck
|
||||
/// taken away and the ones that make it a ship's archer put in.
|
||||
///
|
||||
/// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in
|
||||
/// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This
|
||||
/// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the
|
||||
/// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild
|
||||
/// one that was already there.
|
||||
///
|
||||
/// Taken away from the sentry:
|
||||
/// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship
|
||||
/// has no business following anyone, and E on it would send it after the player;
|
||||
/// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the
|
||||
/// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten
|
||||
/// bone fragments for every archer on every ship that sinks.
|
||||
/// What stays is the bow, the AI and the tamed flag the spawner sets.
|
||||
/// </summary>
|
||||
public static class BoneShipArcher
|
||||
{
|
||||
public const string Name = "BoneShipArcher";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
// The sentry is registered by the bone pile, earlier in the same window.
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers.");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (RaisedThrall thrall in prefab.GetComponentsInChildren<RaisedThrall>(true))
|
||||
{
|
||||
if (thrall != null) Object.DestroyImmediate(thrall);
|
||||
}
|
||||
|
||||
foreach (CharacterDrop drop in prefab.GetComponentsInChildren<CharacterDrop>(true))
|
||||
{
|
||||
if (drop != null) Object.DestroyImmediate(drop);
|
||||
}
|
||||
|
||||
prefab.AddComponent<ShipMount>();
|
||||
prefab.AddComponent<ShipBust>();
|
||||
|
||||
PrefabManager.Instance.AddPrefab(prefab);
|
||||
}
|
||||
}
|
||||
}
|
||||
572
JotunnModStub/BoneShip/BoneShipFittings.cs
Normal file
572
JotunnModStub/BoneShip/BoneShipFittings.cs
Normal file
|
|
@ -0,0 +1,572 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the
|
||||
/// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster).
|
||||
///
|
||||
/// Built when the ship comes into the world, on every client, and not baked into the prefab - because
|
||||
/// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the
|
||||
/// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail"
|
||||
/// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points
|
||||
/// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the
|
||||
/// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy,
|
||||
/// because the boom of the Karve is a collider that spans the whole beam at six metres.
|
||||
///
|
||||
/// Everything is deterministic from the ship's own id, so every client builds the same bones.
|
||||
///
|
||||
/// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and
|
||||
/// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips.
|
||||
/// The model names that are not certain to exist - the bigger bones - are tried in order and whatever
|
||||
/// resolves is logged once.
|
||||
/// </summary>
|
||||
public class BoneShipFittings : MonoBehaviour
|
||||
{
|
||||
private const string SkullPrefab = "TrophySkeleton";
|
||||
private const string FragmentsPrefab = "BoneFragments";
|
||||
// The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to
|
||||
// be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item -
|
||||
// never were). Kept as a list so a second model is one more entry.
|
||||
private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" };
|
||||
|
||||
internal const float RayStartHeight = 14f;
|
||||
private const float RayLength = 32f;
|
||||
// The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's
|
||||
// widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is
|
||||
// clicked and where the skull sits.
|
||||
private const string ChestPrefab = "piece_chest_wood";
|
||||
private const float ChestSize = 0.85f;
|
||||
private const float ChestHeight = 0.62f;
|
||||
|
||||
private static GameObject s_holder;
|
||||
private static readonly Dictionary<string, GameObject> s_templates = new Dictionary<string, GameObject>();
|
||||
private static bool s_reported;
|
||||
|
||||
/// <summary>Where the altar ended up, in the ship's space. The roster keeps its hover on this.</summary>
|
||||
public Switch Altar { get; private set; }
|
||||
|
||||
/// <summary>One archer's place: where it stands on the ship (ship space) and whether it is a bust.</summary>
|
||||
public struct ArcherPost
|
||||
{
|
||||
public Vector3 Local;
|
||||
public bool Bust;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the
|
||||
/// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern.
|
||||
/// All are busts - only the chest and up shows, a figurehead that shoots.
|
||||
/// </summary>
|
||||
public List<ArcherPost> ArcherPosts { get; private set; }
|
||||
|
||||
private void Start()
|
||||
{
|
||||
StartCoroutine(Build());
|
||||
}
|
||||
|
||||
private IEnumerator Build()
|
||||
{
|
||||
ZNetView nview = GetComponent<ZNetView>();
|
||||
if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones
|
||||
|
||||
// One physics step so the hull's colliders exist for the rays.
|
||||
yield return new WaitForFixedUpdate();
|
||||
yield return null;
|
||||
|
||||
Bounds hull;
|
||||
if (!TryHullExtent(out hull))
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted.");
|
||||
yield break;
|
||||
}
|
||||
|
||||
ReportModels();
|
||||
|
||||
System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode());
|
||||
float hx = hull.extents.x;
|
||||
float hz = hull.extents.z;
|
||||
|
||||
int rays = 0;
|
||||
int placed = 0;
|
||||
|
||||
// ---- both rails
|
||||
int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f));
|
||||
for (int side = -1; side <= 1; side += 2)
|
||||
{
|
||||
for (int i = 0; i < slots; i++)
|
||||
{
|
||||
float t = slots == 1 ? 0.5f : i / (float)(slots - 1);
|
||||
float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f);
|
||||
|
||||
Vector3 point;
|
||||
if (!FindRail(side, z, hx, out point, ref rays)) continue;
|
||||
if (rays >= 40) { rays = 0; yield return null; }
|
||||
|
||||
if (PlaceOnRail(point, side, rng)) placed++;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the bow: a cluster on the centre line at the very front
|
||||
Vector3 bow;
|
||||
if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow))
|
||||
{
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f));
|
||||
if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- loose on the deck
|
||||
int scatter = Mathf.Max(5, slots / 2);
|
||||
for (int k = 0; k < scatter; k++)
|
||||
{
|
||||
float x = Range(rng, -0.55f, 0.55f) * hx;
|
||||
float z = Range(rng, -0.8f, 0.8f) * hz;
|
||||
if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear
|
||||
|
||||
Vector3 point;
|
||||
if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue;
|
||||
if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++;
|
||||
if (++rays >= 40) { rays = 0; yield return null; }
|
||||
}
|
||||
|
||||
BuildAltar(hz, rng);
|
||||
FindArcherPosts(hz);
|
||||
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " +
|
||||
$"{ArcherPosts.Count} archer post(s).");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the archers' posts
|
||||
|
||||
/// <summary>
|
||||
/// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often
|
||||
/// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if
|
||||
/// nothing is under the point, the search walks back toward the middle in 30 cm steps.
|
||||
/// </summary>
|
||||
private void FindArcherPosts(float hz)
|
||||
{
|
||||
ArcherPosts = new List<ArcherPost>();
|
||||
|
||||
AddPost(+0.93f * hz, -1f);
|
||||
if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f);
|
||||
}
|
||||
|
||||
private void AddPost(float z, float towardMiddle)
|
||||
{
|
||||
for (float back = 0f; back <= 2.4f; back += 0.3f)
|
||||
{
|
||||
Vector3 point;
|
||||
if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue;
|
||||
|
||||
// A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs
|
||||
// were then sits in the wood instead of resting on it, which is what made it look hung in air.
|
||||
ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true });
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " +
|
||||
(back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip)."));
|
||||
return;
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty.");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the altar
|
||||
|
||||
/// <summary>
|
||||
/// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has
|
||||
/// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve,
|
||||
/// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all
|
||||
/// three and the one a player already knows to look at. The first version put an altar of bones a
|
||||
/// fixed distance down the centre line, which on the Karve is the stretch between the mast and the
|
||||
/// helm, right where its rowers sit.
|
||||
///
|
||||
/// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is
|
||||
/// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five
|
||||
/// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its
|
||||
/// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so.
|
||||
/// </summary>
|
||||
private void BuildAltar(float hz, System.Random rng)
|
||||
{
|
||||
Vector3 spot;
|
||||
string where;
|
||||
if (!FindChestSpot(hz, out spot, out where))
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built.");
|
||||
return;
|
||||
}
|
||||
|
||||
GameObject chest = new GameObject("BoneChest");
|
||||
chest.transform.SetParent(transform, false);
|
||||
chest.transform.localPosition = spot;
|
||||
|
||||
// Its front toward the stern, where the helm is and where a player stands when he looks around.
|
||||
chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
|
||||
chest.layer = LayerMask.NameToLayer("piece_nonsolid");
|
||||
|
||||
// The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours.
|
||||
GameObject template = TemplateOf(ChestPrefab);
|
||||
if (template != null)
|
||||
{
|
||||
GameObject model = Object.Instantiate(template, chest.transform, false);
|
||||
model.name = ChestPrefab;
|
||||
model.transform.localPosition = Vector3.zero;
|
||||
model.transform.localScale = Vector3.one * ChestSize;
|
||||
|
||||
// A chest prefab carries both an open and a closed lid; the container switches them at run
|
||||
// time and the copy has no container, so the open one is turned off here.
|
||||
foreach (Transform node in model.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead.");
|
||||
Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f);
|
||||
}
|
||||
|
||||
Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f);
|
||||
|
||||
BoxCollider box = chest.AddComponent<BoxCollider>();
|
||||
box.center = new Vector3(0f, ChestHeight * 0.5f, 0f);
|
||||
box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f);
|
||||
|
||||
Switch sw = chest.AddComponent<Switch>();
|
||||
sw.m_name = BoneShip.AltarName;
|
||||
Altar = sw;
|
||||
|
||||
BoneShipRoster roster = GetComponent<BoneShipRoster>();
|
||||
if (roster != null) roster.Bind(sw);
|
||||
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " +
|
||||
$"({spot.x:F2}, {spot.y:F2}, {spot.z:F2}).");
|
||||
}
|
||||
|
||||
private bool FindChestSpot(float hz, out Vector3 spot, out string where)
|
||||
{
|
||||
spot = Vector3.zero;
|
||||
where = "";
|
||||
|
||||
Transform hatch = transform.Find("piece_chest");
|
||||
BoxCollider hatchBox = hatch != null ? hatch.GetComponent<BoxCollider>() : null;
|
||||
if (hatch == null)
|
||||
{
|
||||
// A ship with no cargo hatch: the old rule, a fixed place down the centre line.
|
||||
where = "(no hatch found, fixed spot behind the middle) of";
|
||||
return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot);
|
||||
}
|
||||
|
||||
Vector3 centre = hatch.localPosition;
|
||||
float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f;
|
||||
float gap = half + ChestSize * 0.5f + 0.1f;
|
||||
|
||||
Vector3 hatchTop;
|
||||
if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false;
|
||||
float level = hatchTop.y;
|
||||
|
||||
// Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and
|
||||
// in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is
|
||||
// kept away from by position.
|
||||
Vector2[] offsets =
|
||||
{
|
||||
new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap),
|
||||
};
|
||||
string[] names = { "right of", "left of", "behind", "in front of" };
|
||||
|
||||
List<Vector2> masts = MastPositions();
|
||||
|
||||
for (int i = 0; i < offsets.Length; i++)
|
||||
{
|
||||
Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y);
|
||||
if (NearAny(masts, c, 0.7f)) continue;
|
||||
if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue;
|
||||
|
||||
where = names[i];
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chest's whole footprint is on deck: the centre and four points half a chest away all find a
|
||||
/// surface that is flat and at the hatch's own height. Returns the centre's point.
|
||||
/// </summary>
|
||||
private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre)
|
||||
{
|
||||
Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) };
|
||||
centre = Vector3.zero;
|
||||
|
||||
for (int i = 0; i < around.Length; i++)
|
||||
{
|
||||
Vector3 p;
|
||||
if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false;
|
||||
if (Mathf.Abs(p.y - level) > 0.22f) return false;
|
||||
if (i == 0) centre = p;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Within a couple of metres of the cargo hatch, on any side: where the chest will stand.</summary>
|
||||
private bool NearHatch(float x, float z)
|
||||
{
|
||||
Transform hatch = transform.Find("piece_chest");
|
||||
if (hatch == null) return false;
|
||||
|
||||
Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z);
|
||||
return d.sqrMagnitude < 2.2f * 2.2f;
|
||||
}
|
||||
|
||||
private List<Vector2> MastPositions()
|
||||
{
|
||||
List<Vector2> masts = new List<Vector2>();
|
||||
foreach (Transform t in GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
if (t == transform || t.name.ToLowerInvariant() != "mast") continue;
|
||||
|
||||
Vector3 local = transform.InverseTransformPoint(t.position);
|
||||
masts.Add(new Vector2(local.x, local.z));
|
||||
}
|
||||
return masts;
|
||||
}
|
||||
|
||||
private static bool NearAny(List<Vector2> points, Vector2 p, float distance)
|
||||
{
|
||||
foreach (Vector2 q in points)
|
||||
{
|
||||
if ((q - p).sqrMagnitude < distance * distance) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- placing
|
||||
|
||||
private bool PlaceOnRail(Vector3 point, int side, System.Random rng)
|
||||
{
|
||||
double roll = rng.NextDouble();
|
||||
Vector3 up = point + Vector3.up * 0.02f;
|
||||
|
||||
if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f);
|
||||
if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f);
|
||||
if (roll < 0.88)
|
||||
{
|
||||
// The big ones lean outward over the side, like something draped there.
|
||||
string large = LargestAvailable();
|
||||
return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f);
|
||||
}
|
||||
return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over
|
||||
}
|
||||
|
||||
private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt)
|
||||
{
|
||||
return Place(prefabName, transform, localPosition, size, rng, tilt);
|
||||
}
|
||||
|
||||
private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt)
|
||||
{
|
||||
GameObject template = TemplateOf(prefabName);
|
||||
if (template == null) return false;
|
||||
|
||||
GameObject copy = Object.Instantiate(template, parent, false);
|
||||
copy.name = prefabName;
|
||||
copy.transform.localPosition = localPosition;
|
||||
copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt));
|
||||
copy.transform.localScale = Vector3.one * size;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- models
|
||||
|
||||
/// <summary>
|
||||
/// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads.
|
||||
/// Built on first use. The holder being inactive is what keeps the template from ever being drawn.
|
||||
/// </summary>
|
||||
private static GameObject TemplateOf(string prefabName)
|
||||
{
|
||||
GameObject cached;
|
||||
if (s_templates.TryGetValue(prefabName, out cached)) return cached;
|
||||
|
||||
if (s_holder == null)
|
||||
{
|
||||
s_holder = new GameObject("RoV_BoneShipModels");
|
||||
s_holder.SetActive(false);
|
||||
Object.DontDestroyOnLoad(s_holder);
|
||||
}
|
||||
|
||||
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
|
||||
GameObject template = null;
|
||||
if (source != null)
|
||||
{
|
||||
template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip");
|
||||
StripEffects(template);
|
||||
}
|
||||
|
||||
s_templates[prefabName] = template;
|
||||
return template;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a
|
||||
/// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network
|
||||
/// view) but a particle system or a light does not think, it just plays - so the first version of
|
||||
/// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed.
|
||||
///
|
||||
/// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children;
|
||||
/// otherwise just the effect components come off. A particle system cannot be removed while its
|
||||
/// renderer is there, so the renderer goes first.
|
||||
/// </summary>
|
||||
internal static void StripEffects(GameObject template)
|
||||
{
|
||||
if (template == null) return;
|
||||
|
||||
foreach (ParticleSystem system in template.GetComponentsInChildren<ParticleSystem>(true))
|
||||
{
|
||||
if (system == null) continue;
|
||||
|
||||
GameObject node = system.gameObject;
|
||||
if (node == template || node.GetComponent<MeshRenderer>() != null || node.GetComponent<SkinnedMeshRenderer>() != null)
|
||||
{
|
||||
ParticleSystemRenderer renderer = node.GetComponent<ParticleSystemRenderer>();
|
||||
if (renderer != null) Object.DestroyImmediate(renderer);
|
||||
Object.DestroyImmediate(system);
|
||||
}
|
||||
else
|
||||
{
|
||||
Object.DestroyImmediate(node);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Light light in template.GetComponentsInChildren<Light>(true))
|
||||
{
|
||||
if (light != null) Object.DestroyImmediate(light);
|
||||
}
|
||||
|
||||
foreach (AudioSource audio in template.GetComponentsInChildren<AudioSource>(true))
|
||||
{
|
||||
if (audio != null) Object.DestroyImmediate(audio);
|
||||
}
|
||||
|
||||
foreach (TrailRenderer trail in template.GetComponentsInChildren<TrailRenderer>(true))
|
||||
{
|
||||
if (trail != null) Object.DestroyImmediate(trail);
|
||||
}
|
||||
|
||||
foreach (LineRenderer line in template.GetComponentsInChildren<LineRenderer>(true))
|
||||
{
|
||||
if (line != null) Object.DestroyImmediate(line);
|
||||
}
|
||||
}
|
||||
|
||||
private static string LargestAvailable()
|
||||
{
|
||||
foreach (string name in LargeBonePrefabs)
|
||||
{
|
||||
if (TemplateOf(name) != null) return name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void ReportModels()
|
||||
{
|
||||
if (s_reported) return;
|
||||
s_reported = true;
|
||||
|
||||
List<string> found = new List<string>();
|
||||
List<string> missing = new List<string>();
|
||||
foreach (string name in LargeBonePrefabs)
|
||||
{
|
||||
(TemplateOf(name) != null ? found : missing).Add(name);
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) +
|
||||
"], missing [" + string.Join(", ", missing.ToArray()) + "].");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- measuring
|
||||
|
||||
/// <summary>
|
||||
/// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume
|
||||
/// the game uses to decide who is aboard is, by construction, about the hull.
|
||||
/// </summary>
|
||||
internal bool TryHullExtent(out Bounds bounds)
|
||||
{
|
||||
bounds = new Bounds();
|
||||
|
||||
Transform trigger = transform.Find("OnboardTrigger");
|
||||
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
|
||||
if (box == null) return false;
|
||||
|
||||
Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center));
|
||||
Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ;
|
||||
size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
|
||||
|
||||
bounds = new Bounds(centre, size);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that
|
||||
/// lands on the ship is the outer edge of the rail.
|
||||
/// </summary>
|
||||
internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays)
|
||||
{
|
||||
for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f)
|
||||
{
|
||||
rays++;
|
||||
if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true;
|
||||
}
|
||||
|
||||
point = Vector3.zero;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything
|
||||
/// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull.
|
||||
/// </summary>
|
||||
internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f)
|
||||
{
|
||||
Vector3 origin = transform.TransformPoint(localOrigin);
|
||||
|
||||
RaycastHit best = default(RaycastHit);
|
||||
bool found = false;
|
||||
float bestDistance = float.MaxValue;
|
||||
|
||||
foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength))
|
||||
{
|
||||
Collider collider = hit.collider;
|
||||
if (collider == null || collider.isTrigger) continue;
|
||||
if (!collider.transform.IsChildOf(transform)) continue;
|
||||
if (Vector3.Dot(hit.normal, transform.up) < minUp) continue;
|
||||
if (IsRigging(collider.transform)) continue;
|
||||
|
||||
if (hit.distance >= bestDistance) continue;
|
||||
best = hit;
|
||||
bestDistance = hit.distance;
|
||||
found = true;
|
||||
}
|
||||
|
||||
localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero;
|
||||
return found;
|
||||
}
|
||||
|
||||
private bool IsRigging(Transform t)
|
||||
{
|
||||
for (; t != null && t != transform; t = t.parent)
|
||||
{
|
||||
string n = t.name.ToLowerInvariant();
|
||||
if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static float Range(System.Random rng, float min, float max)
|
||||
{
|
||||
return min + (float)rng.NextDouble() * (max - min);
|
||||
}
|
||||
}
|
||||
}
|
||||
709
JotunnModStub/BoneShip/BoneShipRoster.cs
Normal file
709
JotunnModStub/BoneShip/BoneShipRoster.cs
Normal file
|
|
@ -0,0 +1,709 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7.
|
||||
///
|
||||
/// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills
|
||||
/// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same
|
||||
/// design: nothing is created or consumed when a skeleton falls, the place simply stands up again.
|
||||
///
|
||||
/// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own
|
||||
/// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a
|
||||
/// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever
|
||||
/// built the ship; when it moves off again, the ones that are following and close enough go back aboard,
|
||||
/// one at a time, and become a number again.
|
||||
///
|
||||
/// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many
|
||||
/// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own
|
||||
/// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an
|
||||
/// unloaded zone is not counted, so its place can refill while it is away.
|
||||
///
|
||||
/// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would
|
||||
/// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by
|
||||
/// id, and die with it. Only the owner of the ship's ZDO runs any of this.
|
||||
/// </summary>
|
||||
public class BoneShipRoster : MonoBehaviour
|
||||
{
|
||||
// ZDO keys, on the ship.
|
||||
private const string KeyBones = "RoV_bshBones";
|
||||
private const string KeySlotsMelee = "RoV_bshSlotsM";
|
||||
private const string KeySlotsRanged = "RoV_bshSlotsR";
|
||||
private const string KeyAboardMelee = "RoV_bshAbM";
|
||||
private const string KeyAboardRanged = "RoV_bshAbR";
|
||||
|
||||
/// <summary>
|
||||
/// Set when a troop that was told to go home boards a ship that is standing still: they have been
|
||||
/// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship
|
||||
/// moves, so the next stop lands the crew as usual.
|
||||
/// </summary>
|
||||
private const string KeyHold = "RoV_bshHold";
|
||||
|
||||
/// <summary>A recalled troop further than BoardRange but within this many metres is walked to the ship.</summary>
|
||||
private const float RecallReach = 80f;
|
||||
|
||||
/// <summary>How many rowers should show: everyone aboard. Read by the rowers when they exist.</summary>
|
||||
public const string KeyRowers = "RoV_bshRowers";
|
||||
|
||||
/// <summary>ZDO key on a TROOP: the id of the ship it belongs to.</summary>
|
||||
public const string KeyShip = "RoV_bshShip";
|
||||
|
||||
// ─── Balance. Same numbers as the pile where the idea is the same. ───
|
||||
private const float TickSeconds = 0.5f;
|
||||
private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore
|
||||
private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard
|
||||
private const float StepSeconds = 0.8f; // one troop at a time, this far apart
|
||||
private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped
|
||||
private const float BoardRange = 20f; // decided with the orders: same as the pile's home check
|
||||
private const float LandingBand = 10f; // how far past the hull to look for shore
|
||||
private const float LandingMargin = 0.25f; // metres above the water for it to count as land
|
||||
|
||||
private ZNetView m_nview;
|
||||
private Ship m_ship;
|
||||
private Rigidbody m_body;
|
||||
|
||||
// The archers are not troops and are not counted with them: their own key, their own check.
|
||||
private const float ArcherCheckSeconds = 2f;
|
||||
private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one
|
||||
|
||||
private float m_archerTimer;
|
||||
private float[] m_postEmptyFor = new float[0];
|
||||
|
||||
private float m_stillTime;
|
||||
private float m_movingTime;
|
||||
private float m_stepTimer;
|
||||
private float m_refillTimer;
|
||||
private int m_deployIndex;
|
||||
private bool m_toldNoShore;
|
||||
|
||||
private readonly List<Vector3> m_recentLandings = new List<Vector3>();
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
m_nview = GetComponent<ZNetView>();
|
||||
m_ship = GetComponent<Ship>();
|
||||
m_body = GetComponent<Rigidbody>();
|
||||
|
||||
if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost
|
||||
|
||||
m_nview.Register<string, int>("RoV_BshFeed", RPC_Feed);
|
||||
|
||||
WearNTear wear = GetComponent<WearNTear>();
|
||||
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
|
||||
|
||||
InvokeRepeating("Tick", 2f, TickSeconds);
|
||||
}
|
||||
|
||||
/// <summary>The altar's Switch, once the fittings have built it.</summary>
|
||||
public void Bind(Switch altar)
|
||||
{
|
||||
if (altar == null) return;
|
||||
altar.m_onUse = OnUse;
|
||||
altar.m_onHover = Hover;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- interaction
|
||||
|
||||
// With an item in hand every outcome counts as handled, refusals included: false makes
|
||||
// Humanoid.UseItem cover our own message with the generic one. Same as the pile.
|
||||
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
|
||||
{
|
||||
return Use(user, item) || item != null;
|
||||
}
|
||||
|
||||
private bool Use(Humanoid user, ItemDrop.ItemData item)
|
||||
{
|
||||
Player player = user as Player;
|
||||
if (player == null || item == null) return false;
|
||||
|
||||
Inventory inventory = player.GetInventory();
|
||||
if (inventory == null) return false;
|
||||
|
||||
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
|
||||
if (prefabName != SkeletonBonePile.BonePrefab)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid
|
||||
// towards the next place. Taken from the player only if the ship will actually keep it.
|
||||
int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones);
|
||||
if (room <= 0)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
|
||||
return false;
|
||||
}
|
||||
|
||||
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
|
||||
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
|
||||
inventory.RemoveItem(item, taken);
|
||||
|
||||
m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void RPC_Feed(long sender, string prefabName, int count)
|
||||
{
|
||||
if (!m_nview.IsOwner()) return;
|
||||
if (prefabName != SkeletonBonePile.BonePrefab) return;
|
||||
if (count < 1) count = 1;
|
||||
|
||||
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
|
||||
|
||||
// Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones
|
||||
// that are never counted.
|
||||
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
|
||||
{
|
||||
bones -= SkeletonBonePile.BonesPerSlot;
|
||||
|
||||
if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1);
|
||||
else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1);
|
||||
}
|
||||
|
||||
m_nview.GetZDO().Set(KeyBones, bones);
|
||||
}
|
||||
|
||||
private string Hover()
|
||||
{
|
||||
int outM = CountDeployed(SkeletonBonePile.KindMelee);
|
||||
int outR = CountDeployed(SkeletonBonePile.KindRanged);
|
||||
int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
|
||||
|
||||
string body = ModText.Get("rov_hover_boneship_roster",
|
||||
outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(),
|
||||
outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(),
|
||||
aboard);
|
||||
|
||||
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
|
||||
int placesLeft = TotalCap() - PaidSlots();
|
||||
body += placesLeft > 0
|
||||
? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft)
|
||||
: ModText.Get("rov_hover_skeleton_every_place_bought");
|
||||
|
||||
if (m_refillTimer > 0f)
|
||||
{
|
||||
int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer));
|
||||
body += ModText.Get("rov_hover_skeleton_next_rises_s", left);
|
||||
}
|
||||
|
||||
body += ModText.Get("rov_hover_boneship_bone_hand");
|
||||
return Localization.instance.Localize($"{BoneShip.AltarName} ({body})");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the tick
|
||||
|
||||
private void Tick()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
|
||||
if (m_ship == null) return;
|
||||
|
||||
Refill();
|
||||
PublishRowers();
|
||||
|
||||
m_archerTimer += TickSeconds;
|
||||
if (m_archerTimer >= ArcherCheckSeconds)
|
||||
{
|
||||
TickArchers(m_archerTimer);
|
||||
m_archerTimer = 0f;
|
||||
}
|
||||
|
||||
bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop &&
|
||||
(m_body == null || m_body.velocity.magnitude < StillSpeed);
|
||||
|
||||
if (stopped)
|
||||
{
|
||||
m_stillTime += TickSeconds;
|
||||
m_movingTime = 0f;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_movingTime += TickSeconds;
|
||||
m_stillTime = 0f;
|
||||
m_toldNoShore = false;
|
||||
m_recentLandings.Clear();
|
||||
}
|
||||
|
||||
// Moving off ends any hold: the next stop lands the crew as usual.
|
||||
if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false))
|
||||
{
|
||||
m_nview.GetZDO().Set(KeyHold, false);
|
||||
}
|
||||
|
||||
WalkRecalled();
|
||||
|
||||
m_stepTimer -= TickSeconds;
|
||||
if (m_stepTimer > 0f) return;
|
||||
|
||||
// A troop sent home boards whether the ship is moving or not; the ones merely following only
|
||||
// when it is underway. Whichever is first takes the step.
|
||||
bool underway = !stopped && m_movingTime >= UnderwaySeconds;
|
||||
string boarded = BoardOne(underway);
|
||||
if (boarded != null)
|
||||
{
|
||||
m_stepTimer = StepSeconds;
|
||||
|
||||
// Anyone who boards while the ship is standing still came aboard on purpose - called back, or
|
||||
// walked up the plank - and must not be sent straight out again. Held until the ship moves.
|
||||
if (stopped) m_nview.GetZDO().Set(KeyHold, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false))
|
||||
{
|
||||
if (TryDeploy()) m_stepTimer = StepSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as
|
||||
/// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come
|
||||
/// ashore by the ordinary route.
|
||||
/// </summary>
|
||||
private void Refill()
|
||||
{
|
||||
string empty = FirstEmptyKind();
|
||||
if (empty == null)
|
||||
{
|
||||
m_refillTimer = 0f;
|
||||
return;
|
||||
}
|
||||
|
||||
m_refillTimer += TickSeconds;
|
||||
if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return;
|
||||
m_refillTimer = 0f;
|
||||
|
||||
SetAboard(empty, Aboard(empty) + 1);
|
||||
}
|
||||
|
||||
private string FirstEmptyKind()
|
||||
{
|
||||
if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0)
|
||||
return SkeletonBonePile.KindMelee;
|
||||
if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0)
|
||||
return SkeletonBonePile.KindRanged;
|
||||
return null;
|
||||
}
|
||||
|
||||
private void PublishRowers()
|
||||
{
|
||||
int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
|
||||
if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- coming ashore
|
||||
|
||||
private bool TryDeploy()
|
||||
{
|
||||
int melee = Aboard(SkeletonBonePile.KindMelee);
|
||||
int ranged = Aboard(SkeletonBonePile.KindRanged);
|
||||
if (melee + ranged == 0) return false;
|
||||
|
||||
Vector3 landing;
|
||||
if (!FindLanding(out landing))
|
||||
{
|
||||
// Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking.
|
||||
if (!m_toldNoShore && Player.m_localPlayer != null &&
|
||||
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f)
|
||||
{
|
||||
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore"));
|
||||
}
|
||||
m_toldNoShore = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows.
|
||||
string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged;
|
||||
string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName;
|
||||
|
||||
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore.");
|
||||
return false;
|
||||
}
|
||||
|
||||
GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
|
||||
|
||||
// Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor.
|
||||
MonsterAI ai = spawned.GetComponent<MonsterAI>();
|
||||
if (ai != null) ai.MakeTame();
|
||||
Character character = spawned.GetComponent<Character>();
|
||||
if (character != null) character.SetTamed(true);
|
||||
|
||||
ZNetView troopView = spawned.GetComponent<ZNetView>();
|
||||
if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid);
|
||||
|
||||
// Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is
|
||||
// not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand
|
||||
// there, and never be able to come back aboard, because boarding is for the ones that follow. So the
|
||||
// follow target is set directly, as the ship's own right.
|
||||
Player master = Master();
|
||||
if (ai != null && master != null) ai.SetFollowTarget(master.gameObject);
|
||||
|
||||
SetAboard(kind, Aboard(kind) - 1);
|
||||
m_recentLandings.Add(landing);
|
||||
if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out
|
||||
/// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first
|
||||
/// ring angle moves on with each troop, and a point near one already used is skipped, so they do not
|
||||
/// all stack on one spot.
|
||||
/// </summary>
|
||||
private bool FindLanding(out Vector3 landing)
|
||||
{
|
||||
landing = Vector3.zero;
|
||||
if (ZoneSystem.instance == null) return false;
|
||||
|
||||
float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f);
|
||||
float water = ZoneSystem.instance.m_waterLevel + LandingMargin;
|
||||
|
||||
for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f)
|
||||
{
|
||||
for (int step = 0; step < 24; step++)
|
||||
{
|
||||
float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad;
|
||||
Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
|
||||
|
||||
float ground = ZoneSystem.instance.GetGroundHeight(point);
|
||||
if (ground < water) continue;
|
||||
if (NearRecent(point)) continue;
|
||||
|
||||
landing = new Vector3(point.x, ground + 0.5f, point.z);
|
||||
m_deployIndex++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool NearRecent(Vector3 point)
|
||||
{
|
||||
foreach (Vector3 used in m_recentLandings)
|
||||
{
|
||||
Vector3 d = used - point;
|
||||
d.y = 0f;
|
||||
if (d.sqrMagnitude < 1.4f * 1.4f) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- going back aboard
|
||||
|
||||
/// <summary>
|
||||
/// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within
|
||||
/// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the
|
||||
/// ship is underway, that is following its master. Ones told to wait, and followers when the ship is
|
||||
/// standing still, stay where they are: an outpost, still counted, still this ship's.
|
||||
/// Returns "recalled" or "following" for what it took, null for nothing.
|
||||
/// </summary>
|
||||
private string BoardOne(bool underway)
|
||||
{
|
||||
Player master = Master();
|
||||
|
||||
Character nearest = null;
|
||||
RaisedThrall nearestThrall = null;
|
||||
bool nearestRecalled = false;
|
||||
float best = BoardRange * BoardRange;
|
||||
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
||||
|
||||
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
||||
if (thrall == null) continue;
|
||||
|
||||
bool recalled = IsRecalled(character);
|
||||
|
||||
// A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is
|
||||
// doing: standing about on the planks as a creature is not what a crew is. The first version
|
||||
// only took followers once the ship was underway, so stepping off and back on left the crew
|
||||
// standing on deck, never at the oars, until the ship moved.
|
||||
bool followingMaster = master != null && thrall.IsFollowing(master);
|
||||
bool following = followingMaster && (underway || OnDeck(character));
|
||||
if (!recalled && !following) continue;
|
||||
|
||||
float distance = (character.transform.position - transform.position).sqrMagnitude;
|
||||
if (distance >= best) continue;
|
||||
|
||||
best = distance;
|
||||
nearest = character;
|
||||
nearestThrall = thrall;
|
||||
nearestRecalled = recalled;
|
||||
}
|
||||
|
||||
if (nearest == null) return null;
|
||||
|
||||
string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
|
||||
|
||||
ZNetView troopView = nearest.GetComponent<ZNetView>();
|
||||
if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone
|
||||
ZNetScene.instance.Destroy(nearest.gameObject);
|
||||
|
||||
SetAboard(kind, Aboard(kind) + 1);
|
||||
return nearestRecalled ? "recalled" : "following";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship
|
||||
/// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot.
|
||||
/// </summary>
|
||||
private void WalkRecalled()
|
||||
{
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
||||
if (!IsRecalled(character)) continue;
|
||||
|
||||
float distance = Vector3.Distance(character.transform.position, transform.position);
|
||||
if (distance <= BoardRange || distance > RecallReach) continue;
|
||||
|
||||
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
||||
if (thrall != null) thrall.WalkTo(transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard.</summary>
|
||||
private bool OnDeck(Character character)
|
||||
{
|
||||
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
|
||||
Bounds hull;
|
||||
if (fittings == null || !fittings.TryHullExtent(out hull)) return false;
|
||||
|
||||
return hull.Contains(transform.InverseTransformPoint(character.transform.position));
|
||||
}
|
||||
|
||||
private static bool IsRecalled(Character character)
|
||||
{
|
||||
ZNetView view = character.GetComponent<ZNetView>();
|
||||
return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the archers
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer
|
||||
/// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a
|
||||
/// new archer - not at once, because after a reload the ship is loaded a moment before the archers
|
||||
/// that were standing on it, and spawning then would double them. A second archer found on a post
|
||||
/// that is already held is removed.
|
||||
/// </summary>
|
||||
private void TickArchers(float elapsed)
|
||||
{
|
||||
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
|
||||
if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet
|
||||
|
||||
int posts = fittings.ArcherPosts.Count;
|
||||
if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts];
|
||||
|
||||
ZDO shipZdo = m_nview.GetZDO();
|
||||
ZDOID mine = shipZdo.m_uid;
|
||||
|
||||
// ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest.
|
||||
//
|
||||
// The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first
|
||||
// version only counted the archers it could see and spawned one for any post it saw nobody on -
|
||||
// and "can see" is only what is loaded, so a ship that woke before its archers did, or a post
|
||||
// whose archer sat in a zone the owner had not loaded, got a second archer on top of the first,
|
||||
// again at every reload. The register does not depend on what is loaded. Archers made before the
|
||||
// register existed have no entry: the first found is adopted, the others are the duplicates.
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null) continue;
|
||||
|
||||
ZNetView view = character.GetComponent<ZNetView>();
|
||||
if (view == null || view.GetZDO() == null) continue;
|
||||
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
|
||||
|
||||
int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1);
|
||||
if (post < 0 || post >= posts)
|
||||
{
|
||||
RemoveArcher(character, view, "a post this ship no longer has");
|
||||
continue;
|
||||
}
|
||||
|
||||
ZDOID registered = shipZdo.GetZDOID(SlotKey(post));
|
||||
ZDOID self = view.GetZDO().m_uid;
|
||||
|
||||
if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self);
|
||||
else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post);
|
||||
}
|
||||
|
||||
// ---- 2. posts whose registered archer is gone: a new one, after a short grace.
|
||||
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null;
|
||||
|
||||
for (int i = 0; i < posts; i++)
|
||||
{
|
||||
ZDOID registered = shipZdo.GetZDOID(SlotKey(i));
|
||||
bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null;
|
||||
|
||||
if (exists)
|
||||
{
|
||||
m_postEmptyFor[i] = 0f;
|
||||
continue;
|
||||
}
|
||||
|
||||
m_postEmptyFor[i] += elapsed;
|
||||
if (m_postEmptyFor[i] < ArcherGraceSeconds) continue;
|
||||
m_postEmptyFor[i] = 0f;
|
||||
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}.");
|
||||
continue;
|
||||
}
|
||||
|
||||
SpawnArcher(prefab, i, fittings.ArcherPosts[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private static string SlotKey(int post) => "RoV_bshArcher" + post;
|
||||
|
||||
private void RemoveArcher(Character character, ZNetView view, string why)
|
||||
{
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}.");
|
||||
view.ClaimOwnership();
|
||||
ZNetScene.instance.Destroy(character.gameObject);
|
||||
}
|
||||
|
||||
private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at)
|
||||
{
|
||||
Vector3 world = transform.TransformPoint(at.Local);
|
||||
GameObject archer = Instantiate(prefab, world, transform.rotation);
|
||||
|
||||
// The ship's id and the place on it go into the archer's own ZDO at once, before its mount first
|
||||
// runs, so it knows where it stands from its first physics step - and again after any reload.
|
||||
ZNetView view = archer.GetComponent<ZNetView>();
|
||||
if (view != null && view.GetZDO() != null)
|
||||
{
|
||||
ZDO zdo = view.GetZDO();
|
||||
zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid);
|
||||
zdo.Set(ShipMount.KeyArcherPoint, at.Local);
|
||||
zdo.Set(ShipMount.KeyArcherBust, at.Bust);
|
||||
zdo.Set(ShipMount.KeyArcherPost, post);
|
||||
|
||||
// Signed into the ship's register straight away, so the very next check already knows.
|
||||
m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid);
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " +
|
||||
$"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2}).");
|
||||
}
|
||||
|
||||
// Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes.
|
||||
MonsterAI ai = archer.GetComponent<MonsterAI>();
|
||||
if (ai != null) ai.MakeTame();
|
||||
Character character = archer.GetComponent<Character>();
|
||||
if (character != null) character.SetTamed(true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the ship falls
|
||||
|
||||
/// <summary>
|
||||
/// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate
|
||||
/// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone
|
||||
/// outlive the ship - the known gap, noted in the design.
|
||||
/// </summary>
|
||||
private void OnDestroyed()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsOwner()) return;
|
||||
|
||||
int lost = 0;
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
||||
|
||||
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
||||
if (thrall != null) thrall.Kill();
|
||||
lost++;
|
||||
}
|
||||
|
||||
// The archers go down with it as well; they are not counted among the troops that are lost.
|
||||
ZDOID mine = m_nview.GetZDO().m_uid;
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null) continue;
|
||||
|
||||
ZNetView view = character.GetComponent<ZNetView>();
|
||||
if (view == null || view.GetZDO() == null) continue;
|
||||
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
|
||||
|
||||
view.ClaimOwnership();
|
||||
ZNetScene.instance.Destroy(character.gameObject);
|
||||
}
|
||||
|
||||
if (lost > 0 && Player.m_localPlayer != null)
|
||||
{
|
||||
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
private Player Master()
|
||||
{
|
||||
Piece piece = GetComponent<Piece>();
|
||||
long creator = piece != null ? piece.GetCreator() : 0L;
|
||||
|
||||
if (creator != 0L)
|
||||
{
|
||||
foreach (Player player in Player.GetAllPlayers())
|
||||
{
|
||||
if (player != null && player.GetPlayerID() == creator) return player;
|
||||
}
|
||||
}
|
||||
|
||||
// Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed.
|
||||
return Player.GetClosestPlayer(transform.position, 40f);
|
||||
}
|
||||
|
||||
private bool BelongsHere(Character character)
|
||||
{
|
||||
ZNetView view = character.GetComponent<ZNetView>();
|
||||
if (view == null || view.GetZDO() == null) return false;
|
||||
return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid;
|
||||
}
|
||||
|
||||
private int CountDeployed(string kind)
|
||||
{
|
||||
int count = 0;
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
|
||||
|
||||
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
|
||||
string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged
|
||||
? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
|
||||
if (troopKind == kind) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0;
|
||||
|
||||
private void SetSlots(string kind, int value)
|
||||
{
|
||||
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value));
|
||||
}
|
||||
|
||||
private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0;
|
||||
|
||||
private void SetAboard(string kind, int value)
|
||||
{
|
||||
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value));
|
||||
}
|
||||
|
||||
private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged);
|
||||
|
||||
private int MeleeCap() => BoneShip.MeleeCapOf(this);
|
||||
|
||||
private int RangedCap() => BoneShip.RangedCapOf(this);
|
||||
|
||||
private int TotalCap() => MeleeCap() + RangedCap();
|
||||
}
|
||||
}
|
||||
480
JotunnModStub/BoneShip/BoneShipRowers.cs
Normal file
480
JotunnModStub/BoneShip/BoneShipRowers.cs
Normal file
|
|
@ -0,0 +1,480 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship
|
||||
/// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4.
|
||||
///
|
||||
/// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the
|
||||
/// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO
|
||||
/// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come
|
||||
/// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear
|
||||
/// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent.
|
||||
///
|
||||
/// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too,
|
||||
/// from two stretched cubes in the ship's own wood.
|
||||
///
|
||||
/// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench
|
||||
/// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting
|
||||
/// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut.
|
||||
///
|
||||
/// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle
|
||||
/// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so
|
||||
/// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is
|
||||
/// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged
|
||||
/// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides.
|
||||
///
|
||||
/// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull,
|
||||
/// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the
|
||||
/// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level.
|
||||
/// </summary>
|
||||
public class BoneShipRowers : MonoBehaviour
|
||||
{
|
||||
// The model, and how big the oarsmen are.
|
||||
private const string SkeletonPrefab = "Skeleton";
|
||||
private const float ModelHeight = 1.7f;
|
||||
|
||||
// Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's
|
||||
// are further apart because its helm and bow seats leave less room between.
|
||||
// The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3
|
||||
// and the offering chest stands beside it, and a bench at +1.0 was in the way.
|
||||
private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f };
|
||||
private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f };
|
||||
|
||||
private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little
|
||||
private const float OarlockLift = 0.12f; // oarlock above the rail's top
|
||||
private const float OarInboard = 0.75f; // handle end, from the oarlock
|
||||
private const float OarOutboard = 1.70f; // blade end
|
||||
|
||||
// The stroke.
|
||||
private const float SweepMax = 0.45f; // radians, blade fore and aft
|
||||
private const float LiftMax = 0.35f; // radians, blade up on the recovery
|
||||
private const float LeanMax = 14f; // degrees, rower back and forth
|
||||
private const float PeriodSlow = 2.6f;
|
||||
private const float PeriodHalf = 1.9f;
|
||||
private const float PeriodFull = 1.3f;
|
||||
|
||||
private class Seat
|
||||
{
|
||||
public GameObject Root; // at the hips, in the ship's space
|
||||
public GameObject Bench;
|
||||
public Transform Lean; // rotates about the hips
|
||||
public Transform Oar;
|
||||
public int Side; // +1 right, -1 left
|
||||
public Vector3 Oarlock; // ship space
|
||||
public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand;
|
||||
}
|
||||
|
||||
private readonly List<Seat> m_seats = new List<Seat>();
|
||||
private ZNetView m_nview;
|
||||
private Ship m_ship;
|
||||
|
||||
private float m_phase;
|
||||
private float m_amplitude;
|
||||
private bool m_built;
|
||||
|
||||
private static GameObject s_holder;
|
||||
private static GameObject s_template;
|
||||
private static bool s_templateTried;
|
||||
private static Mesh s_cube;
|
||||
private static bool s_loggedBones;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
m_nview = GetComponent<ZNetView>();
|
||||
m_ship = GetComponent<Ship>();
|
||||
if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost
|
||||
|
||||
StartCoroutine(Build());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- building
|
||||
|
||||
private IEnumerator Build()
|
||||
{
|
||||
// The fittings measure the hull the same way, a physics step after the ship exists.
|
||||
yield return new WaitForFixedUpdate();
|
||||
yield return null;
|
||||
yield return null;
|
||||
|
||||
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
|
||||
Bounds hull;
|
||||
if (fittings == null || !fittings.TryHullExtent(out hull))
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on.");
|
||||
yield break;
|
||||
}
|
||||
|
||||
GameObject template = Template();
|
||||
if (template == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers.");
|
||||
yield break;
|
||||
}
|
||||
|
||||
float hx = hull.extents.x;
|
||||
float hz = hull.extents.z;
|
||||
float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2);
|
||||
Material wood = FindWood();
|
||||
int rays = 0;
|
||||
|
||||
for (int side = -1; side <= 1; side += 2)
|
||||
{
|
||||
foreach (float f in zs)
|
||||
{
|
||||
float z = f * hz;
|
||||
|
||||
Vector3 rail;
|
||||
if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue;
|
||||
|
||||
float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f);
|
||||
Vector3 deck;
|
||||
if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue;
|
||||
|
||||
m_seats.Add(MakeSeat(template, wood, side, deck, rail, z));
|
||||
if (++rays >= 30) { rays = 0; yield return null; }
|
||||
}
|
||||
}
|
||||
|
||||
// Fill order: both sides at each station, from the bow back, so a short crew is balanced.
|
||||
m_seats.Sort((a, b) =>
|
||||
{
|
||||
int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z);
|
||||
return byStation != 0 ? byStation : a.Side.CompareTo(b.Side);
|
||||
});
|
||||
|
||||
m_built = true;
|
||||
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where along the hull the benches go, for this many on each side: the hand-placed lists where they
|
||||
/// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any
|
||||
/// other number - the Ashlands ship has six a side.
|
||||
/// </summary>
|
||||
private static float[] SeatStations(int perSide)
|
||||
{
|
||||
if (perSide == SmallSeatsZ.Length) return SmallSeatsZ;
|
||||
if (perSide == LargeSeatsZ.Length) return LargeSeatsZ;
|
||||
|
||||
float[] stations = new float[perSide];
|
||||
for (int i = 0; i < perSide; i++)
|
||||
{
|
||||
float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1);
|
||||
stations[i] = Mathf.Lerp(-0.52f, 0.24f, t);
|
||||
}
|
||||
return stations;
|
||||
}
|
||||
|
||||
private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z)
|
||||
{
|
||||
Seat seat = new Seat { Side = side };
|
||||
|
||||
// The hips, at bench height above the deck.
|
||||
GameObject root = new GameObject("Rower");
|
||||
root.transform.SetParent(transform, false);
|
||||
root.transform.localPosition = deck + Vector3.up * SeatHeight;
|
||||
seat.Root = root;
|
||||
|
||||
GameObject lean = new GameObject("Lean");
|
||||
lean.transform.SetParent(root.transform, false);
|
||||
seat.Lean = lean.transform;
|
||||
|
||||
// Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from
|
||||
// what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is
|
||||
// left as it comes: no turn.
|
||||
GameObject model = Instantiate(template, lean.transform, false);
|
||||
model.name = "model";
|
||||
model.transform.localRotation = Quaternion.identity;
|
||||
model.transform.localScale = Vector3.one * (ModelHeight / 1.8f);
|
||||
model.SetActive(true);
|
||||
|
||||
Animator animator = model.GetComponentInChildren<Animator>(true);
|
||||
if (animator != null)
|
||||
{
|
||||
// The idle clip fires animation events at a receiver the strip removed: unanswered, each
|
||||
// one logs an error. Switched off, the clip still poses the body.
|
||||
animator.fireEvents = false;
|
||||
animator.applyRootMotion = false;
|
||||
}
|
||||
|
||||
FindBones(model.transform, seat);
|
||||
SeatHips(model.transform, lean.transform, seat);
|
||||
|
||||
// A bench, across the beam, so nobody sits on nothing.
|
||||
GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f));
|
||||
bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z);
|
||||
|
||||
// The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard).
|
||||
seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z);
|
||||
GameObject oar = new GameObject("Oar");
|
||||
oar.transform.SetParent(transform, false);
|
||||
oar.transform.localPosition = seat.Oarlock;
|
||||
seat.Oar = oar.transform;
|
||||
|
||||
float length = OarInboard + OarOutboard;
|
||||
GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length));
|
||||
shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f);
|
||||
GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f));
|
||||
blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f);
|
||||
|
||||
root.SetActive(false);
|
||||
oar.SetActive(false);
|
||||
bench.SetActive(false);
|
||||
seat.Root = root;
|
||||
seat.Bench = bench;
|
||||
return seat;
|
||||
}
|
||||
|
||||
/// <summary>Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height.</summary>
|
||||
private static void SeatHips(Transform model, Transform pivot, Seat seat)
|
||||
{
|
||||
Transform hips = Find(model, "hips") ?? Find(model, "pelvis");
|
||||
if (hips != null)
|
||||
{
|
||||
Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position);
|
||||
model.localPosition -= hipsInPivot;
|
||||
}
|
||||
else
|
||||
{
|
||||
model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the stroke
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return;
|
||||
|
||||
int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0);
|
||||
|
||||
Ship.Speed gear = m_ship.GetSpeedSetting();
|
||||
float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow;
|
||||
bool rowing = gear != Ship.Speed.Stop && (crew > 0);
|
||||
|
||||
m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f);
|
||||
if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f);
|
||||
|
||||
float twoPi = Mathf.PI * 2f;
|
||||
float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5
|
||||
float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water
|
||||
recovery = recovery * recovery * (3f - 2f * recovery);
|
||||
float lift = Mathf.Lerp(-0.08f, LiftMax, recovery);
|
||||
float lean = LeanMax * sweep;
|
||||
|
||||
for (int i = 0; i < m_seats.Count; i++)
|
||||
{
|
||||
Seat seat = m_seats[i];
|
||||
bool shown = i < crew;
|
||||
|
||||
seat.Root.SetActive(shown);
|
||||
seat.Oar.gameObject.SetActive(shown);
|
||||
seat.Bench.SetActive(shown);
|
||||
if (!shown) continue;
|
||||
|
||||
float psi = SweepMax * sweep * m_amplitude;
|
||||
float lam = Mathf.Lerp(0.10f, lift, m_amplitude);
|
||||
|
||||
// The oar's outboard direction in the ship's space: out across the beam, a little fore or
|
||||
// aft with the sweep (positive aft), and tilted up by the lift.
|
||||
Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam),
|
||||
Mathf.Sin(lam),
|
||||
-Mathf.Sin(psi) * Mathf.Cos(lam));
|
||||
seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up);
|
||||
|
||||
seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After the animator: the arms reach for the handle.</summary>
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (!m_built) return;
|
||||
|
||||
foreach (Seat seat in m_seats)
|
||||
{
|
||||
if (!seat.Root.activeSelf) continue;
|
||||
|
||||
// Two grips on the handle, near and far from the chest.
|
||||
Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f);
|
||||
Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f);
|
||||
|
||||
Reach(seat.LeftArm, seat.LeftFore, gripNear);
|
||||
Reach(seat.LeftFore, seat.LeftHand, gripNear);
|
||||
Reach(seat.RightArm, seat.RightFore, gripFar);
|
||||
Reach(seat.RightFore, seat.RightHand, gripFar);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Turns a bone, in world space, so the line to its child points at the target.</summary>
|
||||
private static void Reach(Transform bone, Transform child, Vector3 target)
|
||||
{
|
||||
if (bone == null || child == null) return;
|
||||
|
||||
Vector3 now = child.position - bone.position;
|
||||
Vector3 want = target - bone.position;
|
||||
if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return;
|
||||
|
||||
bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- bones
|
||||
|
||||
private static void FindBones(Transform model, Seat seat)
|
||||
{
|
||||
seat.LeftArm = Find(model, "leftarm");
|
||||
seat.LeftFore = Find(model, "leftforearm");
|
||||
seat.LeftHand = Find(model, "lefthand");
|
||||
seat.RightArm = Find(model, "rightarm");
|
||||
seat.RightFore = Find(model, "rightforearm");
|
||||
seat.RightHand = Find(model, "righthand");
|
||||
|
||||
if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null &&
|
||||
seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return;
|
||||
if (s_loggedBones) return;
|
||||
s_loggedBones = true;
|
||||
|
||||
List<string> names = new List<string>();
|
||||
foreach (Transform t in model.GetComponentsInChildren<Transform>(true)) names.Add(t.name);
|
||||
Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " +
|
||||
"their sides. Skeleton: " + string.Join(", ", names.ToArray()));
|
||||
}
|
||||
|
||||
/// <summary>A bone by name, ignoring case and any "mixamorig:"-style prefix.</summary>
|
||||
private static Transform Find(Transform root, string lowerName)
|
||||
{
|
||||
foreach (Transform t in root.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
string n = t.name.ToLowerInvariant();
|
||||
int colon = n.LastIndexOf(':');
|
||||
if (colon >= 0) n = n.Substring(colon + 1);
|
||||
if (n == lowerName) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- model, wood, boxes
|
||||
|
||||
/// <summary>
|
||||
/// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes,
|
||||
/// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because
|
||||
/// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the
|
||||
/// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every
|
||||
/// piece in the game. So each pass removes only what nothing still present requires, and passes repeat.
|
||||
/// </summary>
|
||||
private static GameObject Template()
|
||||
{
|
||||
if (s_templateTried) return s_template;
|
||||
s_templateTried = true;
|
||||
|
||||
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SkeletonPrefab);
|
||||
if (source == null) return null;
|
||||
|
||||
s_holder = new GameObject("RoV_BoneShipRowers");
|
||||
s_holder.SetActive(false);
|
||||
Object.DontDestroyOnLoad(s_holder);
|
||||
|
||||
GameObject copy = Object.Instantiate(source, s_holder.transform);
|
||||
copy.name = "RowerTemplate";
|
||||
|
||||
StripBehaviours(copy);
|
||||
|
||||
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true)) if (body != null) Object.DestroyImmediate(body);
|
||||
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true)) if (collider != null) Object.DestroyImmediate(collider);
|
||||
BoneShipFittings.StripEffects(copy);
|
||||
|
||||
copy.transform.localPosition = Vector3.zero;
|
||||
copy.transform.localRotation = Quaternion.identity;
|
||||
copy.transform.localScale = Vector3.one;
|
||||
|
||||
s_template = copy;
|
||||
return s_template;
|
||||
}
|
||||
|
||||
private static void StripBehaviours(GameObject root)
|
||||
{
|
||||
for (int pass = 0; pass < 12; pass++)
|
||||
{
|
||||
bool any = false;
|
||||
bool removed = false;
|
||||
|
||||
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
|
||||
{
|
||||
if (behaviour == null) continue;
|
||||
any = true;
|
||||
|
||||
if (RequiredByAnother(behaviour)) continue;
|
||||
Object.DestroyImmediate(behaviour);
|
||||
removed = true;
|
||||
}
|
||||
|
||||
if (!any) return;
|
||||
if (!removed) break;
|
||||
}
|
||||
|
||||
int left = 0;
|
||||
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true)) if (behaviour != null) left++;
|
||||
if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed.");
|
||||
}
|
||||
|
||||
private static bool RequiredByAnother(MonoBehaviour behaviour)
|
||||
{
|
||||
System.Type type = behaviour.GetType();
|
||||
|
||||
foreach (Component other in behaviour.GetComponents<Component>())
|
||||
{
|
||||
if (other == null || other == behaviour) continue;
|
||||
|
||||
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
|
||||
{
|
||||
RequireComponent need = (RequireComponent)attribute;
|
||||
if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool Needs(System.Type required, System.Type type)
|
||||
{
|
||||
return required != null && required.IsAssignableFrom(type);
|
||||
}
|
||||
|
||||
/// <summary>The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it.</summary>
|
||||
private Material FindWood()
|
||||
{
|
||||
foreach (Renderer renderer in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
|
||||
|
||||
foreach (Material material in renderer.sharedMaterials)
|
||||
{
|
||||
if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size)
|
||||
{
|
||||
if (s_cube == null)
|
||||
{
|
||||
GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
s_cube = primitive.GetComponent<MeshFilter>().sharedMesh;
|
||||
Object.Destroy(primitive);
|
||||
}
|
||||
|
||||
GameObject box = new GameObject(name);
|
||||
box.transform.SetParent(parent, false);
|
||||
box.transform.localScale = size;
|
||||
box.AddComponent<MeshFilter>().sharedMesh = s_cube;
|
||||
MeshRenderer renderer = box.AddComponent<MeshRenderer>();
|
||||
if (material != null) renderer.sharedMaterial = material;
|
||||
return box;
|
||||
}
|
||||
}
|
||||
}
|
||||
178
JotunnModStub/BoneShip/BoneShipSail.cs
Normal file
178
JotunnModStub/BoneShip/BoneShipSail.cs
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The bone ships' sails: black, and torn.
|
||||
///
|
||||
/// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of
|
||||
/// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is
|
||||
/// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the
|
||||
/// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the
|
||||
/// vanilla ships keep theirs.
|
||||
///
|
||||
/// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two
|
||||
/// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader
|
||||
/// actually clips on that alpha is the one thing only the game can confirm.
|
||||
/// </summary>
|
||||
public static class BoneShipSail
|
||||
{
|
||||
private const int Size = 256;
|
||||
|
||||
// The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes.
|
||||
private const float TearThreshold = 0.62f;
|
||||
private const float ShredThreshold = 0.70f;
|
||||
|
||||
public static void Apply(GameObject prefab, string shipName)
|
||||
{
|
||||
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
|
||||
int seed = shipName.GetHashCode();
|
||||
|
||||
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
|
||||
|
||||
Material[] shared = renderer.sharedMaterials;
|
||||
bool changed = false;
|
||||
|
||||
for (int i = 0; i < shared.Length; i++)
|
||||
{
|
||||
Material source = shared[i];
|
||||
if (!IsSail(source)) continue;
|
||||
|
||||
Material copy;
|
||||
if (!copies.TryGetValue(source, out copy))
|
||||
{
|
||||
copy = new Material(source) { name = source.name + "_bone" };
|
||||
copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode()));
|
||||
copy.SetColor("_Color", Color.white);
|
||||
copies[source] = copy;
|
||||
}
|
||||
|
||||
shared[i] = copy;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) renderer.sharedMaterials = shared;
|
||||
}
|
||||
|
||||
if (copies.Count == 0)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSail(Material material)
|
||||
{
|
||||
if (material == null || material.shader == null) return false;
|
||||
if (!material.HasProperty("_MainTex")) return false;
|
||||
|
||||
string name = material.name.ToLowerInvariant();
|
||||
return name.Contains("sail");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the texture
|
||||
|
||||
private static Texture2D Draw(int seed)
|
||||
{
|
||||
Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true)
|
||||
{
|
||||
name = "boneship_sail",
|
||||
wrapMode = TextureWrapMode.Clamp,
|
||||
filterMode = FilterMode.Bilinear,
|
||||
};
|
||||
|
||||
Color32[] pixels = new Color32[Size * Size];
|
||||
for (int y = 0; y < Size; y++)
|
||||
{
|
||||
float v = (y + 0.5f) / Size;
|
||||
for (int x = 0; x < Size; x++)
|
||||
{
|
||||
float u = (x + 0.5f) / Size;
|
||||
pixels[y * Size + x] = Pixel(u, v, seed);
|
||||
}
|
||||
}
|
||||
|
||||
texture.SetPixels32(pixels);
|
||||
texture.Apply(true, false);
|
||||
return texture;
|
||||
}
|
||||
|
||||
private static Color32 Pixel(float u, float v, int seed)
|
||||
{
|
||||
// Cloth: near black, mottled, with a faint warp of vertical streaks.
|
||||
float mottle = Fbm(u * 7f, v * 7f, seed + 3);
|
||||
float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f);
|
||||
float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak);
|
||||
Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f);
|
||||
|
||||
// Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins.
|
||||
float tear = Fbm(u * 4f, v * 4f, seed + 11);
|
||||
float shred = Fbm(u * 13f, v * 13f, seed + 29);
|
||||
|
||||
float alpha = 1f;
|
||||
alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f);
|
||||
alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f);
|
||||
|
||||
// Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little.
|
||||
float edge = Mathf.Min(v, 1f - v);
|
||||
float teeth = ValueNoise(u * 22f, v * 3f, seed + 41);
|
||||
alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f);
|
||||
|
||||
float side = Mathf.Min(u, 1f - u);
|
||||
float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53);
|
||||
alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f);
|
||||
|
||||
// Scorched round the holes: darker where the tear is nearly through.
|
||||
float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f);
|
||||
cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f);
|
||||
|
||||
cloth.a = Mathf.Clamp01(alpha);
|
||||
return cloth;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- noise
|
||||
|
||||
private static float Hash(int x, int y, int seed)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
|
||||
h = (h ^ (h >> 13)) * 1274126177;
|
||||
return ((h ^ (h >> 16)) & 0xffff) / 65535f;
|
||||
}
|
||||
}
|
||||
|
||||
private static float ValueNoise(float x, float y, int seed)
|
||||
{
|
||||
int xi = Mathf.FloorToInt(x);
|
||||
int yi = Mathf.FloorToInt(y);
|
||||
float tx = x - xi;
|
||||
float ty = y - yi;
|
||||
tx = tx * tx * (3f - 2f * tx);
|
||||
ty = ty * ty * (3f - 2f * ty);
|
||||
|
||||
float a = Hash(xi, yi, seed);
|
||||
float b = Hash(xi + 1, yi, seed);
|
||||
float c = Hash(xi, yi + 1, seed);
|
||||
float d = Hash(xi + 1, yi + 1, seed);
|
||||
|
||||
return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty);
|
||||
}
|
||||
|
||||
private static float Fbm(float x, float y, int seed)
|
||||
{
|
||||
float value = 0f;
|
||||
float amplitude = 0.5f;
|
||||
for (int octave = 0; octave < 4; octave++)
|
||||
{
|
||||
value += amplitude * ValueNoise(x, y, seed + octave * 17);
|
||||
x *= 2.03f;
|
||||
y *= 2.03f;
|
||||
amplitude *= 0.5f;
|
||||
}
|
||||
return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1
|
||||
}
|
||||
}
|
||||
}
|
||||
392
JotunnModStub/BoneShip/ShipMount.cs
Normal file
392
JotunnModStub/BoneShip/ShipMount.cs
Normal file
|
|
@ -0,0 +1,392 @@
|
|||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Holds a creature to one spot of a ship's deck, however the ship moves.
|
||||
///
|
||||
/// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer
|
||||
/// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it
|
||||
/// is carried only as far as the game's own ground-body inheritance happens to carry it. So each
|
||||
/// physics step the mount sets its position to the ship's local point and its velocity to the ship's
|
||||
/// velocity at that point. Rotation is left to the archer: it turns to face what it shoots.
|
||||
///
|
||||
/// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own
|
||||
/// ZSyncTransform.
|
||||
///
|
||||
/// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not
|
||||
/// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab
|
||||
/// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its
|
||||
/// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's
|
||||
/// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies
|
||||
/// with the ship", with nothing to remember.
|
||||
/// </summary>
|
||||
public class ShipMount : MonoBehaviour
|
||||
{
|
||||
/// <summary>ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it.</summary>
|
||||
public const string KeyArcherShip = "RoV_bshArcherShip";
|
||||
public const string KeyArcherPoint = "RoV_bshArcherPoint";
|
||||
public const string KeyArcherBust = "RoV_bshArcherBust";
|
||||
public const string KeyArcherPost = "RoV_bshArcherPost";
|
||||
|
||||
/// <summary>Seconds without the ship's ZDO before the archer decides the ship is gone.</summary>
|
||||
private const float GoneAfter = 6f;
|
||||
|
||||
/// <summary>The ship this creature is bolted to.</summary>
|
||||
public Ship Ship;
|
||||
|
||||
/// <summary>Where on that ship, in the ship's own space.</summary>
|
||||
public Vector3 LocalPoint;
|
||||
|
||||
private ZNetView m_nview;
|
||||
private Rigidbody m_body;
|
||||
private Rigidbody m_shipBody;
|
||||
private ZDOID m_shipId = ZDOID.None;
|
||||
private bool m_byId;
|
||||
private float m_missing;
|
||||
|
||||
private float m_nextResolve;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
m_nview = GetComponent<ZNetView>();
|
||||
m_body = GetComponent<Rigidbody>();
|
||||
|
||||
// No interpolation on the archer's own body: the transform is set by hand every frame in
|
||||
// LateUpdate, and a body that interpolates between physics steps would fight that and put back
|
||||
// the very stutter this exists to remove.
|
||||
if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None;
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
if (Ship != null) { IgnoreShipColliders(); return; }
|
||||
|
||||
// The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the
|
||||
// owner, because every client pins the visual to the ship (LateUpdate).
|
||||
if (m_nview == null || !m_nview.IsValid()) return;
|
||||
m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip);
|
||||
if (m_shipId == ZDOID.None) return;
|
||||
|
||||
LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero);
|
||||
m_byId = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every frame, on every client: the archer's transform is the ship's local point, taken from the
|
||||
/// ship's own (interpolated) transform at render time.
|
||||
///
|
||||
/// The physics pin below only moves the archer once per physics step, from where the ship was at the
|
||||
/// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed
|
||||
/// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind,
|
||||
/// looking not quite attached. Setting the transform here, after everything else has moved it, makes
|
||||
/// it exactly as smooth as the hull it stands on. For a remote client this also overrides the
|
||||
/// position the network would give it, which is itself a few steps old.
|
||||
/// </summary>
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (Ship == null)
|
||||
{
|
||||
if (m_byId && Time.time >= m_nextResolve)
|
||||
{
|
||||
m_nextResolve = Time.time + 0.5f;
|
||||
TryResolveShip();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
transform.position = Ship.transform.TransformPoint(LocalPoint);
|
||||
}
|
||||
|
||||
private bool TryResolveShip()
|
||||
{
|
||||
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null;
|
||||
Ship ship = found != null ? found.GetComponent<Ship>() : null;
|
||||
if (ship == null) return false;
|
||||
|
||||
Ship = ship;
|
||||
m_missing = 0f;
|
||||
IgnoreShipColliders();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the
|
||||
/// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs
|
||||
/// nothing - it is invulnerable, and nobody needs to bump into it.
|
||||
/// </summary>
|
||||
private void IgnoreShipColliders()
|
||||
{
|
||||
Collider[] mine = GetComponentsInChildren<Collider>(true);
|
||||
Collider[] theirs = Ship.GetComponentsInChildren<Collider>(true);
|
||||
foreach (Collider a in mine)
|
||||
{
|
||||
if (a == null) continue;
|
||||
foreach (Collider b in theirs)
|
||||
{
|
||||
if (b != null) Physics.IgnoreCollision(a, b, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
|
||||
|
||||
if (Ship == null)
|
||||
{
|
||||
if (m_byId) FindShip();
|
||||
else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_body == null) return;
|
||||
if (m_shipBody == null) m_shipBody = Ship.GetComponent<Rigidbody>();
|
||||
|
||||
Vector3 target = Ship.transform.TransformPoint(LocalPoint);
|
||||
m_body.position = target;
|
||||
m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is
|
||||
/// about to be (they load together). Not in the books at all, for long enough: it has sunk.
|
||||
/// </summary>
|
||||
private void FindShip()
|
||||
{
|
||||
if (TryResolveShip()) return;
|
||||
|
||||
if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null)
|
||||
{
|
||||
m_missing = 0f;
|
||||
return;
|
||||
}
|
||||
|
||||
m_missing += Time.fixedDeltaTime;
|
||||
if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the
|
||||
/// chest and the arms show - a figurehead that shoots.
|
||||
///
|
||||
/// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned
|
||||
/// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it.
|
||||
/// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them
|
||||
/// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the
|
||||
/// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the
|
||||
/// list the next attempt is written from.
|
||||
/// </summary>
|
||||
public class ShipBust : MonoBehaviour
|
||||
{
|
||||
private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" };
|
||||
|
||||
private readonly List<Transform> m_legs = new List<Transform>();
|
||||
|
||||
/// <summary>Set by the F7 experiment; the real archers say so in their ZDO instead.</summary>
|
||||
public bool Force;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// On the prefab of the real archers this component is always there, and only the ones placed as a
|
||||
// bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs.
|
||||
ZNetView nview = GetComponent<ZNetView>();
|
||||
bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false));
|
||||
if (!bust)
|
||||
{
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (Transform t in GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
string n = t.name.ToLowerInvariant();
|
||||
foreach (string key in LegBones)
|
||||
{
|
||||
if (!n.Contains(key)) continue;
|
||||
|
||||
// Only the topmost of a chain: a bone whose parent is already a leg is covered by it.
|
||||
if (!m_legs.Contains(t.parent)) m_legs.Add(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (m_legs.Count > 0)
|
||||
{
|
||||
List<string> names = new List<string>();
|
||||
foreach (Transform t in m_legs) names.Add(t.name);
|
||||
Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Nothing matched: say what is there so the names can be read instead of guessed.
|
||||
List<string> all = new List<string>();
|
||||
foreach (Transform t in GetComponentsInChildren<Transform>(true)) all.Add(t.name);
|
||||
Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray()));
|
||||
}
|
||||
|
||||
private void LateUpdate()
|
||||
{
|
||||
foreach (Transform leg in m_legs)
|
||||
{
|
||||
if (leg != null) leg.localScale = Vector3.zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping
|
||||
/// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Character), "Damage")]
|
||||
public static class ShipMountInvulnerablePatch
|
||||
{
|
||||
public static bool Prefix(Character __instance)
|
||||
{
|
||||
return __instance.GetComponent<ShipMount>() == null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The deck-finding and post table the bone ships use to place their archers.
|
||||
///
|
||||
/// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that
|
||||
/// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's
|
||||
/// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing
|
||||
/// the table below, not by reading code.
|
||||
/// </summary>
|
||||
public static class ShipMountTest
|
||||
{
|
||||
private const float ShipRange = 40f;
|
||||
private const float RayStartHeight = 8f;
|
||||
private const float RayLength = 20f;
|
||||
|
||||
/// <summary>
|
||||
/// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and
|
||||
/// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots.
|
||||
/// </summary>
|
||||
private struct Post
|
||||
{
|
||||
public Vector2 At;
|
||||
public bool Bust;
|
||||
public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is
|
||||
/// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it.
|
||||
/// The large ships keep their deck posts until they get a bust of their own.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, Post[]> Posts = new Dictionary<string, Post[]>
|
||||
{
|
||||
{ "Karve", new[] { new Post(0f, 4.3f, true) } },
|
||||
{ "BoneKarve", new[] { new Post(0f, 4.3f, true) } },
|
||||
{ "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
||||
{ "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
||||
{ "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
||||
{ "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
||||
};
|
||||
|
||||
private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) };
|
||||
|
||||
/// <summary>
|
||||
/// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the
|
||||
/// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye.
|
||||
/// </summary>
|
||||
private const float BustLift = 0.0f;
|
||||
|
||||
/// <summary>The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail.</summary>
|
||||
private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName)
|
||||
{
|
||||
local = Vector3.zero;
|
||||
hitName = "";
|
||||
|
||||
// A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only
|
||||
// filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under
|
||||
// the point, and if the point is past the end of the hull it walks back toward the middle until
|
||||
// something is there - the step it settled on shows in the reported local z.
|
||||
float minUp = bust ? -1f : 0.5f;
|
||||
float maxBack = bust ? 2.4f : 0f;
|
||||
const float Step = 0.3f;
|
||||
|
||||
for (float back = 0f; back <= maxBack + 0.001f; back += Step)
|
||||
{
|
||||
Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back));
|
||||
Vector3 down = -ship.transform.up;
|
||||
|
||||
RaycastHit best = default(RaycastHit);
|
||||
bool found = false;
|
||||
float bestDistance = float.MaxValue;
|
||||
|
||||
foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength))
|
||||
{
|
||||
if (hit.collider == null || hit.collider.isTrigger) continue;
|
||||
if (!hit.collider.transform.IsChildOf(ship.transform)) continue;
|
||||
if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue;
|
||||
|
||||
string n = hit.collider.name.ToLowerInvariant();
|
||||
if (n.Contains("mast") || n.Contains("cloth")) continue;
|
||||
|
||||
if (hit.distance >= bestDistance) continue;
|
||||
best = hit;
|
||||
bestDistance = hit.distance;
|
||||
found = true;
|
||||
}
|
||||
|
||||
if (!found) continue;
|
||||
|
||||
local = ship.transform.InverseTransformPoint(best.point);
|
||||
hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : "");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Ship NearestShip()
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) return null;
|
||||
|
||||
Ship best = null;
|
||||
float bestDistance = ShipRange;
|
||||
foreach (Ship ship in Object.FindObjectsOfType<Ship>())
|
||||
{
|
||||
float distance = Vector3.Distance(ship.transform.position, player.transform.position);
|
||||
if (distance >= bestDistance) continue;
|
||||
best = ship;
|
||||
bestDistance = distance;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static List<ShipMount> MountsOn(Ship ship)
|
||||
{
|
||||
List<ShipMount> mounts = new List<ShipMount>();
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null) continue;
|
||||
|
||||
ShipMount mount = character.GetComponent<ShipMount>();
|
||||
if (mount != null && mount.Ship == ship) mounts.Add(mount);
|
||||
}
|
||||
return mounts;
|
||||
}
|
||||
|
||||
/// <summary>"Karve(Clone)" to "Karve".</summary>
|
||||
private static string Clean(string name)
|
||||
{
|
||||
int paren = name.IndexOf('(');
|
||||
return (paren >= 0 ? name.Substring(0, paren) : name).Trim();
|
||||
}
|
||||
|
||||
private static void Report(string line)
|
||||
{
|
||||
Jotunn.Logger.LogInfo(line);
|
||||
if (Console.instance != null) Console.instance.Print(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue