Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of NewShip v0.1.2
NewShip.dll
Decompiled 28 minutes agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using ModMenu; using NewShip.Core; using Unity.Collections; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("NewShip")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.2.0")] [assembly: AssemblyInformationalVersion("0.1.2+7580bc23ef579f194089ab813cc8dfc65404bab2")] [assembly: AssemblyProduct("NewShip")] [assembly: AssemblyTitle("NewShip")] [assembly: AssemblyVersion("0.1.2.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace NewShip { internal static class Applier { private const string ShipPath = "Environment/HangarShip"; private static readonly Dictionary<string, AssetBundle> bundles = new Dictionary<string, AssetBundle>(); internal static Transform Ship { get { if (!((Object)(object)StartOfRound.Instance != (Object)null) || !((Object)(object)StartOfRound.Instance.elevatorTransform != (Object)null)) { GameObject obj = GameObject.Find("Environment/HangarShip"); if (obj == null) { return null; } return obj.transform; } return StartOfRound.Instance.elevatorTransform; } } internal static GameObject Instance { get; private set; } internal static string BundlePath(HullSpec hull) { if (hull != null && hull.BundleFile != null) { return Path.Combine(Path.GetDirectoryName(typeof(Plugin).Assembly.Location) ?? ".", hull.BundleFile); } return null; } internal static void Apply(HullSpec hull) { //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) if (hull == null || hull.Id == HullId.Vanilla || !hull.Built) { return; } StartOfRound instance = StartOfRound.Instance; Transform ship = Ship; if ((Object)(object)instance == (Object)null || (Object)(object)ship == (Object)null) { Plugin.Log.LogWarning((object)"No HangarShip to swap"); } else { if ((Object)(object)Instance != (Object)null) { return; } GameObject val = LoadPrefab(hull); if ((Object)(object)val == (Object)null) { Plugin.Log.LogError((object)(hull.DisplayName + ": no prefab " + hull.Prefab + " in " + hull.BundleFile + "; keeping the vanilla hull")); return; } int num = MonitorVerts(ship); List<(Socket, Transform, Anchors.Entry, Vector3, float)> list = new List<(Socket, Transform, Anchors.Entry, Vector3, float)>(); int num2 = 0; foreach (Socket socket in hull.Sockets) { Transform val2 = Resolve(instance, ship, socket.Drives); if ((Object)(object)val2 == (Object)null) { if (!socket.Drives.Contains("(unchanged)") && !socket.Drives.StartsWith("CrewAwards")) { num2++; Plugin.Log.LogWarning((object)("socket " + socket.Name + ": " + socket.Drives + " not found")); } } else { Anchors.Entry entry = Anchors.For(socket.Drives); list.Add((socket, val2, entry, AnchorOf(ship, val2, entry), YawOf(ship, val2, entry))); } } HideVanilla(ship); Instance = Object.Instantiate<GameObject>(val, ship, false); ((Object)Instance).name = ((Object)val).name; SetLayers(ship, Instance.transform); Instance.AddComponent<BusRig>(); try { Porch.Build(ship, Instance); } catch (Exception arg) { Plugin.Log.LogError((object)$"The porch failed: {arg}"); } foreach (var (s, t, e, anchor, vanillaYaw) in list) { MoveToSocket(instance, ship, s, t, e, anchor, vanillaYaw); } Resize(ship, "ShipInnerRoomBoundsTrigger", hull.Room); Resize(ship, "ShipStrictInnerRoomBounds", hull.StrictRoom); Resize(ship, "ShipBoundsTrigger", hull.Bounds); Physics.SyncTransforms(); if (MonitorVerts(ship) != num) { Plugin.Log.LogError((object)"The monitor wall mesh changed; the tide clock and monitor mods will turn off"); } Plugin.Log.LogInfo((object)$"{hull.DisplayName}: hull swapped, {list.Count} parts moved onto their sockets, {num2} not found"); } } internal static void ClearScene() { Instance = null; } private static GameObject LoadPrefab(HullSpec hull) { if (!bundles.TryGetValue(hull.BundleFile, out var value) || (Object)(object)value == (Object)null) { string text = BundlePath(hull); if (text == null || !File.Exists(text)) { return null; } value = AssetBundle.LoadFromFile(text); bundles[hull.BundleFile] = value; } if (!((Object)(object)value != (Object)null)) { return null; } return value.LoadAsset<GameObject>(hull.Prefab); } private static void HideVanilla(Transform ship) { int num = 0; int num2 = 0; string[] hideVisual = Vanilla.HideVisual; foreach (string text in hideVisual) { Transform val = ship.Find(text); if ((Object)(object)val == (Object)null) { Plugin.V("hide: " + text + " not found"); continue; } Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true); for (int j = 0; j < componentsInChildren.Length; j++) { componentsInChildren[j].enabled = false; num++; } } hideVisual = Vanilla.CollidersOff; foreach (string text2 in hideVisual) { Transform val2 = ship.Find(text2); if ((Object)(object)val2 == (Object)null) { Plugin.V("colliders: " + text2 + " not found"); continue; } Collider[] componentsInChildren2 = ((Component)val2).GetComponentsInChildren<Collider>(true); foreach (Collider val3 in componentsInChildren2) { if (!val3.isTrigger) { val3.enabled = false; num2++; } } } hideVisual = Vanilla.Deactivate; foreach (string text3 in hideVisual) { Transform val4 = ship.Find(text3); if ((Object)(object)val4 != (Object)null) { ((Component)val4).gameObject.SetActive(false); } } Plugin.V($"vanilla hull: {num} meshes hidden, {num2} colliders off"); } private static void SetLayers(Transform ship, Transform root) { Transform val = ship.Find("ShipInside"); Transform val2 = ship.Find("ShipHull"); int layer = (((Object)(object)val != (Object)null) ? ((Component)val).gameObject.layer : 8); int layer2 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject.layer : 0); Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true); foreach (Transform val3 in componentsInChildren) { if (((Component)val3).GetComponents<Collider>().Any((Collider c) => !c.isTrigger)) { ((Component)val3).gameObject.layer = layer; } else if ((Object)(object)((Component)val3).GetComponent<Renderer>() != (Object)null) { ((Component)val3).gameObject.layer = layer2; } } } private static Vector3 AnchorOf(Transform ship, Transform t, Anchors.Entry e) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ship.InverseTransformPoint(t.position); if (e.Kind == AnchorKind.Node || e.Kind == AnchorKind.Camera) { return val; } bool flag = false; Bounds val2 = default(Bounds); Renderer[] componentsInChildren = ((Component)t).GetComponentsInChildren<Renderer>(true); Bounds val6 = default(Bounds); foreach (Renderer val3 in componentsInChildren) { if (val3 is ParticleSystemRenderer) { continue; } Bounds bounds = val3.bounds; if (((Bounds)(ref bounds)).size == Vector3.zero) { continue; } bounds = val3.bounds; Vector3 val4 = ship.InverseTransformPoint(((Bounds)(ref bounds)).center); Vector3 val5 = val4 - val; if (!(((Vector3)(ref val5)).magnitude > 3f)) { bounds = val3.bounds; ((Bounds)(ref val6))..ctor(val4, ((Bounds)(ref bounds)).size); if (!flag) { val2 = val6; flag = true; } else { ((Bounds)(ref val2)).Encapsulate(val6); } } } Vector3 val7 = (flag ? ((Bounds)(ref val2)).center : val); if (e.Kind != AnchorKind.Floor) { return val7; } return new Vector3(val7.x, 0f, val7.z); } private static float YawOf(Transform ship, Transform t, Anchors.Entry e) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (e.Kind != AnchorKind.Camera) { return e.VanillaYaw; } Camera componentInChildren = ((Component)t).GetComponentInChildren<Camera>(true); Vector3 val = ship.InverseTransformDirection((((Object)(object)componentInChildren != (Object)null) ? ((Component)componentInChildren).transform : t).forward); float num = Anchors.YawOf(new Vec3(val.x, val.y, val.z)); if (!float.IsNaN(num)) { return num; } return 0f; } private static void MoveToSocket(StartOfRound sor, Transform ship, Socket s, Transform t, Anchors.Entry e, Vector3 anchor, float vanillaYaw) { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(s.Pos.X, s.Pos.Y, s.Pos.Z); if (e.Kind == AnchorKind.Node) { t.position = ship.TransformPoint(val); if (s.Drives == "StartOfRound.rightmostSuitPosition") { Vec3 suitRackDir = Current.Spec.SuitRackDir; t.rotation = ship.rotation * Quaternion.LookRotation(new Vector3(suitRackDir.X, suitRackDir.Y, suitRackDir.Z), Vector3.up); } Plugin.V($"node {s.Name} -> {s.Drives} at {s.Pos}"); return; } float num = Anchors.Turn(vanillaYaw, s.Yaw); Quaternion val2 = Quaternion.Euler(0f, num, 0f); List<Transform> list = new List<Transform> { t }; string[] companions = e.Companions; foreach (string text in companions) { Transform val3 = ship.Find(text); if ((Object)(object)val3 != (Object)null) { list.Add(val3); } } foreach (Transform item in list) { Vector3 val4 = ship.InverseTransformPoint(item.position); Quaternion val5 = Quaternion.Inverse(ship.rotation) * item.rotation; item.position = ship.TransformPoint(val + val2 * ((val4 - anchor) * s.Scale)); item.rotation = ship.rotation * (val2 * val5); if (s.Scale != 1f) { item.localScale *= s.Scale; } FixShipParenting(sor, ship, item); } Plugin.V($"socket {s.Name} -> {s.Drives}: anchor {anchor} -> {val}, turned {num:0}"); } private static void FixShipParenting(StartOfRound sor, Transform ship, Transform m) { //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) PlaceableShipObject componentInChildren = ((Component)m).GetComponentInChildren<PlaceableShipObject>(true); AutoParentToShip val = (((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.parentObject != (Object)null) ? componentInChildren.parentObject : ((Component)m).GetComponent<AutoParentToShip>()); if ((Object)(object)val == (Object)null) { return; } bool flag = false; if ((Object)(object)componentInChildren != (Object)null && componentInChildren.unlockableID >= 0 && componentInChildren.unlockableID < sor.unlockablesList.unlockables.Count) { UnlockableItem val2 = sor.unlockablesList.unlockables[componentInChildren.unlockableID]; flag = val2.hasBeenMoved && val2.placedPosition != Vector3.zero; } if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren.parentObjectSecondary != (Object)null) { val.startingPosition = componentInChildren.parentObjectSecondary.position; val.startingRotation = componentInChildren.parentObjectSecondary.eulerAngles; return; } Transform transform = ((Component)val).transform; Vector3 val3 = ship.InverseTransformPoint(transform.position); Quaternion val4 = Quaternion.Inverse(ship.rotation) * transform.rotation; Vector3 eulerAngles = ((Quaternion)(ref val4)).eulerAngles; val.startingPosition = val3; val.startingRotation = eulerAngles; if (!flag) { val.positionOffset = val3; val.rotationOffset = eulerAngles; } } private static void Resize(Transform ship, string path, Box3 box) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) Transform val = ship.Find(path); if ((Object)(object)val == (Object)null) { Plugin.Log.LogWarning((object)(path + " not found; its bounds stay vanilla")); return; } val.localPosition = new Vector3(box.Center.X, box.Center.Y, box.Center.Z); val.localRotation = Quaternion.identity; val.localScale = new Vector3(box.Size.X, box.Size.Y, box.Size.Z); } private static int MonitorVerts(Transform ship) { Transform obj = ship.Find("ShipModels2b/MonitorWall"); MeshFilter val = ((obj != null) ? ((Component)obj).GetComponent<MeshFilter>() : null); if (!((Object)(object)val != (Object)null) || !((Object)(object)val.sharedMesh != (Object)null)) { return -1; } return val.sharedMesh.vertexCount; } internal static Transform Resolve(StartOfRound sor, Transform ship, string drives) { if (string.IsNullOrEmpty(drives) || drives.Contains("(unchanged)")) { return null; } if (drives.StartsWith("StartOfRound.")) { string text = drives.Substring("StartOfRound.".Length); int result = -1; int num = text.IndexOf('['); if (num > 0) { int.TryParse(text.Substring(num + 1).TrimEnd(']'), out result); text = text.Substring(0, num); } FieldInfo fieldInfo = AccessTools.Field(typeof(StartOfRound), text); if (fieldInfo == null) { return null; } object value = fieldInfo.GetValue(sor); if (result >= 0) { if (!(value is Transform[] array) || result >= array.Length) { return null; } return array[result]; } return (Transform)((value is Transform) ? value : null); } return ship.Find(drives); } } internal sealed class BusRig : MonoBehaviour { private SkinnedMeshRenderer balloon; private Transform flame; private Transform prop; private Vector3 flameScale = Vector3.one; private float fold = 100f; private float propSpeed; private bool first = true; private void Awake() { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) Transform obj = ((Component)this).transform.Find("Rig/Balloon"); balloon = ((obj != null) ? ((Component)obj).GetComponent<SkinnedMeshRenderer>() : null); flame = ((Component)this).transform.Find("Rig/Burner/Flame"); prop = ((Component)this).transform.Find("Rig/Propeller/PropSpin"); if ((Object)(object)flame != (Object)null) { flameScale = flame.localScale; } if ((Object)(object)balloon == (Object)null || (Object)(object)balloon.sharedMesh == (Object)null || balloon.sharedMesh.blendShapeCount == 0) { Plugin.Log.LogWarning((object)"The balloon has no Fold blend shape; it stays as built"); } } private void Update() { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; if (!((Object)(object)instance == (Object)null)) { bool parked = instance.shipHasLanded && !instance.shipIsLeaving; float num = Rig.Target(instance.shipHasLanded, instance.shipIsLeaving); fold = (first ? num : Rig.Step(fold, num, Time.deltaTime)); first = false; if ((Object)(object)balloon != (Object)null && (Object)(object)balloon.sharedMesh != (Object)null && balloon.sharedMesh.blendShapeCount > 0) { balloon.SetBlendShapeWeight(0, fold); } if ((Object)(object)flame != (Object)null) { flame.localScale = flameScale * Rig.Flame(fold); } propSpeed = Rig.PropStep(propSpeed, parked, Time.deltaTime); if ((Object)(object)prop != (Object)null && propSpeed > 0f) { prop.Rotate(Vector3.right * (propSpeed * Time.deltaTime), (Space)1); } } } } internal static class MenuHooks { internal const string ModMenuGuid = "daniel.lethalcompany.modmenu"; private const string Tab = "Ships"; [MethodImpl(MethodImplOptions.NoInlining)] internal static void Register() { HullId[] array = new HullId[5] { HullId.BattleBus, HullId.Haulback, HullId.Lantern, HullId.Mule, HullId.Vanilla }; string[] array2 = array.Select((HullId h) => Catalog.Get(h)?.DisplayName ?? "Vanilla ship").ToArray(); for (int num = 0; num < array.Length; num++) { HullId id = array[num]; string name = array2[num]; MenuApi.Button("Ships", "Hull: " + name, (Func<string>)(() => Pick(id, name)), false, false, (Func<string>)(() => Blocked(id)), (id == HullId.Vanilla) ? "the game's own ship" : Catalog.Get(id)?.Summary); } } private static string Blocked(HullId id) { if (Picker.Parse(Plugin.Hull.Value) == id) { if (Current.Hull != id) { return "picked, from the next game you host"; } return "picked, flying it now"; } if (id != HullId.Vanilla) { HullSpec hullSpec = Catalog.Get(id); if (hullSpec == null || !hullSpec.Built) { return "not built yet"; } } return null; } private static string Pick(HullId id, string name) { Plugin.Hull.Value = id.ToString(); if (Current.Hull != id) { return "picked the " + name + ": you fly it from the next game you host"; } return "picked the " + name + ", which you're flying now"; } } internal static class Net { [CompilerGenerated] private static class <>O { public static Action<ulong> <0>__OnConnected; public static Action<ulong> <1>__OnDisconnected; public static HandleNamedMessageDelegate <2>__OnHello; } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static HandleNamedMessageDelegate <>9__15_0; public static HandleNamedMessageDelegate <>9__15_1; public static Func<HullId, bool> <>9__18_0; internal void <Register>b__15_0(ulong sender, FastBufferReader r) { if (NM.IsServer) { SendHello(sender); } } internal void <Register>b__15_1(ulong sender, FastBufferReader r) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (NM.IsServer) { int num = default(int); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num, default(ForPrimitives)); answers[sender] = (HullId)num; Plugin.V($"client {sender} flies {(HullId)num}"); } } internal bool <OnHello>b__18_0(HullId id) { return Catalog.Get(id)?.Built ?? false; } } private const string AskMsg = "NewShip.Ask"; private const string HelloMsg = "NewShip.Hello"; private const string AckMsg = "NewShip.Ack"; private static CustomMessagingManager registeredOn; private static NetworkManager callbacksOn; private static readonly Dictionary<ulong, float> joinedAt = new Dictionary<ulong, float>(); private static readonly Dictionary<ulong, HullId> answers = new Dictionary<ulong, HullId>(); private static readonly HashSet<ulong> warned = new HashSet<ulong>(); private static bool gotHello; private static float nextAsk; private static int asks; private static readonly List<ulong> scratch = new List<ulong>(); private static NetworkManager NM => NetworkManager.Singleton; private static bool Online { get { if ((Object)(object)NM != (Object)null && NM.IsListening) { return NM.CustomMessagingManager != null; } return false; } } internal static void Register() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Expected O, but got Unknown NetworkManager nM = NM; if ((Object)(object)nM == (Object)null) { return; } if ((Object)(object)callbacksOn != (Object)(object)nM) { nM.OnClientConnectedCallback += OnConnected; nM.OnClientDisconnectCallback += OnDisconnected; callbacksOn = nM; } if (nM.CustomMessagingManager == null || registeredOn == nM.CustomMessagingManager) { return; } CustomMessagingManager customMessagingManager = nM.CustomMessagingManager; object obj = <>c.<>9__15_0; if (obj == null) { HandleNamedMessageDelegate val = delegate(ulong sender, FastBufferReader r) { if (NM.IsServer) { SendHello(sender); } }; <>c.<>9__15_0 = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("NewShip.Ask", (HandleNamedMessageDelegate)obj); object obj2 = <>O.<2>__OnHello; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnHello; <>O.<2>__OnHello = val2; obj2 = (object)val2; } customMessagingManager.RegisterNamedMessageHandler("NewShip.Hello", (HandleNamedMessageDelegate)obj2); object obj3 = <>c.<>9__15_1; if (obj3 == null) { HandleNamedMessageDelegate val3 = delegate(ulong sender, FastBufferReader r) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (NM.IsServer) { int num = default(int); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num, default(ForPrimitives)); answers[sender] = (HullId)num; Plugin.V($"client {sender} flies {(HullId)num}"); } }; <>c.<>9__15_1 = val3; obj3 = (object)val3; } customMessagingManager.RegisterNamedMessageHandler("NewShip.Ack", (HandleNamedMessageDelegate)obj3); registeredOn = customMessagingManager; } private static void OnConnected(ulong id) { if ((Object)(object)NM != (Object)null && NM.IsServer && id != 0L) { joinedAt[id] = Time.realtimeSinceStartup; } } private static void OnDisconnected(ulong id) { joinedAt.Remove(id); answers.Remove(id); warned.Remove(id); } private static void OnHello(ulong sender, FastBufferReader r) { if (NM.IsServer) { return; } string text = default(string); ((FastBufferReader)(ref r)).ReadValueSafe(ref text, false); gotHello = true; if (!Hello.TryDecode(text, out var hello)) { Plugin.Log.LogWarning((object)("Unreadable hello from the host: " + text)); Current.Set(HullId.Vanilla, "unreadable hello"); SendAck(HullId.Vanilla); return; } HullId fly; HandshakeResult num = Handshake.Check(hello, "0.1.2", (HullId id) => Catalog.Get(id)?.Built ?? false, out fly); if (num == HandshakeResult.VersionDiffers) { Plugin.Log.LogWarning((object)("The host has NewShip " + hello.ModVersion + ", you have 0.1.2")); } if (num == HandshakeResult.FallBackToVanilla) { Plugin.Log.LogWarning((object)$"Can't fly the host's {hello.Hull}; flying vanilla"); } Current.Set(fly, "the host's pick"); SendAck(fly); } internal static void ClearSession() { joinedAt.Clear(); answers.Clear(); warned.Clear(); gotHello = false; asks = 0; nextAsk = 0f; } private unsafe static void SendHello(ulong to) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(64, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe(new Hello("0.1.2", Current.Hull).Encode(), false); NM.CustomMessagingManager.SendNamedMessage("NewShip.Hello", to, val, (NetworkDelivery)2); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private unsafe static void SendAck(HullId fly) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1); try { int num = (int)fly; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); NM.CustomMessagingManager.SendNamedMessage("NewShip.Ack", 0uL, val, (NetworkDelivery)2); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } internal unsafe static void Tick() { //IL_01e3: Unknown result type (might be due to invalid IL or missing references) if (!Online) { return; } Register(); float realtimeSinceStartup = Time.realtimeSinceStartup; if (NM.IsServer) { scratch.Clear(); foreach (KeyValuePair<ulong, float> item in joinedAt) { if (!warned.Contains(item.Key)) { HullId value; HullId? answer = (answers.TryGetValue(item.Key, out value) ? new HullId?(value) : ((HullId?)null)); if (Handshake.NeedsWarning(Current.Hull, answer, realtimeSinceStartup - item.Value)) { scratch.Add(item.Key); } } } { foreach (ulong item2 in scratch) { warned.Add(item2); string text = (answers.ContainsKey(item2) ? ("can't fly the " + Current.Spec?.DisplayName) : "doesn't have NewShip"); Plugin.Log.LogWarning((object)$"Client {item2} {text}"); HUDManager instance = HUDManager.Instance; if (instance != null) { instance.DisplayTip("New Ship", "A player " + text + ". They see the vanilla ship and will walk through walls.", true, false, "LC_Tip1"); } } return; } } if (gotHello || asks >= 5 || realtimeSinceStartup < nextAsk || !NM.IsConnectedClient || (Object)(object)StartOfRound.Instance == (Object)null) { return; } asks++; nextAsk = realtimeSinceStartup + 3f; FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); try { NM.CustomMessagingManager.SendNamedMessage("NewShip.Ask", 0uL, val, (NetworkDelivery)2); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } } [HarmonyPatch(typeof(StartOfRound))] internal static class StartOfRoundHooks { [HarmonyPrefix] [HarmonyPatch("Start")] private static void StartPrefix() { Net.ClearSession(); Current.Reset(); Applier.ClearScene(); Net.Register(); if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsServer) { try { Current.Set(Picker.Resolve(Picker.Parse(Plugin.Hull.Value)), "host config"); } catch (Exception arg) { Plugin.Log.LogError((object)$"The hull swap failed: {arg}"); } } } [HarmonyPostfix] [HarmonyPatch("Start")] private static void StartPostfix() { if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.IsServer) { return; } try { SaveFix.AfterLoad(); } catch (Exception arg) { Plugin.Log.LogError((object)$"The old-save check failed: {arg}"); } } [HarmonyPostfix] [HarmonyPatch("Update")] private static void Update() { Net.Tick(); } } public static class PluginInfo { public const string Guid = "daniel.lethalcompany.newship"; public const string Name = "NewShip"; public const string Version = "0.1.2"; } [BepInPlugin("daniel.lethalcompany.newship", "NewShip", "0.1.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Log; internal static ConfigEntry<string> Hull; internal static ConfigEntry<bool> Verbose; private readonly Harmony _harmony = new Harmony("daniel.lethalcompany.newship"); private void Awake() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Hull = ((BaseUnityPlugin)this).Config.Bind<string>("Ship", "Hull", "BattleBus", new ConfigDescription("The ship the lobby flies when you host. Clients fly whatever the host picked. A ship that isn't built yet falls back to Vanilla.", (AcceptableValueBase)(object)new AcceptableValueList<string>(Enum.GetNames(typeof(HullId))), Array.Empty<object>())); Verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLog", false, "Log every hello and socket move."); string text = StandDown.Conflict(Chainloader.PluginInfos.Values.SelectMany((PluginInfo p) => new string[2] { p.Metadata.GUID, p.Metadata.Name })); if (text != null) { Log.LogWarning((object)(text + " reshapes the ship too; every lobby flies the vanilla ship")); } foreach (HullSpec item in Catalog.All) { item.Built = text == null && item.BundleFile != null && File.Exists(Applier.BundlePath(item)); } _harmony.PatchAll(typeof(Plugin).Assembly); if (Chainloader.PluginInfos.ContainsKey("daniel.lethalcompany.modmenu")) { MenuHooks.Register(); } foreach (HullSpec item2 in Catalog.All) { Log.LogInfo((object)(item2.DisplayName + ": " + item2.Summary + (item2.Built ? "" : " [falls back to vanilla]"))); } } internal static void V(string s) { if (Verbose != null && Verbose.Value) { Log.LogInfo((object)s); } } } internal static class Current { internal static HullId Hull { get; private set; } internal static HullSpec Spec => Catalog.Get(Hull); internal static void Set(HullId id, string why) { if (Hull != id) { Hull = id; Plugin.Log.LogInfo((object)("Flying " + ((Spec != null) ? Spec.DisplayName : "the vanilla ship") + " (" + why + ")")); Applier.Apply(Spec); } } internal static void Reset() { Hull = HullId.Vanilla; } } internal static class Porch { internal static void Build(Transform ship, GameObject hull) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) Transform val = ship.Find("LadderShort (1)"); if ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(false); } if ((Object)(object)hull.transform.Find("Porch") != (Object)null) { hull.AddComponent<PorchRig>().Init(ship); return; } Transform val2 = ship.Find("CatwalkShip"); object obj; if (!((Object)(object)val2 != (Object)null)) { obj = null; } else { Renderer component = ((Component)val2).GetComponent<Renderer>(); obj = ((component != null) ? component.sharedMaterial : null); } Material val3 = (Material)obj; Transform obj2 = ship.Find("ShipRails"); Renderer val4 = ((obj2 != null) ? ((Component)obj2).GetComponent<Renderer>() : null); Material mat = (((Object)(object)val4 != (Object)null) ? val4.sharedMaterial : val3); int layer = (((Object)(object)val2 != (Object)null) ? ((Component)val2).gameObject.layer : 0); Transform transform = new GameObject("FallbackPorch").transform; transform.SetParent(hull.transform, false); float num = -11f; float xb = -8.75f; float num2 = 2.4f; float num3 = -0.07f; float num4 = 0.12f; float h = 1.05f; float num5 = 0.06f; float num6 = 0.6f; Box(transform, "Deck", val3, layer, num, xb, 0f - num2, num2, num3 - num4, num3); Rail(transform, mat, layer, "RailLeft", num, xb, 0f - num2, 0f - num2 + num5, num3, h); Rail(transform, mat, layer, "RailRight", num, xb, num2 - num5, num2, num3, h); Rail(transform, mat, layer, "RailBackLeft", num, num + num5, 0f - num2, 0f - num6, num3, h); Rail(transform, mat, layer, "RailBackRight", num, num + num5, num6, num2, num3, h); Transform val5 = ship.Find("LadderShort"); if ((Object)(object)val5 != (Object)null) { val5.localPosition = ToShip(num + 0.13f, 0f, -2.58f); val5.localRotation = Quaternion.identity; Renderer[] componentsInChildren = ((Component)val5).GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].enabled = true; } } Plugin.V("fallback porch built at the door"); } private static Vector3 ToShip(float x, float y, float z) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) Vec3 vec = Catalog.D(x, y, z); return new Vector3(vec.X, vec.Y, vec.Z); } private static void Rail(Transform root, Material mat, int layer, string name, float xa, float xb, float ya, float yb, float top, float h) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) Transform transform = new GameObject(name).transform; transform.SetParent(root, false); ((Component)transform).gameObject.layer = layer; BoxCollider obj = ((Component)transform).gameObject.AddComponent<BoxCollider>(); Vector3 val = ToShip(xa, ya, top); Vector3 val2 = ToShip(xb, yb, top + h); obj.center = (val + val2) * 0.5f; obj.size = Abs(val2 - val); Box(transform, "Top", mat, layer, xa, xb, ya, yb, top + h - 0.05f, top + h, collide: false); Box(transform, "Mid", mat, layer, xa, xb, ya, yb, top + h * 0.5f - 0.025f, top + h * 0.5f + 0.025f, collide: false); bool flag = xb - xa > yb - ya; float num = (flag ? (xb - xa) : (yb - ya)); int num2 = Mathf.Max(1, Mathf.CeilToInt(num / 1.1f)); for (int i = 0; i <= num2; i++) { float num3 = (float)i / (float)num2; float num4 = (flag ? Mathf.Lerp(xa, xb - 0.05f, num3) : xa); float num5 = (flag ? ya : Mathf.Lerp(ya, yb - 0.05f, num3)); Box(transform, "Post" + i, mat, layer, num4, num4 + (flag ? 0.05f : (xb - xa)), num5, num5 + (flag ? (yb - ya) : 0.05f), top, top + h, collide: false); } } private static void Box(Transform parent, string name, Material mat, int layer, float xa, float xb, float ya, float yb, float za, float zb, bool collide = true) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.CreatePrimitive((PrimitiveType)3); ((Object)val).name = name; val.layer = layer; if (!collide) { Object.Destroy((Object)(object)val.GetComponent<Collider>()); } val.transform.SetParent(parent, false); Vector3 val2 = ToShip(xa, ya, za); Vector3 val3 = ToShip(xb, yb, zb); val.transform.localPosition = (val2 + val3) * 0.5f; val.transform.localScale = Abs(val3 - val2); Renderer component = val.GetComponent<Renderer>(); if ((Object)(object)mat != (Object)null) { component.sharedMaterial = mat; } } private static Vector3 Abs(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z)); } } internal sealed class PorchRig : MonoBehaviour { private sealed class Leg { public Transform Strut; public Transform Foot; public Vector3 StrutScale; public Vector3 FootRest; public int Axis; public float Extend; } private Transform ship; private readonly List<Leg> legs = new List<Leg>(); private readonly Transform[] sections = (Transform[])(object)new Transform[3]; private readonly Vector3[] sectionRest = (Vector3[])(object)new Vector3[3]; private float[] slides = new float[3]; private float t; private bool measured; private float ladderDepth = -1f; private InteractTrigger climb; private BoxCollider climbBox; private Transform climbTop; private Transform climbBottom; private Transform climbHorizontal; private Transform climbNode; internal void Init(Transform hangarShip) { //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) ship = hangarShip; Transform val = ((Component)this).transform.Find("Rig/Gear"); string[] array = Gear.Legs; foreach (string text in array) { Transform val2 = (((Object)(object)val != (Object)null) ? val.Find(text) : null); Transform val3 = (((Object)(object)val2 != (Object)null) ? val2.Find(text + "_Strut") : null); Transform val4 = (((Object)(object)val2 != (Object)null) ? val2.Find(text + "_Foot") : null); if ((Object)(object)val3 == (Object)null || (Object)(object)val4 == (Object)null) { Plugin.Log.LogWarning((object)("gear: " + text + " strut or foot missing")); continue; } legs.Add(new Leg { Strut = val3, Foot = val4, StrutScale = val3.localScale, FootRest = ship.InverseTransformPoint(val4.position), Axis = DownAxis(val3) }); } Transform val5 = ((Component)this).transform.Find("Porch/Ladder"); for (int j = 0; j < 3; j++) { sections[j] = (((Object)(object)val5 != (Object)null) ? val5.Find("Section" + j) : null); if ((Object)(object)sections[j] != (Object)null) { sectionRest[j] = ship.InverseTransformPoint(sections[j].position); } else { Plugin.Log.LogWarning((object)$"ladder: Section{j} missing"); } } SetUpClimb(); Plugin.V(string.Format("porch rig: {0} legs, ladder {1}, climb {2}", legs.Count, ((Object)(object)sections[0] != (Object)null) ? "found" : "missing", ((Object)(object)climb != (Object)null) ? "moved" : "missing")); } private int DownAxis(Transform strut) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Vector3 val = strut.InverseTransformDirection(-ship.up); float num = Mathf.Abs(val.x); float num2 = Mathf.Abs(val.y); float num3 = Mathf.Abs(val.z); if (!(num > num2) || !(num > num3)) { if (!(num2 > num3)) { return 2; } return 1; } return 0; } private void SetUpClimb() { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) Transform val = ship.Find("LadderShort/LadderTrigger"); climb = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<InteractTrigger>() : null); if ((Object)(object)climb == (Object)null || (Object)(object)climb.topOfLadderPosition == (Object)null || (Object)(object)climb.bottomOfLadderPosition == (Object)null || (Object)(object)climb.ladderHorizontalPosition == (Object)null || (Object)(object)climb.ladderPlayerPositionNode == (Object)null) { climb = null; Plugin.Log.LogWarning((object)"ladder: the vanilla climb trigger wasn't found; the drop ladder can't be climbed"); return; } Transform transform = new GameObject("LadderClimb").transform; transform.SetParent(((Component)this).transform, false); climbTop = climb.topOfLadderPosition; climbBottom = climb.bottomOfLadderPosition; climbHorizontal = climb.ladderHorizontalPosition; climbNode = climb.ladderPlayerPositionNode; Transform[] array = (Transform[])(object)new Transform[4] { climbTop, climbBottom, climbHorizontal, climbNode }; for (int i = 0; i < array.Length; i++) { array[i].SetParent(transform, true); } val.SetParent(transform, false); val.localScale = Vector3.one; climbBox = ((Component)val).GetComponent<BoxCollider>(); ((Component)val).gameObject.SetActive(false); } private void PlaceClimb(float groundZ) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)climb == (Object)null)) { float num = Mathf.Max(groundZ, Gear.LadderBottom(slides)); Quaternion rot = ship.rotation * Quaternion.LookRotation(Vector3.right); float x = -11.5f; Set(climbBottom, x, num, rot); Set(climbHorizontal, x, num, rot); Set(climbNode, x, num, rot); Set(climbTop, -10.45f, -0.07f, rot); Transform transform = ((Component)climb).transform; float num2 = 1.53f; Set(transform, -11.25f, (num + num2) * 0.5f, rot); if ((Object)(object)climbBox != (Object)null) { climbBox.center = Vector3.zero; climbBox.size = new Vector3(0.9f, Mathf.Max(0.5f, num2 - num), 0.6f); } } } private void Set(Transform t, float x, float z, Quaternion rot) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Vec3 vec = Catalog.D(x, 0f, z); t.position = ship.TransformPoint(new Vector3(vec.X, vec.Y, vec.Z)); t.rotation = rot; } private float Depth(Vector3 shipLocal) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) Vector3 val = -ship.up; float num = 1f; RaycastHit[] array = Physics.RaycastAll(ship.TransformPoint(new Vector3(shipLocal.x, num, shipLocal.z)), val, num + 6f + 2f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1); float num2 = float.MaxValue; RaycastHit[] array2 = array; for (int i = 0; i < array2.Length; i++) { RaycastHit val2 = array2[i]; if (!((RaycastHit)(ref val2)).transform.IsChildOf(ship) && ((RaycastHit)(ref val2)).distance < num2) { num2 = ((RaycastHit)(ref val2)).distance; } } if (num2 != float.MaxValue) { return Mathf.Max(0f, num2 - num); } return -1f; } private void Measure() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) foreach (Leg leg in legs) { leg.Extend = Gear.Extend(Depth(ship.InverseTransformPoint(leg.Strut.position))); } Vec3 vec = Catalog.D(-11.5f, 0f, 0f); ladderDepth = Depth(new Vector3(vec.X, 0f, vec.Z)); slides = Gear.Ladder(ladderDepth); PlaceClimb((ladderDepth < 0f) ? Gear.LadderBottom(slides) : (0f - ladderDepth)); Plugin.V(string.Format("porch rig: ground {0:0.00} m under the ladder, struts {1}", ladderDepth, string.Join("/", legs.ConvertAll((Leg l) => l.Extend.ToString("0.00"))))); } private void Update() { StartOfRound instance = StartOfRound.Instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)ship == (Object)null)) { bool flag = instance.shipHasLanded && !instance.shipIsLeaving; if (flag && !measured) { Physics.SyncTransforms(); Measure(); measured = true; } if (!flag) { measured = false; } float num = t; t = Gear.Step(t, flag, Time.deltaTime); if (t != num || Time.frameCount % 120 == 0) { Pose(Gear.Ease(t)); } if ((Object)(object)climb != (Object)null) { ((Component)climb).gameObject.SetActive(flag && t >= 1f); } } } private void Pose(float k) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) Vector3 down = Vector3.down; foreach (Leg leg in legs) { float num = leg.Extend * k; Vector3 strutScale = leg.StrutScale; if (leg.Axis == 0) { strutScale.x *= 1f + num; } else if (leg.Axis == 1) { strutScale.y *= 1f + num; } else { strutScale.z *= 1f + num; } leg.Strut.localScale = strutScale; leg.Foot.position = ship.TransformPoint(leg.FootRest + down * num); } for (int i = 0; i < 3; i++) { if ((Object)(object)sections[i] != (Object)null) { sections[i].position = ship.TransformPoint(sectionRest[i] + down * (slides[i] * k)); } } } } internal static class SaveFix { private const string HullKey = "NewShip_Hull"; private const string StoredKey = "NewShip_DefaultStored"; private static bool storedThisSave; internal static void AfterLoad() { StartOfRound sor = StartOfRound.Instance; HullSpec spec = Current.Spec; Transform ship = Applier.Ship; if ((Object)(object)sor == (Object)null || (Object)(object)ship == (Object)null || spec == null || (Object)(object)Applier.Instance == (Object)null) { return; } string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; int num = 0; try { num = (ES3.KeyExists("NewShip_Hull", currentSaveFileName) ? ES3.Load<int>("NewShip_Hull", currentSaveFileName) : 0); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't read the save's hull: " + ex.Message)); } int num2 = StoreDefaults(sor, ship, currentSaveFileName); List<PlaceableShipObject> list = (from p in Object.FindObjectsOfType<PlaceableShipObject>() where Usable(sor, p) select p).ToList(); int num3 = 0; if (num != (int)spec.Id) { foreach (PlaceableShipObject item in list) { if (sor.unlockablesList.unlockables[item.unlockableID].hasBeenMoved) { ShipBuildModeManager.Instance.ResetShipObjectToDefaultPosition(item); if ((Object)(object)item.parentObject != (Object)null) { item.parentObject.MoveToOffset(); } num3++; } } Physics.SyncTransforms(); } int num4 = 0; foreach (PlaceableShipObject item2 in list) { if (!Fits(ship, spec, item2) && Relocate(ship, spec, item2)) { num4++; } } int num5 = DropStrayScrap(sor, ship, spec); Plugin.Log.LogInfo((object)$"{spec.DisplayName}: save last flew {(HullId)num}; {num2} pieces put in storage, {num3} moved pieces reset, {num4} pieces refitted, {num5} scrap moved inside"); } internal static void Save() { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; if (Current.Hull != HullId.Vanilla || ES3.KeyExists("NewShip_Hull", currentSaveFileName)) { ES3.Save<int>("NewShip_Hull", (int)Current.Hull, currentSaveFileName); if (storedThisSave) { ES3.Save<bool>("NewShip_DefaultStored", true, currentSaveFileName); } } } private static int StoreDefaults(StartOfRound sor, Transform ship, string file) { //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) storedThisSave = false; bool flag = false; try { flag = ES3.KeyExists("NewShip_DefaultStored", file) && ES3.Load<bool>("NewShip_DefaultStored", file); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't read the stored-furniture flag: " + ex.Message)); } if (flag) { return 0; } int num = 0; string[] storedByDefault = Catalog.StoredByDefault; foreach (string text in storedByDefault) { Transform val = ship.Find(text); PlaceableShipObject val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentInChildren<PlaceableShipObject>(true) : null); if ((Object)(object)val2 == (Object)null || (Object)(object)val2.parentObject == (Object)null || val2.unlockableID < 0 || val2.unlockableID >= sor.unlockablesList.unlockables.Count) { Plugin.V("store: " + text + " not found"); continue; } UnlockableItem val3 = sor.unlockablesList.unlockables[val2.unlockableID]; if (!val3.inStorage && val3.canBeStored && (!val3.hasBeenMoved || !(val3.placedPosition != Vector3.zero))) { val3.inStorage = true; val2.parentObject.disableObject = true; num++; } } storedThisSave = true; return num; } private static bool Usable(StartOfRound sor, PlaceableShipObject p) { if ((Object)(object)p == (Object)null || (Object)(object)p.placeObjectCollider == (Object)null || p.unlockableID < 0 || p.unlockableID >= sor.unlockablesList.unlockables.Count) { return false; } UnlockableItem val = sor.unlockablesList.unlockables[p.unlockableID]; if (!val.inStorage) { if (!val.hasBeenUnlockedByPlayer) { return val.alreadyUnlocked; } return true; } return false; } private static Vec3 V(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vec3(v.x, v.y, v.z); } private static bool Fits(Transform ship, HullSpec hull, PlaceableShipObject p) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) Bounds bounds = p.placeObjectCollider.bounds; Vector3 v = ship.InverseTransformPoint(((Bounds)(ref bounds)).center); if (!Fit.InsideRoom(hull.Room, V(v), V(((Bounds)(ref bounds)).extents))) { return false; } return !HitsHull(((Bounds)(ref bounds)).center, ((Bounds)(ref bounds)).extents * 0.9f, p); } private static bool HitsHull(Vector3 center, Vector3 halfExtents, PlaceableShipObject self) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) Transform transform = Applier.Instance.transform; Transform val = (((Object)(object)self.parentObject != (Object)null) ? ((Component)self.parentObject).transform : ((Component)self).transform); Collider[] array = Physics.OverlapBox(center, halfExtents, Quaternion.identity, -1, (QueryTriggerInteraction)1); foreach (Collider val2 in array) { if (!((Component)val2).transform.IsChildOf(val) && ((Component)val2).transform.IsChildOf(transform)) { return true; } } return false; } private static bool Relocate(Transform ship, HullSpec hull, PlaceableShipObject p) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) Collider placeObjectCollider = p.placeObjectCollider; Bounds bounds = placeObjectCollider.bounds; Vector3 val = ship.InverseTransformPoint(((Bounds)(ref bounds)).center); float y = val.y; foreach (Vec3 item in Fit.Candidates(hull.Room, V(val))) { if (!Fit.InsideRoom(hull.Room, new Vec3(item.X, y, item.Z), V(((Bounds)(ref bounds)).extents))) { continue; } Vector3 val2 = ship.TransformPoint(new Vector3(item.X, y, item.Z)); if (!HitsHull(val2, ((Bounds)(ref bounds)).extents * 0.9f, p)) { Vector3 val3 = ((Component)placeObjectCollider).transform.position + (val2 - ((Bounds)(ref bounds)).center); ShipBuildModeManager.Instance.PlaceShipObject(val3, ((Component)p.mainMesh).transform.eulerAngles, p, false); if ((Object)(object)p.parentObject != (Object)null) { p.parentObject.MoveToOffset(); } Physics.SyncTransforms(); Plugin.V($"refit {Name(p)} to {item}"); return true; } } Plugin.Log.LogWarning((object)("No free spot on the floor for " + Name(p) + "; left where it is")); return false; } private static string Name(PlaceableShipObject p) { if (!((Object)(object)p.parentObject != (Object)null)) { return ((Object)p).name; } return ((Object)p.parentObject).name; } private static int DropStrayScrap(StartOfRound sor, Transform ship, HullSpec hull) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) Transform[] insideShipPositions = sor.insideShipPositions; if (insideShipPositions == null || insideShipPositions.Length == 0) { return 0; } int num = 0; int num2 = 0; GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>(); foreach (GrabbableObject val in array) { if (!((Object)(object)val == (Object)null) && val.isInShipRoom && !val.isHeld && !val.isHeldByEnemy) { Vector3 v = ship.InverseTransformPoint(((Component)val).transform.position); if (!hull.Room.Contains(V(v), -0.1f) || HitsHullPoint(((Component)val).transform.position)) { Vector3 position = insideShipPositions[num2++ % insideShipPositions.Length].position; ((Component)val).transform.position = position + Vector3.up * 0.5f; val.FallToGround(false, false, default(Vector3)); num++; } } } return num; } private static bool HitsHullPoint(Vector3 p) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) Transform root = Applier.Instance.transform; return Physics.OverlapSphere(p, 0.05f, -1, (QueryTriggerInteraction)1).Any((Collider c) => ((Component)c).transform.IsChildOf(root)); } } [HarmonyPatch(typeof(GameNetworkManager), "SaveGame")] internal static class SaveHullPatch { private static void Postfix() { if ((Object)(object)GameNetworkManager.Instance == (Object)null || !GameNetworkManager.Instance.isHostingGame) { return; } try { SaveFix.Save(); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't save the hull: " + ex.Message)); } } } [HarmonyPatch] internal static class SuitRackPatch { internal static int Replaced; private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method(typeof(StartOfRound), "SpawnUnlockable", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(StartOfRound), "PositionSuitsOnRack", (Type[])null, (Type[])null); } public static Vector3 Origin() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) Vec3 vec = SuitRack.Origin(Current.Spec); return new Vector3(vec.X, vec.Y, vec.Z); } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original) { //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); ConstructorInfo objB = AccessTools.Constructor(typeof(Vector3), new Type[3] { typeof(float), typeof(float), typeof(float) }, false); MethodInfo methodInfo = AccessTools.Method(typeof(SuitRackPatch), "Origin", (Type[])null, (Type[])null); int num = 0; for (int i = 0; i + 3 < list.Count; i++) { if (Is(list[i], Vanilla.SuitRackOffset.X) && Is(list[i + 1], Vanilla.SuitRackOffset.Y) && Is(list[i + 2], Vanilla.SuitRackOffset.Z) && !(list[i + 3].opcode != OpCodes.Newobj) && object.Equals(list[i + 3].operand, objB)) { CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)methodInfo); CodeInstructionExtensions.MoveLabelsTo(list[i], val); CodeInstructionExtensions.MoveBlocksTo(list[i], val); list.RemoveRange(i, 4); list.Insert(i, val); num++; } } Replaced += num; if (num != 1) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)$"Suit rack: expected one rack offset in {original?.Name}, found {num}; suits may hang at the vanilla spot"); } } return list; } private static bool Is(CodeInstruction c, float v) { if (c.opcode == OpCodes.Ldc_R4 && c.operand is float num) { return Mathf.Abs(num - v) < 0.0001f; } return false; } } } namespace NewShip.Core { public enum AnchorKind { Node, Floor, Mount, Camera } public static class Anchors { public sealed class Entry { public readonly AnchorKind Kind; public readonly float VanillaYaw; public readonly string[] Companions; public Entry(AnchorKind kind, float yaw, params string[] companions) { Kind = kind; VanillaYaw = yaw; Companions = companions; } } private static readonly Dictionary<string, Entry> table = new Dictionary<string, Entry> { ["Terminal"] = new Entry(AnchorKind.Floor, -90f), ["StartGameLever"] = new Entry(AnchorKind.Mount, 180f, "HangarDoorLever", "ControlPanelWTexture"), ["ClipboardManual"] = new Entry(AnchorKind.Mount, 180f), ["ShipModels2b/MonitorWall"] = new Entry(AnchorKind.Mount, 180f), ["Cameras/ShipCamera"] = new Entry(AnchorKind.Camera, 0f), ["Cameras/FrontDoorSecurityCam"] = new Entry(AnchorKind.Camera, 0f), ["MagnetLever"] = new Entry(AnchorKind.Mount, -90f), ["AnimatedShipDoor/HangarDoorButtonPanel"] = new Entry(AnchorKind.Mount, -90f), ["LightSwitchContainer"] = new Entry(AnchorKind.Mount, 90f), ["StorageCloset"] = new Entry(AnchorKind.Floor, 90f), ["FileCabinet"] = new Entry(AnchorKind.Floor, 90f), ["Bunkbeds"] = new Entry(AnchorKind.Floor, 90f), ["ShipModels2b/ChargeStation"] = new Entry(AnchorKind.Mount, -90f), ["VentEntrance"] = new Entry(AnchorKind.Floor, -90f) }; public static IEnumerable<string> Driven => table.Keys; public static Entry For(string drives) { if (drives == null || !table.TryGetValue(drives, out var value)) { return new Entry(AnchorKind.Node, 0f); } return value; } public static float Turn(float vanillaYaw, float socketYaw) { float num = (socketYaw - vanillaYaw) % 360f; if (num > 180f) { num -= 360f; } if (num <= -180f) { num += 360f; } return num; } public static Vec3 TurnY(Vec3 v, float deg) { double num = (double)deg * Math.PI / 180.0; double num2 = Math.Cos(num); double num3 = Math.Sin(num); return new Vec3((float)(num2 * (double)v.X + num3 * (double)v.Z), v.Y, (float)((0.0 - num3) * (double)v.X + num2 * (double)v.Z)); } public static Vec3 Move(Vec3 p, Vec3 anchor, Vec3 socket, float turnDeg) { return socket + TurnY(p - anchor, turnDeg); } public static float YawOf(Vec3 dir) { if (Math.Abs(dir.X) < 0.0001f && Math.Abs(dir.Z) < 0.0001f) { return float.NaN; } return (float)(Math.Atan2(0f - dir.Z, dir.X) * 180.0 / Math.PI); } } public static class Catalog { public const float DesignToShipX = 1.3f; public const float RoomCentreZ = -6.67f; private static readonly Dictionary<HullId, HullSpec> all = new Dictionary<HullId, HullSpec> { [HullId.BattleBus] = BattleBus(), [HullId.Haulback] = new HullSpec { Id = HullId.Haulback, DisplayName = "Haulback", Summary = "armoured salvage tug (not built yet)" }, [HullId.Lantern] = new HullSpec { Id = HullId.Lantern, DisplayName = "Lantern", Summary = "observation lander with a loft (not built yet)" }, [HullId.Mule] = new HullSpec { Id = HullId.Mule, DisplayName = "Mule", Summary = "container freight hauler (not built yet)" } }; public const float BusX0 = -8.6f; public const float BusX1 = 8.6f; public const float BusHalfWidth = 3.55f; public const float BusWall = 0.15f; public const float BusWallH = 3.35f; public const float BusRoofRise = 1.25f; public const float RigLift = 0.5f; public const float BalloonZ = 12.9f; public const float RingZ = 7f; public const float BalloonR = 5.2f; public const float BalloonTall = 1.1f; public const float BalloonX = 0.4f; public const float MagnetOut = 0.45f; public const float PorchX0 = -11f; public const float PorchX1 = -8.75f; public const float PorchHalfWidth = 2.4f; public const float PorchTop = -0.07f; public const float PorchDeck = 0.12f; public const float PorchRailH = 1.05f; public const float PorchRailW = 0.06f; public const float PorchGap = 0.6f; public const float PorchPostGap = 1.1f; public const float LadderInset = 0.13f; public const float MonitorScale = 0.7f; public static readonly string[] StoredByDefault = new string[2] { "FileCabinet", "Bunkbeds" }; public const float WheelR = 0.55f; public const float UndersideLift = 0.45f; public const float WheelZ = 0.099999994f; public static IEnumerable<HullSpec> All => all.Values; public static float[] AxleX => new float[2] { -4.45f, 5.6f }; public static Vec3 D(float x, float y, float z) { return new Vec3(x + 1.3f, z, y + -6.67f); } public static HullSpec Get(HullId id) { if (!all.TryGetValue(id, out var value)) { return null; } return value; } private static HullSpec BattleBus() { float num = 3.55f; float outer = 3.7f; HullSpec s = new HullSpec { Id = HullId.BattleBus, DisplayName = "Battle Bus", Built = false, BundleFile = "newship_battlebus", Prefab = "NewShip_BattleBus", Summary = "blue bus under an azure and white balloon", Room = Box3.FromMinMax(D(-8.6f, 0f - num, -0.9f), D(8.6f, num, 4.6f)), Bounds = Box3.FromMinMax(D(-10.200001f, 0f - outer - 2.5f, -0.9f), D(10f, outer + 2.5f, 18.619999f)), SuitRackStart = D(-4.9f, 0f - num + 0.32f, 2.75f), SuitRackDir = new Vec3(1f, 0f, 0f), SuitRackLength = 3f }; s.StrictRoom = Box3.FromMinMax(D(-8f, 0f - num + 0.6f, -0.4f), D(7.7000003f, num - 0.6f, 3.9499998f)); Sock("Terminal", D(7.0000005f, 0f - num + 1f, 0f), 180f, "Terminal"); Sock("Lever", D(7.6800003f, 1f, 1.42f), 180f, "StartGameLever"); Sock("Clipboard", D(8f, 2.35f, 1.08f), 180f, "ClipboardManual"); Sock("MonitorWall", D(5.1f, num - 0.12f - 0.8f, 2.16f), 90f, "ShipModels2b/MonitorWall", 0.7f); Sock("Plaque", D(3.0000005f, num, 2f), 90f, "CrewAwards plaque wall"); Sock("ShipCamera", D(8.200001f, 0f - num + 0.4f, 2.8f), -160f, "Cameras/ShipCamera"); Sock("DoorCamera", D(-9f, 0f - num, 3.2f), 180f, "Cameras/FrontDoorSecurityCam"); Sock("MagnetLever", D(8.26f, -0.6f, 1.44f), 180f, "MagnetLever"); Sock("DoorPanel", D(-8.450001f, -1.9f, 1.5f), 0f, "AnimatedShipDoor/HangarDoorButtonPanel"); Sock("LightSwitch", D(-8.450001f, 1.9f, 1.4f), 0f, "LightSwitchContainer"); Sock("Closet", D(-7.6000004f, 0f - num + 0.45f, 0f), -90f, "StorageCloset"); Sock("SuitRack", s.SuitRackStart, 0f, "StartOfRound.rightmostSuitPosition"); Sock("FileCabinet", D(-3.1000004f, 0f - num + 0.45f, 0f), -90f, "FileCabinet"); Sock("Bunks", D(-6.2000003f, num - 0.6f, 0f), 90f, "Bunkbeds"); Sock("Charger", D(-6.0000005f, num - 0.2f, 2.05f), 90f, "ShipModels2b/ChargeStation"); Sock("Vent", D(-2.1000004f, num - 0.3f, 0f), 90f, "VentEntrance"); Sock("CeilingLights", D(-1.5f, 0f, 3.8999999f), 0f, "ShipElectricLights"); Sock("ShipMiddle", D(0f, 0f, 0.5f), 0f, "StartOfRound.middleOfShipNode"); Sock("DoorPos", D(-8.1f, 0f, 0f), 0f, "StartOfRound.shipDoorNode"); Sock("BackOfShip", D(7.6000004f, 0f, 0f), 0f, "PositionNodes/BackOfShip"); Sock("OutsideDoorPoint", Vanilla.OutsideDoorPoint, 0f, "AnimatedShipDoor/OutsideDoorPoint (unchanged)"); Sock("Magnet", Vanilla.MagnetPoint + new Vec3(0f, 0f, -0.45f), 0f, "StartOfRound.magnetPoint"); for (int i = 0; i < 4; i++) { Sock($"Spawn{i + 1}", D(-6.8f + (float)(i / 2) * 1f, (i % 2 == 0) ? (-0.5f) : 0.5f, 0f), 0f, $"StartOfRound.playerSpawnPositions[{i}]"); } for (int j = 0; j < 11; j++) { Sock($"InsidePos{j + 1}", D(-7.0000005f + (float)j * 1.35f, (j % 2 == 0) ? (-0.35f) : 0.35f, 0.1f), 0f, $"StartOfRound.insideShipPositions[{j}]"); } P("body", HullPart.Body, D(-8.75f, 0f - outer, -0.3f), D(8.75f, outer, 3.35f)); P("roof", HullPart.Body, D(-8.75f, (0f - outer) * 0.8f, 3.35f), D(8.75f, outer * 0.8f, 4.72f)); P("nose", HullPart.Body, D(8.75f, 0f - outer, -0.3f), D(9.8f, outer, 1f)); P("rear_bumper", HullPart.Body, D(-9.150001f, 0f - outer, -0.45f), D(-8.75f, outer, -0.1f)); P("roof_units", HullPart.Body, D(-7.1000004f, -1.6f, 4.6f), D(7.6000004f, 1.6f, 5.2f)); P("belly", HullPart.Undercarriage, D(-6.8f, 0f - outer + 0.9f, -0.3f), D(7.8f, outer - 0.9f, 0.14999998f)); float[] axleX = AxleX; foreach (float num2 in axleX) { float[] array = new float[2] { -1f, 1f }; foreach (float num3 in array) { float num4 = num3 * (num - 0.25f); P("wheel_" + ((num2 < 0f) ? "rear" : "front") + "_" + ((num3 < 0f) ? "terminal" : "far"), HullPart.Undercarriage, D(num2 - 0.55f, num4 - 0.38f, -0.45000002f), D(num2 + 0.55f, num4 + 0.38f, 0.65f)); } } int num5 = 0; (float, float)[] array2 = new(float, float)[4] { (-6.4000006f, -1f), (-6.4000006f, 1f), (6.4000006f, -1f), (6.4000006f, 1f) }; for (int k = 0; k < array2.Length; k++) { (float, float) tuple = array2[k]; float item = tuple.Item1; float item2 = tuple.Item2; Vec3 a = D(0.4f + (item - 0.4f) * 0.55f, item2 * 2f, 6.95f); Vec3 vec = D(item * 0.82f, item2 * 2.6f, (zr(item2) + 7f) / 2f + 0.6f); Vec3 b = D(item, item2, zr(item2) + 0.35f); C($"arm{num5}_upper", HullPart.Rig, a, vec, 0.3f); C($"arm{num5}_lower", HullPart.Rig, vec, b, 0.3f); num5++; } P("ring", HullPart.Rig, D(-4.45f, -2.8f, 6.25f), D(5.25f, 2.8f, 7.6f)); float num6 = -4.68f; P("propeller", HullPart.Rig, D(num6 - 1f, -1.9f, 5.1f), D(num6 + 0.6f, 1.9f, 8.9f)); float num7 = 0.52f; C("balloon", HullPart.Balloon, D(0.4f, 0f, 12.9f - num7), D(0.4f, 0f, 12.9f + num7), 5.2f); return s; void C(string n, HullPart part, Vec3 a2, Vec3 b2, float r) { s.Proxies.Add(Proxy.Capsule(n, part, a2, b2, r)); } void P(string n, HullPart part, Vec3 lo, Vec3 hi) { s.Proxies.Add(Proxy.Box(n, part, Box3.FromMinMax(Min(lo, hi), Max(lo, hi)))); } void Sock(string name, Vec3 p, float yaw, string drives, float scale = 1f) { s.Sockets.Add(new Socket(name, p, yaw, drives, scale)); } float zr(float y) { return 3.35f + 1.25f * (float)Math.Sqrt(Math.Max(0f, 1f - y / outer * (y / outer))); } } private static Vec3 Min(Vec3 a, Vec3 b) { return new Vec3(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Min(a.Z, b.Z)); } private static Vec3 Max(Vec3 a, Vec3 b) { return new Vec3(Math.Max(a.X, b.X), Math.Max(a.Y, b.Y), Math.Max(a.Z, b.Z)); } } public static class Gear { public static readonly string[] Legs = new string[4] { "Leg_RT", "Leg_RF", "Leg_FT", "Leg_FF" }; public const string GearPath = "Rig/Gear"; public const string PorchPath = "Porch"; public const string LadderPath = "Porch/Ladder"; public const float FootBottomZ = -0.45f; public const float MaxExtend = 6f; public const float DeckTopZ = -0.07f; public const float SectionLen = 2.1f; public static readonly float[] SectionMax = new float[3] { 2.1f, 4f, 5.9f }; public const float LadderX = -11.05f; public const float ClimbStandOff = 0.45f; public const float ClimbTopX = -10.45f; public const float DeploySeconds = 1.6f; public const float StowSeconds = 1.2f; public const float NoGround = -1f; public static float Extend(float depth) { if (depth < 0f) { return 0f; } return Clamp(depth + -0.45f, 0f, 6f); } public static float[] Ladder(float depth) { float num = SectionMax[0]; float num2 = Clamp((depth < 0f) ? SectionMax[2] : (depth + -0.07f + 0.15f), num, SectionMax[2]); float num3 = Clamp((num + num2) * 0.5f, num, SectionMax[1]); return new float[3] { num, num3, num2 }; } public static float LadderBottom(float[] slides) { return -0.07f - slides[^1]; } public static float Step(float t, bool parked, float dt) { float num = Math.Max(0f, dt) / (parked ? 1.6f : 1.2f); if (!parked) { return Math.Max(0f, t - num); } return Math.Min(1f, t + num); } public static float Ease(float t) { t = Clamp(t, 0f, 1f); return t * t * (3f - 2f * t); } private static float Clamp(float v, float lo, float hi) { if (!(v < lo)) { if (!(v > hi)) { return v; } return hi; } return lo; } } public enum HullId { Vanilla, BattleBus, Haulback, Lantern, Mule } public enum HullPart { Body, Undercarriage, Rig, Balloon } public sealed class Socket { public readonly string Name; public readonly Vec3 Pos; public readonly float Yaw; public readonly string Drives; public readonly float Scale; public Vec3 Facing { get { double num = (double)Yaw * Math.PI / 180.0; return new Vec3((float)Math.Cos(num), 0f, (float)(0.0 - Math.Sin(num))); } } public Socket(string name, Vec3 pos, float yaw, string drives, float scale = 1f) { Name = name; Pos = pos; Yaw = yaw; Drives = drives; Scale = scale; } } public enum ProxyShape { Box, Capsule } public sealed class Proxy { public readonly string Name; public readonly HullPart Part; public readonly ProxyShape Shape; public readonly Vec3 A; public readonly Vec3 B; public readonly float Radius; public Box3 Bounds { get { if (Shape == ProxyShape.Box) { return new Box3(A, B); } Vec3 min = new Vec3(Math.Min(A.X, B.X) - Radius, Math.Min(A.Y, B.Y) - Radius, Math.Min(A.Z, B.Z) - Radius); Vec3 max = new Vec3(Math.Max(A.X, B.X) + Radius, Math.Max(A.Y, B.Y) + Radius, Math.Max(A.Z, B.Z) + Radius); return Box3.FromMinMax(min, max); } } private Proxy(string name, HullPart part, ProxyShape shape, Vec3 a, Vec3 b, float r) { Name = name; Part = part; Shape = shape; A = a; B = b; Radius = r; } public static Proxy Box(string name, HullPart part, Box3 box) { return new Proxy(name, part, ProxyShape.Box, box.Center, box.Size, 0f); } public static Proxy Capsule(string name, HullPart part, Vec3 a, Vec3 b, float r) { return new Proxy(name, part, ProxyShape.Capsule, a, b, r); } public float Depth(Vec3 p) { if (Shape == ProxyShape.Box) { return new Box3(A, B).Depth(p); } Vec3 vec = B - A; float val = Vec3.Dot(p - A, vec) / Math.Max(1E-06f, Vec3.Dot(vec, vec)); val = Math.Max(0f, Math.Min(1f, val)); return Radius - (p - (A + vec * val)).Length; } } public sealed class HullSpec { public HullId Id; public string DisplayName; public bool Built; public string Summary; public string BundleFile; public string Prefab; public Box3 Room; public Box3 StrictRoom; public Box3 Bounds; public Vec3 SuitRackStart; public Vec3 SuitRackDir; public float SuitRackLength; public List<Socket> Sockets = new List<Socket>(); public List<Proxy> Proxies = new List<Proxy>(); public int SuitCapacity => (int)Math.Floor((double)(SuitRackLength / 0.18f) + 0.001) + 1; public Socket Socket(string name) { return Sockets.FirstOrDefault((Socket s) => s.Name == name); } } public static class Picker { public static HullId Parse(string text) { if (string.IsNullOrWhiteSpace(text)) { return HullId.Vanilla; } string text2 = text.Trim(); if (int.TryParse(text2, out var result)) { if (!Enum.IsDefined(typeof(HullId), result)) { return HullId.Vanilla; } return (HullId)result; } StringBuilder stringBuilder = new StringBuilder(); string text3 = text2; foreach (char c in text3) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(char.ToLowerInvariant(c)); } } foreach (HullId value in Enum.GetValues(typeof(HullId))) { if (value.ToString().ToLowerInvariant() == stringBuilder.ToString()) { return value; } } return HullId.Vanilla; } public static HullId Resolve(HullId wanted, Func<HullId, bool> isBuilt) { if (wanted == HullId.Vanilla) { return HullId.Vanilla; } if (isBuilt == null || !isBuilt(wanted)) { return HullId.Vanilla; } return wanted; } public static HullId Resolve(HullId wanted) { return Resolve(wanted, (HullId id) => Catalog.Get(id)?.Built ?? false); } } public readonly struct Hello { public const int Protocol = 1; public readonly int ProtocolVersion; public readonly string ModVersion; public readonly HullId Hull; public Hello(string modVersion, HullId hull, int protocol = 1) { ProtocolVersion = protocol; ModVersion = modVersion ?? ""; Hull = hull; } public string Encode() { return $"NS{ProtocolVersion}|{ModVersion}|{(int)Hull}"; } public static bool TryDecode(string s, out Hello hello) { hello = default(Hello); if (string.IsNullOrEmpty(s) || !s.StartsWith("NS")) { return false; } string[] array = s.Substring(2).Split('|'); if (array.Length != 3 || !int.TryParse(array[0], out var result) || !int.TryParse(array[2], out var result2)) { return false; } if (!Enum.IsDefined(typeof(HullId), result2)) { result2 = 0; } hello = new Hello(array[1], (HullId)result2, result); return true; } } public enum HandshakeResult { Ok, VersionDiffers, FallBackToVanilla } public static class Handshake { public const float AnswerWait = 6f; public static HandshakeResult Check(Hello host, string clientVersion, Func<HullId, bool> clientHasHull, out HullId fly) { if (host.ProtocolVersion != 1 || (host.Hull != HullId.Vanilla && (clientHasHull == null || !clientHasHull(host.Hull)))) { fly = HullId.Vanilla; return HandshakeResult.FallBackToVanilla; } fly = host.Hull; if (!(host.ModVersion == clientVersion)) { return HandshakeResult.VersionDiffers; } return HandshakeResult.Ok; } public static bool NeedsWarning(HullId lobbyHull, HullId? answer, float secondsSinceJoin) { if (lobbyHull == HullId.Vanilla) { return false; } if (!answer.HasValue) { return secondsSinceJoin >= 6f; } return answer.Value != lobbyHull; } } public static class Rig { public const float Inflated = 0f; public const float Folded = 100f; public const float FoldSeconds = 2.5f; public const float InflateSeconds = 5f; public const float PropFlyingDegPerSec = 300f; public const float PropParkedDegPerSec = 0f; public const float PropRampSeconds = 3f; public const float FlameFolded = 0.3f; public static float Target(bool shipHasLanded, bool shipIsLeaving) { if (!shipHasLanded || shipIsLeaving) { return 100f; } return 0f; } public static float Step(float current, float target, float dt) { if (dt <= 0f || current == target) { return current; } float num = ((target > current) ? 40f : 20f) * dt; if (!(target > current)) { return Math.Max(target, current - num); } return Math.Min(target, current + num); } public static float Flame(float fold) { return 1f + -0.7f * Clamp01(fold / 100f); } public static float PropStep(float current, bool parked, float dt) { float num = (parked ? 0f : 300f); float num2 = 100f * Math.Max(0f, dt); if (!(num > current)) { return Math.Max(num, current - num2); } return Math.Min(num, current + num2); } private static float Clamp01(float v) { if (!(v < 0f)) { if (!(v > 1f)) { return v; } return 1f; } return 0f; } } public static class StandDown { private static readonly string[] Conflicts = new string[5] { "shipwindows", "2storyship", "twostoryship", "widership", "biggership" }; public static string Conflict(IEnumerable<string> pluginIdsAndNames) { if (pluginIdsAndNames == null) { return null; } foreach (string pluginIdsAndName in pluginIdsAndNames) { if (!string.IsNullOrEmpty(pluginIdsAndName)) { string k = new string(pluginIdsAndName.ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray()); if (Conflicts.Any((string c) => k.Contains(c))) { return pluginIdsAndName; } } } return null; } } public static class Fit { public const float Step = 0.5f; public const float WallMargin = 0.45f; public static List<Vec3> Candidates(Box3 room, Vec3 from, float floorY = 0f) { List<Vec3> list = new List<Vec3>(); Vec3 min = room.Min; Vec3 max = room.Max; for (float num = min.X + 0.45f; num <= max.X - 0.45f + 0.001f; num += 0.5f) { for (float num2 = min.Z + 0.45f; num2 <= max.Z - 0.45f + 0.001f; num2 += 0.5f) { list.Add(new Vec3(num, floorY, num2)); } } return list.OrderBy((Vec3 p) => Sq(p.X - from.X) + Sq(p.Z - from.Z)).ToList(); } public static bool InsideRoom(Box3 room, Vec3 c, Vec3 h) { if (c.X - h.X >= room.Min.X - 0.05f && c.X + h.X <= room.Max.X + 0.05f && c.Z - h.Z >= room.Min.Z - 0.05f && c.Z + h.Z <= room.Max.Z + 0.05f && c.Y >= room.Min.Y) { return c.Y <= room.Max.Y; } return false; } private static float Sq(float v) { return v * v; } } public static class SuitRack { public static Vec3 Origin(HullSpec hull) { if (hull != null && hull.Id != HullId.Vanilla) { return hull.SuitRackStart; } return Vanilla.SuitRackOffset; } public static Vec3 Offset(HullSpec hull, Vec3 forward, int i) { return Origin(hull) + forward * (0.18f * (float)i); } public static int Capacity(HullSpec hull) { if (hull != null && hull.Id != HullId.Vanilla) { return hull.SuitCapacity; } return int.MaxValue; } } public static class Vanilla { public static readonly Box3 ShipBounds = new Box3(new Vec3(1.49f, 4.17f, -6.36f), new Vec3(23.76f, 10.11f, 12.46f)); public static readonly Box3 InnerRoom = new Box3(new Vec3(1.44f, 1.78f, -6.67f), new Vec3(17.52f, 5.34f, 7f)); public static readonly Vec3 SuitRackOffset = new Vec3(-2.45f, 2.75f, -8.41f); public const float SuitSpacing = 0.18f; public const float LadderShortY = -2.58f; public static readonly Vec3 OutsideDoorPoint = new Vec3(-8.48f, 0f, -6.69f); public static readonly Vec3 MagnetPoint = new Vec3(2.2f, 2.5f, -10f); public const float DoorX = -7.3f; public const float DoorWidth = 3.7f; public const float DoorHeight = 3.8f; public const string MonitorWallPath = "ShipModels2b/MonitorWall"; public static readonly string[] HideVisual = new string[58] { "ShipInside", "ShipInside.001", "ShipHull", "ShipSupportBeams", "ShipSupportBeams.001", "ControlDesk", "ControlDesk.001", "CatwalkShip", "CatwalkRailLining", "CatwalkRailLiningB", "CatwalkUnderneathSupports", "ShipRails", "ShipRailPosts", "Railing", "ClimbOntoCatwalkHelper", "ThrusterBackLeft", "ThrusterBackRight", "ThrusterFrontLeft", "ThrusterFrontRight", "UnderbellyMachineParts", "LadderShort", "LadderShort (1)", "warningStickers", "warningStickers.001", "warningStickers.003", "Cube", "Cube.004", "Cube.005", "Cube.006", "Cube.007", "Cube.008", "NurbsPath", "NurbsPath.001", "NurbsPath.002", "NurbsPath.004", "BezierCurve", "Cylinder.002", "Pipework2.002", "SideMachineryLeft", "SideMachineryRight", "WallInsulator", "WallInsulator2", "WallCords", "Plane.001", "MeterBoxDevice.001", "DoorGenerator", "VaultDoor", "HangingLamp", "SmallDetails", "ShipBottomColliders", "ShipModels2b/AirFilterThing", "ShipModels2b/Light", "ShipModels2b/Light (1)", "ShipModels2b/Light (2)", "ShipModels2b/Light (3)", "ShipModels2b/Cube.005 (1)", "ShipModels2b/Cube.005 (2)", "ShipModels2b/ShipLightsPost" }; public static readonly string[] CollidersOff = new string[15] { "ShipInside", "ShipRails", "ShipRailPosts", "Railing", "WallInsulator", "WallInsulator2", "CatwalkShip", "ClimbOntoCatwalkHelper", "SideMachineryLeft", "SideMachineryRight", "ControlDesk", "ControlDesk.001", "VaultDoor", "ShipModels2b/Cube.005 (2)", "ShipModels2b/ShipLightsPost" }; public static readonly string[] Deactivate = new string[1] { "OutsideShipRoom/Ladder" }; public const string InnerRoomBoundsPath = "ShipInnerRoomBoundsTrigger"; public const string StrictRoomBoundsPath = "ShipStrictInnerRoomBounds"; public const string ShipBoundsPath = "ShipBoundsTrigger"; } public readonly struct Vec3 : IEquatable<Vec3> { public readonly float X; public readonly float Y; public readonly float Z; public float Length => (float)Math.Sqrt(X * X + Y * Y + Z * Z); public Vec3 Normalized { get { float length = Length; if (!(length > 1E-06f)) { return this; } return this * (1f / length); } } public Vec3(float x, float y, float z) { X = x; Y = y; Z = z; } public static Vec3 operator +(Vec3 a, Vec3 b) { return new Vec3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static Vec3 operator -(Vec3 a, Vec3 b) { return new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static Vec3 operator *(Vec3 a, float k) { return new Vec3(a.X * k, a.Y * k, a.Z * k); } public static float Dot(Vec3 a, Vec3 b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } public bool Equals(Vec3 o) { if (X == o.X && Y == o.Y) { return Z == o.Z; } return false; } public override bool Equals(object o) { if (o is Vec3 o2) { return Equals(o2); } return false; } public override int GetHashCode() { return (X, Y, Z).GetHashCode(); } public bool Near(Vec3 o, float eps = 0.0001f) { if (Math.Abs(X - o.X) <= eps && Math.Abs(Y - o.Y) <= eps) { return Math.Abs(Z - o.Z) <= eps; } return false; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "({0:0.###}, {1:0.###}, {2:0.###})", X, Y, Z); } public string Json() { return string.Format(CultureInfo.InvariantCulture, "[{0:0.####}, {1:0.####}, {2:0.####}]", X, Y, Z); } } public readonly struct Box3 { public readonly Vec3 Center; public readonly Vec3 Size; public Vec3 Min => Center - Size * 0.5f; public Vec3 Max => Center + Size * 0.5f; public Box3(Vec3 center, Vec3 size) { Center = center; Size = size; } public static Box3 FromMinMax(Vec3 min, Vec3 max) { return new Box3((min + max) * 0.5f, max - min); } public bool Contains(Vec3 p, float margin = 0f) { if (p.X >= Min.X - margin && p.X <= Max.X + margin && p.Y >= Min.Y - margin && p.Y <= Max.Y + margin && p.Z >= Min.Z - margin) { return p.Z <= Max.Z + margin; } return false; } public float Depth(Vec3 p) { Vec3 min = Min; Vec3 max = Max; float val = Math.Min(p.X - min.X, max.X - p.X); float val2 = Math.Min(p.Y - min.Y, max.Y - p.Y); float val3 = Math.Min(p.Z - min.Z, max.Z - p.Z); return Math.Min(val, Math.Min(val2, val3)); } } }