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 Fysik v0.2.4
plugins/Fysik.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Fysik.Game; using Fysik.Structure; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("assembly_valheim")] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("menezesbruno")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2026 Bruno Menezes")] [assembly: AssemblyDescription("Structural physics for building. Shape matters: arches carry load in compression, trusses stay rigid, cantilevers bend, stone rests on stone like real masonry. Adds arch stones, tower stones, thin walls and floors. Pieces crack before they fall.")] [assembly: AssemblyFileVersion("0.2.4.0")] [assembly: AssemblyInformationalVersion("0.2.4+4eacf80550b5254bba0418cb064613eb2b24bd5a")] [assembly: AssemblyProduct("Fysik")] [assembly: AssemblyTitle("Fysik")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/menezesbruno/Fysik")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.2.4.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 Fysik { internal enum StructureMode { Physics, DisplayOnly, Sandbox } internal enum WorldBuildingMode { Vanilla, Physics } internal enum Difficulty { Relaxed, Normal, Strict } internal static class FysikConfig { internal sealed class MaterialEntries { public string Name; public ConfigEntry<float> Density; public ConfigEntry<float> Compression; public ConfigEntry<float> Tension; public ConfigEntry<float> Shear; public ConfigEntry<float> Slenderness; } internal const float XRayRadiusMin = 40f; internal const float XRayRadiusMax = 80f; internal const float XRayRadiusStep = 10f; internal static readonly Dictionary<MaterialType, MaterialEntries> Materials = new Dictionary<MaterialType, MaterialEntries>(); internal static ConfigEntry<StructureMode> Mode { get; private set; } internal static ConfigEntry<WorldBuildingMode> WorldBuildings { get; private set; } internal static ConfigEntry<float> CrackWarningSeconds { get; private set; } internal static ConfigEntry<bool> DamageWeakens { get; private set; } internal static ConfigEntry<int> MaxFrameBodies { get; private set; } internal static ConfigEntry<Difficulty> StructureDifficulty { get; private set; } internal static ConfigEntry<bool> MasonryJoints { get; private set; } internal static double StrengthMultiplier { get { if (StructureDifficulty.Value != Difficulty.Relaxed) { if (StructureDifficulty.Value != Difficulty.Strict) { return 1.0; } return 0.7; } return 1.5; } } internal static ConfigEntry<float> WoodWeight { get; private set; } internal static ConfigEntry<float> StoneWeight { get; private set; } internal static ConfigEntry<float> MetalBarWeight { get; private set; } internal static ConfigEntry<float> NailWeight { get; private set; } internal static ConfigEntry<float> KilogramsPerItemWeight { get; private set; } internal static ConfigEntry<bool> LiveLoads { get; private set; } internal static ConfigEntry<float> ContentsWeight { get; private set; } internal static ConfigEntry<float> PlayerWeight { get; private set; } internal static ConfigEntry<float> SnowWeight { get; private set; } internal static ConfigEntry<float> FrameBudgetMs { get; private set; } internal static ConfigEntry<bool> BackgroundSolver { get; private set; } internal static ConfigEntry<bool> HammerInfo { get; private set; } internal static ConfigEntry<bool> PlacementPreview { get; private set; } internal static ConfigEntry<bool> CollapseAnimation { get; private set; } internal static ConfigEntry<KeyboardShortcut> XRayKey { get; private set; } internal static ConfigEntry<float> XRayRadius { get; private set; } internal static ConfigEntry<KeyboardShortcut> XRayRadiusKey { get; private set; } internal static ConfigEntry<bool> DetailedLog { get; private set; } internal static ConfigEntry<KeyboardShortcut> DumpKey { get; private set; } internal static MaterialEntries Unknown { get; private set; } internal static void Bind(ConfigFile config) { //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Expected O, but got Unknown //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_041e: Unknown result type (might be due to invalid IL or missing references) //IL_0428: Expected O, but got Unknown //IL_044b: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) Mode = config.Bind<StructureMode>("Structure", "Mode", StructureMode.Physics, Server("Physics: overloaded pieces crack, then fall (vanilla support is replaced). DisplayOnly: vanilla decides what falls, Fysik only shows the forces. Sandbox: nothing falls for lack of support, Fysik shows the forces (calibration, test worlds).", null)); WorldBuildings = config.Bind<WorldBuildingMode>("Structure", "WorldBuildings", WorldBuildingMode.Vanilla, Server("Buildings that come with the world, not built by a player: stone towers, abandoned houses, villages, ruins, fortresses. Vanilla: they keep vanilla support and Fysik never brings them down; only what players build is simulated, and a player build resting on them is held as if on rock. Physics: they are simulated like player builds. Warning: many were not built to stand up to real forces and may crack and fall as soon as a player comes near, changing the world for good.", null)); CrackWarningSeconds = config.Bind<float>("Failure", "CrackWarningSeconds", 5f, Server("Seconds an overloaded piece stays cracked (red, shaking) before it falls, giving time to shore it up or take the load off. That is for a piece just past its limit (up to 110%): the further past, the shorter the warning, down to none at twice its limit. Once the first piece falls, the rest of the collapse is instant.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f))); DamageWeakens = config.Bind<bool>("Failure", "DamageWeakens", true, Server("Badly damaged pieces are weaker: down to half health they keep their full strength (rain wear alone never weakens them); below that, strength falls to 25% at the brink of breaking, so a pillar under attack can crack under the same load. Off: damage never changes strength.", null)); MaxFrameBodies = config.Bind<int>("Structure", "MaxFrameBodies", 2000, Server("Largest connected structure (pieces) solved with the full frame analysis. Bigger ones use a simplified load-path model, which does not recognise arches. Higher values recognise arches in big bases but take longer to update (about 0.5 s for 2000 pieces, 2 s for 5000, on a worker thread).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(500, 5000))); StructureDifficulty = config.Bind<Difficulty>("Structure", "Difficulty", Difficulty.Normal, Server("Relaxed: materials 50% stronger (longer spans and cantilevers). Normal. Strict: materials 30% weaker (structures need more thought).", null)); MasonryJoints = config.Bind<bool>("Structure", "MasonryJoints", true, Server("Stone, black marble and grausten pieces rest on each other like real masonry: the joint between two of them cannot pull, so it opens or rocks on its edge when the weight above is off-centre, and slides when pushed sideways harder than friction holds. A stone needs something under its weight, and an arch stands only once its keystone is in. Off: these joints hold like glue, as up to 0.1.5.", null)); WoodWeight = config.Bind<float>("Weight", "Wood", 4f, Server("Objects (furniture, crafting stations, chests, torches, lighting, decor) weigh the materials they are made of, not their volume. Kilograms per wood item (" + string.Join(", ", Recipe.WoodItems) + ").", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); StoneWeight = config.Bind<float>("Weight", "Stone", 10f, Server("Objects (furniture, crafting stations, chests, torches, lighting, decor) weigh the materials they are made of, not their volume. Kilograms per stone item (" + string.Join(", ", Recipe.StoneItems) + ").", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); MetalBarWeight = config.Bind<float>("Weight", "MetalBar", 4f, Server("Objects (furniture, crafting stations, chests, torches, lighting, decor) weigh the materials they are made of, not their volume. Kilograms per metal bar (" + string.Join(", ", Recipe.MetalBars) + ").", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); NailWeight = config.Bind<float>("Weight", "Nail", 0.1f, Server("Objects (furniture, crafting stations, chests, torches, lighting, decor) weigh the materials they are made of, not their volume. Kilograms per nail (" + string.Join(", ", Recipe.Nails) + ").", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); KilogramsPerItemWeight = config.Bind<float>("Weight", "PerItemWeight", 2f, Server("Objects (furniture, crafting stations, chests, torches, lighting, decor) weigh the materials they are made of, not their volume. Kilograms per unit of the game's item weight, for every other material (an item that weighs 0.5 in the inventory counts as 1 kg at the default 2).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f))); LiveLoads = config.Bind<bool>("Weight", "LiveLoads", true, Server("Loads that are not part of the building weigh on it: what is inside chests, players, carts and Deep North snow (Contents, Player and Snow below). Off: only the pieces and the objects built on them (furniture, crafting stations, piles and stacks) weigh.", null)); ContentsWeight = config.Bind<float>("Weight", "Contents", 1f, Server("Stored items weigh this many kilograms per unit of the game's item weight: inside chests, carts and players' inventories, and piled up in piles and stacks. At the default 1 the game's weights read as kilograms (50 stones = 100 kg, a stack of 30 iron bars = 360 kg).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f))); PlayerWeight = config.Bind<float>("Weight", "Player", 80f, Server("Body weight of a player, kilograms. A player standing, sitting or lying on a piece adds this plus their inventory (Contents) to it, and a cart adds its own weight plus its cargo to the pieces under its wheels.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 500f))); SnowWeight = config.Bind<float>("Weight", "Snow", 150f, Server("Weight of a full layer of Deep North snow, kilograms per square metre of ground. Snow builds up on pieces left in the open and can be shoveled off; a roof up to 30° steep holds 80% of it, less as it gets steeper, none from 60°. Pieces the game protects from heavy snow (tarred roofs, stave church) and worlds with the no heavy snow modifier hold none. 0: snow weighs nothing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); FrameBudgetMs = config.Bind<float>("Performance", "FrameBudgetMs", 1.5f, new ConfigDescription("Milliseconds per frame spent on structural calculations; the rest waits for the next frame.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 10f), Array.Empty<object>())); BackgroundSolver = config.Bind<bool>("Performance", "BackgroundSolver", true, "Solve structures on a worker thread, so big bases update in about a second without taking frame time. Off: the solver shares the per-frame budget (slower for big structures)."); HammerInfo = config.Bind<bool>("Display", "HammerInfo", true, "Color the piece under the hammer by Fysik stress (blue = relaxed, red = at its limit) instead of vanilla support, and show its value next to the crosshair."); PlacementPreview = config.Bind<bool>("Display", "PlacementPreview", true, "While placing a piece, color it by the stress it would have once placed, and warn if it would overload another piece."); CollapseAnimation = config.Bind<bool>("Display", "CollapseAnimation", true, "Pieces brought down by Fysik fall together as debris and burst when they hit something, like a building being imploded. Off: they shatter where they stand, as in vanilla."); XRayKey = config.Bind<KeyboardShortcut>("Display", "XRayKey", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Toggles the X-ray view: every piece nearby is colored by stress."); XRayRadius = config.Bind<float>("Display", "XRayRadius", 40f, new ConfigDescription("X-ray view radius, metres. Also changed in game with XRayRadiusKey.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(40f, 80f), Array.Empty<object>())); XRayRadiusKey = config.Bind<KeyboardShortcut>("Display", "XRayRadiusKey", new KeyboardShortcut((KeyCode)288, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), "Widens the X-ray radius by 10 m, from 40 m up to 80 m, then back to 40 m."); DetailedLog = config.Bind<bool>("Debug", "DetailedLog", false, "Write to the log each structure solved (size, solver, time, worst piece), each piece that cracks or falls, each kind of piece the first time it is seen (colliders, box, volume, weight) and each ownership handover. For developers and bug reports; off keeps the log clean."); DumpKey = config.Bind<KeyboardShortcut>("Debug", "DumpKey", new KeyboardShortcut((KeyCode)289, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), "Writes the structure under the hammer to BepInEx/fysik-dump.txt (same as the console command 'fysik dump')."); BindMaterial(config, (MaterialType)0, "Wood", 500f, 4f, 4f, 1f, 60f); BindMaterial(config, (MaterialType)3, "HardWood", 600f, 6f, 6f, 1.5f, 65f); BindMaterial(config, (MaterialType)8, "Timberwood", 650f, 8f, 8f, 2f, 70f); BindMaterial(config, (MaterialType)6, "Ancient", 700f, 15f, 15f, 3f, 80f); BindMaterial(config, (MaterialType)1, "Stone", 2400f, 20f, 0.8f, 2f, 30f); BindMaterial(config, (MaterialType)4, "Marble", 2700f, 30f, 1.5f, 3f, 35f); BindMaterial(config, (MaterialType)5, "Ashstone", 2300f, 25f, 1.2f, 2.5f, 30f); BindMaterial(config, (MaterialType)2, "Iron", 1200f, 20f, 20f, 10f, 90f); BindMaterial(config, (MaterialType)7, "Ice", 920f, 5f, 0.5f, 0.8f, 30f); Unknown = BindMaterialSection(config, "Material.Unknown", 600f, 3f, 3f, 0.8f, 50f, "Pieces whose material Fysik does not know (other mods)"); Unknown.Name = "unknown"; } private static void BindMaterial(ConfigFile config, MaterialType type, string name, float density, float compression, float tension, float shear, float slenderness) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) MaterialEntries materialEntries = BindMaterialSection(config, "Material." + name, density, compression, tension, shear, slenderness, name); materialEntries.Name = name; Materials[type] = materialEntries; } private static MaterialEntries BindMaterialSection(ConfigFile config, string section, float density, float compression, float tension, float shear, float slenderness, string what) { return new MaterialEntries { Density = config.Bind<float>(section, "Density", density, Server(what + ": density, kg/m³ (a structural piece weighs its volume times this; objects weigh their materials, see the Weight section).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 20000f))), Compression = config.Bind<float>(section, "CompressiveStrength", compression, Server(what + ": compressive strength, MPa.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1000f))), Tension = config.Bind<float>(section, "TensileStrength", tension, Server(what + ": tensile strength, MPa (also limits bending).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1000f))), Shear = config.Bind<float>(section, "ShearStrength", shear, Server(what + ": shear strength, MPa.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1000f))), Slenderness = config.Bind<float>(section, "BucklingSlenderness", slenderness, Server(what + ": slenderness (length / radius of gyration) at which the compressive limit halves. Lower = buckles sooner.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 500f))) }; } private static ConfigDescription Server(string description, AcceptableValueBase range) { //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_0021: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown return new ConfigDescription(description + " Enforced by the server.", range, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } }); } } [BepInPlugin("menezesbruno.fysik", "Fysik", "0.2.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { private Harmony _harmony; internal static ManualLogSource Log { get; private set; } private void Awake() { Log = ((BaseUnityPlugin)this).Logger; FysikConfig.Bind(((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Config.SettingChanged += OnSettingChanged; SynchronizationManager.OnConfigurationSynchronized += OnConfigurationSynchronized; Texts.Register(); ArchStones.Register(); ThinStones.Register(); TowerStones.Register(); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new FysikCommand()); ApplyPatches(); Log.LogInfo((object)("Fysik 0.2.4 loaded " + $"(Valheim {Version.GetVersionString(false)}, crack warning {FysikConfig.CrackWarningSeconds.Value:0.#} s)")); } private void ApplyPatches() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _harmony = new Harmony("menezesbruno.fysik"); int num = 0; int num2 = 0; Type[] types; try { types = typeof(Plugin).Assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } Type[] array = types; foreach (Type type in array) { if (!(type == null) && type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0) { try { _harmony.CreateClassProcessor(type).Patch(); num++; } catch (Exception ex2) { num2++; Log.LogWarning((object)("Hook " + type.Name + " not applied, that feature is off (different game version?): " + ex2.GetBaseException().Message)); } } } if (num2 > 0) { Log.LogWarning((object)$"{num2} of {num + num2} hooks could not be applied."); } } private void Update() { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()) { try { OwnershipHandover.Tick(); return; } catch (Exception e) { Guard.Report("Ownership handover", e); return; } } if ((Object)(object)ZNetScene.instance == (Object)null) { if (StructureManager.Instance.NodeCount > 0) { StructureManager.Instance.Clear(); MovingLoads.Instance.Clear(); } ArchFit.Clear(); return; } try { Overlay.Instance.HideIfStale(); XRayView.Instance.Tick(); } catch (Exception e2) { Guard.Report("X-ray view", e2); } try { ArchFit.Tick(); } catch (Exception e3) { Guard.Report("Stones fitted to arches", e3); } try { StructureManager.Instance.Tick(FysikConfig.FrameBudgetMs.Value); } catch (Exception e4) { Guard.Report("Structure solver", e4); StructureManager.Instance.AbortJob(); } try { MovingLoads.Instance.Tick(); } catch (Exception e5) { Guard.Report("Moving loads", e5); } try { CollapseController.Instance.Tick(); } catch (Exception e6) { Guard.Report("Collapse", e6); } try { FallingDebris.Instance.Tick(); } catch (Exception e7) { Guard.Report("Collapse animation", e7); } try { CrackEffects.Instance.Tick(); } catch (Exception e8) { Guard.Report("Crack effects", e8); } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.SettingChanged -= OnSettingChanged; SynchronizationManager.OnConfigurationSynchronized -= OnConfigurationSynchronized; Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private static void OnSettingChanged(object sender, SettingChangedEventArgs args) { string section = args.ChangedSetting.Definition.Section; if (section.StartsWith("Material.") || section == "Structure" || section == "Weight" || (object)args.ChangedSetting == FysikConfig.DamageWeakens) { SolveAgain(); } } private static void OnConfigurationSynchronized(object sender, ConfigurationSynchronizationEventArgs args) { if (args.UpdatedPluginGUIDs.Contains("menezesbruno.fysik")) { Log.LogInfo((object)$"Server config applied: crack warning {FysikConfig.CrackWarningSeconds.Value:0.#} s"); SolveAgain(); } } private static void SolveAgain() { MaterialTable.Invalidate(); StructureManager.Instance.InvalidateAllResults(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "menezesbruno.fysik"; public const string PLUGIN_NAME = "Fysik"; public const string PLUGIN_VERSION = "0.2.4"; } } namespace Fysik.Structure { public static class Angles { public const double SavedTolerance = 0.6; public static bool TrySnap(double degrees, double origin, double step, out double snapped, double tolerance = 0.6) { snapped = origin + Math.Round((degrees - origin) / step) * step; return Math.Abs(degrees - snapped) <= tolerance; } } public static class ContactSpan { public const int GridSide = 3; public static double[] Open() { return new double[6] { double.MaxValue, double.MinValue, double.MaxValue, double.MinValue, double.MaxValue, double.MinValue }; } public static void Include(double[] span, OrientedBox frame, Vec3 point) { Vec3 a = point - frame.Center; for (int i = 0; i < 3; i++) { double val = Vec3.Dot(a, frame.Axis(i)); span[2 * i] = Math.Min(span[2 * i], val); span[2 * i + 1] = Math.Max(span[2 * i + 1], val); } } public static void Include(double[] span, OrientedBox frame, List<Vec3> points) { foreach (Vec3 point in points) { Include(span, frame, point); } } public static double[] Close(double[] span, OrientedBox frame, double margin) { if (span[0] > span[1]) { return null; } double[] array = new double[6]; for (int i = 0; i < 3; i++) { double num = span[2 * i] + margin; double num2 = span[2 * i + 1] - margin; if (num > num2) { num = (num2 = (num + num2) / 2.0); } double num3 = frame.Half[i]; array[2 * i] = Math.Max(0.0 - num3, Math.Min(num3, num)); array[2 * i + 1] = Math.Max(0.0 - num3, Math.Min(num3, num2)); } return array; } public static int Patches(bool[] hit, int[] label) { int num = 9; for (int i = 0; i < num; i++) { label[i] = (hit[i] ? i : (-1)); } bool flag = true; while (flag) { flag = false; for (int j = 0; j < num; j++) { if (label[j] < 0) { continue; } int num2 = j / 3; int num3 = j % 3; for (int k = -1; k <= 1; k++) { for (int l = -1; l <= 1; l++) { int num4 = num2 + k; int num5 = num3 + l; if (num4 >= 0 && num5 >= 0 && num4 < 3 && num5 < 3) { int num6 = num4 * 3 + num5; if (label[num6] >= 0 && label[num6] < label[j]) { label[j] = label[num6]; flag = true; } } } } } } int result = 0; int[] array = new int[num]; for (int m = 0; m < num; m++) { array[m] = -1; } for (int n = 0; n < num; n++) { if (label[n] >= 0) { if (array[label[n]] < 0) { array[label[n]] = result++; } label[n] = array[label[n]]; } } return result; } } public enum CrackAction : byte { None, StartCrack, StopCrack, Fall } public static class CrackPolicy { public const double FullWarningUpTo = 1.1; public const double NoWarningFrom = 2.0; public static double WarningFor(double utilization, double warningSeconds) { return warningSeconds * Math.Max(0.0, Math.Min(1.0, (2.0 - utilization) / 0.8999999999999999)); } public static CrackAction Decide(double utilization, bool unsupported, bool cracking, double secondsCracking, double warningSeconds, bool cascading, bool ready, bool canFall) { if (!ready) { return CrackAction.None; } if ((!unsupported && !(utilization >= 1.0)) || !canFall) { if (!cracking) { return CrackAction.None; } return CrackAction.StopCrack; } double num = WarningFor(utilization, warningSeconds); if (unsupported || cascading || num <= 0.0) { return CrackAction.Fall; } if (!cracking) { return CrackAction.StartCrack; } if (!(secondsCracking >= num)) { return CrackAction.None; } return CrackAction.Fall; } } public static class Damage { public const double FullStrengthHealth = 0.5; public const double MinStrength = 0.25; public static double StrengthFactor(double health) { if (health >= 0.5) { return 1.0; } if (health <= 0.0) { return 0.25; } return 0.25 + 0.75 * health / 0.5; } } public struct JointRelease { public bool Open; public bool Moved; public Vec3 Point; public Vec3 HingeA; public Vec3 HingeB; public Vec3 SlipA; public Vec3 SlipB; public double[] SpanA; public double[] SpanB; } public sealed class FrameAnalysis { private struct LinkData { public int A; public int B; public Vec3 ArmA; public Vec3 ArmB; } public const double DefaultResidual = 0.0001; private const int Dof = 6; private const int Block = 36; private readonly StructureModel _model; private readonly int _n; private readonly LinkData[] _links; private readonly double[] _diagonal; private readonly double[] _offDiagonal; private readonly double[] _linkStiffness; private readonly double[] _preconditioner; private readonly double[] _x; private readonly double[] _r; private readonly double[] _z; private readonly double[] _p; private readonly double[] _q; private readonly double[] _f; private readonly double _tolerance; private readonly int _maxIterations; private double _rz; private bool _finished; private const int LinksPerStep = 16; private int _assembled; private bool _ready; private readonly double[] _ta = new double[36]; private readonly double[] _tb = new double[36]; private readonly double[] _d = new double[36]; private readonly double[] _dta = new double[36]; private readonly double[] _dtb = new double[36]; private readonly double[] _tmp = new double[36]; private readonly double[] _compliance = new double[36]; private readonly double[] _factor = new double[36]; private readonly double[] _unit = new double[6]; private readonly double[] _column = new double[6]; private readonly JointRelease[] _releases; private readonly double _residual; public int Iterations { get; private set; } public bool Converged { get; private set; } public double RelativeResidual { get; private set; } public double[] Solution => _x; public double Residual => _residual; public FrameAnalysis(StructureModel model, double tolerance = 1E-06, int maxIterations = 0, JointRelease[] releases = null, double[] start = null, double residual = 0.0001, bool[] weightless = null) { _model = model; _releases = releases; _residual = residual; _n = model.Bodies.Count; _tolerance = tolerance; _maxIterations = ((maxIterations > 0) ? maxIterations : Math.Max(500, 24 * _n)); _links = new LinkData[model.Links.Count]; _diagonal = new double[_n * 36]; _offDiagonal = new double[model.Links.Count * 36]; _linkStiffness = new double[model.Links.Count * 36]; _preconditioner = new double[_n * 36]; _x = new double[_n * 6]; _r = new double[_n * 6]; _z = new double[_n * 6]; _p = new double[_n * 6]; _q = new double[_n * 6]; _f = new double[_n * 6]; for (int i = 0; i < _n; i++) { if (weightless == null || !weightless[i]) { Vec3 vec = model.Gravity * model.Bodies[i].Mass; _f[i * 6] = vec.X; _f[i * 6 + 1] = vec.Y; _f[i * 6 + 2] = vec.Z; } } if (start != null && start.Length == _x.Length) { Array.Copy(start, _x, _x.Length); } } public Vec3 TranslationOf(int body) { return Translation(body); } public Vec3 RotationOf(int body) { return Rotation(body); } public void LinkMotion(int li, out Vec3 delta, out Vec3 turn) { LinkData linkData = _links[li]; Vec3 vec = Translation(linkData.A); Vec3 vec2 = Rotation(linkData.A); delta = -(vec + Vec3.Cross(vec2, linkData.ArmA)); turn = -vec2; if (linkData.B >= 0) { Vec3 vec3 = Translation(linkData.B); Vec3 vec4 = Rotation(linkData.B); delta += vec3 + Vec3.Cross(vec4, linkData.ArmB); turn += vec4; } } public ContactLoad LinkLoad(int li) { LinkData linkData = _links[li]; double[] array = new double[6]; LinkMotion(li, out var delta, out var turn); array[0] = delta.X; array[1] = delta.Y; array[2] = delta.Z; array[3] = turn.X; array[4] = turn.Y; array[5] = turn.Z; return new ContactLoad { Point = _model.Bodies[linkData.A].Center + linkData.ArmA, Force = new Vec3(Row(li, 0, array), Row(li, 1, array), Row(li, 2, array)), Moment = new Vec3(Row(li, 3, array), Row(li, 4, array), Row(li, 5, array)), Ground = (linkData.B < 0) }; } public bool Iterate(int steps) { if (!_ready) { int num = Math.Min(_links.Length, _assembled + steps * 16); while (_assembled < num) { AssembleLink(_assembled); _assembled++; } if (_assembled < _links.Length) { return false; } Initialize(); return _finished; } for (int i = 0; i < steps; i++) { if (_finished) { break; } Multiply(_p, _q); double num2 = Dot(_p, _q); if (num2 <= 0.0 || double.IsNaN(num2)) { _finished = true; break; } double num3 = _rz / num2; for (int j = 0; j < _x.Length; j++) { _x[j] += num3 * _p[j]; _r[j] -= num3 * _q[j]; } Iterations++; UpdateResidual(); if (_finished) { break; } ApplyPreconditioner(_r, _z); double num4 = Dot(_r, _z); double num5 = num4 / _rz; _rz = num4; for (int k = 0; k < _p.Length; k++) { _p[k] = _z[k] + num5 * _p[k]; } } return _finished; } public void Solve() { while (!Iterate(64)) { } } public List<ContactLoad>[] ContactLoads() { List<ContactLoad>[] array = new List<ContactLoad>[_n]; for (int i = 0; i < _n; i++) { array[i] = new List<ContactLoad>(); } double[] array2 = new double[6]; for (int j = 0; j < _links.Length; j++) { LinkData linkData = _links[j]; Vec3 vec = Translation(linkData.A); Vec3 vec2 = Rotation(linkData.A); Vec3 vec3 = -(vec + Vec3.Cross(vec2, linkData.ArmA)); Vec3 vec4 = -vec2; if (linkData.B >= 0) { Vec3 vec5 = Translation(linkData.B); Vec3 vec6 = Rotation(linkData.B); vec3 += vec5 + Vec3.Cross(vec6, linkData.ArmB); vec4 += vec6; } array2[0] = vec3.X; array2[1] = vec3.Y; array2[2] = vec3.Z; array2[3] = vec4.X; array2[4] = vec4.Y; array2[5] = vec4.Z; Vec3 vec7 = new Vec3(Row(j, 0, array2), Row(j, 1, array2), Row(j, 2, array2)); Vec3 vec8 = new Vec3(Row(j, 3, array2), Row(j, 4, array2), Row(j, 5, array2)); Vec3 point = _model.Bodies[linkData.A].Center + linkData.ArmA; Link link = _model.Links[j]; double[] spanA = link.SpanA; double[] spanB = link.SpanB; if (_releases != null && (_releases[j].Open || _releases[j].Moved)) { spanA = _releases[j].SpanA; spanB = _releases[j].SpanB; } array[linkData.A].Add(new ContactLoad { Point = point, Force = vec7, Moment = vec8, Ground = (linkData.B < 0), Span = spanA }); if (linkData.B >= 0) { array[linkData.B].Add(new ContactLoad { Point = point, Force = -vec7, Moment = -vec8, Span = spanB }); } } return array; } public BodyResult[] Evaluate() { List<ContactLoad>[] array = ContactLoads(); BodyResult[] array2 = new BodyResult[_n]; for (int i = 0; i < _n; i++) { array2[i] = Mechanics.Evaluate(_model.Bodies[i], array[i], _model.Gravity); } return array2; } private double Row(int link, int row, double[] v) { int num = link * 36 + row * 6; return _linkStiffness[num] * v[0] + _linkStiffness[num + 1] * v[1] + _linkStiffness[num + 2] * v[2] + _linkStiffness[num + 3] * v[3] + _linkStiffness[num + 4] * v[4] + _linkStiffness[num + 5] * v[5]; } private Vec3 Translation(int i) { return new Vec3(_x[i * 6], _x[i * 6 + 1], _x[i * 6 + 2]); } private Vec3 Rotation(int i) { return new Vec3(_x[i * 6 + 3], _x[i * 6 + 4], _x[i * 6 + 5]); } private void UpdateResidual() { double num = Math.Sqrt(Dot(_f, _f)); RelativeResidual = ((num > 0.0) ? (Math.Sqrt(Dot(_r, _r)) / num) : 0.0); if (RelativeResidual <= _tolerance) { Converged = true; _finished = true; } else if (Iterations >= _maxIterations) { _finished = true; } } private void AssembleLink(int li) { Link link = _model.Links[li]; JointRelease release = ((_releases != null) ? _releases[li] : default(JointRelease)); Vec3 vec = (release.Moved ? release.Point : link.Point); Body body = _model.Bodies[link.A]; LinkData linkData = new LinkData { A = link.A, B = link.B, ArmA = vec - body.Center }; Array.Clear(_compliance, 0, 36); Mechanics.AddSegmentCompliance(body, vec, _compliance); if (!link.IsGround) { Body body2 = _model.Bodies[link.B]; linkData.ArmB = vec - body2.Center; Mechanics.AddSegmentCompliance(body2, vec, _compliance); } _links[li] = linkData; InvertSymmetric(_compliance, _linkStiffness, li * 36); Release(li * 36, release); Array.Clear(_ta, 0, 36); SetBlock(_ta, 0, 0, -Mat3.Identity); SetBlock(_ta, 0, 3, Mat3.Skew(linkData.ArmA)); SetBlock(_ta, 3, 3, -Mat3.Identity); Array.Copy(_linkStiffness, li * 36, _d, 0, 36); Mul6(_d, _ta, _dta); MulT6(_ta, _dta, _tmp); Add6(_diagonal, link.A * 36, _tmp); if (!link.IsGround) { Array.Clear(_tb, 0, 36); SetBlock(_tb, 0, 0, Mat3.Identity); SetBlock(_tb, 0, 3, -Mat3.Skew(linkData.ArmB)); SetBlock(_tb, 3, 3, Mat3.Identity); Mul6(_d, _tb, _dtb); MulT6(_tb, _dtb, _tmp); Add6(_diagonal, link.B * 36, _tmp); MulT6(_ta, _dtb, _tmp); Array.Copy(_tmp, 0, _offDiagonal, li * 36, 36); } } private void Release(int offset, JointRelease release) { if (release.Open) { for (int i = 0; i < 36; i++) { _linkStiffness[offset + i] *= _residual; } } else { Free(offset, release.HingeA, 3); Free(offset, release.HingeB, 3); Free(offset, release.SlipA, 0); Free(offset, release.SlipB, 0); } } private void Free(int offset, Vec3 axis, int first) { if (axis.LengthSquared < 1E-12) { return; } for (int i = 0; i < 6; i++) { _column[i] = _linkStiffness[offset + i * 6 + first] * axis.X + _linkStiffness[offset + i * 6 + first + 1] * axis.Y + _linkStiffness[offset + i * 6 + first + 2] * axis.Z; } double num = _column[first] * axis.X + _column[first + 1] * axis.Y + _column[first + 2] * axis.Z; if (num <= 0.0) { return; } double num2 = (1.0 - _residual) / num; for (int j = 0; j < 6; j++) { for (int k = 0; k < 6; k++) { _linkStiffness[offset + j * 6 + k] -= _column[j] * _column[k] * num2; } } } private void InvertSymmetric(double[] m, double[] target, int offset) { Cholesky6(m, 0, _factor, 0); for (int i = 0; i < 6; i++) { Array.Clear(_unit, 0, 6); _unit[i] = 1.0; CholeskySolve6(_factor, 0, _unit, _column, 0); for (int j = 0; j < 6; j++) { target[offset + j * 6 + i] = _column[j]; } } for (int k = 0; k < 6; k++) { for (int l = k + 1; l < 6; l++) { target[offset + l * 6 + k] = (target[offset + k * 6 + l] = (target[offset + k * 6 + l] + target[offset + l * 6 + k]) / 2.0); } } } private void Initialize() { for (int i = 0; i < _n; i++) { Cholesky6(_diagonal, i * 36, _preconditioner, i * 36); } Multiply(_x, _q); for (int j = 0; j < _r.Length; j++) { _r[j] = _f[j] - _q[j]; } ApplyPreconditioner(_r, _z); Array.Copy(_z, _p, _z.Length); _rz = Dot(_r, _z); _ready = true; UpdateResidual(); } private void Multiply(double[] x, double[] y) { for (int i = 0; i < _n; i++) { MulVec6(_diagonal, i * 36, x, i * 6, y, i * 6, overwrite: true); } for (int j = 0; j < _links.Length; j++) { int a = _links[j].A; int b = _links[j].B; if (b >= 0) { MulVec6(_offDiagonal, j * 36, x, b * 6, y, a * 6, overwrite: false); MulVecT6(_offDiagonal, j * 36, x, a * 6, y, b * 6); } } } private void ApplyPreconditioner(double[] r, double[] z) { for (int i = 0; i < _n; i++) { CholeskySolve6(_preconditioner, i * 36, r, z, i * 6); } } private static double Dot(double[] a, double[] b) { double num = 0.0; for (int i = 0; i < a.Length; i++) { num += a[i] * b[i]; } return num; } private static void SetBlock(double[] m, int row, int col, Mat3 b) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { m[(row + i) * 6 + col + j] = b[i, j]; } } } private static void Mul6(double[] a, double[] b, double[] result) { for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { double num = 0.0; for (int k = 0; k < 6; k++) { num += a[i * 6 + k] * b[k * 6 + j]; } result[i * 6 + j] = num; } } } private static void MulT6(double[] a, double[] b, double[] result) { for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { double num = 0.0; for (int k = 0; k < 6; k++) { num += a[k * 6 + i] * b[k * 6 + j]; } result[i * 6 + j] = num; } } } private static void Add6(double[] target, int offset, double[] m) { for (int i = 0; i < 36; i++) { target[offset + i] += m[i]; } } private static void MulVec6(double[] m, int mo, double[] x, int xo, double[] y, int yo, bool overwrite) { for (int i = 0; i < 6; i++) { int num = mo + i * 6; double num2 = m[num] * x[xo] + m[num + 1] * x[xo + 1] + m[num + 2] * x[xo + 2] + m[num + 3] * x[xo + 3] + m[num + 4] * x[xo + 4] + m[num + 5] * x[xo + 5]; y[yo + i] = (overwrite ? num2 : (y[yo + i] + num2)); } } private static void MulVecT6(double[] m, int mo, double[] x, int xo, double[] y, int yo) { for (int i = 0; i < 6; i++) { double num = 0.0; for (int j = 0; j < 6; j++) { num += m[mo + j * 6 + i] * x[xo + j]; } y[yo + i] += num; } } private static void Cholesky6(double[] a, int ao, double[] l, int lo) { for (int i = 0; i < 6; i++) { for (int j = 0; j <= i; j++) { double num = a[ao + i * 6 + j]; for (int k = 0; k < j; k++) { num -= l[lo + i * 6 + k] * l[lo + j * 6 + k]; } if (i == j) { l[lo + i * 6 + i] = Math.Sqrt(Math.Max(num, 1E-30)); } else { l[lo + i * 6 + j] = num / l[lo + j * 6 + j]; } } } } private static void CholeskySolve6(double[] l, int lo, double[] b, double[] x, int o) { for (int i = 0; i < 6; i++) { double num = b[o + i]; for (int j = 0; j < i; j++) { num -= l[lo + i * 6 + j] * x[o + j]; } x[o + i] = num / l[lo + i * 6 + i]; } for (int num2 = 5; num2 >= 0; num2--) { double num3 = x[o + num2]; for (int k = num2 + 1; k < 6; k++) { num3 -= l[lo + k * 6 + num2] * x[o + k]; } x[o + num2] = num3 / l[lo + num2 * 6 + num2]; } } } public static class LoadPathAnalysis { private struct Neighbour { public int Other; public Vec3 Point; } private struct Support { public int Other; public Vec3 Point; public double Weight; } public static BodyResult[] Run(StructureModel model) { int count = model.Bodies.Count; BodyResult[] array = new BodyResult[count]; List<Neighbour>[] array2 = new List<Neighbour>[count]; List<Vec3>[] array3 = new List<Vec3>[count]; for (int i = 0; i < count; i++) { array2[i] = new List<Neighbour>(); array3[i] = new List<Vec3>(); } foreach (Link link in model.Links) { if (link.IsGround) { array3[link.A].Add(link.Point); continue; } array2[link.A].Add(new Neighbour { Other = link.B, Point = link.Point }); array2[link.B].Add(new Neighbour { Other = link.A, Point = link.Point }); } int[] level = new int[count]; Queue<int> queue = new Queue<int>(); for (int j = 0; j < count; j++) { level[j] = ((array3[j].Count <= 0) ? int.MaxValue : 0); if (level[j] == 0) { queue.Enqueue(j); } } while (queue.Count > 0) { int num = queue.Dequeue(); foreach (Neighbour item in array2[num]) { int other = item.Other; if (level[other] == int.MaxValue) { level[other] = level[num] + 1; queue.Enqueue(other); } } } int[] array4 = new int[count]; for (int k = 0; k < count; k++) { array4[k] = k; } Array.Sort(array4, (int a, int b) => (level[a] == level[b]) ? a.CompareTo(b) : level[b].CompareTo(level[a])); double length = model.Gravity.Length; Vec3 vec = model.Gravity.Normalized(); double[] array5 = new double[count]; Vec3[] array6 = new Vec3[count]; for (int num2 = 0; num2 < count; num2++) { array5[num2] = model.Bodies[num2].Mass * length; array6[num2] = model.Bodies[num2].Center * array5[num2]; } List<Support> list = new List<Support>(); int[] array7 = array4; foreach (int num4 in array7) { if (level[num4] == int.MaxValue) { array[num4] = BodyResult.Unsupported; continue; } Body body = model.Bodies[num4]; list.Clear(); if (level[num4] == 0) { foreach (Vec3 item2 in array3[num4]) { list.Add(new Support { Other = -1, Point = item2, Weight = SupportWeight(body, item2, vec) }); } } else { foreach (Neighbour item3 in array2[num4]) { if (level[item3.Other] < level[num4]) { list.Add(new Support { Other = item3.Other, Point = item3.Point, Weight = SupportWeight(body, item3.Point, vec) }); } } } double num5 = 0.0; Vec3 zero = Vec3.Zero; foreach (Support item4 in list) { num5 += item4.Weight; zero += item4.Point * item4.Weight; } zero /= num5; Vec3 vec2 = array6[num4] / array5[num4]; foreach (Support item5 in list) { if (item5.Other >= 0) { double num6 = array5[num4] * item5.Weight / num5; array5[item5.Other] += num6; array6[item5.Other] += vec2 * num6; } } array[num4] = Check(body, array5[num4], vec2, zero, list, vec); array[num4].HeldWeight = Math.Max(0.0, array5[num4] - body.Mass * length); array[num4].MemberForce = (0.0 - Math.Abs(Vec3.Dot(vec, body.Axis(Mechanics.LongestAxis(body))))) * (array5[num4] - 0.5 * body.Mass * length); } return array; } private static double SupportWeight(Body body, Vec3 point, Vec3 down) { Vec3 a = (point - body.Center).Normalized(); return 0.25 + Math.Max(0.0, Vec3.Dot(a, down)); } private static Vec3 Horizontal(Vec3 v, Vec3 down) { return v - down * Vec3.Dot(v, down); } private static BodyResult Check(Body body, double load, Vec3 centroid, Vec3 supportPoint, List<Support> supports, Vec3 down) { Vec3 vec = down * load; int num = MostAligned(body, down); BodyResult result = Section(body, num, vec, Vec3.Zero, (num == Mechanics.LongestAxis(body)) ? Mechanics.BucklingFactor(body) : 1.0); Vec3 vec2 = Horizontal(centroid - supportPoint, down); double num2 = 0.0; for (int i = 0; i < supports.Count; i++) { for (int j = i + 1; j < supports.Count; j++) { num2 = Math.Max(num2, Horizontal(supports[i].Point - supports[j].Point, down).Length); } } if (vec2.Length > 1E-06 || num2 > 1E-06) { Vec3 vec3 = ((vec2.Length > 1E-06) ? vec2.Normalized() : Horizontal(supports[1].Point - supports[0].Point, down).Normalized()); Vec3 moment = Vec3.Cross(vec3, vec) * (vec2.Length + num2 / 8.0); int axis = MostAligned(body, vec3); BodyResult bodyResult = Section(body, axis, vec, moment, 1.0); if (bodyResult.Utilization > result.Utilization) { result = bodyResult; } } return result; } private static BodyResult Section(Body body, int axis, Vec3 force, Vec3 moment, double buckling) { Vec3 vec = body.Axis(axis); int i = (axis + 1) % 3; int i2 = (axis + 2) % 3; if (Vec3.Dot(vec, force) > 0.0) { vec = -vec; } return Mechanics.SectionCheck(body.Material, force, moment, vec, body.Axis(i), body.Axis(i2), body.Size[i], body.Size[i2], buckling, body.StrengthFactor); } private static int MostAligned(Body body, Vec3 dir) { int result = 0; double num = -1.0; for (int i = 0; i < 3; i++) { double num2 = Math.Abs(Vec3.Dot(body.Axis(i), dir)); if (num2 > num) { num = num2; result = i; } } return result; } } public static class Loads { public const double FlatSnowShare = 0.8; public const double SnowSlidesFrom = 30.0; public const double SnowGoneAt = 60.0; public static double SnowShapeFactor(double slopeDegrees) { if (slopeDegrees <= 30.0) { return 0.8; } if (slopeDegrees >= 60.0) { return 0.0; } return 0.8 * (60.0 - slopeDegrees) / 30.0; } public static double SnowArea(Vec3 axisX, Vec3 axisY, Vec3 axisZ, Vec3 size) { double num = Math.Abs(axisX.Y); double num2 = Math.Abs(axisY.Y); double num3 = Math.Abs(axisZ.Y); double num4 = size.Y * size.Z * num + size.X * size.Z * num2 + size.X * size.Y * num3; double slopeDegrees = Math.Acos(Math.Min(1.0, Math.Max(num, Math.Max(num2, num3)))) * 180.0 / Math.PI; return num4 * SnowShapeFactor(slopeDegrees); } } public sealed class Masonry { private struct State { public bool Open; public bool Slip; public int Side1; public int Side2; } private sealed class Joint { public int Link; public Vec3 Normal; public Vec3 T1; public Vec3 T2; public Vec3 Centre; public double A1; public double A2; public double Friction; public double Reference; public bool Edges; public bool Held; public State Now; public State Before; public State Released; public double Rank; public double Force; public double Shear; public double Turning; public double Tipping; public double Sliding; public double E1; public double E2; } private const int MaxSolves = 40; private const double JointLimit = 0.99; private const double UnstableUtilization = 1.5; private const double Suspicion = 5.0; private const double ProbeShare = 0.1; private const double Mechanism = 3.0; private const double Tolerance = 0.01; private const double Bite = 0.01; private const double Pull = 1000000.0; private const double ThinShare = 0.3; private const double EdgeShare = 0.05; private const double OuterShare = 0.25; private const double EmbeddedVolume = 0.001; private readonly StructureModel _model; private readonly List<Joint> _joints = new List<Joint>(); private readonly List<int>[] _bodyLinks; private readonly List<Joint> _applied = new List<Joint>(); private double[] _start; private double[] _steady; private double[] _normal; private bool _probing; private bool _settling; private bool _edgesOpened; public JointRelease[] Releases { get; } public double Residual { get; private set; } = 0.0001; public bool[] Gone { get; } public int Rounds { get; private set; } public bool Settled { get; private set; } = true; public bool Active => _joints.Count > 0; public Masonry(StructureModel model) { _model = model; Releases = new JointRelease[model.Links.Count]; Gone = new bool[model.Bodies.Count]; _bodyLinks = new List<int>[model.Bodies.Count]; for (int i = 0; i < _bodyLinks.Length; i++) { _bodyLinks[i] = new List<int>(); } for (int j = 0; j < model.Links.Count; j++) { Link link = model.Links[j]; _bodyLinks[link.A].Add(j); if (!link.IsGround) { _bodyLinks[link.B].Add(j); } Joint joint = Build(model, j); if (joint != null) { _joints.Add(joint); } } } public bool Next(FrameAnalysis frame) { if (_settling) { return false; } if (_start == null) { _start = new double[_model.Bodies.Count]; for (int i = 0; i < _start.Length; i++) { _start[i] = Motion(frame, i); } _steady = (double[])_start.Clone(); } else if (_probing) { _probing = false; Residual = 0.0001; if (Moving(frame)) { if (Rounds < 40 && (Hold(frame) || Retry(frame))) { Rounds++; return true; } Collapse(frame); _settling = true; Rounds++; return true; } _steady = _normal; } else { _normal = new double[_model.Bodies.Count]; for (int j = 0; j < _normal.Length; j++) { _normal[j] = Motion(frame, j); } if (Rounds < 40 && Suspicious()) { _probing = true; Residual = 1E-05; Rounds++; return true; } _steady = _normal; } if (Rounds >= 40) { Settled = false; return false; } if (!_edgesOpened) { _edgesOpened = true; if (OpenEdges()) { Rounds++; return true; } } if (!Decide(frame)) { return false; } Rounds++; return true; } public void Finish(FrameAnalysis frame, BodyResult[] results) { if (_start == null) { return; } foreach (Joint joint in _joints) { Link link = _model.Links[joint.Link]; if (!joint.Now.Open && !joint.Edges && !Gone[link.A] && !Gone[link.B]) { Measure(joint, frame.LinkLoad(joint.Link)); if (!(joint.Force <= 0.0)) { double num = (joint.Now.Slip ? 0.0 : joint.Sliding); double num2 = Math.Min(1.0, joint.Force / joint.Reference); StressMode mode = ((joint.Tipping >= num) ? StressMode.Tipping : StressMode.Sliding); double utilization = Math.Min(0.99, Math.Max(joint.Tipping, num) * num2); Raise(results, link.A, utilization, mode); Raise(results, link.B, utilization, mode); } } } for (int i = 0; i < results.Length; i++) { if (Gone[i] && results[i].Mode != StressMode.Unsupported) { results[i].Utilization = Math.Max(results[i].Utilization, 1.5); results[i].Mode = StressMode.Unstable; } } } private bool OpenEdges() { _applied.Clear(); bool result = false; foreach (Joint joint in _joints) { if (joint.Edges && !joint.Now.Open) { joint.Now = new State { Open = true }; Releases[joint.Link] = Release(joint); result = true; } } return result; } private bool Decide(FrameAnalysis frame) { foreach (Joint joint in _joints) { Link link = _model.Links[joint.Link]; joint.Rank = 0.0; joint.Released = joint.Now; if (joint.Edges || joint.Now.Open || Gone[link.A] || Gone[link.B]) { continue; } double num = 0.01 * joint.Reference; Measure(joint, frame.LinkLoad(joint.Link)); if (joint.Held) { if (!joint.Now.Slip && joint.Force > num && (joint.Sliding - 1.0) * joint.Friction * joint.Force > num) { joint.Released = new State { Slip = true, Side1 = joint.Now.Side1, Side2 = joint.Now.Side2 }; joint.Rank = joint.Sliding; } continue; } if (joint.Force < 0.0 - num || (joint.Force <= num && joint.Turning > num * Math.Max(joint.A1, joint.A2))) { joint.Released = new State { Open = true }; joint.Rank = 1000000.0 - joint.Force / joint.Reference; continue; } if (joint.Force <= num) { if (!joint.Now.Slip && joint.Shear > num) { joint.Released = new State { Slip = true, Side1 = joint.Now.Side1, Side2 = joint.Now.Side2 }; joint.Rank = 1000000.0; } continue; } State now = joint.Now; if (now.Side1 == 0 && (Math.Abs(joint.E1) - joint.A1) * joint.Force > num * joint.A1) { now.Side1 = Math.Sign(joint.E1); joint.Rank = joint.Tipping; } if (now.Side2 == 0 && (Math.Abs(joint.E2) - joint.A2) * joint.Force > num * joint.A2) { now.Side2 = Math.Sign(joint.E2); joint.Rank = joint.Tipping; } if (!now.Slip && (joint.Sliding - 1.0) * joint.Friction * joint.Force > num) { now.Slip = true; joint.Rank = Math.Max(joint.Rank, joint.Sliding); } joint.Released = now; } _applied.Clear(); foreach (Joint joint2 in _joints) { if (!(joint2.Rank <= 0.0)) { joint2.Before = joint2.Now; joint2.Now = joint2.Released; Releases[joint2.Link] = Release(joint2); _applied.Add(joint2); } } return _applied.Count > 0; } private bool Hold(FrameAnalysis frame) { bool flag = false; foreach (Joint joint in _joints) { Link link = _model.Links[joint.Link]; if (joint.Edges || joint.Held || Gone[link.A] || Gone[link.B] || (!joint.Now.Open && joint.Now.Side1 == 0 && joint.Now.Side2 == 0) || (!Unstable(frame, link.A) && !Unstable(frame, link.B))) { continue; } frame.LinkMotion(joint.Link, out var delta, out var turn); Vec3 point = frame.LinkLoad(joint.Link).Point; double num = Motion(frame, link.A) + Motion(frame, link.B); int num2 = 0; int num3 = -1; int num4 = -1; for (int i = 0; i < 4; i++) { Vec3 vec = joint.Centre + joint.T1 * ((double)Sign(i, 1) * joint.A1) + joint.T2 * ((double)Sign(i, 2) * joint.A2); if (!(Vec3.Dot(joint.Normal, delta + Vec3.Cross(turn, vec - point)) >= -0.01 * num)) { num2++; if (num3 < 0) { num3 = i; } num4 = i; } } if (num2 != 0) { State now = new State { Slip = joint.Now.Slip }; if (joint.Now.Open && num2 == 1) { now.Side1 = Sign(num3, 1); now.Side2 = Sign(num3, 2); } else if (joint.Now.Open && num2 == 2 && (num3 & 1) == (num4 & 1)) { now.Side1 = Sign(num3, 1); } else if (joint.Now.Open && num2 == 2 && (num3 & 2) == (num4 & 2)) { now.Side2 = Sign(num3, 2); } joint.Now = now; joint.Held = true; Releases[joint.Link] = Release(joint); flag = true; } } if (flag) { _applied.Clear(); } return flag; } private static int Sign(int corner, int bit) { if ((corner & bit) != 0) { return 1; } return -1; } private bool Retry(FrameAnalysis frame) { if (_applied.Count < 2) { return false; } Joint joint = null; foreach (Joint item in _applied) { Link link = _model.Links[item.Link]; if (Unstable(frame, link.A) || Unstable(frame, link.B)) { item.Now = item.Before; Releases[item.Link] = Release(item); if (joint == null || item.Rank > joint.Rank) { joint = item; } } } _applied.Clear(); if (joint == null) { return false; } joint.Now = joint.Released; Releases[joint.Link] = Release(joint); _applied.Add(joint); return true; } private bool Suspicious() { for (int i = 0; i < Gone.Length; i++) { if (!Gone[i] && _normal[i] > 5.0 * _steady[i] + 1E-09) { return true; } } return false; } private bool Moving(FrameAnalysis frame) { for (int i = 0; i < Gone.Length; i++) { if (!Gone[i] && Unstable(frame, i)) { return true; } } return false; } private bool Unstable(FrameAnalysis frame, int body) { if (!Gone[body]) { return Motion(frame, body) > 3.0 * _normal[body] + 1E-09; } return false; } private void Collapse(FrameAnalysis frame) { List<int> list = new List<int>(); for (int i = 0; i < Gone.Length; i++) { if (Unstable(frame, i)) { list.Add(i); } } foreach (int item in list) { Gone[item] = true; foreach (int item2 in _bodyLinks[item]) { Releases[item2] = new JointRelease { Open = true }; } } _applied.Clear(); } private static double Share(double e, double a) { if (!(a > 1E-06)) { return 0.0; } return Math.Abs(e) / a; } private static void Raise(BodyResult[] results, int body, double utilization, StressMode mode) { if (results[body].Mode != StressMode.Unsupported && !(utilization <= results[body].Utilization)) { results[body].Utilization = utilization; results[body].Mode = mode; } } private double Motion(FrameAnalysis frame, int body) { Body body2 = _model.Bodies[body]; return frame.TranslationOf(body).Length + frame.RotationOf(body).Length * body2.Size.Length / 2.0; } private static void Measure(Joint joint, ContactLoad load) { Vec3 vec = load.Moment + Vec3.Cross(load.Point - joint.Centre, load.Force); double num = (joint.Force = 0.0 - Vec3.Dot(load.Force, joint.Normal)); joint.Shear = (load.Force + joint.Normal * num).Length; joint.Turning = (vec - joint.Normal * Vec3.Dot(vec, joint.Normal)).Length; if (num <= 0.0) { joint.E1 = (joint.E2 = (joint.Tipping = (joint.Sliding = 0.0))); return; } joint.E1 = Vec3.Dot(vec, joint.T2) / num; joint.E2 = (0.0 - Vec3.Dot(vec, joint.T1)) / num; joint.Tipping = Math.Max((joint.Now.Side1 != 0) ? 0.0 : Share(joint.E1, joint.A1), (joint.Now.Side2 != 0) ? 0.0 : Share(joint.E2, joint.A2)); joint.Sliding = joint.Shear / (joint.Friction * num); } private JointRelease Release(Joint joint) { State now = joint.Now; if (now.Open) { return new JointRelease { Open = true }; } JointRelease result = default(JointRelease); if (now.Side1 != 0 || now.Side2 != 0) { Vec3 vec = joint.Centre + joint.T1 * ((double)now.Side1 * joint.A1) + joint.T2 * ((double)now.Side2 * joint.A2); Vec3 vec2 = ((now.Side1 != 0) ? Vec3.Zero : (joint.T1 * joint.A1)) + ((now.Side2 != 0) ? Vec3.Zero : (joint.T2 * joint.A2)); Link link = _model.Links[joint.Link]; result.Moved = true; result.Point = vec; result.HingeA = ((now.Side1 != 0) ? joint.T2 : Vec3.Zero); result.HingeB = ((now.Side2 != 0) ? joint.T1 : Vec3.Zero); result.SpanA = LocalSpan(_model.Bodies[link.A], vec - vec2, vec + vec2); result.SpanB = LocalSpan(_model.Bodies[link.B], vec - vec2, vec + vec2); } if (now.Slip) { result.SlipA = joint.T1; result.SlipB = joint.T2; } return result; } private static double[] LocalSpan(Body body, Vec3 from, Vec3 to) { double[] array = new double[6]; for (int i = 0; i < 3; i++) { double num = body.Size[i] / 2.0; double val = Vec3.Dot(from - body.Center, body.Axis(i)); double val2 = Vec3.Dot(to - body.Center, body.Axis(i)); array[2 * i] = Math.Max(0.0 - num, Math.Min(num, Math.Min(val, val2))); array[2 * i + 1] = Math.Max(0.0 - num, Math.Min(num, Math.Max(val, val2))); } return array; } private static Joint Build(StructureModel model, int li) { Link link = model.Links[li]; if (link.IsGround || link.SpanA == null || link.SpanB == null) { return null; } Body body = model.Bodies[link.A]; Body body2 = model.Bodies[link.B]; if (body.Material == null || body2.Material == null || !body.Material.Masonry || !body2.Material.Masonry) { return null; } Vec3 outward; int thin; bool flag = Face(body, link.SpanA, out outward, out thin); Vec3 outward2; int thin2; bool flag2 = Face(body2, link.SpanB, out outward2, out thin2); bool edges = false; bool flag3 = body.Fitted != body2.Fitted && Embedded(body, body2); Vec3 vec; if (flag3 && body.Fitted) { if (!flag2) { return null; } vec = -outward2; } else if (flag3) { if (!flag) { return null; } vec = outward; } else { if (!flag || !flag2) { return null; } vec = ((thin < thin2) ? outward : ((thin2 < thin) ? (-outward2) : (outward - outward2))); edges = thin > 1 && thin2 > 1; } if (vec.LengthSquared < 1E-12) { return null; } vec = vec.Normalized(); int i = 0; double num = double.MaxValue; for (int j = 0; j < 3; j++) { double num2 = Math.Abs(Vec3.Dot(body.Axis(j), vec)); if (num2 < num - 1E-09) { num = num2; i = j; } } Vec3 vec2 = (body.Axis(i) - vec * Vec3.Dot(body.Axis(i), vec)).Normalized(); Vec3 vec3 = Vec3.Cross(vec, vec2); Project(body, link.SpanA, vec2, out var lo, out var hi); Project(body2, link.SpanB, vec2, out var lo2, out var hi2); Project(body, link.SpanA, vec3, out var lo3, out var hi3); Project(body2, link.SpanB, vec3, out var lo4, out var hi4); Project(body, link.SpanA, vec, out var lo5, out var hi5); Project(body2, link.SpanB, vec, out var lo6, out var hi6); Overlap(ref lo, ref hi, lo2, hi2); Overlap(ref lo3, ref hi3, lo4, hi4); return new Joint { Link = li, Normal = vec, T1 = vec2, T2 = vec3, Centre = vec2 * ((lo + hi) / 2.0) + vec3 * ((lo3 + hi3) / 2.0) + vec * ((lo5 + hi5 + lo6 + hi6) / 4.0), A1 = (hi - lo) / 2.0, A2 = (hi3 - lo3) / 2.0, Friction = Math.Min(body.Material.Friction, body2.Material.Friction), Reference = Math.Max(1E-06, Math.Min(body.Mass, body2.Mass) * model.Gravity.Length), Edges = edges }; } private static bool Embedded(Body a, Body b) { if (Fysik.Structure.Overlap.Of(Box(a), Box(b), out var _, out var volume)) { return volume > 0.001; } return false; } private static OrientedBox Box(Body body) { return new OrientedBox { Center = body.Center, AxisX = body.AxisX, AxisY = body.AxisY, AxisZ = body.AxisZ, Half = body.Size * 0.5 }; } private static bool Face(Body body, double[] span, out Vec3 outward, out int thin) { outward = Vec3.Zero; thin = 0; int num = -1; double num2 = double.MaxValue; for (int i = 0; i < 3; i++) { double num3 = (span[2 * i + 1] - span[2 * i]) / Math.Max(body.Size[i], 1E-06); if (num3 < num2 - 1E-09) { num2 = num3; num = i; } } if (num2 > 0.3) { return false; } for (int j = 0; j < 3; j++) { double num4 = (span[2 * j + 1] - span[2 * j]) / Math.Max(body.Size[j], 1E-06); if (j != num && num4 > 0.05) { continue; } double value = (span[2 * j] + span[2 * j + 1]) / 2.0; if (Math.Abs(value) < 0.25 * body.Size[j]) { if (j == num) { return false; } } else { outward += body.Axis(j) * Math.Sign(value); thin++; } } outward = outward.Normalized(); return true; } private static void Project(Body body, double[] span, Vec3 direction, out double lo, out double hi) { lo = (hi = Vec3.Dot(body.Center, direction)); for (int i = 0; i < 3; i++) { double num = Vec3.Dot(body.Axis(i), direction); double val = num * span[2 * i]; double val2 = num * span[2 * i + 1]; lo += Math.Min(val, val2); hi += Math.Max(val, val2); } } private static void Overlap(ref double lo, ref double hi, double otherLo, double otherHi) { lo = Math.Max(lo, otherLo); hi = Math.Min(hi, otherHi); if (lo > hi) { lo = (hi = (lo + hi) / 2.0); } } } public readonly struct Vec3 { public readonly double X; public readonly double Y; public readonly double Z; public static readonly Vec3 Zero = new Vec3(0.0, 0.0, 0.0); public static readonly Vec3 UnitX = new Vec3(1.0, 0.0, 0.0); public static readonly Vec3 UnitY = new Vec3(0.0, 1.0, 0.0); public static readonly Vec3 UnitZ = new Vec3(0.0, 0.0, 1.0); public double this[int i] => i switch { 1 => Y, 0 => X, _ => Z, }; public double LengthSquared => X * X + Y * Y + Z * Z; public double Length => Math.Sqrt(LengthSquared); public Vec3(double x, double y, double 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) { return new Vec3(0.0 - a.X, 0.0 - a.Y, 0.0 - a.Z); } public static Vec3 operator *(Vec3 a, double s) { return new Vec3(a.X * s, a.Y * s, a.Z * s); } public static Vec3 operator /(Vec3 a, double s) { return new Vec3(a.X / s, a.Y / s, a.Z / s); } public static double Dot(Vec3 a, Vec3 b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } public static Vec3 Cross(Vec3 a, Vec3 b) { return new Vec3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X); } public Vec3 Normalized() { double length = Length; if (!(length > 1E-12)) { return Zero; } return this / length; } public override string ToString() { return $"({X:0.###}, {Y:0.###}, {Z:0.###})"; } } public struct Mat3 { public double M00; public double M01; public double M02; public double M10; public double M11; public double M12; public double M20; public double M21; public double M22; public static readonly Mat3 Identity = new Mat3 { M00 = 1.0, M11 = 1.0, M22 = 1.0 }; public double this[int r, int c] => (r * 3 + c) switch { 0 => M00, 1 => M01, 2 => M02, 3 => M10, 4 => M11, 5 => M12, 6 => M20, 7 => M21, _ => M22, }; public static Mat3 Skew(Vec3 r) { return new Mat3 { M01 = 0.0 - r.Z, M02 = r.Y, M10 = r.Z, M12 = 0.0 - r.X, M20 = 0.0 - r.Y, M21 = r.X }; } public static Mat3 operator -(Mat3 a) { return new Mat3 { M00 = 0.0 - a.M00, M01 = 0.0 - a.M01, M02 = 0.0 - a.M02, M10 = 0.0 - a.M10, M11 = 0.0 - a.M11, M12 = 0.0 - a.M12, M20 = 0.0 - a.M20, M21 = 0.0 - a.M21, M22 = 0.0 - a.M22 }; } } public struct ContactLoad { public Vec3 Point; public Vec3 Force; public Vec3 Moment; public bool Ground; public double[] Span; } public static class Mechanics { private const double ShearCorrection = 5.0 / 6.0; private const double PlateAspect = 4.0; private const double MinSegmentLength = 0.05; private const double FaceShare = 0.5; public static void AddSegmentCompliance(Body body, Vec3 point, double[] compliance) { Vec3 a = point - body.Center; int num = 0; double num2 = -1.0; for (int i = 0; i < 3; i++) { double num3 = Math.Abs(Vec3.Dot(a, body.Axis(i))); if (num3 > num2) { num2 = num3; num = i; } } if (a.LengthSquared < 1E-12) { num = SmallestAxis(body); } double num4 = Math.Max(num2, 0.05); int i2 = (num + 1) % 3; int i3 = (num + 2) % 3; double num5 = body.Size[i2]; double num6 = body.Size[i3]; Vec3 vec = ((Vec3.Dot(a, body.Axis(num)) < 0.0) ? (-body.Axis(num)) : body.Axis(num)); Vec3 vec2 = body.Axis(i2); Vec3 vec3 = body.Axis(i3); double num7 = num5 * num6; double num8 = num5 * num6 * num6 * num6 / 12.0; double num9 = num6 * num5 * num5 * num5 / 12.0; double num10 = TorsionConstant(num5, num6); double elasticity = body.Material.Elasticity; double shearModulus = body.Material.ShearModulus; double num11 = num4 / (5.0 / 6.0 * shearModulus * num7); double num12 = num4 * num4; double num13 = num12 * num4; AddOuter(compliance, 0, 0, vec, vec, num4 / (elasticity * num7)); AddOuter(compliance, 0, 0, vec2, vec2, num11 + num13 / (3.0 * elasticity * num9)); AddOuter(compliance, 0, 0, vec3, vec3, num11 + num13 / (3.0 * elasticity * num8)); AddOuter(compliance, 3, 3, vec, vec, num4 / (shearModulus * num10)); AddOuter(compliance, 3, 3, vec2, vec2, num4 / (elasticity * num8)); AddOuter(compliance, 3, 3, vec3, vec3, num4 / (elasticity * num9)); Vec3 vec4 = Vec3.Cross(vec, vec2); Vec3 vec5 = Vec3.Cross(vec, vec3); AddOuter(compliance, 0, 3, vec2, vec4, num12 / (2.0 * elasticity * num9)); AddOuter(compliance, 3, 0, vec4, vec2, num12 / (2.0 * elasticity * num9)); AddOuter(compliance, 0, 3, vec3, vec5, num12 / (2.0 * elasticity * num8)); AddOuter(compliance, 3, 0, vec5, vec3, num12 / (2.0 * elasticity * num8)); } private static void AddOuter(double[] m, int row, int col, Vec3 u, Vec3 v, double s) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { m[(row + i) * 6 + col + j] += s * u[i] * v[j]; } } } public static double TorsionConstant(double s1, double s2) { double num = Math.Max(s1, s2); double num2 = Math.Min(s1, s2); double num3 = num2 / num; return num * num2 * num2 * num2 * (1.0 / 3.0 - 0.21 * num3 * (1.0 - num3 * num3 * num3 * num3 / 12.0)); } public static int SmallestAxis(Body body) { Vec3 size = body.Size; if (!(size.X <= size.Y) || !(size.X <= size.Z)) { if (!(size.Y <= size.Z)) { return 2; } return 1; } return 0; } public static int LongestAxis(Body body) { Vec3 size = body.Size; if (!(size.X >= size.Y) || !(size.X >= size.Z)) { if (!(size.Y >= size.Z)) { return 2; } return 1; } return 0; } public static double BucklingFactor(Body body) { int num = LongestAxis(body); double num2 = body.Size[num]; double val = Math.Min(body.Size[(num + 1) % 3], body.Size[(num + 2) % 3]) / Math.Sqrt(12.0); double num3 = num2 / Math.Max(val, 1E-06) / Math.Max(body.Material.BucklingSlenderness, 1E-06); return 1.0 / (1.0 + num3 * num3); } public static BodyResult Evaluate(Body body, IReadOnlyList<ContactLoad> contacts, Vec3 gravity) { Vec3 vec = gravity * body.Mass; int num = LongestAxis(body); double num2 = BucklingFactor(body); BodyResult result = new BodyResult { Mode = StressMode.None }; List<double> list = new List<double>(contacts.Count * 2 + 1); for (int i = 0; i < 3; i++) { Vec3 vec2 = body.Axis(i); double num3 = body.Size[i]; double num4 = num3 / 2.0; double num5 = 0.001 * num3 + 1E-06; list.Clear(); bool flag = true; foreach (ContactLoad contact in contacts) { if (Spread(contact, i, num4, num5, out var lo, out var hi)) { list.Add(Clamp(lo, 0.0 - num4 + num5, num4 - num5)); list.Add(Clamp(hi, 0.0 - num4 + num5, num4 - num5)); if (hi - lo >= 0.5 * num3) { list.Add(Clamp((lo + hi) / 2.0, 0.0 - num4 + num5, num4 - num5)); } continue; } double num6 = Vec3.Dot(contact.Point - body.Center, vec2); if (Math.Abs(num6) < num5) { flag = false; } list.Add(Clamp(num6 - num5, 0.0 - num4 + num5, num4 - num5)); list.Add(Clamp(num6 + num5, 0.0 - num4 + num5, num4 - num5)); } if (flag) { list.Insert(0, 0.0); } int i2 = (i + 1) % 3; int i3 = (i + 2) % 3; Vec3 e = body.Axis(i2); Vec3 e2 = body.Axis(i3); double s = body.Size[i2]; double s2 = body.Size[i3]; double buckling = ((i == num) ? num2 : 1.0); foreach (double item in list) { Vec3 vec3 = body.Center + vec2 * item; Vec3 force = Vec3.Zero; Vec3 moment = Vec3.Zero; foreach (ContactLoad contact2 in contacts) { if (Spread(contact2, i, num4, num5, out var lo2, out var hi2)) { AddSpread(contact2, body, vec2, lo2, hi2, item, vec3, hi2 - lo2 >= 0.5 * num3, ref force, ref moment); } else if (!(Vec3.Dot(contact2.Point - body.Center, vec2) <= item)) { force += contact2.Force; moment += contact2.Moment + Vec3.Cross(contact2.Point - vec3, contact2.Force); } } double num7 = ((num3 > 0.0) ? ((num4 - item) / num3) : 0.0); Vec3 vec4 = vec * num7; Vec3 vec5 = body.Center + vec2 * ((item + num4) / 2.0); force += vec4; moment += Vec3.Cross(vec5 - vec3, vec4); BodyResult bodyResult = SectionCheck(body.Material, force, moment, vec2, e, e2, s, s2, buckling, body.StrengthFactor); if (bodyResult.Utilization > result.Utilization || result.Mode == StressMode.None) { result = bodyResult; } } } Vec3 b = gravity.Normalized(); Vec3 b2 = body.Axis(num); Vec3 a = vec * 0.5; foreach (ContactLoad contact3 in contacts) { if (!contact3.Ground) { result.HeldWeight += Math.Max(0.0, Vec3.Dot(contact3.Force, b)); } if (Vec3.Dot(contact3.Point - body.Center, b2) > 0.0) { a += contact3.Force; } } result.MemberForce = Vec3.Dot(a, b2); return result; } public static BodyResult SectionCheck(MaterialProps m, Vec3 force, Vec3 moment, Vec3 e, Vec3 e1, Vec3 e2, double s1, double s2, double buckling, double strengthFactor = 1.0) { double num = Math.Max(strengthFactor, 0.001); double num2 = s1 * s2; double num3 = Vec3.Dot(force, e); double length = (force - e * num3).Length; double num4 = Math.Abs(Vec3.Dot(moment, e)); double num5 = Math.Abs(Vec3.Dot(moment, e1)); double num6 = Math.Abs(Vec3.Dot(moment, e2)); double num7 = s1 * s2 * s2 / 6.0; double num8 = s2 * s1 * s1 / 6.0; double num9 = num3 / num2; double num10 = 1.5 * length / num2; double num11 = Math.Max(s1, s2); double num12 = Math.Min(s1, s2); double num18; double num19; if (num11 >= 4.0 * num12) { double num13 = ((s1 >= s2) ? num5 : num6); double num14 = ((s1 >= s2) ? num6 : num5); double num15 = num13 / num11; double num16 = num4 / num11; double num17 = Math.Abs(num15) / 2.0 + Math.Sqrt(num15 * num15 / 4.0 + num16 * num16); num18 = 6.0 * num17 / (num12 * num12) + num14 / (num12 * num11 * num11 / 6.0); num19 = 0.0; } else { num18 = num5 / num7 + num6 / num8; num19 = num4 * (3.0 + 1.8 * num12 / num11) / (num11 * num12 * num12); } double num20 = num10 + num19; double num21 = Math.Max(0.0, 0.0 - num9) / Math.Max(buckling, 1E-06) - Math.Max(0.0, num9) + num18; double num22 = num9 + num18; double num23 = num21 / (m.CompressiveStrength * num); double num24 = num22 / (m.TensileStrength * num); double num25 = num20 / (m.ShearStrength * num); bool flag = num18 > Math.Abs(num9); BodyResult result = new BodyResult { AxialForce = num3, BendingMoment = Math.Sqrt(num5 * num5 + num6 * num6), Torque = num4 }; if (num23 >= num24 && num23 >= num25) { result.Utilization = Math.Max(0.0, num23); result.Mode = ((!flag) ? StressMode.Compression : StressMode.Bending); } else if (num24 >= num25) { result.Utilization = num24; result.Mode = (flag ? StressMode.Bending : StressMode.Tension); } else { result.Utilization = num25; result.Mode = ((num19 > num10) ? StressMode.Torsion : StressMode.Shear); } return result; } private static double Clamp(double v, double lo, double hi) { if (!(v < lo)) { if (!(v > hi)) { return v; } return hi; } return lo; } private static bool Spread(ContactLoad c, int axis, double half, double eps, out double lo, out double hi) { lo = (hi = 0.0); if (c.Span == null) { return false; } lo = Math.Max(c.Span[2 * axis], 0.0 - half); hi = Math.Min(c.Span[2 * axis + 1], half); return hi - lo >= 2.0 * eps; } private static void AddSpread(ContactLoad c, Body body, Vec3 e, double lo, double hi, double t, Vec3 origin, bool face, ref Vec3 force, ref Vec3 moment) { if (t >= hi) { return; } double num = Vec3.Dot(c.Point - body.Center, e); double num2 = (lo + hi) / 2.0; double num3 = hi - lo; Vec3 vec = c.Point + e * (num2 - num); Vec3 vec2 = c.Moment - Vec3.Cross(e * (num2 - num), c.Force); if (t <= lo) { force += c.Force; moment += vec2 + Vec3.Cross(vec - origin, c.Force); } else if (!face) { double num4 = (hi - t) / num3; Vec3 vec3 = c.Force * num4; force += vec3; moment += Vec3.Cross(vec + e * ((t + hi) / 2.0 - num2) - origin, vec3); if (num2 > t) { moment += vec2; } } else { Vec3 vec4 = e * Vec3.Dot(vec2, e); Vec3 a = vec2 - vec4; double num5 = num3 * num3 * num3 / 12.0; Vec3 vec5 = Vec3.Cross(a, e) / num5; double num6 = t - num2; double num7 = hi - num2; double num8 = (hi - t) / num3; double num9 = (num7 * num7 - num6 * num6) / 2.0; double num10 = (num7 * num7 * num7 - num6 * num6 * num6) / 3.0; Vec3 vec6 = c.Force * num8 + vec5 * num9; force += vec6; moment += Vec3.Cross(vec - origin, vec6) + Vec3.Cross(e, c.Force * (num9 / num3) + vec5 * num10) + vec4 * num8; } } } public sealed class MeshCarver { public readonly List<Vec3> Points; public readonly int OriginalCount; public readonly List<int> FirstParent = new List<int>(); public readonly List<int> SecondParent = new List<int>(); private readonly Func<Vec3, int> _wedgeOf; private readonly int _maxDepth; private readonly Func<int, double> _longest; private readonly double _inside; private readonly Dictionary<long, int> _middles = new Dictionary<long, int>(); private const int DeepestSplit = 8; private readonly int[] _samples = new int[7]; public MeshCarver(IEnumerable<Vec3> points, Func<Vec3, int> wedgeOf, int maxDepth, Func<int, double> longest = null, double inside = 1.0) { Points = new List<Vec3>(points); OriginalCount = Points.Count; _wedgeOf = wedgeOf; _maxDepth = maxDepth; _longest = longest; _inside = inside; } public List<int> Split(IReadOnlyList<int> triangles) { List<int> list = new List<int>(triangles.Count); for (int i = 0; i + 2 < triangles.Count; i += 3) { Split(triangles[i], triangles[i + 1], triangles[i + 2], 0, list); } List<int> list2 = new List<int>(list.Count); for (int j = 0; j + 2 < list.Count; j += 3) { Conform(list[j], list[j + 1], list[j + 2], list2); } return list2; } private void Conform(int a, int b, int c, List<int> output) { if (_middles.TryGetValue(Key(a, b), out var value)) { Conform(a, value, c, output); Conform(value, b, c, output); } else if (_middles.TryGetValue(Key(b, c), out value)) { Conform(a, b, value, output); Conform(a, value, c, output); } else if (_middles.TryGetValue(Key(c, a), out value)) { Conform(a, b, value, output); Conform(value, b, c, output); } else { output.Add(a); output.Add(b); output.Add(c); } } private static long Key(int a, int b) { if (a >= b) { return ((long)b << 32) | (uint)a; } return ((long)a << 32) | (uint)b; } public bool Push(Func<Vec3, int, Vec3> push) { bool result = false; for (int i = 0; i < Points.Count; i++) { int num = _wedgeOf(Points[i]); if (num >= 0) { Points[i] = push(Points[i], num); result = true; } } return result; } public void Clamp(OrientedBox box) { for (int i = 0; i < Points.Count; i++) { Vec3 a = Points[i] - box.Center; double num = Math.Max(0.0 - box.Half.X, Math.Min(box.Half.X, Vec3.Dot(a, box.AxisX))); double num2 = Math.Max(0.0 - box.Half.Y, Math.Min(box.Half.Y, Vec3.Dot(a, box.AxisY))); double num3 = Math.Max(0.0 - box.Half.Z, Math.Min(box.Half.Z, Vec3.Dot(a, box.AxisZ))); Points[i] = box.Center + box.AxisX * num + box.AxisY * num2 + box.AxisZ * num3; } } private void Split(int a, int b, int c, int depth, List<int> output) { if (Divides(Points[a], Points[b], Points[c], depth)) { int num = Middle(a, b); int num2 = Middle(b, c); int num3 = Middle(c, a); Split(a, num, num3, depth + 1, output); Split(num, b, num2, depth + 1, output); Split(num3, num2, c, depth + 1, output); Split(num, num2, num3, depth + 1, output); } else { output.Add(a); output.Add(b); output.Add(c); } } private bool Divides(Vec3 a, Vec3 b, Vec3 c, int depth) { _samples[0] = _wedgeOf(a); _samples[1] = _wedgeOf(b); _samples[2] = _wedgeOf(c); _samples[3] = _wedgeOf((a + b) * 0.5); _samples[4] = _wedgeOf((b + c) * 0.5); _samples[5] = _wedgeOf((c + a) * 0.5); _samples[6] = _wedgeOf((a + b + c) / 3.0); bool flag = false; for (int i = 1; i < _samples.Length; i++) { flag |= _samples[i] != _samples[0]; } if (flag && depth < _maxDepth) { return true; } if (_longest == null || depth >= 8) { return false; } double num = 0.0; int[] samples = _samples; foreach (int num2 in samples) { double num3 = ((num2 >= 0) ? _longest(num2) : 0.0); if (num3 > 0.0 && (num == 0.0 || num3 < num)) { num = num3; } } if (num <= 0.0 || (!flag && _samples[0] < 0)) { return false; } if (!flag) { num *= _inside; } return Math.Max((a - b).Length, Math.Max((b - c).Length, (c - a).Length)) > num; } private int Middle(int a, int b) { long key = Key(a, b); if (_middles.TryGetValue(key, out var value)) { return value; } value = Points.Count; Points.Add((Points[a] + Points[b]) * 0.5); FirstParent.Add(a); SecondParent.Add(b); _middles[key] = value; return value; } } public static class MeshVolume { public static double Of(IReadOnlyList<Vec3> vertices, IReadOnlyList<int> triangles) { double num = 0.0; for (int i = 0; i + 2 < triangles.Count; i += 3) { Vec3 a = vertices[triangles[i]]; Vec3 a2 = vertices[triangles[i + 1]]; Vec3 b = vertices[triangles[i + 2]]; num += Vec3.Dot(a, Vec3.Cross(a2, b)) / 6.0; } if (!(num < 0.0)) { return num; } return 0.0 - num; } } public struct OrientedBox { public Vec3 Center; public Vec3 AxisX; public Vec3 AxisY; public Vec3 AxisZ; public Vec3 Half; public Vec3 Axis(int i) { return i switch { 1 => AxisY, 0 => AxisX, _ => AxisZ, }; } } public static class Overlap { private const double PlaneTolerance = 1E-09; private const double SamePoint = 1E-12; private const double MinVolume = 1E-12; public static bool Of(OrientedBox a, OrientedBox b, out Vec3 centroid, out double volume, List<Vec3> vertices = null) { centroid = Vec3.Zero; volume = 0.0; vertices?.Clear(); Vec3 center = a.Center; List<List<Vec3>> list = Faces(a, center); for (int i = 0; i < 3; i++) { Vec3 vec = b.Axis(i); double num = Vec3.Dot(vec, b.Center - center); list = Clip(list, vec, num + b.Half[i]); if (list.Count == 0) { return false; } list = Clip(list, -vec, b.Half[i] - num); if (list.Count == 0) { return false; } } if (!Measure(list, out var centroid2, out volume)) { return false; } centroid = centroid2 + center; if (vertices != null) { foreach (List<Vec3> item in list) { foreach (Vec3 item2 in item) { vertices.Add(item2 + center); } } } return true; } private static List<List<Vec3>> Faces(OrientedBox box, Vec3 origin) { Vec3 vec = box.Center - origin; Vec3 vec2 = box.AxisX * box.Half.X; Vec3 vec3 = box.AxisY * box.Half.Y; Vec3 vec4 = box.AxisZ * box.Half.Z; Vec3[] array = new Vec3[8]; for (int i = 0; i < 8; i++) { array[i] = vec + vec2 * (((i & 1) != 0) ? 1 : (-1)) + vec3 * (((i & 2) != 0) ? 1 : (-1)) + vec4 * (((i & 4) != 0) ? 1 : (-1)); } int[][] obj = new int[6][] { new int[4] { 0, 2, 6, 4 }, new int[4] { 1, 5, 7, 3 }, new int[4] { 0, 4, 5, 1 }, new int[4] { 2, 3, 7, 6 }, new int[4] { 0, 1, 3, 2 }, new int[4] { 4, 6, 7, 5 } }; List<List<Vec3>> list = new List<List<Vec3>>(6); int[][] array2 = obj; foreach (int[] array3 in array2) { list.Add(new List<Vec3> { array[array3[0]], array[array3[1]], array[array3[2]], array[array3[3]] }); } return list; } private static List<List<Vec3>> Clip(List<List<Vec3>> faces, Vec3 n, double limit) { bool flag = false; bool flag2 = false; foreach (List<Vec3> face in faces) { foreach (Vec3 item in face) { double num = Vec3.Dot(n, item) - limit; flag = flag || num > 1E-09; flag2 = flag2 || num < -1E-09; } } if (!flag) { return faces; } if (!flag2) { return new List<List<Vec3>>(); } List<List<Vec3>> list = new List<List<Vec3>>(faces.Count + 1); List<Vec3> list2 = new List<Vec3>(); foreach (List<Vec3> face2 in faces) { List<Vec3> list3 = new List<Vec3>(face2.Count + 1); for (int i = 0; i < face2.Count; i++) { Vec3 vec = face2[i]; Vec3 vec2 = face2[(i + 1) % face2.Count]; double num2 = Vec3.Dot(n, vec) - limit; double num3 = Vec3.Dot(n, vec2) - limit; bool num4 = num2 <= 1E-09; bool flag3 = num3 <= 1E-09; if (num4) { list3.Add(vec); } if (num4 != flag3) { list3.Add(vec + (vec2 - vec) * (num2 / (num2 - num3))); } } if (list3.Count < 3) { continue; } list.Add(list3); foreach (Vec3 item2 in list3) { if (Math.Abs(Vec3.Dot(n, item2) - limit) <= 1E-09) { AddUnique(list2, item2); } } } if (list2.Count >= 3) { list.Add(Ordered(list2, n)); } return list; } private static void AddUnique(List<Vec3> points, Vec3 p) { foreach (Vec3 point in points) { if ((point - p).LengthSquared < 1E-12) { return; } } points.Add(p); } private static List<Vec3> Ordered(List<Vec3> points, Vec3 n) { Vec3 zero = Vec3.Zero; foreach (Vec3 point in points) { zero += point; } zero /= (double)points.Count; Vec3 b = (points[0] - zero).Normalized(); Vec3 b2 = Vec3.Cross(n, b); double[] array = new double[points.Count]; int[] array2 = new int[points.Count]; for (int i = 0; i < points.Count; i++) { Vec3 a = points[i] - zero; array[i] = PseudoAngle(Vec3.Dot(a, b), Vec3.Dot(a, b2)); array2[i] = i; } Array.Sort(array, array2); List<Vec3> list = new List<Vec3>(points.Count); int[] array3 = array2; foreach (int index in array3) { list.Add(points[index]); } return list; } private static double PseudoAngle(double x, double y) { double num = Math.Abs(x) + Math.Abs(y); if (num <= 0.0) { return 0.0; } double num2 = y / num; if (!(x >= 0.0)) { return 2.0 - num2; } if (!(y >= 0.0)) { return 4.0 + num2; } return num2; } private static bool Measure(List<List<Vec3>> faces, out Vec3 centroid, out double volume) { centroid = Vec3.Zero; volume = 0.0; Vec3 zero = Vec3.Zero; int num = 0; foreach (List<Vec3> face in faces) { foreach (Vec3 item in face) { zero += item; num++; } } if (num == 0) { return false; } zero /= (double)num; Vec3 zero2 = Vec3.Zero; foreach (List<Vec3> face2 in faces) { for (int i = 1; i + 1 < face2.Count; i++) { Vec3 vec = face2[0] - zero; Vec3 vec2 = face2[i] - zero; Vec3 vec3 = face2[i + 1] - zero; double num2 = Math.Abs(Vec3.Dot(vec, Vec3.Cross(vec2, vec3))) / 6.0; volume += num2; zero2 += (vec + vec2 + vec3) * (num2 / 4.0); } } if (volume < 1E-12) { return false; } centroid = zero + zero2 / volume; return true; } } public static class Panel { public const double Thickest = 0.35; public const double Narrowest = 0.9; public static bool Is(Vec3 size) { double num = Math.Abs(size.X); double num2 = Math.Abs(size.Y); double num3 = Math.Abs(size.Z); double num4 = Math.Min(num, Math.Min(num2, num3)); double num5 = Math.Max(num, Math.Max(num2, num3)); if (num4 <= 0.35) { return num + num2 + num3 - num4 - num5 >= 0.9; } return false; } } public enum SolverKind : byte { None, Frame, LoadPath } public sealed class StructureAnalysis { public const double DefaultTolerance = 1E-06; private const int BodiesPerStep = 8; private readonly StructureModel _model; private readonly Masonry _masonry; private FrameAnalysis _frame; private List<ContactLoad>[] _loads; private BodyResult[] _pending; private int _evaluated; private int _earlierIterations; public SolverKind Solver { get; } public BodyResult[] Results { get; private set; } public bool Finished => Results != null; public int Iterations => _earlierIterations + (_frame?.Iterations ?? 0); public bool Converged => _frame?.Converged ?? true; public int MasonryRounds => _masonry?.Rounds ?? 0; public bool MasonrySettled => _masonry?.Settled ?? true; public StructureAnalysis(StructureModel model, int maxFrameBodies) { _model = model; bool flag = false; foreach (Link link in model.Links) { flag |= link.IsGround; } if (!flag || model.Bodies.Count == 0) { Solver = SolverKind.None; Results = new BodyResult[model.Bodies.Count]; for (int i = 0; i < Results.Length; i++) { Results[i] = BodyResult.Unsupported; } } else if (model.Bodies.Count <= maxFrameBodies) { Solver = SolverKind.Frame; _frame = new FrameAnalysis(model); Masonry masonry = new Masonry(model); if (masonry.Active) { _masonry = masonry; } } else { Solver = SolverKind.LoadPath; } } public void RunToCompletion(Func<bool> cancelled) { while (!Finished && !cancelled()) { Step(16); } } public bool Step(int units) { if (Finished) { return true; } units = Math.Max(1, units); if (Solver == SolverKind.LoadPath) { Results = LoadPathAnalysis.Run(_model); return true; } if (_loads == null) { if (!_frame.Iterate(units)) { return false; } if (_masonry != null && _masonry.Next(_frame)) { _earlierIterations += _frame.Iterations; _frame = new FrameAnalysis(_model, 1E-06, 0, _masonry.Releases, _frame.Solution, _masonry.Residual, _masonry.Gone); return false; } _loads = _frame.ContactLoads(); _pending = new BodyResult[_model.Bodies.Count]; return false; } int num = Math.Min(_pending.Length, _evaluated + units * 8); while (_evaluated < num) { _pending[_evaluated] = Mechanics.Evaluate(_model.Bodies[_evaluated], _loads[_evaluated], _model.Gravity); _evaluated++; } if (_evaluated == _pending.Length) { _masonry?.Finish(_frame, _pending); Results = _pending; } return Finished; } } public sealed class MaterialProps { public string Name = "default"; public double Density = 500.0; public double Elasticity = 10000000000.0; public double ShearModulus = 600000000.0; public double CompressiveStrength = 4000000.0; public double TensileStrength = 4000000.0; public double ShearStrength = 1000000.0; public double BucklingSlenderness = 60.0; public bool Masonry; public double Friction = 0.6; } public sealed class Body { public Vec3 Center; public Vec3 AxisX = Vec3.UnitX; public Vec3 AxisY = Vec3.UnitY; public Vec3 AxisZ = Vec3.UnitZ; public Vec3 Size; public double Mass; public MaterialProps Material; public double StrengthFactor = 1.0; public bool Fitted; public Vec3 Axis(int i) { return i switch { 1 => AxisY, 0 => AxisX, _ => AxisZ, }; } } public readonly struct Link { public const int Ground = -1; public readonly int A; public readonly int B; public readonly Vec3 Point; public readonly double[] SpanA; public readonly double[] SpanB; public bool IsGround => B == -1; public Link(int a, int b, Vec3 point, double[] spanA = null, double[] spanB = null) { if (a < 0) { throw new ArgumentOutOfRangeException("a", "The first body of a link cannot be the ground"); } A = a; B = b; Point = point; SpanA = spanA; SpanB = spanB; } } public sealed class StructureModel { public readonly List<Body> Bodies = new List<Body>(); public readonly List<Link> Links = new List<Link>(); public Vec3 Gravity = new Vec3(0.0, -9.81, 0.0); public int AddBody(Body body) { Bodies.Add(body); return Bodies.Count - 1; } public void Connect(int a, int b, Vec3 point, double[] spanA = null, double[] spanB = null) { Links.Add(new Link(a, b, point, spanA, spanB)); } public void Ground(int a, Vec3 point, double[] span = null) { Links.Add(new Link(a, -1, point, span)); } } public enum StressMode : byte { None, Compression, Tension, Bending, Shear, Unsupported, Torsion, Tipping, Sliding, Unstable } public struct BodyResult { public double Utilization; public StressMode Mode; public double AxialForce; public double BendingMoment; public double Torque; public double HeldWeight; public double MemberForce; public static BodyResult Unsupported => new BodyResult { Utilization = double.PositiveInfinity, Mode = StressMode.Unsupported }; } public readonly struct TowerRing { public const double Overlap = 0.01; public readonly double OuterRadius; public readonly double Thickness; public readonly double Angle; public readonly double Height; public double InnerRadius => OuterRadius - Thickness; public double MidRadius => OuterRadius - Thickness / 2.0; public double MeanWidth => MidRadius * Angle * Math.PI / 180.0; public double Volume => MeanWidth * Thickness * Height; public double BoxTurn => Angle / 2.0; public double Sag => OuterRadius * (1.0 - Math.Cos(Angle / 2.0 * Math.PI / 180.0)); public double BoxDepth => Thickness - Sag; public double BoxShift => (0.0 - Sag) / 2.0; public Vec3 Centre => Direction(Angle / 2.0) * (0.0 - MidRadius); public TowerRing(double outerRadius, double thickness, double angle, double height = 1.0) { OuterRadius = outerRadius; Thickness = thickness; Angle = angle; Height = height; } public static Vec3 Direction(double degrees) { double num = degrees * Math.PI / 180.0; return new Vec3(Math.Sin(num), 0.0, Math.Cos(num)); } public static Vec3 Turn(Vec3 v, double degrees) { double num = degrees * Math.PI / 180.0; double num2 = Math.Cos(num); double num3 = Math.Sin(num); return new Vec3(v.X * num2 + v.Z * num3, v.Y, (0.0 - v.X) * num3 + v.Z * num2); } public Vec3 Point(double degrees, double radius, double y) { return Centre + Direction(degrees) * radius + new Vec3(0.0, y, 0.0); } public double AngleOf(Vec3 p) { Vec3 vec = p - Centre; return Math.Atan2(vec.X, vec.Z) * 180.0 / Math.PI; } public int SideOf(Vec3 p) { if (!(AngleOf(p) >= Angle / 2.0)) { return -1; } return 1; } public double Next(TowerRing ghost, int side, bool above, bool flush) { if (!above) { if (side < 0) { return 0.0 - ghost.Angle; } return Angle; } if (flush) { if (side < 0) { return 0.0; } return Angle - ghost.Angle; } if (side < 0) { return (0.0 - ghost.Angle) / 2.0; } return Angle - ghost.Angle / 2.0; } public Vec3 Origin(TowerRing ghost, double start, bool above) { double y = (above ? ((Height + ghost.Height) / 2.0) : 0.0); return Centre - Turn(ghost.Centre, start) + new Vec3(0.0, y, 0.0); } private static Vec3 Tangent(double degrees) { double num = degrees * Math.PI / 180.0; return new Vec3(Math.Cos(num), 0.0, 0.0 - Math.Sin(num)); } public double RadiusOf(Vec3 p) { Vec3 vec = p - Centre; return Math.Sqrt(vec.X * vec.X + vec.Z * vec.Z); } public double FromStart(Vec3 p) { return Vec3.Dot(p - Centre, Tangent(0.0)); } public double FromEnd(Vec3 p) { return 0.0 - Vec3.Dot(p - Centre, Tangent(Angle)); } public bool InSector(Vec3 p) { if (FromStart(p) >= 0.0) { return FromEnd(p) >= 0.0; } return false; } public bool Beyond(Vec3 p) { return RadiusOf(p) > MidRadius; } public bool Contains(Vec3 p, double margin, bool openSides = false, bool openDepth = false, double outerGrow = 0.0, double innerGrow = 0.0, double depthGrow = 0.0) { if (Math.Abs(p.Y) > Height / 2.0 + (openDepth ? (margin + depthGrow) : (0.0 - margin))) { return false; } double num = RadiusOf(p); if (num < InnerRadius - innerGrow + margin || num > OuterRadius + outerGrow - margin) { return false; } double num2 = (openSides ? (0.0 - margin) : margin); if (FromStart(p) > num2) { return FromEnd(p) > num2; } return false; } public bool Claims(Vec3 p, bool outward, double margin, bool openSides = false, bool openDepth = false, double outerGrow = 0.0, double innerGrow = 0.0, double depthGrow = 0.0) { if (Math.Abs(p.Y) > Height / 2.0 + (openDepth ? (margin + depthGrow) : (0.0 - margin))) { return false; } double num = RadiusOf(p); if (outward ? (num > OuterRadius + outerGrow - margin) : (num < InnerRadius - innerGrow + margin)) { return false; } double num2 = (openSides ? (0.0 - margin) : margin); if (FromStart(p) > num2) { return FromEnd(p) > num2; } return false; } public Vec3 ToFace(Vec3 p, bool outward, double offset) { double num = RadiusOf(p); if (num < 1E-09) { return p; } double num2 = (outward ? (OuterRadius + offset) : (InnerRadius - offset)) / num; Vec3 vec = p - Centre; return new Vec3(Centre.X + vec.X * num2, p.Y, Centre.Z + vec.Z * num2); } public Vec3 ToFaceWithin(Vec3 p, OrientedBox block, bool outward, double offset, double slack) { Vec3 vec = ToFace(p, outward, offset); if (Inside(vec, block, slack)) { return vec; } double num = (outward ? (OuterRadius + offset) : (InnerRadius - offset)); double num2 = p.X - Centre.X; double num3 = p.Z - Centre.Z; Vec3 result = default(Vec3); double num4 = double.MaxValue; for (int i = 0; i < 2; i++) { Vec3 b = ((i == 0) ? block.AxisX : block.AxisZ); double num5 = ((i == 0) ? block.Half.X : block.Half.Z) + slack; double num6 = Math.Sqrt(b.X * b.X + b.Z * b.Z); if (num6 < 1E-09) { continue; } double num7 = b.X / num6; double num8 = b.Z / num6; double num9 = num2 * num7 + num3 * num8; double num10 = num9 * num9 - (num2 * num2 + num3 * num3) + num * num; if (num10 < 0.0) { continue; } double[] array = new double[2] { 0.0 - num9 - Math.Sqrt(num10), 0.0 - num9 + Math.Sqrt(num10) }; foreach (double num11 in array) { if (!(Math.Abs(num11) >= num4)) { Vec3 vec2 = new Vec3(p.X + num7 * num11, p.Y, p.Z + num8 * num11); if (!(Math.Abs(Vec3.Dot(vec2 - block.Center, b) / b.Length) > num5)) { num4 = Math.Abs(num11); result = vec2; } } } } if (!(num4 < double.MaxValue)) { return vec; } return result; } private static bool Inside(Vec3 p, OrientedBox block, double slack) { Vec3 a = p - block.Center; if (Math.Abs(Vec3.Dot(a, block.AxisX)) <= block.Half.X + slack) { return Math.Abs(Vec3.Dot(a, block.AxisZ)) <= block.Half.Z + slack; } return false; } public bool Opens(Vec3 centre, IEnumerable<Vec3> corners) { if (InSector(ce