From 2e7fa097345431fde548c5a5b1477b38c573cb32 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 4 May 2022 20:18:20 -0400 Subject: [PATCH 01/15] Allow separately setting dialogue interact radius and remote trigger radius --- NewHorizons/AssetBundle/WarpDriveConfig.json | 3 ++- NewHorizons/Builder/Props/DialogueBuilder.cs | 17 ++++++++++++----- NewHorizons/External/PropModule.cs | 1 + NewHorizons/schema.json | 6 +++++- 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/NewHorizons/AssetBundle/WarpDriveConfig.json b/NewHorizons/AssetBundle/WarpDriveConfig.json index cc45a642..42b79828 100644 --- a/NewHorizons/AssetBundle/WarpDriveConfig.json +++ b/NewHorizons/AssetBundle/WarpDriveConfig.json @@ -6,7 +6,8 @@ "dialogue": [ { "position":{"x": -0.3071011, "y": 2.741472, "z": -4.005298}, - "radius":1, + "radius": 0, + "remoteTriggerRadius": 1, "xmlFile":"AssetBundle/WarpDriveDialogue.xml", "remoteTriggerPosition": {"x": -0.05656214, "y": 0.5362684, "z": 0.5467669}, "blockAfterPersistentCondition" : "KnowsAboutWarpDrive" diff --git a/NewHorizons/Builder/Props/DialogueBuilder.cs b/NewHorizons/Builder/Props/DialogueBuilder.cs index ce80363f..e3f59d95 100644 --- a/NewHorizons/Builder/Props/DialogueBuilder.cs +++ b/NewHorizons/Builder/Props/DialogueBuilder.cs @@ -21,7 +21,7 @@ namespace NewHorizons.Builder.Props if (info.blockAfterPersistentCondition != null && PlayerData._currentGameSave.GetPersistentCondition(info.blockAfterPersistentCondition)) return; var dialogue = MakeConversationZone(go, sector, info, mod.ModHelper); - if (info.remoteTriggerPosition != null) MakeRemoteDialogueTrigger(go, sector, info, dialogue); + if (info.remoteTriggerPosition != null || info.remoteTriggerRadius != 0) MakeRemoteDialogueTrigger(go, sector, info, dialogue); // Make the character look at the player // Useful for dialogue replacement @@ -51,10 +51,10 @@ namespace NewHorizons.Builder.Props remoteDialogueTrigger._activatedDialogues = new bool[1]; remoteDialogueTrigger._deactivateTriggerPostConversation = true; - sphereCollider.radius = info.radius; + sphereCollider.radius = info.remoteTriggerRadius == 0 ? info.radius : info.remoteTriggerRadius; conversationTrigger.transform.parent = sector?.transform ?? go.transform; - conversationTrigger.transform.localPosition = info.remoteTriggerPosition; + conversationTrigger.transform.localPosition = info.remoteTriggerPosition ?? info.position; conversationTrigger.SetActive(true); } @@ -69,8 +69,15 @@ namespace NewHorizons.Builder.Props sphere.radius = info.radius; sphere.isTrigger = true; - conversationZone.AddComponent(); - conversationZone.AddComponent(); + var owCollider = conversationZone.AddComponent(); + var interact = conversationZone.AddComponent(); + + if(info.radius <= 0) + { + sphere.enabled = false; + owCollider.enabled = false; + interact.enabled = false; + } var dialogueTree = conversationZone.AddComponent(); diff --git a/NewHorizons/External/PropModule.cs b/NewHorizons/External/PropModule.cs index 65019d0d..6d2c631e 100644 --- a/NewHorizons/External/PropModule.cs +++ b/NewHorizons/External/PropModule.cs @@ -79,6 +79,7 @@ namespace NewHorizons.External { public MVector3 position; public float radius = 1f; + public float remoteTriggerRadius; public string xmlFile; public MVector3 remoteTriggerPosition; public string blockAfterPersistentCondition; diff --git a/NewHorizons/schema.json b/NewHorizons/schema.json index 9cc71147..ce28457d 100644 --- a/NewHorizons/schema.json +++ b/NewHorizons/schema.json @@ -646,7 +646,7 @@ "radius": { "type": "number", "default": 0, - "description": "Radius of the spherical collision volume where you get the \"talk to\" prompt when looking at. If you use a remoteTriggerPosition, this will instead be the size of the volume that will trigger the dialogue when you enter it." + "description": "Radius of the spherical collision volume where you get the \"talk to\" prompt when looking at. If you use a remoteTriggerPosition, you can set this to 0 to make the dialogue only trigger remotely." }, "xmlFile": { "type": "string", @@ -656,6 +656,10 @@ "$ref": "#/$defs/vector3", "description": "Allows you to trigger dialogue from a distance when you walk into an area." }, + "remoteTriggerRadius": { + "type": "number", + "description": "The radius of the remote trigger volume." + }, "blockAfterPersistentCondition": { "type": "string", "description": "Prevents the dialogue from being created after a specific persistent condition is set. Useful for remote dialogue triggers that you want to have happen only once." From bdb6fb40ab6065400b75c11c49aa42e9d88bf6ab Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 4 May 2022 23:01:18 -0400 Subject: [PATCH 02/15] Add option to enable/disable showing body on title screen --- NewHorizons/External/Configs/IPlanetConfig.cs | 1 + NewHorizons/External/Configs/PlanetConfig.cs | 1 + NewHorizons/Handlers/TitleSceneHandler.cs | 2 +- NewHorizons/schema.json | 5 +++++ 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/NewHorizons/External/Configs/IPlanetConfig.cs b/NewHorizons/External/Configs/IPlanetConfig.cs index 4b1a157a..3630396d 100644 --- a/NewHorizons/External/Configs/IPlanetConfig.cs +++ b/NewHorizons/External/Configs/IPlanetConfig.cs @@ -10,6 +10,7 @@ namespace NewHorizons.External.Configs bool Destroy { get; } string[] ChildrenToDestroy { get; } int BuildPriority { get; } + bool CanShowOnTitle { get; } BaseModule Base { get; } AtmosphereModule Atmosphere { get; } OrbitModule Orbit { get; } diff --git a/NewHorizons/External/Configs/PlanetConfig.cs b/NewHorizons/External/Configs/PlanetConfig.cs index f4708f35..8aa9b6b4 100644 --- a/NewHorizons/External/Configs/PlanetConfig.cs +++ b/NewHorizons/External/Configs/PlanetConfig.cs @@ -13,6 +13,7 @@ namespace NewHorizons.External.Configs public bool Destroy { get; set; } public string[] ChildrenToDestroy { get; set; } public int BuildPriority { get; set; } = -1; + public bool CanShowOnTitle { get; set; } = true; public BaseModule Base { get; set; } public AtmosphereModule Atmosphere { get; set; } public OrbitModule Orbit { get; set; } diff --git a/NewHorizons/Handlers/TitleSceneHandler.cs b/NewHorizons/Handlers/TitleSceneHandler.cs index f5428566..89a0ad2c 100644 --- a/NewHorizons/Handlers/TitleSceneHandler.cs +++ b/NewHorizons/Handlers/TitleSceneHandler.cs @@ -18,7 +18,7 @@ namespace NewHorizons.Handlers { //Try loading one planet why not //var eligible = BodyDict.Values.ToList().SelectMany(x => x).ToList().Where(b => (b.Config.HeightMap != null || b.Config.Atmosphere?.Cloud != null) && b.Config.Star == null).ToArray(); - var eligible = bodies.Where(b => (b.Config.HeightMap != null || b.Config.Atmosphere?.Cloud != null) && b.Config.Star == null).ToArray(); + var eligible = bodies.Where(b => (b.Config.HeightMap != null || b.Config.Atmosphere?.Cloud != null) && b.Config.Star == null && b.Config.CanShowOnTitle).ToArray(); var eligibleCount = eligible.Count(); if (eligibleCount == 0) return; diff --git a/NewHorizons/schema.json b/NewHorizons/schema.json index ce28457d..99d8aebc 100644 --- a/NewHorizons/schema.json +++ b/NewHorizons/schema.json @@ -145,6 +145,11 @@ "description": "A list of paths to child GameObjects to destroy on this planet", "default": [] }, + "canShowOnTitle": { + "type": "boolean", + "description": "Should this planet ever be shown on the title screen", + "default": "true" + } "Base": { "type": "object", "additionalProperties": false, From 68316f7cfe7f5573ca0f843b164c749cd6dac29a Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 4 May 2022 23:17:18 -0400 Subject: [PATCH 03/15] Add setting to enable/disable custom title screen --- NewHorizons/Main.cs | 23 ++++++++++++++++++++--- NewHorizons/default-config.json | 3 ++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index f5264ba8..c9342c6e 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -36,7 +36,10 @@ namespace NewHorizons public static AssetBundle ShaderBundle; public static Main Instance { get; private set; } + // Settings public static bool Debug; + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; public static Dictionary SystemDict = new Dictionary(); public static Dictionary> BodyDict = new Dictionary>(); @@ -63,7 +66,7 @@ namespace NewHorizons public StarSystemEvent OnChangeStarSystem; public StarSystemEvent OnStarSystemLoaded; - + // For warping to the eye system private GameObject _ship; public override object GetApi() @@ -73,9 +76,23 @@ namespace NewHorizons public override void Configure(IModConfig config) { + Logger.Log("Settings changed"); + Debug = config.GetSettingsValue("Debug"); DebugReload.UpdateReloadButton(); - Logger.UpdateLogLevel(Debug? Logger.LogType.Log : Logger.LogType.Error); + Logger.UpdateLogLevel(Debug ? Logger.LogType.Log : Logger.LogType.Error); + + var wasUsingCustomTitleScreen = _useCustomTitleScreen; + _useCustomTitleScreen = config.GetSettingsValue("Custom title screen"); + // Reload the title screen if this was updated on it + // Don't reload if we haven't configured yet (called on game start) + if (wasUsingCustomTitleScreen != _useCustomTitleScreen && SceneManager.GetActiveScene().name == "TitleScreen" && _wasConfigured) + { + Logger.Log("Reloading"); + SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single); + } + + _wasConfigured = true; } public void Start() @@ -144,7 +161,7 @@ namespace NewHorizons _isChangingStarSystem = false; - if (scene.name == "TitleScreen") + if (scene.name == "TitleScreen" && _useCustomTitleScreen) { TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); } diff --git a/NewHorizons/default-config.json b/NewHorizons/default-config.json index 28384587..75790651 100644 --- a/NewHorizons/default-config.json +++ b/NewHorizons/default-config.json @@ -1,6 +1,7 @@ { "enabled": true, "settings": { - "Debug": false + "Debug": false, + "Custom title screen": true } } \ No newline at end of file From 2460bbafb76eb88b73ccf2140c4c15ad106899aa Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 03:05:35 -0400 Subject: [PATCH 04/15] Add FluidType to rings --- NewHorizons/Builder/Body/RingBuilder.cs | 56 ++-- NewHorizons/Components/RingShape.cs | 262 ++++++++++++++++++ .../External/VariableSize/RingModule.cs | 1 + NewHorizons/schema.json | 12 + 4 files changed, 312 insertions(+), 19 deletions(-) create mode 100644 NewHorizons/Components/RingShape.cs diff --git a/NewHorizons/Builder/Body/RingBuilder.cs b/NewHorizons/Builder/Body/RingBuilder.cs index 805bdf59..f9a7d105 100644 --- a/NewHorizons/Builder/Body/RingBuilder.cs +++ b/NewHorizons/Builder/Body/RingBuilder.cs @@ -77,29 +77,47 @@ namespace NewHorizons.Builder.Body rot._localAxis = Vector3.down; } - // Collider can't be concave so nvm - /* - var collider = new GameObject("Collider"); - collider.SetActive(false); - collider.transform.parent = ringGO.transform; - collider.transform.localPosition = Vector3.zero; - collider.transform.localScale = Vector3.one; - collider.layer = 17; + // Funny collider thing + var ringVolume = new GameObject("RingVolume"); + ringVolume.SetActive(false); + ringVolume.transform.parent = ringGO.transform; + ringVolume.transform.localPosition = Vector3.zero; + ringVolume.transform.localScale = Vector3.one; + ringVolume.transform.localRotation = Quaternion.identity; + ringVolume.layer = LayerMask.NameToLayer("BasicEffectVolume"); - var mf = collider.AddComponent(); - mf.mesh = ringMesh; + var ringShape = ringVolume.AddComponent(); + ringShape.innerRadius = ring.InnerRadius; + ringShape.outerRadius = ring.OuterRadius; + ringShape.height = 2f; + ringShape.center = Vector3.zero; + ringShape.SetCollisionMode(Shape.CollisionMode.Volume); + ringShape.SetLayer(Shape.Layer.Default); + ringShape.layerMask = -1; + ringShape.pointChecksOnly = true; + + var trigger = ringVolume.AddComponent(); + trigger._shape = ringShape; - var mc = collider.AddComponent(); - mc.isTrigger = true; + var sfv = ringVolume.AddComponent(); + var fluidType = FluidVolume.Type.NONE; - var owCollider = collider.AddComponent(); - var trigger = collider.AddComponent(); - var sfv = collider.AddComponent(); - sfv._fluidType = FluidVolume.Type.SAND; - sfv._density = 2f; + if(!string.IsNullOrEmpty(ring.FluidType)) + { + try + { + fluidType = (FluidVolume.Type)Enum.Parse(typeof(FluidVolume.Type), ring.FluidType.ToUpper()); + } + catch (Exception ex) + { + Logger.LogError($"Couldn't parse fluid volume type [{ring.FluidType}]: {ex.Message}, {ex.StackTrace}"); + } + } - collider.SetActive(true); - */ + sfv._fluidType = fluidType; + sfv._density = 1f; + + ringVolume.SetActive(true); if (ring.Curve != null) { diff --git a/NewHorizons/Components/RingShape.cs b/NewHorizons/Components/RingShape.cs new file mode 100644 index 00000000..cb35b9e2 --- /dev/null +++ b/NewHorizons/Components/RingShape.cs @@ -0,0 +1,262 @@ +using System.Collections.Generic; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons.Components +{ + public class RingShape : Shape + { + private Vector3 _center; + private float _innerRadius; + private float _outerRadius; + private float _height; + + private CylinderShape _innerCylinderShape; + private CylinderShape _outerCylinderShape; + + public Vector3 center + { + get { return _center; } + set + { + _center = value; + RecalculateLocalBounds(); + } + } + + public float innerRadius + { + get { return _innerRadius; } + set + { + _innerRadius = Mathf.Max(value, 0f); + RecalculateLocalBounds(); + + if (_innerCylinderShape) _innerCylinderShape.radius = _innerRadius; + } + } + + public float outerRadius + { + get { return _outerRadius; } + set + { + _outerRadius = Mathf.Max(value, 0f); + RecalculateLocalBounds(); + + if (_outerCylinderShape) _outerCylinderShape.radius = _outerRadius; + } + } + + public float height + { + get { return _height; } + set + { + _height = Mathf.Max(value, 0f); + RecalculateLocalBounds(); + + if (_innerCylinderShape) _innerCylinderShape.height = height + 30; + if (_outerCylinderShape) _outerCylinderShape.height = height; + } + } + + public override int layerMask + { + get { return base.layerMask; } + set + { + base.layerMask = value; + if (_innerCylinderShape) _innerCylinderShape.layerMask = value; + if (_outerCylinderShape) _outerCylinderShape.layerMask = value; + } + } + + public override bool pointChecksOnly + { + get { return base.pointChecksOnly; } + set + { + base.pointChecksOnly = value; + if (_innerCylinderShape) _innerCylinderShape.pointChecksOnly = value; + if (_outerCylinderShape) _outerCylinderShape.pointChecksOnly = value; + } + } + + public override void Awake() + { + base.Awake(); + + var innerCylinderGO = new GameObject("InnerCylinder"); + innerCylinderGO.layer = gameObject.layer; + innerCylinderGO.transform.parent = transform; + innerCylinderGO.transform.localPosition = Vector3.zero; + innerCylinderGO.transform.localRotation = Quaternion.identity; + _innerCylinderShape = innerCylinderGO.AddComponent(); + innerCylinderGO.AddComponent(); + _innerCylinderShape.OnCollisionEnter += OnInnerCollisionEnter; + _innerCylinderShape.OnCollisionExit += OnInnerCollisionExit; + + _innerCylinderShape.center = center; + _innerCylinderShape.height = height + 30; + _innerCylinderShape.radius = innerRadius; + _innerCylinderShape.layerMask = layerMask; + _innerCylinderShape.pointChecksOnly = pointChecksOnly; + + var outerCylinderGO = new GameObject("OuterCylinder"); + outerCylinderGO.layer = gameObject.layer; + outerCylinderGO.transform.parent = transform; + outerCylinderGO.transform.localPosition = Vector3.zero; + outerCylinderGO.transform.localRotation = Quaternion.identity; + _outerCylinderShape = outerCylinderGO.AddComponent(); + outerCylinderGO.AddComponent(); + _outerCylinderShape.OnCollisionEnter += OnOuterCollisionEnter; + _outerCylinderShape.OnCollisionExit += OnOuterCollisionExit; + + _outerCylinderShape.center = center; + _outerCylinderShape.height = height; + _outerCylinderShape.radius = outerRadius; + _outerCylinderShape.layerMask = layerMask; + _outerCylinderShape.pointChecksOnly = pointChecksOnly; + } + + public void OnDestroy() + { + if (_innerCylinderShape) + { + _innerCylinderShape.OnCollisionEnter -= OnInnerCollisionEnter; + _innerCylinderShape.OnCollisionExit -= OnInnerCollisionExit; + } + + if (_outerCylinderShape) + { + _outerCylinderShape.OnCollisionEnter -= OnOuterCollisionEnter; + _outerCylinderShape.OnCollisionExit -= OnOuterCollisionExit; + } + } + + public void Start() + { + RecalculateLocalBounds(); + } + + public override void OnEnable() + { + base.OnEnable(); + _innerCylinderShape?.OnEnable(); + _outerCylinderShape?.OnEnable(); + } + + public override void OnDisable() + { + base.OnDisable(); + _innerCylinderShape?.OnDisable(); + _outerCylinderShape?.OnDisable(); + } + + public override void SetCollisionMode(CollisionMode newCollisionMode) + { + base.SetCollisionMode(newCollisionMode); + _innerCylinderShape?.SetCollisionMode(newCollisionMode); + _outerCylinderShape?.SetCollisionMode(newCollisionMode); + } + + public override void SetLayer(Layer newLayer) + { + base.SetLayer(newLayer); + _innerCylinderShape?.SetLayer(newLayer); + _outerCylinderShape?.SetLayer(newLayer); + } + + public override void SetActivation(bool newActive) + { + base.SetActivation(newActive); + _innerCylinderShape?.SetActivation(newActive); + _outerCylinderShape?.SetActivation(newActive); + } + + public override Vector3 GetWorldSpaceCenter() + { + return transform.TransformPoint(_center); + } + + public override void RecalculateLocalBounds() + { + localBounds.Set(_center, outerRadius); + } + + public override bool PointInside(Vector3 point) + { + return (!_innerCylinderShape.PointInside(point) && _outerCylinderShape.PointInside(point)); + } + + private List _shapesInInner = new List(); + private List _shapesInOuter = new List(); + private List _shapesInside = new List(); + + private void UpdateCollisionStatus(Shape shape) + { + var inside = _shapesInside.Contains(shape); + var insideInner = _shapesInInner.Contains(shape); + var insideOuter = _shapesInOuter.Contains(shape); + + if (inside) + { + // If we've moved into the inner cylinder then we're not in the ring + // If we've excited the outer radius we're not in the ring either + if (insideInner || !insideOuter) + { + //Logger.Log($"Shape [{shape}] exited ring"); + FireCollisionExitEvent(shape); + _shapesInside.Remove(shape); + } + } + else + { + // If we've moved into the outer cylinder but not the inner one, we're now in the ring + if (insideOuter && !insideInner) + { + //Logger.Log($"Shape [{shape}] entered ring"); + FireCollisionEnterEvent(shape); + _shapesInside.Add(shape); + } + } + } + + public void OnInnerCollisionEnter(Shape shape) + { + //Logger.Log($"Shape [{shape}] entered inner radius"); + + _shapesInInner.Add(shape); + + UpdateCollisionStatus(shape); + } + + public void OnInnerCollisionExit(Shape shape) + { + //Logger.Log($"Shape [{shape}] exited inner radius"); + + _shapesInInner.Remove(shape); + + UpdateCollisionStatus(shape); + } + + public void OnOuterCollisionEnter(Shape shape) + { + //Logger.Log($"Shape [{shape}] entered outer radius"); + + _shapesInOuter.Add(shape); + + UpdateCollisionStatus(shape); + } + + public void OnOuterCollisionExit(Shape shape) + { + //Logger.Log($"Shape [{shape}] exited outer radius"); + + _shapesInOuter.Remove(shape); + + UpdateCollisionStatus(shape); + } + } +} diff --git a/NewHorizons/External/VariableSize/RingModule.cs b/NewHorizons/External/VariableSize/RingModule.cs index 60a6cd2d..86cda68c 100644 --- a/NewHorizons/External/VariableSize/RingModule.cs +++ b/NewHorizons/External/VariableSize/RingModule.cs @@ -15,5 +15,6 @@ namespace NewHorizons.External.VariableSize public string Texture { get; set; } public bool Unlit { get; set; } = false; public float RotationSpeed { get; set; } = 0f; + public string FluidType { get; set; } } } diff --git a/NewHorizons/schema.json b/NewHorizons/schema.json index 99d8aebc..eaf6d622 100644 --- a/NewHorizons/schema.json +++ b/NewHorizons/schema.json @@ -421,6 +421,18 @@ "default": 0, "description": "Allows the rings to rotate." }, + "fluidType": { + "type": "string", + "default": "NONE", + "description": "Fluid type for sounds/effects when colliding with this ring.", + "enum": [ + "NONE", + "WATER", + "CLOUD", + "SAND", + "PLASMA" + ] + }, "curve": { "$ref": "#/$defs/curve", "description": "Allows the rings to grow/shrink with time." From 176d9e3011c4a2f1144f81133c84e86a7e593156 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 03:15:53 -0400 Subject: [PATCH 05/15] Added fluid type to clouds to customize splashes --- NewHorizons/Builder/Atmosphere/CloudsBuilder.cs | 16 +++++++++++++++- NewHorizons/External/AtmosphereModule.cs | 1 + NewHorizons/schema.json | 12 ++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/NewHorizons/Builder/Atmosphere/CloudsBuilder.cs b/NewHorizons/Builder/Atmosphere/CloudsBuilder.cs index 895ccd31..48ab7d77 100644 --- a/NewHorizons/Builder/Atmosphere/CloudsBuilder.cs +++ b/NewHorizons/Builder/Atmosphere/CloudsBuilder.cs @@ -138,7 +138,21 @@ namespace NewHorizons.Builder.Atmosphere fluidCLFV._layer = 5; fluidCLFV._priority = 1; fluidCLFV._density = 1.2f; - fluidCLFV._fluidType = FluidVolume.Type.CLOUD; + + var fluidType = FluidVolume.Type.CLOUD; + if (!string.IsNullOrEmpty(atmo.CloudFluidType)) + { + try + { + fluidType = (FluidVolume.Type)Enum.Parse(typeof(FluidVolume.Type), atmo.CloudFluidType.ToUpper()); + } + catch (Exception ex) + { + Logger.LogError($"Couldn't parse fluid volume type [{atmo.CloudFluidType}]: {ex.Message}, {ex.StackTrace}"); + } + } + + fluidCLFV._fluidType = fluidType; fluidCLFV._allowShipAutoroll = true; fluidCLFV._disableOnStart = false; diff --git a/NewHorizons/External/AtmosphereModule.cs b/NewHorizons/External/AtmosphereModule.cs index bc766718..88c54229 100644 --- a/NewHorizons/External/AtmosphereModule.cs +++ b/NewHorizons/External/AtmosphereModule.cs @@ -14,6 +14,7 @@ namespace NewHorizons.External public string Cloud { get; set; } public string CloudCap { get; set; } public string CloudRamp { get; set; } + public string CloudFluidType { get; set; } public bool UseBasicCloudShader { get; set; } public bool ShadowsOnClouds { get; set; } = true; public MColor FogTint { get; set; } diff --git a/NewHorizons/schema.json b/NewHorizons/schema.json index eaf6d622..2641380f 100644 --- a/NewHorizons/schema.json +++ b/NewHorizons/schema.json @@ -254,6 +254,18 @@ "type": "string", "description": "Relative filepath to the cloud ramp texture, if the planet has clouds. If you don't put anything here it will be auto-generated." }, + "cloudFluidType": { + "type": "string", + "default": "CLOUD", + "description": "Fluid type for sounds/effects when colliding with this cloud.", + "enum": [ + "NONE", + "WATER", + "CLOUD", + "SAND", + "PLASMA" + ] + }, "useBasicCloudShader": { "type": "boolean", "default": false, From 74a683def02065a608f0daa28cea547e808ad727 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 18:43:04 -0400 Subject: [PATCH 06/15] Rafts + patching with HarmonyLib --- NewHorizons/Builder/Body/WaterBuilder.cs | 2 +- .../Builder/Props/PlanetaryRaftController.cs | 124 ------------------ NewHorizons/Builder/Props/PropBuildManager.cs | 7 +- NewHorizons/Builder/Props/RaftBuilder.cs | 116 +++++++--------- NewHorizons/Components/NHFluidVolume.cs | 19 +++ NewHorizons/Components/NHPlanetaryRaftFix.cs | 41 ++++++ NewHorizons/Handlers/PlanetCreationHandler.cs | 2 +- NewHorizons/Main.cs | 5 + NewHorizons/NewHorizons.csproj | 1 + NewHorizons/Patches/RaftPatches.cs | 116 ++++++++++++++++ NewHorizons/Tools/Patches.cs | 2 +- 11 files changed, 235 insertions(+), 200 deletions(-) delete mode 100644 NewHorizons/Builder/Props/PlanetaryRaftController.cs create mode 100644 NewHorizons/Components/NHFluidVolume.cs create mode 100644 NewHorizons/Components/NHPlanetaryRaftFix.cs create mode 100644 NewHorizons/Patches/RaftPatches.cs diff --git a/NewHorizons/Builder/Body/WaterBuilder.cs b/NewHorizons/Builder/Body/WaterBuilder.cs index 0e8a94d0..f77306c8 100644 --- a/NewHorizons/Builder/Body/WaterBuilder.cs +++ b/NewHorizons/Builder/Body/WaterBuilder.cs @@ -70,7 +70,7 @@ namespace NewHorizons.Builder.Body var buoyancyTriggerVolume = buoyancyObject.AddComponent(); buoyancyTriggerVolume._owCollider = owCollider; - var fluidVolume = buoyancyObject.AddComponent(); + var fluidVolume = buoyancyObject.AddComponent(); fluidVolume._fluidType = FluidVolume.Type.WATER; fluidVolume._attachedBody = rb; fluidVolume._triggerVolume = buoyancyTriggerVolume; diff --git a/NewHorizons/Builder/Props/PlanetaryRaftController.cs b/NewHorizons/Builder/Props/PlanetaryRaftController.cs deleted file mode 100644 index 0da56284..00000000 --- a/NewHorizons/Builder/Props/PlanetaryRaftController.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons.Builder.Props -{ - public class PlanetaryRaftController : MonoBehaviour - { - private LightSensor[] _lightSensors; - private float _acceleration = 5f; - private Vector3 _localAcceleration = Vector3.zero; - private OWRigidbody _raftBody; - private Sector _sector; - private GameObject parentBody; - //private GravityVolume gravityVolume; - - public float BuoyancyModifier = 5f; - - private Vector3 initialPosition; - private float targetRadius; - - private void Awake() - { - this._raftBody = base.GetComponent(); - _lightSensors = GetComponentsInChildren(); - - //gravity = (GetComponentInChildren()._activeVolumes[0] as GravityVolume); - //gravityVolume = _sector.transform.parent.GetComponentInChildren(); - - initialPosition = transform.position - _sector.transform.position; - targetRadius = initialPosition.magnitude; - parentBody = _sector.transform.parent.gameObject; - Logger.Log($"{targetRadius}"); - } - - public void OnDestroy() - { - if(_sector != null) - { - _sector.OnOccupantEnterSector += OnOccupantEnterSector; - _sector.OnOccupantExitSector += OnOccupantExitSector; - } - } - - private void FixedUpdate() - { - if (this._lightSensors[0].IsIlluminated()) - { - this._localAcceleration += Vector3.forward * this._acceleration; - } - if (this._lightSensors[1].IsIlluminated()) - { - this._localAcceleration += Vector3.right * this._acceleration; - } - if (this._lightSensors[2].IsIlluminated()) - { - this._localAcceleration -= Vector3.forward * this._acceleration; - } - if (this._lightSensors[3].IsIlluminated()) - { - this._localAcceleration -= Vector3.right * this._acceleration; - } - - /* - var currentRadius = GetRelativePosition().magnitude; - if(currentRadius != targetRadius) - { - float g = 1f; - var r = (currentRadius / targetRadius); - //if (gravityVolume != null) g = gravityVolume.CalculateGravityMagnitude(currentRadius); - _raftBody.AddAcceleration((1f - Mathf.Sqrt(r)) * GetRelativePosition().normalized * g * BuoyancyModifier); - } - */ - - /* - Vector3 vector2 = _raftBody.GetVelocity(); - var normalVector = GetRelativePosition().normalized; - float normalComponent2 = Vector3.Dot(vector2, normalVector); - vector2 -= normalComponent2 * normalVector; - _raftBody.SetVelocity(vector2); - _raftBody.SetPosition(_sector.transform.position + normalVector * targetRadius); - */ - - if (this._localAcceleration.sqrMagnitude > 0.001f) - { - this._raftBody.AddLocalAcceleration(this._localAcceleration); - } - this._localAcceleration = Vector3.zero; - - } - - private Vector3 GetRelativePosition() - { - return transform.position - parentBody.transform.position; - } - - public void SetSector(Sector sector) - { - _sector = sector; - _sector.OnOccupantEnterSector += OnOccupantEnterSector; - _sector.OnOccupantExitSector += OnOccupantExitSector; - } - - private void OnOccupantEnterSector(SectorDetector sectorDetector) - { - if (sectorDetector.GetOccupantType() == DynamicOccupant.Player) - { - _raftBody.Unsuspend(); - } - } - - private void OnOccupantExitSector(SectorDetector sectorDetector) - { - if (sectorDetector.GetOccupantType() == DynamicOccupant.Player) - { - _raftBody.Suspend(); - } - } - } -} diff --git a/NewHorizons/Builder/Props/PropBuildManager.cs b/NewHorizons/Builder/Props/PropBuildManager.cs index 69ba4ab4..c64a47f5 100644 --- a/NewHorizons/Builder/Props/PropBuildManager.cs +++ b/NewHorizons/Builder/Props/PropBuildManager.cs @@ -18,7 +18,7 @@ namespace NewHorizons.Builder.Props { public static class PropBuildManager { - public static void Make(GameObject go, Sector sector, IPlanetConfig config, IModBehaviour mod, string uniqueModName) + public static void Make(GameObject go, Sector sector, OWRigidbody planetBody, IPlanetConfig config, IModBehaviour mod, string uniqueModName) { if (config.Props.Scatter != null) { @@ -40,7 +40,10 @@ namespace NewHorizons.Builder.Props } if(config.Props.Rafts != null) { - // TODO + foreach(var raftInfo in config.Props.Rafts) + { + RaftBuilder.Make(go, sector, raftInfo, planetBody); + } } if(config.Props.Tornados != null) { diff --git a/NewHorizons/Builder/Props/RaftBuilder.cs b/NewHorizons/Builder/Props/RaftBuilder.cs index b9e06222..7e661295 100644 --- a/NewHorizons/Builder/Props/RaftBuilder.cs +++ b/NewHorizons/Builder/Props/RaftBuilder.cs @@ -1,4 +1,8 @@ using NewHorizons.Builder.General; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using NewHorizons.Utility; using OWML.Utils; using System; using System.Collections.Generic; @@ -12,86 +16,56 @@ namespace NewHorizons.Builder.Props { public static class RaftBuilder { - public static void Make(GameObject body, Vector3 position, Sector sector, OWRigidbody OWRB, AstroObject ao) + private static GameObject _prefab; + + public static void Make(GameObject planetGO, Sector sector, PropModule.RaftInfo info, OWRigidbody planetBody) { - var originalRaft = GameObject.Find("RingWorld_Body/Sector_RingInterior/Interactibles_RingInterior/Rafts/Raft_Body"); - - GameObject raftObject = new GameObject($"{body.name}Raft"); - raftObject.SetActive(false); - - GameObject lightSensors = GameObject.Instantiate(GameObject.Find("RingWorld_Body/Sector_RingInterior/Sector_Zone2/Structures_Zone2/RaftHouse_Eye_Zone2/Interactables_RaftHouse_Eye_Zone2/Prefab_IP_RaftDock/RaftSocket/Raft_Body (7)/LightSensorRoot"), raftObject.transform); - GameObject geometry = GameObject.Instantiate(GameObject.Find("RingWorld_Body/Sector_RingInterior/Sector_Zone2/Structures_Zone2/RaftHouse_Eye_Zone2/Interactables_RaftHouse_Eye_Zone2/Prefab_IP_RaftDock/RaftSocket/Raft_Body (7)/Structure_IP_Raft"), raftObject.transform); - GameObject collidersObject = GameObject.Instantiate(GameObject.Find("RingWorld_Body/Sector_RingInterior/Sector_Zone2/Structures_Zone2/RaftHouse_Eye_Zone2/Interactables_RaftHouse_Eye_Zone2/Prefab_IP_RaftDock/RaftSocket/Raft_Body (7)/Colliders/"), raftObject.transform); + if(_prefab == null) + { + _prefab = GameObject.FindObjectOfType().gameObject.InstantiateInactive(); + _prefab.name = "Raft_Body_Prefab"; + } + GameObject raftObject = _prefab.InstantiateInactive(); + raftObject.name = "Raft_Body"; raftObject.transform.parent = sector.transform; - raftObject.transform.localPosition = position; - raftObject.transform.rotation = Quaternion.FromToRotation(raftObject.transform.TransformDirection(Vector3.up), position.normalized); + raftObject.transform.localPosition = info.position; + raftObject.transform.localRotation = Quaternion.identity; - foreach (var l in lightSensors.GetComponentsInChildren()) + sector.OnOccupantEnterSector += (sd) => OWAssetHandler.OnOccupantEnterSector(raftObject, sd, sector); + OWAssetHandler.LoadObject(raftObject); + + var raftController = raftObject.GetComponent(); + // Since awake already ran we have to unhook these events + raftController._sector.OnOccupantEnterSector -= raftController.OnOccupantEnterSector; + raftController._sector.OnOccupantExitSector -= raftController.OnOccupantExitSector; + raftController._riverFluid = null; + + raftController._sector = sector; + sector.OnOccupantEnterSector += raftController.OnOccupantEnterSector; + sector.OnOccupantExitSector += raftController.OnOccupantExitSector; + + // Detectors + var fluidDetector = raftObject.transform.Find("Detector_Raft").GetComponent(); + var waterVolume = planetGO.GetComponentInChildren(); + fluidDetector._alignmentFluid = waterVolume; + + // Light sensors + foreach(var lightSensor in raftObject.GetComponentsInChildren()) { - if (l._sector != null) l._sector.OnSectorOccupantsUpdated -= l.OnSectorOccupantsUpdated; - l._sector = sector; - l._sector.OnSectorOccupantsUpdated += l.OnSectorOccupantsUpdated; - l._lightSourceMask = LightSourceType.FLASHLIGHT; - l.SetDetectorActive(true); - l.gameObject.SetActive(true); + lightSensor._sector.OnSectorOccupantsUpdated -= lightSensor.OnSectorOccupantsUpdated; + lightSensor._sector = sector; + sector.OnSectorOccupantsUpdated += lightSensor.OnSectorOccupantsUpdated; } - var rigidBody = raftObject.AddComponent(); - rigidBody.isKinematic = true; - rigidBody.interpolation = originalRaft.GetComponent().interpolation; - rigidBody.collisionDetectionMode = originalRaft.GetComponent().collisionDetectionMode; - rigidBody.mass = originalRaft.GetComponent().mass; - rigidBody.drag = originalRaft.GetComponent().drag; - rigidBody.angularDrag = originalRaft.GetComponent().angularDrag; - - var kinematicRigidBody = raftObject.AddComponent(); - kinematicRigidBody.centerOfMass = Vector3.zero; - - var owRigidBody = raftObject.AddComponent(); - owRigidBody._kinematicSimulation = true; - owRigidBody._rigidbody = rigidBody; - owRigidBody._kinematicRigidbody = kinematicRigidBody; - kinematicRigidBody._rigidbody = rigidBody; - kinematicRigidBody._owRigidbody = owRigidBody; - - //var motion = raftObject.AddComponent(); - //motion.SetBodyToMatch(OWRB); - - foreach (var c in collidersObject.GetComponentsInChildren()) + /* + // Debug + foreach (var point in fluidDetector._localAlignmentCheckPoints) { - c.ClearParentBody(); - c._parentBody = owRigidBody; - c.ListenForParentBodySuspension(); + var sphere = AddDebugShape.AddSphere(fluidDetector.gameObject, 0.5f, Color.green); + sphere.transform.localPosition = point; } - var meshColliders = collidersObject.GetComponentsInChildren(); - foreach (var c in meshColliders) - { - var child = c.gameObject; - var newCollider = child.AddComponent(); - newCollider.sharedMesh = c.sharedMesh; - newCollider.material = c.material; - newCollider.sharedMaterial = c.sharedMaterial; - GameObject.Destroy(c); - } - - foreach (var child in raftObject.GetComponentsInChildren()) - { - StreamingManager.LoadStreamingAssets(child.assetBundle); - } - - //var detectorGO = DetectorBuilder.Make(raftObject, owRigidBody, ao, null, false, false); - //var fluidDetector = detectorGO.AddComponent(); - //Main.Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => fluidDetector._activeVolumes = new EffectVolume[] { body.GetComponentInChildren() }.ToList()); - - - var targetBodyAlignment = raftObject.AddComponent(); - targetBodyAlignment._owRigidbody = owRigidBody; - targetBodyAlignment.SetTargetBody(OWRB); - targetBodyAlignment.SetUsePhysicsToRotate(true); - - var controller = raftObject.AddComponent(); - controller.SetSector(sector); + */ raftObject.SetActive(true); } diff --git a/NewHorizons/Components/NHFluidVolume.cs b/NewHorizons/Components/NHFluidVolume.cs new file mode 100644 index 00000000..3f01a0d1 --- /dev/null +++ b/NewHorizons/Components/NHFluidVolume.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Components +{ + public class NHFluidVolume : RadialFluidVolume + { + public override float GetDepthAtPosition(Vector3 worldPosition) + { + Vector3 vector = transform.InverseTransformPoint(worldPosition); + float dist = Mathf.Sqrt(vector.x * vector.x + vector.z * vector.z + vector.y * vector.y); + return dist - _radius; + } + } +} diff --git a/NewHorizons/Components/NHPlanetaryRaftFix.cs b/NewHorizons/Components/NHPlanetaryRaftFix.cs new file mode 100644 index 00000000..4e5a9408 --- /dev/null +++ b/NewHorizons/Components/NHPlanetaryRaftFix.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons.Components +{ + public class NHPlanetaryRaftFix : MonoBehaviour + { + private RaftController _raftController; + private RaftFluidDetector _fluidDetector; + private FluidVolume _fluidVolume; + private RaftEffectsController _effectsController; + + public void Awake() + { + _raftController = gameObject.GetComponent(); + _fluidDetector = _raftController._fluidDetector; + _fluidVolume = _fluidDetector._alignmentFluid; + _effectsController = _raftController._effectsController; + } + + public void FixedUpdate() + { + if (_raftController._raftBody.IsSuspended()) return; + if (!_raftController._playerInEffectsRange) return; + + // Normally this part won't get called because in RaftController it checks how submerged we are in the Ringworld river + // Just copy pasted it here using the actual fluid volume instead of making an ugly patch + float num = _fluidDetector.InFluidType(FluidVolume.Type.WATER) ? _fluidVolume.GetFractionSubmerged(_fluidDetector) : 0f; + bool allowMovement = num > 0.25f && num < 1f; + Logger.Log($"AllowMovement? [{allowMovement}]"); + allowMovement = true; + _effectsController.UpdateMovementAudio(allowMovement, _raftController._lightSensors); + _effectsController.UpdateGroundedAudio(_fluidDetector); + } + } +} diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index 7fe0378a..8a362255 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -340,7 +340,7 @@ namespace NewHorizons.Handlers } if (body.Config.Props != null) - PropBuildManager.Make(go, sector, body.Config, body.Mod, body.Mod.ModHelper.Manifest.UniqueName); + PropBuildManager.Make(go, sector, rb, body.Config, body.Mod, body.Mod.ModHelper.Manifest.UniqueName); if (body.Config.Signal != null) SignalBuilder.Make(go, sector, body.Config.Signal, body.Mod); diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index c9342c6e..cc4191db 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -28,6 +28,8 @@ using NewHorizons.Builder.Atmosphere; using PacificEngine.OW_CommonResources.Geometry.Orbits; using NewHorizons.Utility.CommonResources; using UnityEngine.Events; +using HarmonyLib; +using System.Reflection; namespace NewHorizons { @@ -111,6 +113,9 @@ namespace NewHorizons BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(null), this); + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + Tools.Patches.Apply(); Tools.WarpDrivePatches.Apply(); Tools.OWCameraFix.Apply(); diff --git a/NewHorizons/NewHorizons.csproj b/NewHorizons/NewHorizons.csproj index 97bef051..013043d0 100644 --- a/NewHorizons/NewHorizons.csproj +++ b/NewHorizons/NewHorizons.csproj @@ -16,6 +16,7 @@ none + diff --git a/NewHorizons/Patches/RaftPatches.cs b/NewHorizons/Patches/RaftPatches.cs new file mode 100644 index 00000000..3b061cd4 --- /dev/null +++ b/NewHorizons/Patches/RaftPatches.cs @@ -0,0 +1,116 @@ +using HarmonyLib; +using NewHorizons.Components; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public class RaftPatches : HarmonyPatch + { + [HarmonyPrefix] + [HarmonyPatch(typeof(RaftController), nameof(RaftController.FixedUpdate))] + public static bool RaftController_FixedUpdate(RaftController __instance) + { + // If it has a river fluid its a normal one and we don't do anything + if (__instance._riverFluid != null) return true; + + // Copy paste the original method + if (__instance._raftBody.IsSuspended()) + { + return false; + } + bool playerInEffectsRange = __instance._playerInEffectsRange; + __instance._playerInEffectsRange = ((Locator.GetPlayerBody().GetPosition() - __instance._raftBody.GetPosition()).sqrMagnitude < 2500f); + if (playerInEffectsRange && !__instance._playerInEffectsRange) + { + __instance._effectsController.StopAllEffects(); + } + if (__instance._dock != null || __instance._movingToTarget) + { + __instance._localAcceleration = Vector3.zero; + if (__instance._playerInEffectsRange) + { + __instance._effectsController.UpdateMovementAudio(false, __instance._lightSensors); + } + if (__instance._movingToTarget) + { + __instance.UpdateMoveToTarget(); + } + return false; + } + if (__instance._fluidDetector.InFluidType(FluidVolume.Type.WATER)) + { + if (__instance._lightSensors[0].IsIlluminated()) + { + __instance._localAcceleration += Vector3.forward * __instance._acceleration; + } + if (__instance._lightSensors[1].IsIlluminated()) + { + __instance._localAcceleration += Vector3.right * __instance._acceleration; + } + if (__instance._lightSensors[2].IsIlluminated()) + { + __instance._localAcceleration -= Vector3.forward * __instance._acceleration; + } + if (__instance._lightSensors[3].IsIlluminated()) + { + __instance._localAcceleration -= Vector3.right * __instance._acceleration; + } + } + if (__instance._localAcceleration.sqrMagnitude > 0.001f) + { + __instance._raftBody.AddLocalAcceleration(__instance._localAcceleration); + } + if (__instance._playerInEffectsRange) + { + // All this to change what fluidVolume we use on this line + float num = __instance._fluidDetector.InFluidType(FluidVolume.Type.WATER) ? __instance._fluidDetector._alignmentFluid.GetFractionSubmerged(__instance._fluidDetector) : 0f; + bool allowMovement = num > 0.25f && num < 1f; + __instance._effectsController.UpdateMovementAudio(allowMovement, __instance._lightSensors); + __instance._effectsController.UpdateGroundedAudio(__instance._fluidDetector); + } + __instance._localAcceleration = Vector3.zero; + + return false; + } + + [HarmonyReversePatch] + [HarmonyPatch(typeof(AsymmetricFluidDetector), "ManagedFixedUpdate")] + public static void AsymmetricFluidDetector_ManagedFixedUpdate(AsymmetricFluidDetector __instance) + { + // This is like doing base.FixedUpdate + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AlignToSurfaceFluidDetector), "ManagedFixedUpdate")] + public static bool AlignToSurfaceFluidDetector_ManagedFixedUpdate(AlignToSurfaceFluidDetector __instance) + { + if (!__instance._alignmentFluid is NHFluidVolume) return true; + + // Mostly copy pasting from the AlignWithDirection class + AsymmetricFluidDetector_ManagedFixedUpdate(__instance); + + if (__instance._inAlignmentFluid) + { + // Both in world space + var currentDirection = __instance._owRigidbody.transform.up; + var alignmentDirection = (__instance.transform.position - __instance._alignmentFluid.transform.position).normalized; + var degreesToTarget = Vector3.Angle(currentDirection, alignmentDirection); + + var adjustedSlerpRate = Mathf.Clamp01(100f / degreesToTarget * Time.fixedDeltaTime); + + Vector3 a = OWPhysics.FromToAngularVelocity(currentDirection, alignmentDirection); + __instance._owRigidbody.SetAngularVelocity(Vector3.zero); + __instance._owRigidbody.AddAngularVelocityChange(a * adjustedSlerpRate); + } + + return false; + } + } +} diff --git a/NewHorizons/Tools/Patches.cs b/NewHorizons/Tools/Patches.cs index 25a653a2..78ecbac7 100644 --- a/NewHorizons/Tools/Patches.cs +++ b/NewHorizons/Tools/Patches.cs @@ -10,7 +10,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; -using Harmony; +using HarmonyLib; using NewHorizons.Utility; using OWML.Utils; using UnityEngine; From c953ee6de05d2accfff8c2dc031e9c6a296bee41 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 18:43:14 -0400 Subject: [PATCH 07/15] Try some other tornado stuff --- NewHorizons/Builder/Props/TornadoBuilder.cs | 68 ++++++--------------- NewHorizons/Components/TornadoFix.cs | 17 ++++-- 2 files changed, 31 insertions(+), 54 deletions(-) diff --git a/NewHorizons/Builder/Props/TornadoBuilder.cs b/NewHorizons/Builder/Props/TornadoBuilder.cs index 6c086a4a..34f128af 100644 --- a/NewHorizons/Builder/Props/TornadoBuilder.cs +++ b/NewHorizons/Builder/Props/TornadoBuilder.cs @@ -1,5 +1,6 @@ using NewHorizons.Components; using NewHorizons.External; +using NewHorizons.Utility; using System; using System.Collections.Generic; using System.Linq; @@ -41,10 +42,11 @@ namespace NewHorizons.Builder.Props // Default radius is 40, height is 837.0669 - var tornado = GameObject.Instantiate(prefab, sector.transform); - tornado.SetActive(false); - - tornado.transform.localPosition = Vector3.zero; + var tornadoGO = prefab.InstantiateInactive(); + tornadoGO.transform.parent = sector?.transform ?? go.transform; + tornadoGO.transform.localPosition = Vector3.zero; + var tornado = tornadoGO.GetComponent(); + tornado.SetSector(sector); var height = 837.0669f; if (info.height != 0f) height = info.height; @@ -52,54 +54,24 @@ namespace NewHorizons.Builder.Props var width = 40f; if (info.width != 0f) width = info.width; - var scale = new Vector3(width / 40f, 1f, width / 40f); + tornado._bottomBone.localPosition = new Vector3(0, elevation, 0); + tornado._midBone.localPosition = new Vector3(0, elevation + height / 2f, 0); + tornado._topBone.localPosition = new Vector3(0, elevation + height, 0); - tornado.transform.localScale = scale; + tornado._startActive = false; - var tornadoController = tornado.GetComponent(); - tornadoController.SetSector(sector); - var n = position.normalized; + // TODO make these settings + tornado._wanderRate = 0.5f; + tornado._wanderDegreesX = 45f; + tornado._wanderDegreesZ = 45f; - var up = new Vector3(0, 1, 0); - - var h1 = elevation; - var h2 = (elevation + height / 2f); - var h3 = (elevation + height); - - tornadoController._bottomElevation = h1; - tornadoController._bottomStartElevation = h1; - tornadoController._bottomStartPos = n * h1; - tornadoController._bottomBasePos = up * h1; - tornadoController._bottomBone.localPosition = n * h1; - tornadoController._bottomBone.rotation.SetFromToRotation(tornadoController._bottomBone.up, up); - - tornadoController._midElevation = h2; - tornadoController._midStartElevation = h2; - tornadoController._midStartPos = n * h2; - tornadoController._midBasePos = up * h2; - tornadoController._midBone.localPosition = n * h2; - tornadoController._midBone.rotation.SetFromToRotation(tornadoController._midBone.up, up); - - tornadoController._topElevation = h3; - tornadoController._topStartPos = n * h3; - tornadoController._topBasePos = up * h3; - tornadoController._topBone.localPosition = n * h3; - tornadoController._topBone.rotation.SetFromToRotation(tornadoController._topBone.up, up); - - tornadoController._snapBonesToSphere = true; - tornadoController._wander = true; - tornadoController._wanderRate = 0.02f; - tornadoController._wanderDegreesX = 45f; - tornadoController._wanderDegreesZ = 45f; - - if(!hasClouds) + /* + if (!hasClouds) { - var fix = tornado.AddComponent(); + var fix = tornadoGO.AddComponent(); fix.SetSector(sector); - var top = tornado.transform.Find("UpTornado/Effects_GD_TornadoCyclone/Tornado_Top"); - - Logger.Log($"{top.name}"); + var top = tornadoGO.transform.Find("UpTornado/Effects_GD_TornadoCyclone/Tornado_Top"); // Get rid of the bit that appears above the clouds GameObject.Destroy(top.transform.Find("Effects_GD_TornadoCloudCap_Large")?.gameObject); @@ -117,9 +89,9 @@ namespace NewHorizons.Builder.Props obj.transform.localRotation = Quaternion.Euler(180, 0, 0); } } + */ - tornadoController._startActive = false; - tornado.SetActive(true); + tornadoGO.SetActive(true); } } } diff --git a/NewHorizons/Components/TornadoFix.cs b/NewHorizons/Components/TornadoFix.cs index 35eae09b..0968451e 100644 --- a/NewHorizons/Components/TornadoFix.cs +++ b/NewHorizons/Components/TornadoFix.cs @@ -48,16 +48,21 @@ namespace NewHorizons.Components public void OnOccupantEnterSector(SectorDetector _) { - if(!tornadoController._tornadoRoot.activeInHierarchy) tornadoController.StartFormation(); + // Only form if not active and not forming + if (tornadoController._tornadoRoot.activeInHierarchy || tornadoController._tornadoForming) return; + + tornadoController.StartFormation(); } public void OnOccupantExitSector(SectorDetector _) { - - if (!_sector.ContainsAnyOccupants(DynamicOccupant.Player | DynamicOccupant.Probe | DynamicOccupant.Ship)) - { - tornadoController.StartCollapse(); - } + + if (_sector.ContainsAnyOccupants(DynamicOccupant.Player | DynamicOccupant.Probe | DynamicOccupant.Ship)) return; + + // If the root is inactive it has collapsed. Also don't collapse if we're already doing it + if (!tornadoController._tornadoRoot.activeInHierarchy || tornadoController._tornadoCollapsing) return; + + tornadoController.StartCollapse(); } } } From e6ac6c9c8aa7a9e068ff8f02eec36b8c716865be Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 20:15:18 -0400 Subject: [PATCH 08/15] Switch all patches over to HarmonyLib --- NewHorizons/Main.cs | 14 +- NewHorizons/Patches/AudioSignalPatches.cs | 134 +++++ .../Patches/EyeOfTheUniversePatches.cs | 124 ++++ NewHorizons/Patches/LocatorPatches.cs | 25 + NewHorizons/Patches/MapControllerPatches.cs | 32 + .../OWCameraPatch.cs} | 17 +- NewHorizons/Patches/PlayerDataPatches.cs | 128 ++++ NewHorizons/Patches/PlayerSpawnerPatches.cs | 35 ++ NewHorizons/Patches/PlayerStatePatches.cs | 33 ++ NewHorizons/Patches/ProbeLauncherPatches.cs | 25 + NewHorizons/Patches/RaftPatches.cs | 168 +++--- .../{Tools => Patches}/ShipLogPatches.cs | 80 +-- NewHorizons/Patches/SignalScopePatches.cs | 41 ++ NewHorizons/Patches/SingularityPatches.cs | 60 ++ NewHorizons/Patches/SunPatches.cs | 54 ++ NewHorizons/Patches/TranslationPatches.cs | 49 ++ .../{Tools => Patches}/WarpDrivePatches.cs | 26 +- NewHorizons/Tools/Patches.cs | 559 ------------------ NewHorizons/Tools/TranslationPatches.cs | 52 -- 19 files changed, 891 insertions(+), 765 deletions(-) create mode 100644 NewHorizons/Patches/AudioSignalPatches.cs create mode 100644 NewHorizons/Patches/EyeOfTheUniversePatches.cs create mode 100644 NewHorizons/Patches/LocatorPatches.cs create mode 100644 NewHorizons/Patches/MapControllerPatches.cs rename NewHorizons/{Tools/OWCameraFix.cs => Patches/OWCameraPatch.cs} (62%) create mode 100644 NewHorizons/Patches/PlayerDataPatches.cs create mode 100644 NewHorizons/Patches/PlayerSpawnerPatches.cs create mode 100644 NewHorizons/Patches/PlayerStatePatches.cs create mode 100644 NewHorizons/Patches/ProbeLauncherPatches.cs rename NewHorizons/{Tools => Patches}/ShipLogPatches.cs (63%) create mode 100644 NewHorizons/Patches/SignalScopePatches.cs create mode 100644 NewHorizons/Patches/SingularityPatches.cs create mode 100644 NewHorizons/Patches/SunPatches.cs create mode 100644 NewHorizons/Patches/TranslationPatches.cs rename NewHorizons/{Tools => Patches}/WarpDrivePatches.cs (77%) delete mode 100644 NewHorizons/Tools/Patches.cs delete mode 100644 NewHorizons/Tools/TranslationPatches.cs diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index cc4191db..5c4a3b73 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -24,8 +24,6 @@ using OWML.Common.Menus; using UnityEngine; using UnityEngine.SceneManagement; using Logger = NewHorizons.Utility.Logger; -using NewHorizons.Builder.Atmosphere; -using PacificEngine.OW_CommonResources.Geometry.Orbits; using NewHorizons.Utility.CommonResources; using UnityEngine.Events; using HarmonyLib; @@ -99,6 +97,9 @@ namespace NewHorizons public void Start() { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + OnChangeStarSystem = new StarSystemEvent(); OnStarSystemLoaded = new StarSystemEvent(); @@ -113,15 +114,6 @@ namespace NewHorizons BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(null), this); - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - Tools.Patches.Apply(); - Tools.WarpDrivePatches.Apply(); - Tools.OWCameraFix.Apply(); - Tools.ShipLogPatches.Apply(); - Tools.TranslationPatches.Apply(); - Logger.Log("Begin load of config files...", Logger.LogType.Log); try diff --git a/NewHorizons/Patches/AudioSignalPatches.cs b/NewHorizons/Patches/AudioSignalPatches.cs new file mode 100644 index 00000000..ed7cbdde --- /dev/null +++ b/NewHorizons/Patches/AudioSignalPatches.cs @@ -0,0 +1,134 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class AudioSignalPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSignal), nameof(AudioSignal.SignalNameToString))] + public static bool AudioSignal_SignalNameToString(SignalName __0, ref string __result) + { + var customSignalName = SignalBuilder.GetCustomSignalName(__0); + if (customSignalName == null) return true; + else + { + __result = TranslationHandler.GetTranslation(customSignalName, TranslationHandler.TextType.UI).ToUpper(); + return false; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSignal), nameof(AudioSignal.FrequencyToIndex))] + public static bool AudioSignal_FrequencyToIndex(SignalFrequency __0, ref int __result) + { + switch (__0) + { + case (SignalFrequency.Default): + __result = 0; + break; + case (SignalFrequency.Traveler): + __result = 1; + break; + case (SignalFrequency.Quantum): + __result = 2; + break; + case (SignalFrequency.EscapePod): + __result = 3; + break; + case (SignalFrequency.WarpCore): + __result = 4; + break; + case (SignalFrequency.HideAndSeek): + __result = 5; + break; + case (SignalFrequency.Radio): + __result = 6; + break; + case (SignalFrequency.Statue): + __result = 7; + break; + default: + // Frequencies are in powers of 2 + __result = (int)(Mathf.Log((float)__0) / Mathf.Log(2f)); + break; + } + + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSignal), nameof(AudioSignal.IndexToFrequency))] + public static bool AudioSignal_IndexToFrequency(int __0, ref SignalFrequency __result) + { + switch (__0) + { + case 0: + __result = SignalFrequency.Default; + break; + case 1: + __result = SignalFrequency.Traveler; + break; + case 2: + __result = SignalFrequency.Quantum; + break; + case 3: + __result = SignalFrequency.EscapePod; + break; + case 4: + __result = SignalFrequency.WarpCore; + break; + case 5: + __result = SignalFrequency.HideAndSeek; + break; + case 6: + __result = SignalFrequency.Radio; + break; + case 7: + __result = SignalFrequency.Statue; + break; + default: + __result = (SignalFrequency)(Math.Pow(2, __0)); + break; + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSignal), nameof(AudioSignal.FrequencyToString))] + public static bool AudioSignal_FrequencyToString(SignalFrequency __0, ref string __result) + { + var customName = SignalBuilder.GetCustomFrequencyName(__0); + if (customName != null && customName != "") + { + if (NewHorizonsData.KnowsFrequency(customName)) __result = TranslationHandler.GetTranslation(customName, TranslationHandler.TextType.UI).ToUpper(); + else __result = UITextLibrary.GetString(UITextType.SignalFreqUnidentified); + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSignal), nameof(AudioSignal.UpdateSignalStrength))] + public static bool AudioSignal_UpdateSignalStrength(AudioSignal __instance, Signalscope __0, float __1) + { + // I hate this, just because I can't override the base method in CloakedAudioSignal + if (__instance is CloakedAudioSignal) + { + ((CloakedAudioSignal)__instance).UpdateSignalStrength(__0, __1); + return false; + } + return true; + } + } +} diff --git a/NewHorizons/Patches/EyeOfTheUniversePatches.cs b/NewHorizons/Patches/EyeOfTheUniversePatches.cs new file mode 100644 index 00000000..94b6616d --- /dev/null +++ b/NewHorizons/Patches/EyeOfTheUniversePatches.cs @@ -0,0 +1,124 @@ +using NewHorizons.Builder.General; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using OWML.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; +using HarmonyLib; +using NewHorizons.Utility; +using OWML.Utils; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; +using Object = UnityEngine.Object; +using NewHorizons.Handlers; +using NewHorizons.Builder.ShipLog; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class EyeOfTheUniversePatches + { + // Funny eye of the universe stuff + [HarmonyPrefix] + [HarmonyPatch(typeof(DeathManager), nameof(DeathManager.KillPlayer))] + public static bool DeathManager_KillPlayer() + { + return (Main.Instance.CurrentStarSystem != "EyeOfTheUniverse"); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipThrusterController), nameof(ShipThrusterController.ReadTranslationalInput))] + public static bool ShipThrusterController_ReadTranslationalInput(ShipThrusterController __instance, ref Vector3 __result) + { + if (Main.Instance.CurrentStarSystem != "EyeOfTheUniverse") return true; + + float value = OWInput.GetValue(InputLibrary.thrustX, InputMode.All); + float value2 = OWInput.GetValue(InputLibrary.thrustZ, InputMode.All); + float value3 = OWInput.GetValue(InputLibrary.thrustUp, InputMode.All); + float value4 = OWInput.GetValue(InputLibrary.thrustDown, InputMode.All); + if (!OWInput.IsInputMode(InputMode.ShipCockpit | InputMode.LandingCam)) + { + __result = Vector3.zero; + return false; + } + if (!__instance._shipResources.AreThrustersUsable()) + { + __result = Vector3.zero; + return false; + } + if (__instance._autopilot.IsFlyingToDestination()) + { + __result = Vector3.zero; + return false; + } + Vector3 vector = new Vector3(value, 0f, value2); + if (vector.sqrMagnitude > 1f) + { + vector.Normalize(); + } + vector.y = value3 - value4; + if (__instance._requireIgnition && __instance._landingManager.IsLanded()) + { + vector.x = 0f; + vector.z = 0f; + vector.y = Mathf.Clamp01(vector.y); + if (!__instance._isIgniting && __instance._lastTranslationalInput.y <= 0f && vector.y > 0f) + { + __instance._isIgniting = true; + __instance._ignitionTime = Time.time; + GlobalMessenger.FireEvent("StartShipIgnition"); + } + if (__instance._isIgniting) + { + if (vector.y <= 0f) + { + __instance._isIgniting = false; + GlobalMessenger.FireEvent("CancelShipIgnition"); + } + if (Time.time < __instance._ignitionTime + __instance._ignitionDuration) + { + vector.y = 0f; + } + else + { + __instance._isIgniting = false; + __instance._requireIgnition = false; + GlobalMessenger.FireEvent("CompleteShipIgnition"); + RumbleManager.PlayShipIgnition(); + } + } + } + float d = __instance._thrusterModel.GetMaxTranslationalThrust() / __instance._thrusterModel.GetMaxTranslationalThrust(); + Vector3 vector2 = vector * d; + if (__instance._limitOrbitSpeed && vector2.magnitude > 0f) + { + Vector3 vector3 = __instance._landingRF.GetOWRigidBody().GetWorldCenterOfMass() - __instance._shipBody.GetWorldCenterOfMass(); + Vector3 vector4 = __instance._shipBody.GetVelocity() - __instance._landingRF.GetVelocity(); + Vector3 vector5 = vector4 - Vector3.Project(vector4, vector3); + Vector3 vector6 = Quaternion.FromToRotation(-__instance._shipBody.transform.up, vector3) * __instance._shipBody.transform.TransformDirection(vector2 * __instance._thrusterModel.GetMaxTranslationalThrust()); + Vector3 vector7 = Vector3.Project(vector6, vector3); + Vector3 vector8 = vector6 - vector7; + Vector3 a = vector5 + vector8 * Time.deltaTime; + float magnitude = a.magnitude; + float orbitSpeed = __instance._landingRF.GetOrbitSpeed(vector3.magnitude); + if (magnitude > orbitSpeed) + { + a = a.normalized * orbitSpeed; + vector8 = (a - vector5) / Time.deltaTime; + vector6 = vector7 + vector8; + vector2 = __instance._shipBody.transform.InverseTransformDirection(vector6 / __instance._thrusterModel.GetMaxTranslationalThrust()); + } + } + __instance._lastTranslationalInput = vector; + __result = vector2; + + return false; + } + } +} diff --git a/NewHorizons/Patches/LocatorPatches.cs b/NewHorizons/Patches/LocatorPatches.cs new file mode 100644 index 00000000..2ec5ffbc --- /dev/null +++ b/NewHorizons/Patches/LocatorPatches.cs @@ -0,0 +1,25 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class LocatorPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(Locator), nameof(Locator.RegisterCloakFieldController))] + public static bool Locator_RegisterCloakFieldController() + { + return Locator._cloakFieldController == null; + } + } +} diff --git a/NewHorizons/Patches/MapControllerPatches.cs b/NewHorizons/Patches/MapControllerPatches.cs new file mode 100644 index 00000000..c3bda603 --- /dev/null +++ b/NewHorizons/Patches/MapControllerPatches.cs @@ -0,0 +1,32 @@ +using HarmonyLib; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class MapControllerPatches + { + [HarmonyPostfix] + [HarmonyPatch(typeof(MapController), nameof(MapController.Awake))] + public static void MapController_Awake(MapController __instance, ref float ____maxPanDistance, ref float ____maxZoomDistance, ref float ____minPitchAngle, ref float ____zoomSpeed) + { + ____maxPanDistance = Main.FurthestOrbit * 1.5f; + ____maxZoomDistance *= 6f; + ____minPitchAngle = -90f; + ____zoomSpeed *= 4f; + __instance._mapCamera.farClipPlane = Main.FurthestOrbit * 10f; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(MapController), nameof(MapController.OnTargetReferenceFrame))] + public static void MapController_OnTargetReferenceFrame(MapController __instance, ReferenceFrame __0) + { + __instance._isLockedOntoMapSatellite = true; + } + } +} diff --git a/NewHorizons/Tools/OWCameraFix.cs b/NewHorizons/Patches/OWCameraPatch.cs similarity index 62% rename from NewHorizons/Tools/OWCameraFix.cs rename to NewHorizons/Patches/OWCameraPatch.cs index 0d1e8f6b..5bfde6ee 100644 --- a/NewHorizons/Tools/OWCameraFix.cs +++ b/NewHorizons/Patches/OWCameraPatch.cs @@ -1,20 +1,19 @@ -using System; +using HarmonyLib; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; -namespace NewHorizons.Tools +namespace NewHorizons.Patches { - public static class OWCameraFix + [HarmonyPatch] + public static class OWCameraPatch { - public static void Apply() - { - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("Awake", typeof(OWCameraFix), nameof(OWCameraFix.OnOWCameraAwake)); - } - - private static void OnOWCameraAwake(OWCamera __instance) + [HarmonyPostfix] + [HarmonyPatch(typeof(OWCamera), nameof(OWCamera.Awake))] + public static void OnOWCameraAwake(OWCamera __instance) { var oldDist = __instance.farClipPlane; var newDist = __instance.farClipPlane * 10f; diff --git a/NewHorizons/Patches/PlayerDataPatches.cs b/NewHorizons/Patches/PlayerDataPatches.cs new file mode 100644 index 00000000..f7e5317d --- /dev/null +++ b/NewHorizons/Patches/PlayerDataPatches.cs @@ -0,0 +1,128 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class PlayerDataPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.KnowsFrequency))] + public static bool OnPlayerDataKnowsFrequency(SignalFrequency __0, ref bool __result) + { + var freqString = SignalBuilder.GetCustomFrequencyName(__0); + + if (freqString != null && freqString != "") + { + __result = NewHorizonsData.KnowsFrequency(freqString); + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.LearnFrequency))] + public static bool OnPlayerDataLearnFrequency(SignalFrequency __0) + { + var freqString = SignalBuilder.GetCustomFrequencyName(__0); + if (freqString != null && freqString != "") + { + NewHorizonsData.LearnFrequency(freqString); + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.KnowsSignal))] + public static bool OnPlayerDataKnowsSignal(SignalName __0, ref bool __result) + { + var customSignalName = SignalBuilder.GetCustomSignalName(__0); + if (customSignalName != null) + { + __result = NewHorizonsData.KnowsSignal(customSignalName); + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.LearnSignal))] + public static bool OnPlayerDataLearnSignal(SignalName __0) + { + var customSignalName = SignalBuilder.GetCustomSignalName(__0); + if (customSignalName != null) + { + if (!NewHorizonsData.KnowsSignal(customSignalName)) NewHorizonsData.LearnSignal(customSignalName); + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.KnowsMultipleFrequencies))] + public static bool OnPlayerDataKnowsMultipleFrequencies(ref bool __result) + { + if (NewHorizonsData.KnowsMultipleFrequencies()) + { + __result = true; + return false; + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.AddNewlyRevealedFactID))] + public static bool OnPlayerDataAddNewlyRevealedFactID(string __0) + { + if (ShipLogHandler.IsModdedFact(__0)) + { + NewHorizonsData.AddNewlyRevealedFactID(__0); + return false; + } + else + { + return true; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.GetNewlyRevealedFactIDs))] + public static bool OnPlayerDataGetNewlyRevealedFactIDs(ref List __result) + { + __result = PlayerData._currentGameSave.newlyRevealedFactIDs.Concat(NewHorizonsData.GetNewlyRevealedFactIDs()).ToList(); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.ClearNewlyRevealedFactIDs))] + public static bool OnPlayerDataClearNewlyRevealedFactIDs() + { + PlayerData._currentGameSave.newlyRevealedFactIDs.Clear(); + NewHorizonsData.ClearNewlyRevealedFactIDs(); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.ResetGame))] + public static void OnPlayerDataResetGame() + { + NewHorizonsData.Reset(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerData), nameof(PlayerData.GetNewlyRevealedFactIDs))] + public static void PlayerData_GetNewlyRevealedFactIDs(ref List __result) + { + ShipLogManager manager = Locator.GetShipLogManager(); + __result = __result.Where(e => manager.GetFact(e) != null).ToList(); + } + } +} diff --git a/NewHorizons/Patches/PlayerSpawnerPatches.cs b/NewHorizons/Patches/PlayerSpawnerPatches.cs new file mode 100644 index 00000000..dab43313 --- /dev/null +++ b/NewHorizons/Patches/PlayerSpawnerPatches.cs @@ -0,0 +1,35 @@ +using NewHorizons.Builder.General; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using OWML.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; +using HarmonyLib; +using NewHorizons.Utility; +using OWML.Utils; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; +using Object = UnityEngine.Object; +using NewHorizons.Handlers; +using NewHorizons.Builder.ShipLog; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class PlayerSpawnerPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerSpawner), nameof(PlayerSpawner.SpawnPlayer))] + public static void PlayerSpawner_SpawnPlayer(PlayerSpawner __instance) + { + Logger.Log("Player spawning"); + __instance.SetInitialSpawnPoint(Main.SystemDict[Main.Instance.CurrentStarSystem].SpawnPoint); + } + } +} diff --git a/NewHorizons/Patches/PlayerStatePatches.cs b/NewHorizons/Patches/PlayerStatePatches.cs new file mode 100644 index 00000000..a279bc9a --- /dev/null +++ b/NewHorizons/Patches/PlayerStatePatches.cs @@ -0,0 +1,33 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class PlayerStatePatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.CheckShipOutsideSolarSystem))] + public static bool PlayerState_CheckShipOutsideSolarSystem(PlayerState __instance, ref bool __result) + { + if (PlayerState._inBrambleDimension) return false; + + // Stop the game from trying to recall your ship when you're visiting far away planets + + Transform sunTransform = Locator.GetSunTransform(); + OWRigidbody shipBody = Locator.GetShipBody(); + var maxDist2 = Mathf.Max(900000000f, Main.FurthestOrbit * Main.FurthestOrbit * 2f); + __result = sunTransform != null && shipBody != null && (sunTransform.position - shipBody.transform.position).sqrMagnitude > maxDist2; + return false; + } + } +} diff --git a/NewHorizons/Patches/ProbeLauncherPatches.cs b/NewHorizons/Patches/ProbeLauncherPatches.cs new file mode 100644 index 00000000..40407e93 --- /dev/null +++ b/NewHorizons/Patches/ProbeLauncherPatches.cs @@ -0,0 +1,25 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class ProbeLauncherPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(ProbeLauncher), nameof(ProbeLauncher.UpdateOrbitalLaunchValues))] + public static bool ProbeLauncher_UpdateOrbitalLaunchValues(ProbeLauncher __instance) + { + return (Locator.GetPlayerRulesetDetector()?.GetPlanetoidRuleset()?.GetGravityVolume() != null); + } + } +} diff --git a/NewHorizons/Patches/RaftPatches.cs b/NewHorizons/Patches/RaftPatches.cs index 3b061cd4..331edd69 100644 --- a/NewHorizons/Patches/RaftPatches.cs +++ b/NewHorizons/Patches/RaftPatches.cs @@ -20,97 +20,97 @@ namespace NewHorizons.Patches // If it has a river fluid its a normal one and we don't do anything if (__instance._riverFluid != null) return true; - // Copy paste the original method - if (__instance._raftBody.IsSuspended()) - { - return false; - } - bool playerInEffectsRange = __instance._playerInEffectsRange; - __instance._playerInEffectsRange = ((Locator.GetPlayerBody().GetPosition() - __instance._raftBody.GetPosition()).sqrMagnitude < 2500f); - if (playerInEffectsRange && !__instance._playerInEffectsRange) - { - __instance._effectsController.StopAllEffects(); - } - if (__instance._dock != null || __instance._movingToTarget) - { - __instance._localAcceleration = Vector3.zero; - if (__instance._playerInEffectsRange) - { - __instance._effectsController.UpdateMovementAudio(false, __instance._lightSensors); - } - if (__instance._movingToTarget) - { - __instance.UpdateMoveToTarget(); - } - return false; - } - if (__instance._fluidDetector.InFluidType(FluidVolume.Type.WATER)) - { - if (__instance._lightSensors[0].IsIlluminated()) - { - __instance._localAcceleration += Vector3.forward * __instance._acceleration; - } - if (__instance._lightSensors[1].IsIlluminated()) - { - __instance._localAcceleration += Vector3.right * __instance._acceleration; - } - if (__instance._lightSensors[2].IsIlluminated()) - { - __instance._localAcceleration -= Vector3.forward * __instance._acceleration; - } - if (__instance._lightSensors[3].IsIlluminated()) - { - __instance._localAcceleration -= Vector3.right * __instance._acceleration; - } - } - if (__instance._localAcceleration.sqrMagnitude > 0.001f) - { - __instance._raftBody.AddLocalAcceleration(__instance._localAcceleration); - } - if (__instance._playerInEffectsRange) - { - // All this to change what fluidVolume we use on this line - float num = __instance._fluidDetector.InFluidType(FluidVolume.Type.WATER) ? __instance._fluidDetector._alignmentFluid.GetFractionSubmerged(__instance._fluidDetector) : 0f; - bool allowMovement = num > 0.25f && num < 1f; - __instance._effectsController.UpdateMovementAudio(allowMovement, __instance._lightSensors); - __instance._effectsController.UpdateGroundedAudio(__instance._fluidDetector); - } - __instance._localAcceleration = Vector3.zero; + // Copy paste the original method + if (__instance._raftBody.IsSuspended()) + { + return false; + } + bool playerInEffectsRange = __instance._playerInEffectsRange; + __instance._playerInEffectsRange = ((Locator.GetPlayerBody().GetPosition() - __instance._raftBody.GetPosition()).sqrMagnitude < 2500f); + if (playerInEffectsRange && !__instance._playerInEffectsRange) + { + __instance._effectsController.StopAllEffects(); + } + if (__instance._dock != null || __instance._movingToTarget) + { + __instance._localAcceleration = Vector3.zero; + if (__instance._playerInEffectsRange) + { + __instance._effectsController.UpdateMovementAudio(false, __instance._lightSensors); + } + if (__instance._movingToTarget) + { + __instance.UpdateMoveToTarget(); + } + return false; + } + if (__instance._fluidDetector.InFluidType(FluidVolume.Type.WATER)) + { + if (__instance._lightSensors[0].IsIlluminated()) + { + __instance._localAcceleration += Vector3.forward * __instance._acceleration; + } + if (__instance._lightSensors[1].IsIlluminated()) + { + __instance._localAcceleration += Vector3.right * __instance._acceleration; + } + if (__instance._lightSensors[2].IsIlluminated()) + { + __instance._localAcceleration -= Vector3.forward * __instance._acceleration; + } + if (__instance._lightSensors[3].IsIlluminated()) + { + __instance._localAcceleration -= Vector3.right * __instance._acceleration; + } + } + if (__instance._localAcceleration.sqrMagnitude > 0.001f) + { + __instance._raftBody.AddLocalAcceleration(__instance._localAcceleration); + } + if (__instance._playerInEffectsRange) + { + // All this to change what fluidVolume we use on this line + float num = __instance._fluidDetector.InFluidType(FluidVolume.Type.WATER) ? __instance._fluidDetector._alignmentFluid.GetFractionSubmerged(__instance._fluidDetector) : 0f; + bool allowMovement = num > 0.25f && num < 1f; + __instance._effectsController.UpdateMovementAudio(allowMovement, __instance._lightSensors); + __instance._effectsController.UpdateGroundedAudio(__instance._fluidDetector); + } + __instance._localAcceleration = Vector3.zero; - return false; - } - - [HarmonyReversePatch] - [HarmonyPatch(typeof(AsymmetricFluidDetector), "ManagedFixedUpdate")] - public static void AsymmetricFluidDetector_ManagedFixedUpdate(AsymmetricFluidDetector __instance) - { - // This is like doing base.FixedUpdate + return false; } - [HarmonyPrefix] - [HarmonyPatch(typeof(AlignToSurfaceFluidDetector), "ManagedFixedUpdate")] - public static bool AlignToSurfaceFluidDetector_ManagedFixedUpdate(AlignToSurfaceFluidDetector __instance) + [HarmonyReversePatch] + [HarmonyPatch(typeof(AsymmetricFluidDetector), "ManagedFixedUpdate")] + public static void AsymmetricFluidDetector_ManagedFixedUpdate(AsymmetricFluidDetector __instance) { - if (!__instance._alignmentFluid is NHFluidVolume) return true; + // This is like doing base.FixedUpdate + } - // Mostly copy pasting from the AlignWithDirection class - AsymmetricFluidDetector_ManagedFixedUpdate(__instance); + [HarmonyPrefix] + [HarmonyPatch(typeof(AlignToSurfaceFluidDetector), "ManagedFixedUpdate")] + public static bool AlignToSurfaceFluidDetector_ManagedFixedUpdate(AlignToSurfaceFluidDetector __instance) + { + if (!__instance._alignmentFluid is NHFluidVolume) return true; - if (__instance._inAlignmentFluid) - { - // Both in world space - var currentDirection = __instance._owRigidbody.transform.up; - var alignmentDirection = (__instance.transform.position - __instance._alignmentFluid.transform.position).normalized; - var degreesToTarget = Vector3.Angle(currentDirection, alignmentDirection); + // Mostly copy pasting from the AlignWithDirection class + AsymmetricFluidDetector_ManagedFixedUpdate(__instance); - var adjustedSlerpRate = Mathf.Clamp01(100f / degreesToTarget * Time.fixedDeltaTime); + if (__instance._inAlignmentFluid) + { + // Both in world space + var currentDirection = __instance._owRigidbody.transform.up; + var alignmentDirection = (__instance.transform.position - __instance._alignmentFluid.transform.position).normalized; + var degreesToTarget = Vector3.Angle(currentDirection, alignmentDirection); - Vector3 a = OWPhysics.FromToAngularVelocity(currentDirection, alignmentDirection); - __instance._owRigidbody.SetAngularVelocity(Vector3.zero); - __instance._owRigidbody.AddAngularVelocityChange(a * adjustedSlerpRate); - } + var adjustedSlerpRate = Mathf.Clamp01(10f / degreesToTarget * Time.fixedDeltaTime); - return false; - } - } + Vector3 a = OWPhysics.FromToAngularVelocity(currentDirection, alignmentDirection); + //__instance._owRigidbody.SetAngularVelocity(Vector3.zero); + __instance._owRigidbody.AddAngularVelocityChange(a * adjustedSlerpRate); + } + + return false; + } + } } diff --git a/NewHorizons/Tools/ShipLogPatches.cs b/NewHorizons/Patches/ShipLogPatches.cs similarity index 63% rename from NewHorizons/Tools/ShipLogPatches.cs rename to NewHorizons/Patches/ShipLogPatches.cs index 439073af..81dfe5ba 100644 --- a/NewHorizons/Tools/ShipLogPatches.cs +++ b/NewHorizons/Patches/ShipLogPatches.cs @@ -8,32 +8,16 @@ using Logger = NewHorizons.Utility.Logger; using Object = UnityEngine.Object; using NewHorizons.Builder.ShipLog; using NewHorizons.Handlers; +using HarmonyLib; -namespace NewHorizons.Tools +namespace NewHorizons.Patches { + [HarmonyPatch] public static class ShipLogPatches { - public static void Apply() - { - var playerDataGetNewlyRevealedFactIDs = typeof(PlayerData).GetMethod("GetNewlyRevealedFactIDs"); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix(playerDataGetNewlyRevealedFactIDs, typeof(ShipLogPatches), nameof(ShipLogPatches.OnPlayerDataGetNewlyRevealedFactIDsComplete)); - - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Awake", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerAwake)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Start", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerStart)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("IsFactRevealed", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerIsFactRevealed)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("CheckForCompletionAchievement", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerCheckForCompletionAchievement)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("GetCuriosityColor", typeof(ShipLogPatches), nameof(ShipLogPatches.OnUIStyleManagerGetCuriosityColor)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Awake", typeof(ShipLogPatches), nameof(ShipLogPatches.DisableShipLogSandFunnel)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("UpdateState", typeof(ShipLogPatches), nameof(ShipLogPatches.DisableShipLogSandFunnel)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("GetName", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogAstroObjectGetName)); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("Initialize", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogMapModeInitialize)); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("Awake", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerAwakeComplete)); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("UpdateState", typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogAstroObjectUpdateState)); - - Main.Instance.ModHelper.HarmonyHelper.AddPostfix(nameof(ShipLogManager.RevealFact), typeof(ShipLogPatches), nameof(ShipLogPatches.OnShipLogManagerRevealFact)); - } - - public static void OnShipLogManagerAwake(ShipLogManager __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.Awake))] + public static void ShipLogManager_Awake_Prefix(ShipLogManager __instance) { RumorModeBuilder.Init(); ShipLogHandler.Init(); @@ -64,7 +48,9 @@ namespace NewHorizons.Tools } } - public static void OnShipLogManagerAwakeComplete(ShipLogManager __instance) + [HarmonyPostfix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.Awake))] + public static void ShipLogManager_Awake_Postfix(ShipLogManager __instance) { ShipLogHandler.CheckForModdedFacts(__instance); RumorModeBuilder.GenerateEntryData(__instance); @@ -77,7 +63,9 @@ namespace NewHorizons.Tools Logger.Log("Ship Log Generation Complete For: " + Main.Instance.CurrentStarSystem, Logger.LogType.Log); } - public static bool OnShipLogManagerIsFactRevealed(ShipLogManager __instance, ref bool __result, string __0) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.IsFactRevealed))] + public static bool ShipLogManager_IsFactRevealed(ShipLogManager __instance, ref bool __result, string __0) { if (__instance._factDict != null && __instance._factDict.ContainsKey(__0)) { @@ -91,7 +79,9 @@ namespace NewHorizons.Tools return false; } - public static bool OnShipLogManagerCheckForCompletionAchievement(ShipLogManager __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.CheckForCompletionAchievement))] + public static bool ShipLogManager_CheckForCompletionAchievement(ShipLogManager __instance) { foreach (KeyValuePair keyValuePair in __instance._factDict) { @@ -104,7 +94,9 @@ namespace NewHorizons.Tools return false; } - public static bool OnShipLogManagerStart(ShipLogManager __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.Start))] + public static bool ShipLogManager_Start(ShipLogManager __instance) { foreach (NewHorizonsBody body in Main.BodyDict[Main.Instance.CurrentStarSystem]) { @@ -125,9 +117,11 @@ namespace NewHorizons.Tools } } - public static bool OnUIStyleManagerGetCuriosityColor(UIStyleManager __instance, CuriosityName __0, bool __1, ref Color __result) + [HarmonyPrefix] + [HarmonyPatch(typeof(UIStyleManager), nameof(UIStyleManager.GetCuriosityColor))] + public static bool UIStyleManager_GetCuriosityColor(UIStyleManager __instance, CuriosityName __0, bool __1, ref Color __result) { - if ((int) __0 < 7) + if ((int)__0 < 7) { return true; } @@ -138,7 +132,9 @@ namespace NewHorizons.Tools } } - public static void OnShipLogMapModeInitialize(ShipLogMapMode __instance) + [HarmonyPostfix] + [HarmonyPatch(typeof(ShipLogMapMode), nameof(ShipLogMapMode.Initialize))] + public static void ShipLogMapMode_Initialize(ShipLogMapMode __instance) { GameObject panRoot = GameObject.Find(ShipLogHandler.PAN_ROOT_PATH); GameObject sunObject = GameObject.Find(ShipLogHandler.PAN_ROOT_PATH + "/Sun"); @@ -168,7 +164,9 @@ namespace NewHorizons.Tools Logger.Log("Map Mode Construction Complete", Logger.LogType.Log); } - public static bool OnShipLogAstroObjectGetName(ShipLogAstroObject __instance, ref string __result) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogAstroObject), nameof(ShipLogAstroObject.GetName))] + public static bool ShipLogAstroObject_GetName(ShipLogAstroObject __instance, ref string __result) { if (ShipLogHandler.IsVanillaAstroID(__instance.GetID())) { @@ -181,15 +179,16 @@ namespace NewHorizons.Tools } } - public static void OnShipLogAstroObjectUpdateState(ShipLogAstroObject __instance) + [HarmonyPostfix] + [HarmonyPatch(typeof(ShipLogAstroObject), nameof(ShipLogAstroObject.UpdateState))] + public static void ShipLogAstroObject_UpdateState(ShipLogAstroObject __instance) { Transform detailsParent = __instance.transform.Find("Details"); if (detailsParent != null) { foreach (GameObject child in SearchUtilities.GetAllChildren(detailsParent.gameObject)) { - Component detail; - if (child.TryGetComponent(typeof(ShipLogDetail), out detail)) + if (child.TryGetComponent(typeof(ShipLogDetail), out Component detail)) { (detail as ShipLogDetail)?.UpdateState(__instance._state); } @@ -204,18 +203,23 @@ namespace NewHorizons.Tools } } - public static bool DisableShipLogSandFunnel() + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogSandFunnel), nameof(ShipLogSandFunnel.UpdateState))] + public static bool ShipLogSandFunnel_UpdateState() { return Main.Instance.CurrentStarSystem == "SolarSystem"; } - public static void OnPlayerDataGetNewlyRevealedFactIDsComplete(ref List __result) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogSandFunnel), nameof(ShipLogSandFunnel.Awake))] + public static bool ShipLogSandFunnel_Awake() { - ShipLogManager manager = Locator.GetShipLogManager(); - __result = __result.Where(e => manager.GetFact(e) != null).ToList(); + return Main.Instance.CurrentStarSystem == "SolarSystem"; } - public static void OnShipLogManagerRevealFact(string __0) + [HarmonyPostfix] + [HarmonyPatch(typeof(ShipLogManager), nameof(ShipLogManager.RevealFact))] + public static void ShipLogManager_RevealFact(string __0) { StarChartHandler.OnRevealFact(__0); } diff --git a/NewHorizons/Patches/SignalScopePatches.cs b/NewHorizons/Patches/SignalScopePatches.cs new file mode 100644 index 00000000..dc40b22e --- /dev/null +++ b/NewHorizons/Patches/SignalScopePatches.cs @@ -0,0 +1,41 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class SignalScopePatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(Signalscope), nameof(Signalscope.Awake))] + public static bool Signalscope_Awake(Signalscope __instance, ref AudioSignal[] ____strongestSignals) + { + ____strongestSignals = new AudioSignal[8]; + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Signalscope), nameof(Signalscope.SwitchFrequencyFilter))] + public static bool Signalscope_SwitchFrequencyFilter(Signalscope __instance, int __0) + { + var increment = __0; + var count = SignalBuilder.NumberOfFrequencies; + __instance._frequencyFilterIndex += increment; + __instance._frequencyFilterIndex = ((__instance._frequencyFilterIndex >= count) ? 0 : __instance._frequencyFilterIndex); + __instance._frequencyFilterIndex = ((__instance._frequencyFilterIndex < 0) ? count - 1 : __instance._frequencyFilterIndex); + SignalFrequency signalFrequency = AudioSignal.IndexToFrequency(__instance._frequencyFilterIndex); + + if (!PlayerData.KnowsFrequency(signalFrequency) && (!__instance._isUnknownFreqNearby || __instance._unknownFrequency != signalFrequency)) + { + __instance.SwitchFrequencyFilter(increment); + } + return false; + } + } +} diff --git a/NewHorizons/Patches/SingularityPatches.cs b/NewHorizons/Patches/SingularityPatches.cs new file mode 100644 index 00000000..eaf64dd4 --- /dev/null +++ b/NewHorizons/Patches/SingularityPatches.cs @@ -0,0 +1,60 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class SingularityPatches + { + // For our custom black holes that don't link to anything + [HarmonyPrefix] + [HarmonyPatch(typeof(BlackHoleVolume), nameof(BlackHoleVolume.Start))] + public static bool BlackHoleVolume_Start(BlackHoleVolume __instance) + { + return __instance._whiteHole == null; + } + + // To fix custom white holes + [HarmonyPrefix] + [HarmonyPatch(typeof(WhiteHoleVolume), nameof(WhiteHoleVolume.Awake))] + public static bool WhiteHoleVolume_Awake(WhiteHoleVolume __instance) + { + __instance._growQueue = new List(8); + __instance._growQueueLocationData = new List(8); + __instance._ejectedBodyList = new List(64); + try + { + __instance._whiteHoleBody = __instance.gameObject.GetAttachedOWRigidbody(false); + __instance._whiteHoleProxyShadowSuperGroup = __instance._whiteHoleBody.GetComponentInChildren(); + __instance._fluidVolume = __instance.gameObject.GetRequiredComponent(); + } + catch (Exception) { } + return false; + } + + // This is to stop the game throwing too many errors if the probe is destroyed by a blackhole + [HarmonyPrefix] + [HarmonyPatch(typeof(SurveyorProbe), nameof(SurveyorProbe.IsLaunched))] + public static bool SurveyorProbe_IsLaunched(SurveyorProbe __instance, ref bool __result) + { + try + { + __result = __instance.gameObject.activeSelf; + } + catch (Exception) + { + __result = true; + } + return false; + } + } +} diff --git a/NewHorizons/Patches/SunPatches.cs b/NewHorizons/Patches/SunPatches.cs new file mode 100644 index 00000000..d8cc13a0 --- /dev/null +++ b/NewHorizons/Patches/SunPatches.cs @@ -0,0 +1,54 @@ +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class SunPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(SunLightParamUpdater), nameof(SunLightParamUpdater.LateUpdate))] + public static bool SunLightParamUpdater_LateUpdate(SunLightParamUpdater __instance) + { + if (__instance.sunLight) + { + Vector3 position = __instance.transform.position; + float w = 2000f; + if (__instance._sunController != null) + { + w = (__instance._sunController.HasSupernovaStarted() ? __instance._sunController.GetSupernovaRadius() : __instance._sunController.GetSurfaceRadius()); + } + float range = __instance.sunLight.range; + Color color = (__instance._sunLightController != null) ? __instance._sunLightController.sunColor : __instance.sunLight.color; + float w2 = (__instance._sunLightController != null) ? __instance._sunLightController.sunIntensity : __instance.sunLight.intensity; + Shader.SetGlobalVector(__instance._propID_SunPosition, new Vector4(position.x, position.y, position.z, w)); + Shader.SetGlobalVector(__instance._propID_OWSunPositionRange, new Vector4(position.x, position.y, position.z, 1f / (range * range))); + Shader.SetGlobalVector(__instance._propID_OWSunColorIntensity, new Vector4(color.r, color.g, color.b, w2)); + } + + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SunSurfaceAudioController), nameof(SunSurfaceAudioController.Update))] + public static bool SunSurfaceAudioController_Update(SunSurfaceAudioController __instance) + { + if (__instance._sunController != null) return true; + + var surfaceRadius = __instance.transform.parent.parent.localScale.magnitude; + float value = Mathf.Max(0f, Vector3.Distance(Locator.GetPlayerCamera().transform.position, __instance.transform.position) - surfaceRadius); + float num = Mathf.InverseLerp(1600f, 100f, value); + __instance._audioSource.SetLocalVolume(num * num * __instance._fade); + return false; + } + } +} diff --git a/NewHorizons/Patches/TranslationPatches.cs b/NewHorizons/Patches/TranslationPatches.cs new file mode 100644 index 00000000..7f99f346 --- /dev/null +++ b/NewHorizons/Patches/TranslationPatches.cs @@ -0,0 +1,49 @@ +using HarmonyLib; +using NewHorizons.Components.Orbital; +using NewHorizons.Handlers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using Logger = NewHorizons.Utility.Logger; + +namespace NewHorizons.Patches +{ + [HarmonyPatch] + public static class TranslationPatches + { + [HarmonyPrefix] + [HarmonyPatch(typeof(ReferenceFrame), nameof(ReferenceFrame.GetHUDDisplayName))] + public static bool ReferenceFrame_GetHUDDisplayName(ReferenceFrame __instance, ref string __result) + { + var ao = __instance.GetAstroObject(); + + if (ao == null) return true; + + if (ao is NHAstroObject) + { + if ((ao as NHAstroObject).HideDisplayName) __result = ""; + else __result = TranslationHandler.GetTranslation(ao.GetCustomName(), TranslationHandler.TextType.UI); + return false; + } + + return true; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CanvasMapMarker), nameof(CanvasMapMarker.Init), new Type[] { typeof(Canvas), typeof(Transform), typeof(string) })] + public static void CanvasMapMarker_Init(CanvasMapMarker __instance) + { + __instance._label = TranslationHandler.GetTranslation(__instance._label, TranslationHandler.TextType.UI); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(CanvasMapMarker), nameof(CanvasMapMarker.SetLabel))] + public static void CanvasMapMarker_SetLabel(CanvasMapMarker __instance) + { + __instance._label = TranslationHandler.GetTranslation(__instance._label, TranslationHandler.TextType.UI); + } + } +} diff --git a/NewHorizons/Tools/WarpDrivePatches.cs b/NewHorizons/Patches/WarpDrivePatches.cs similarity index 77% rename from NewHorizons/Tools/WarpDrivePatches.cs rename to NewHorizons/Patches/WarpDrivePatches.cs index bff3cb01..b358a855 100644 --- a/NewHorizons/Tools/WarpDrivePatches.cs +++ b/NewHorizons/Patches/WarpDrivePatches.cs @@ -1,4 +1,5 @@ -using NewHorizons.Builder.General; +using HarmonyLib; +using NewHorizons.Builder.General; using NewHorizons.Handlers; using System; using System.Collections.Generic; @@ -7,18 +8,14 @@ using System.Text; using System.Threading.Tasks; using UnityEngine; -namespace NewHorizons.Tools +namespace NewHorizons.Patches { + [HarmonyPatch] public static class WarpDrivePatches { - public static void Apply() - { - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Update", typeof(WarpDrivePatches), nameof(WarpDrivePatches.OnShipCockpitControllerUpdate)); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("EnterMode", typeof(WarpDrivePatches), nameof(WarpDrivePatches.OnShipLogMapModeEnterMode)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Update", typeof(WarpDrivePatches), nameof(WarpDrivePatches.OnShipLogControllerUpdate)); - } - - public static void OnShipLogMapModeEnterMode(ShipLogMapMode __instance) + [HarmonyPostfix] + [HarmonyPatch(typeof(ShipLogMapMode), nameof(ShipLogMapMode.EnterMode))] + public static void ShipLogMapMode_EnterMode(ShipLogMapMode __instance) { if (!Main.HasWarpDrive) return; @@ -28,7 +25,9 @@ namespace NewHorizons.Tools text.text = newPrompt; } - public static bool OnShipCockpitControllerUpdate(ShipCockpitController __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipCockpitController), nameof(ShipCockpitController.Update))] + public static bool ShipCockpitController_Update(ShipCockpitController __instance) { if (!Main.HasWarpDrive) return true; @@ -44,7 +43,9 @@ namespace NewHorizons.Tools return true; } - public static bool OnShipLogControllerUpdate(ShipLogController __instance) + [HarmonyPrefix] + [HarmonyPatch(typeof(ShipLogController), nameof(ShipLogController.Update))] + public static bool ShipLogController_Update(ShipLogController __instance) { if (!Main.HasWarpDrive) return true; @@ -54,6 +55,7 @@ namespace NewHorizons.Tools || StarChartHandler.ShipLogStarChartMode == null) return true; + // Mostly copied from the base method but we're trying to fit in our new mode __instance._exitPrompt.SetVisibility(__instance._currentMode.AllowCancelInput()); __instance._currentMode.UpdateMode(); if (__instance._currentMode.AllowModeSwap() && OWInput.IsNewlyPressed(InputLibrary.swapShipLogMode, InputMode.All)) diff --git a/NewHorizons/Tools/Patches.cs b/NewHorizons/Tools/Patches.cs deleted file mode 100644 index 78ecbac7..00000000 --- a/NewHorizons/Tools/Patches.cs +++ /dev/null @@ -1,559 +0,0 @@ -using NewHorizons.Builder.General; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External; -using OWML.Common; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Linq; -using HarmonyLib; -using NewHorizons.Utility; -using OWML.Utils; -using UnityEngine; -using Logger = NewHorizons.Utility.Logger; -using Object = UnityEngine.Object; -using NewHorizons.Handlers; -using NewHorizons.Builder.ShipLog; - -namespace NewHorizons.Tools -{ - public class Patches - { - public static void Apply() - { - // Prefixes - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("CheckShipOutsideSolarSystem", typeof(Patches), nameof(Patches.CheckShipOutersideSolarSystem)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("LateUpdate", typeof(Patches), nameof(Patches.OnSunLightParamUpdaterLateUpdate)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Update", typeof(Patches), nameof(Patches.OnSunSurfaceAudioControllerUpdate)); - - var locatorRegisterCloakFieldController = typeof(Locator).GetMethod(nameof(Locator.RegisterCloakFieldController)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(locatorRegisterCloakFieldController, typeof(Patches), nameof(Patches.OnLocatorRegisterCloakFieldController)); - - // Lot of audio signal stuff - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("SignalNameToString", typeof(Patches), nameof(Patches.OnAudioSignalSignalNameToString)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("IndexToFrequency", typeof(Patches), nameof(Patches.OnAudioSignalIndexToFrequency)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("FrequencyToIndex", typeof(Patches), nameof(Patches.OnAudioSignalFrequencyToIndex)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("FrequencyToString", typeof(Patches), nameof(Patches.OnAudioSignalFrequencyToString)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Awake", typeof(Patches), nameof(Patches.OnSignalscopeAwake)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("SwitchFrequencyFilter", typeof(Patches), nameof(Patches.OnSignalscopeSwitchFrequencyFilter)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("UpdateSignalStrength", typeof(Patches), nameof(Patches.OnAudioSignalUpdateSignalStrength)); - - var playerDataKnowsSignal = typeof(PlayerData).GetMethod("KnowsSignal"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataKnowsSignal, typeof(Patches), nameof(Patches.OnPlayerDataKnowsSignal)); - var playerDataLearnSignal = typeof(PlayerData).GetMethod("LearnSignal"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataLearnSignal, typeof(Patches), nameof(Patches.OnPlayerDataLearnSignal)); - var playerDataKnowsFrequency = typeof(PlayerData).GetMethod("KnowsFrequency"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataKnowsFrequency, typeof(Patches), nameof(Patches.OnPlayerDataKnowsFrequency)); - var playerDataLearnFrequency = typeof(PlayerData).GetMethod("LearnFrequency"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataLearnFrequency, typeof(Patches), nameof(Patches.OnPlayerDataLearnFrequency)); - var playerDataKnowsMultipleFrequencies = typeof(PlayerData).GetMethod("KnowsMultipleFrequencies"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataKnowsMultipleFrequencies, typeof(Patches), nameof(Patches.OnPlayerDataKnowsMultipleFrequencies)); - var playerDataResetGame = typeof(PlayerData).GetMethod("ResetGame"); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix(playerDataResetGame, typeof(Patches), nameof(Patches.OnPlayerDataResetGame)); - - var playerDataAddNewlyRevealedFactID = typeof(PlayerData).GetMethod("AddNewlyRevealedFactID"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataAddNewlyRevealedFactID, typeof(Patches), nameof(Patches.OnPlayerDataAddNewlyRevealedFactID)); - var playerDataGetNewlyRevealedFactIDs = typeof(PlayerData).GetMethod("GetNewlyRevealedFactIDs"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataGetNewlyRevealedFactIDs, typeof(Patches), nameof(Patches.OnPlayerDataGetNewlyRevealedFactIDs)); - var playerDataClearNewlyRevealedFactIDs = typeof(PlayerData).GetMethod("ClearNewlyRevealedFactIDs"); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(playerDataClearNewlyRevealedFactIDs, typeof(Patches), nameof(Patches.OnPlayerDataClearNewlyRevealedFactIDs)); - - - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Start", typeof(Patches), nameof(Patches.OnBlackHoleVolumeStart)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Awake", typeof(Patches), nameof(Patches.OnWhiteHoleVolumeAwake)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("UpdateOrbitalLaunchValues", typeof(Patches), nameof(Patches.OnProbeLauncherUpdateOrbitalLaunchValues)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("IsLaunched", typeof(Patches), nameof(Patches.OnSurveyorProbeIsLaunched)); - - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("SpawnPlayer", typeof(Patches), nameof(Patches.OnPlayerSpawnerSpawnPlayerPreFix)); - - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("KillPlayer", typeof(Patches), nameof(Patches.OnDeathManagerKillPlayer)); - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("ReadTranslationalInput", typeof(Patches), nameof(Patches.OnShipThrusterControllerReadTranslationalInput)); - - // Postfixes - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("Awake", typeof(Patches), nameof(Patches.OnMapControllerAwake)); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix("OnTargetReferenceFrame", typeof(Patches), nameof(Patches.OnMapControllerOnTargetReferenceFrame)); - - Main.Instance.ModHelper.HarmonyHelper.AddPrefix("Awake", typeof(Patches), nameof(Patches.OnScrollItemAwake)); - } - - public static bool CheckShipOutersideSolarSystem(PlayerState __instance, ref bool __result) - { - if (PlayerState._inBrambleDimension) return false; - - Transform sunTransform = Locator.GetSunTransform(); - OWRigidbody shipBody = Locator.GetShipBody(); - var maxDist2 = Mathf.Max(900000000f, Main.FurthestOrbit * Main.FurthestOrbit * 2f); - __result = sunTransform != null && shipBody != null && (sunTransform.position - shipBody.transform.position).sqrMagnitude > maxDist2; - return false; - } - - public static void OnMapControllerAwake(MapController __instance, ref float ____maxPanDistance, ref float ____maxZoomDistance, ref float ____minPitchAngle, ref float ____zoomSpeed) - { - ____maxPanDistance = Main.FurthestOrbit * 1.5f; - ____maxZoomDistance *= 6f; - ____minPitchAngle = -90f; - ____zoomSpeed *= 4f; - __instance._mapCamera.farClipPlane = Main.FurthestOrbit * 10f; - } - - public static bool OnSunLightParamUpdaterLateUpdate(SunLightParamUpdater __instance) - { - if (__instance.sunLight) - { - Vector3 position = __instance.transform.position; - float w = 2000f; - if (__instance._sunController != null) - { - w = (__instance._sunController.HasSupernovaStarted() ? __instance._sunController.GetSupernovaRadius() : __instance._sunController.GetSurfaceRadius()); - } - float range = __instance.sunLight.range; - Color color = (__instance._sunLightController != null) ? __instance._sunLightController.sunColor : __instance.sunLight.color; - float w2 = (__instance._sunLightController != null) ? __instance._sunLightController.sunIntensity : __instance.sunLight.intensity; - Shader.SetGlobalVector(__instance._propID_SunPosition, new Vector4(position.x, position.y, position.z, w)); - Shader.SetGlobalVector(__instance._propID_OWSunPositionRange, new Vector4(position.x, position.y, position.z, 1f / (range * range))); - Shader.SetGlobalVector(__instance._propID_OWSunColorIntensity, new Vector4(color.r, color.g, color.b, w2)); - } - - return false; - } - - public static bool OnSunSurfaceAudioControllerUpdate(SunSurfaceAudioController __instance) - { - if (__instance._sunController != null) return true; - - var surfaceRadius = __instance.transform.parent.parent.localScale.magnitude; - float value = Mathf.Max(0f, Vector3.Distance(Locator.GetPlayerCamera().transform.position, __instance.transform.position) - surfaceRadius); - float num = Mathf.InverseLerp(1600f, 100f, value); - __instance._audioSource.SetLocalVolume(num * num * __instance._fade); - return false; - } - - #region AudioSignal - - public static bool OnAudioSignalSignalNameToString(SignalName __0, ref string __result) - { - var customSignalName = SignalBuilder.GetCustomSignalName(__0); - if (customSignalName == null) return true; - else - { - __result = TranslationHandler.GetTranslation(customSignalName, TranslationHandler.TextType.UI).ToUpper(); - return false; - } - } - - public static bool OnAudioSignalFrequencyToIndex(SignalFrequency __0, ref int __result) - { - switch(__0) - { - case (SignalFrequency.Default): - __result = 0; - break; - case (SignalFrequency.Traveler): - __result = 1; - break; - case (SignalFrequency.Quantum): - __result = 2; - break; - case (SignalFrequency.EscapePod): - __result = 3; - break; - case (SignalFrequency.WarpCore): - __result = 4; - break; - case (SignalFrequency.HideAndSeek): - __result = 5; - break; - case (SignalFrequency.Radio): - __result = 6; - break; - case (SignalFrequency.Statue): - __result = 7; - break; - default: - // Frequencies are in powers of 2 - __result = (int)(Mathf.Log((float)__0) / Mathf.Log(2f)); - break; - } - - return false; - } - - public static bool OnAudioSignalIndexToFrequency(int __0, ref SignalFrequency __result) { - switch (__0) - { - case 0: - __result = SignalFrequency.Default; - break; - case 1: - __result = SignalFrequency.Traveler; - break; - case 2: - __result = SignalFrequency.Quantum; - break; - case 3: - __result = SignalFrequency.EscapePod; - break; - case 4: - __result = SignalFrequency.WarpCore; - break; - case 5: - __result = SignalFrequency.HideAndSeek; - break; - case 6: - __result = SignalFrequency.Radio; - break; - case 7: - __result = SignalFrequency.Statue; - break; - default: - __result = (SignalFrequency)(Math.Pow(2, __0)); - break; - } - return false; - } - - public static bool OnAudioSignalFrequencyToString(SignalFrequency __0, ref string __result) - { - var customName = SignalBuilder.GetCustomFrequencyName(__0); - if (customName != null && customName != "") - { - if (NewHorizonsData.KnowsFrequency(customName)) __result = TranslationHandler.GetTranslation(customName, TranslationHandler.TextType.UI).ToUpper(); - else __result = UITextLibrary.GetString(UITextType.SignalFreqUnidentified); - return false; - } - return true; - } - - public static bool OnAudioSignalUpdateSignalStrength(AudioSignal __instance, Signalscope __0, float __1) - { - // I hate this - if(__instance is CloakedAudioSignal) - { - ((CloakedAudioSignal)__instance).UpdateSignalStrength(__0, __1); - return false; - } - return true; - } - #endregion - - #region Signalscope - public static bool OnSignalscopeAwake(Signalscope __instance, ref AudioSignal[] ____strongestSignals) - { - ____strongestSignals = new AudioSignal[8]; - return true; - } - - public static bool OnSignalscopeSwitchFrequencyFilter(Signalscope __instance, int __0) - { - var increment = __0; - var count = SignalBuilder.NumberOfFrequencies; - __instance._frequencyFilterIndex += increment; - __instance._frequencyFilterIndex = ((__instance._frequencyFilterIndex >= count) ? 0 : __instance._frequencyFilterIndex); - __instance._frequencyFilterIndex = ((__instance._frequencyFilterIndex < 0) ? count - 1 : __instance._frequencyFilterIndex); - SignalFrequency signalFrequency = AudioSignal.IndexToFrequency(__instance._frequencyFilterIndex); - - if (!PlayerData.KnowsFrequency(signalFrequency) && (!__instance._isUnknownFreqNearby || __instance._unknownFrequency != signalFrequency)) - { - __instance.SwitchFrequencyFilter(increment); - } - return false; - } - - #endregion f - - #region PlayerData - public static bool OnPlayerDataKnowsFrequency(SignalFrequency __0, ref bool __result) - { - var freqString = SignalBuilder.GetCustomFrequencyName(__0); - - if (freqString != null && freqString != "") - { - __result = NewHorizonsData.KnowsFrequency(freqString); - return false; - } - return true; - } - - public static bool OnPlayerDataLearnFrequency(SignalFrequency __0) - { - var freqString = SignalBuilder.GetCustomFrequencyName(__0); - if (freqString != null && freqString != "") - { - NewHorizonsData.LearnFrequency(freqString); - return false; - } - return true; - } - - public static bool OnPlayerDataKnowsSignal(SignalName __0, ref bool __result) - { - var customSignalName = SignalBuilder.GetCustomSignalName(__0); - if (customSignalName != null) - { - __result = NewHorizonsData.KnowsSignal(customSignalName); - return false; - } - return true; - } - - public static bool OnPlayerDataLearnSignal(SignalName __0) - { - var customSignalName = SignalBuilder.GetCustomSignalName(__0); - if (customSignalName != null) - { - if (!NewHorizonsData.KnowsSignal(customSignalName)) NewHorizonsData.LearnSignal(customSignalName); - return false; - } - return true; - } - - public static bool OnPlayerDataKnowsMultipleFrequencies(ref bool __result) - { - if (NewHorizonsData.KnowsMultipleFrequencies()) - { - __result = true; - return false; - } - return true; - } - - public static bool OnPlayerDataAddNewlyRevealedFactID(string __0) - { - if (ShipLogHandler.IsModdedFact(__0)) - { - NewHorizonsData.AddNewlyRevealedFactID(__0); - return false; - } - else - { - return true; - } - } - - public static bool OnPlayerDataGetNewlyRevealedFactIDs(ref List __result) - { - __result = PlayerData._currentGameSave.newlyRevealedFactIDs.Concat(NewHorizonsData.GetNewlyRevealedFactIDs()).ToList(); - return false; - } - - public static bool OnPlayerDataClearNewlyRevealedFactIDs() - { - PlayerData._currentGameSave.newlyRevealedFactIDs.Clear(); - NewHorizonsData.ClearNewlyRevealedFactIDs(); - return false; - } - - public static void OnPlayerDataResetGame() - { - NewHorizonsData.Reset(); - } - #endregion - - public static bool OnBlackHoleVolumeStart(BlackHoleVolume __instance) - { - return __instance._whiteHole == null; - } - - public static bool OnWhiteHoleVolumeAwake(WhiteHoleVolume __instance) - { - __instance._growQueue = new List(8); - __instance._growQueueLocationData = new List(8); - __instance._ejectedBodyList = new List(64); - try - { - __instance._whiteHoleBody = __instance.gameObject.GetAttachedOWRigidbody(false); - __instance._whiteHoleProxyShadowSuperGroup = __instance._whiteHoleBody.GetComponentInChildren(); - __instance._fluidVolume = __instance.gameObject.GetRequiredComponent(); - } - catch (Exception) { } - return false; - } - - public static bool OnProbeLauncherUpdateOrbitalLaunchValues(ProbeLauncher __instance) - { - return (Locator.GetPlayerRulesetDetector()?.GetPlanetoidRuleset()?.GetGravityVolume() != null); - } - - public static bool OnSurveyorProbeIsLaunched(SurveyorProbe __instance, ref bool __result) - { - try - { - __result = __instance.gameObject.activeSelf; - } - catch(Exception) - { - __result = true; - } - return false; - } - - public static void OnMapControllerOnTargetReferenceFrame(MapController __instance, ReferenceFrame __0) - { - __instance._isLockedOntoMapSatellite = true; - } - - - public static void OnPlayerSpawnerSpawnPlayerPreFix(PlayerSpawner __instance) - { - Logger.Log("Player spawning"); - __instance.SetInitialSpawnPoint(Main.SystemDict[Main.Instance.CurrentStarSystem].SpawnPoint); - } - - public static bool OnDeathManagerKillPlayer() - { - return (Main.Instance.CurrentStarSystem != "EyeOfTheUniverse"); - } - - public static bool OnShipThrusterControllerReadTranslationalInput(ShipThrusterController __instance, ref Vector3 __result) - { - if (Main.Instance.CurrentStarSystem != "EyeOfTheUniverse") return true; - - float value = OWInput.GetValue(InputLibrary.thrustX, InputMode.All); - float value2 = OWInput.GetValue(InputLibrary.thrustZ, InputMode.All); - float value3 = OWInput.GetValue(InputLibrary.thrustUp, InputMode.All); - float value4 = OWInput.GetValue(InputLibrary.thrustDown, InputMode.All); - if (!OWInput.IsInputMode(InputMode.ShipCockpit | InputMode.LandingCam)) - { - __result = Vector3.zero; - return false; - } - if (!__instance._shipResources.AreThrustersUsable()) - { - __result = Vector3.zero; - return false; - } - if (__instance._autopilot.IsFlyingToDestination()) - { - __result = Vector3.zero; - return false; - } - Vector3 vector = new Vector3(value, 0f, value2); - if (vector.sqrMagnitude > 1f) - { - vector.Normalize(); - } - vector.y = value3 - value4; - if (__instance._requireIgnition && __instance._landingManager.IsLanded()) - { - vector.x = 0f; - vector.z = 0f; - vector.y = Mathf.Clamp01(vector.y); - if (!__instance._isIgniting && __instance._lastTranslationalInput.y <= 0f && vector.y > 0f) - { - __instance._isIgniting = true; - __instance._ignitionTime = Time.time; - GlobalMessenger.FireEvent("StartShipIgnition"); - } - if (__instance._isIgniting) - { - if (vector.y <= 0f) - { - __instance._isIgniting = false; - GlobalMessenger.FireEvent("CancelShipIgnition"); - } - if (Time.time < __instance._ignitionTime + __instance._ignitionDuration) - { - vector.y = 0f; - } - else - { - __instance._isIgniting = false; - __instance._requireIgnition = false; - GlobalMessenger.FireEvent("CompleteShipIgnition"); - RumbleManager.PlayShipIgnition(); - } - } - } - float d = __instance._thrusterModel.GetMaxTranslationalThrust() / __instance._thrusterModel.GetMaxTranslationalThrust(); - Vector3 vector2 = vector * d; - if (__instance._limitOrbitSpeed && vector2.magnitude > 0f) - { - Vector3 vector3 = __instance._landingRF.GetOWRigidBody().GetWorldCenterOfMass() - __instance._shipBody.GetWorldCenterOfMass(); - Vector3 vector4 = __instance._shipBody.GetVelocity() - __instance._landingRF.GetVelocity(); - Vector3 vector5 = vector4 - Vector3.Project(vector4, vector3); - Vector3 vector6 = Quaternion.FromToRotation(-__instance._shipBody.transform.up, vector3) * __instance._shipBody.transform.TransformDirection(vector2 * __instance._thrusterModel.GetMaxTranslationalThrust()); - Vector3 vector7 = Vector3.Project(vector6, vector3); - Vector3 vector8 = vector6 - vector7; - Vector3 a = vector5 + vector8 * Time.deltaTime; - float magnitude = a.magnitude; - float orbitSpeed = __instance._landingRF.GetOrbitSpeed(vector3.magnitude); - if (magnitude > orbitSpeed) - { - a = a.normalized * orbitSpeed; - vector8 = (a - vector5) / Time.deltaTime; - vector6 = vector7 + vector8; - vector2 = __instance._shipBody.transform.InverseTransformDirection(vector6 / __instance._thrusterModel.GetMaxTranslationalThrust()); - } - } - __instance._lastTranslationalInput = vector; - __result = vector2; - - return false; - } - - public static bool OnLocatorRegisterCloakFieldController() - { - return Locator._cloakFieldController == null; - } - - public static bool OnScrollItemAwake(ScrollItem __instance) - { - try - { - __instance._type = ItemType.Scroll; - __instance._nomaiWallText = __instance.GetComponentInChildren(); - if (__instance._nomaiWallText == null) - { - Logger.LogError("No NomaiWallText found!"); - return false; - } - __instance._nomaiWallText.InitializeAsWhiteboardText(); - - // base.awake - //base.awake - if (__instance._sector == null) - { - __instance._sector = __instance.GetComponentInParent(); - } - if (__instance._sector != null) - { - __instance._sector.OnOccupantEnterSector += __instance.OnSectorOccupantAdded; - __instance._sector.OnOccupantExitSector += __instance.OnSectorOccupantRemoved; - __instance._sector.OnSectorOccupantsUpdated += __instance.OnSectorOccupantsUpdated; - } - // back - - if (!__instance._prebuilt) - { - __instance.FindComponentsInHierarchy(); - } - __instance._parentFragment = __instance.GetComponentInParent(); - if (__instance._parentFragment != null) - { - __instance._parentFragment.OnChangeSector += __instance.OnParentFragmentChangeSector; - } - GlobalMessenger.AddListener("EnterMapView", new Callback(__instance.OnEnterMapView)); - GlobalMessenger.AddListener("ExitMapView", new Callback(__instance.OnExitMapView)); - - // Back to normal stuff - for (int i = 0; i < __instance._colliders.Length; i++) - { - if (__instance._colliders[i].GetComponent() != null) - { - __instance._colliders[i] = null; - } - } - return false; - } - catch(Exception e) - { - Logger.LogError($"{e.Message}, {e.StackTrace}"); - } - return false; - } - } -} diff --git a/NewHorizons/Tools/TranslationPatches.cs b/NewHorizons/Tools/TranslationPatches.cs deleted file mode 100644 index 72012687..00000000 --- a/NewHorizons/Tools/TranslationPatches.cs +++ /dev/null @@ -1,52 +0,0 @@ -using NewHorizons.Components.Orbital; -using NewHorizons.Handlers; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons.Tools -{ - public static class TranslationPatches - { - public static void Apply() - { - Main.Instance.ModHelper.HarmonyHelper.AddPrefix(nameof(ReferenceFrame.GetHUDDisplayName), typeof(TranslationPatches), nameof(TranslationPatches.GetHUDDisplayName)); - - var canvasMapMarkerInit = typeof(CanvasMapMarker).GetMethod(nameof(CanvasMapMarker.Init), new Type[] { typeof(Canvas), typeof(Transform), typeof(string) }); - Main.Instance.ModHelper.HarmonyHelper.AddPostfix(canvasMapMarkerInit, typeof(TranslationPatches), nameof(TranslationPatches.OnCanvasMapMarkerInit)); - - Main.Instance.ModHelper.HarmonyHelper.AddPostfix(nameof(CanvasMapMarker.SetLabel), typeof(TranslationPatches), nameof(TranslationPatches.OnCanvasMapMarkerSetLabel)); - - } - - public static bool GetHUDDisplayName(ReferenceFrame __instance, ref string __result) - { - var ao = __instance.GetAstroObject(); - - if (ao == null) return true; - - if(ao is NHAstroObject) - { - if((ao as NHAstroObject).HideDisplayName) __result = ""; - else __result = TranslationHandler.GetTranslation(ao.GetCustomName(), TranslationHandler.TextType.UI); - return false; - } - - return true; - } - - public static void OnCanvasMapMarkerInit(CanvasMapMarker __instance) - { - __instance._label = TranslationHandler.GetTranslation(__instance._label, TranslationHandler.TextType.UI); - } - - public static void OnCanvasMapMarkerSetLabel(CanvasMapMarker __instance) - { - __instance._label = TranslationHandler.GetTranslation(__instance._label, TranslationHandler.TextType.UI); - } - } -} From 51f68030b265c889cab462af50fde5690b75cb97 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 20:15:34 -0400 Subject: [PATCH 09/15] Going to use the mock tornados --- NewHorizons/Builder/Props/TornadoBuilder.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/NewHorizons/Builder/Props/TornadoBuilder.cs b/NewHorizons/Builder/Props/TornadoBuilder.cs index 34f128af..ad16c040 100644 --- a/NewHorizons/Builder/Props/TornadoBuilder.cs +++ b/NewHorizons/Builder/Props/TornadoBuilder.cs @@ -38,11 +38,11 @@ namespace NewHorizons.Builder.Props return; } - var prefab = GameObject.Find("GiantsDeep_Body/Sector_GD/Sector_GDInterior/Tornadoes_GDInterior/MovingTornadoes/Root/UpTornado_Pivot (2)"); - + var upPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockUpTornado"); + var downPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockDownTornado"); // Default radius is 40, height is 837.0669 - var tornadoGO = prefab.InstantiateInactive(); + var tornadoGO = upPrefab.InstantiateInactive(); tornadoGO.transform.parent = sector?.transform ?? go.transform; tornadoGO.transform.localPosition = Vector3.zero; var tornado = tornadoGO.GetComponent(); From 7d86dd56c7065980ab03edd976b9f0a8abbd8807 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 22:27:17 -0400 Subject: [PATCH 10/15] Improve raft handling --- NewHorizons/Patches/RaftPatches.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/NewHorizons/Patches/RaftPatches.cs b/NewHorizons/Patches/RaftPatches.cs index 331edd69..79af3b4b 100644 --- a/NewHorizons/Patches/RaftPatches.cs +++ b/NewHorizons/Patches/RaftPatches.cs @@ -103,10 +103,9 @@ namespace NewHorizons.Patches var alignmentDirection = (__instance.transform.position - __instance._alignmentFluid.transform.position).normalized; var degreesToTarget = Vector3.Angle(currentDirection, alignmentDirection); - var adjustedSlerpRate = Mathf.Clamp01(10f / degreesToTarget * Time.fixedDeltaTime); + var adjustedSlerpRate = Mathf.Clamp01(0.01f * degreesToTarget * Time.fixedDeltaTime); Vector3 a = OWPhysics.FromToAngularVelocity(currentDirection, alignmentDirection); - //__instance._owRigidbody.SetAngularVelocity(Vector3.zero); __instance._owRigidbody.AddAngularVelocityChange(a * adjustedSlerpRate); } From 859adc0ff4e771752d8913c68671b23376ec6270 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 22:27:25 -0400 Subject: [PATCH 11/15] Bump version number --- NewHorizons/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NewHorizons/manifest.json b/NewHorizons/manifest.json index 3fcd535a..93744c43 100644 --- a/NewHorizons/manifest.json +++ b/NewHorizons/manifest.json @@ -3,7 +3,7 @@ "author": "xen, Bwc9876, & Book", "name": "New Horizons", "uniqueName": "xen.NewHorizons", - "version": "0.12.0", + "version": "0.13.0", "owmlVersion": "2.1.0", "dependencies": [ "PacificEngine.OW_CommonResources" ], "conflicts": [ "Raicuparta.QuantumSpaceBuddies", "Vesper.AutoResume" ], From 9faa08a0c8a5eeb6106a65aaa11a161d4072e95f Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 22:27:54 -0400 Subject: [PATCH 12/15] Finish tornados (missing sound) --- NewHorizons/Builder/Props/PropBuildManager.cs | 2 +- NewHorizons/Builder/Props/TornadoBuilder.cs | 108 +++++++++--------- .../Components/NHTornadoWanderController.cs | 56 +++++++++ NewHorizons/External/PropModule.cs | 7 +- 4 files changed, 118 insertions(+), 55 deletions(-) create mode 100644 NewHorizons/Components/NHTornadoWanderController.cs diff --git a/NewHorizons/Builder/Props/PropBuildManager.cs b/NewHorizons/Builder/Props/PropBuildManager.cs index c64a47f5..95112980 100644 --- a/NewHorizons/Builder/Props/PropBuildManager.cs +++ b/NewHorizons/Builder/Props/PropBuildManager.cs @@ -49,7 +49,7 @@ namespace NewHorizons.Builder.Props { foreach(var tornadoInfo in config.Props.Tornados) { - //TornadoBuilder.Make(go, sector, tornadoInfo, config.Atmosphere?.Cloud != null); + TornadoBuilder.Make(go, sector, tornadoInfo, config.Atmosphere?.Cloud != null); } } if (config.Props.Volcanoes != null) diff --git a/NewHorizons/Builder/Props/TornadoBuilder.cs b/NewHorizons/Builder/Props/TornadoBuilder.cs index ad16c040..64329a21 100644 --- a/NewHorizons/Builder/Props/TornadoBuilder.cs +++ b/NewHorizons/Builder/Props/TornadoBuilder.cs @@ -1,5 +1,6 @@ using NewHorizons.Components; using NewHorizons.External; +using NewHorizons.Handlers; using NewHorizons.Utility; using System; using System.Collections.Generic; @@ -8,88 +9,91 @@ using System.Text; using System.Threading.Tasks; using UnityEngine; using Logger = NewHorizons.Utility.Logger; +using Random = UnityEngine.Random; namespace NewHorizons.Builder.Props { public static class TornadoBuilder { - public static string tornadoParentName = "Tornados"; + private static GameObject upPrefab; + private static GameObject downPrefab; public static void Make(GameObject go, Sector sector, PropModule.TornadoInfo info, bool hasClouds) { - // If we are given elevation choose a random position - Vector3 position; - float elevation = 0f; - - if (info.position != null) + if (upPrefab == null) { - position = info.position; + upPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockUpTornado").InstantiateInactive(); + upPrefab.name = "Tornado_Up_Prefab"; + } + if(downPrefab == null) + { + downPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockDownTornado").InstantiateInactive(); + downPrefab.name = "Tornado_Down_Prefab"; + downPrefab.name = "Tornado_Down_Prefab"; + } + + float elevation; + Vector3 position; + if(info.position != null) + { + position = info.position ?? Random.onUnitSphere * info.elevation; elevation = position.magnitude; } - else if (info.elevation != 0f) + else if(info.elevation != 0) { - Logger.Log("Giving tornado random pos"); - position = UnityEngine.Random.insideUnitSphere * info.elevation; + position = Random.onUnitSphere * info.elevation; elevation = info.elevation; } else { - Logger.LogError($"Couldn't make tornado for {go.name}: No elevation or position was given"); + Logger.LogError($"Need either a position or an elevation for tornados"); return; } - var upPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockUpTornado"); - var downPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockDownTornado"); - // Default radius is 40, height is 837.0669 + var tornadoGO = info.downwards ? downPrefab.InstantiateInactive() : upPrefab.InstantiateInactive(); + tornadoGO.transform.parent = sector.transform; + tornadoGO.transform.localPosition = position; + tornadoGO.transform.rotation = Quaternion.FromToRotation(Vector3.up, sector.transform.TransformDirection(position.normalized)); - var tornadoGO = upPrefab.InstantiateInactive(); - tornadoGO.transform.parent = sector?.transform ?? go.transform; - tornadoGO.transform.localPosition = Vector3.zero; - var tornado = tornadoGO.GetComponent(); - tornado.SetSector(sector); + var scale = info.height == 0 ? 1 : info.height / 10f; - var height = 837.0669f; - if (info.height != 0f) height = info.height; + tornadoGO.transform.localScale = Vector3.one * scale; - var width = 40f; - if (info.width != 0f) width = info.width; + var controller = tornadoGO.GetComponent(); + controller.SetSector(sector); - tornado._bottomBone.localPosition = new Vector3(0, elevation, 0); - tornado._midBone.localPosition = new Vector3(0, elevation + height / 2f, 0); - tornado._topBone.localPosition = new Vector3(0, elevation + height, 0); + controller._bottomStartPos = Vector3.up * -20; + controller._midStartPos = Vector3.up * 150; + controller._topStartPos = Vector3.up * 300; - tornado._startActive = false; + controller._bottomBone.localPosition = controller._bottomStartPos; + controller._midBone.localPosition = controller._midStartPos; + controller._topBone.localPosition = controller._topStartPos; + + OWAssetHandler.LoadObject(tornadoGO); + sector.OnOccupantEnterSector += (sd) => OWAssetHandler.LoadObject(tornadoGO); - // TODO make these settings - tornado._wanderRate = 0.5f; - tornado._wanderDegreesX = 45f; - tornado._wanderDegreesZ = 45f; + tornadoGO.GetComponentInChildren().enabled = true; - /* - if (!hasClouds) + if(info.tint != null) { - var fix = tornadoGO.AddComponent(); - fix.SetSector(sector); - - var top = tornadoGO.transform.Find("UpTornado/Effects_GD_TornadoCyclone/Tornado_Top"); - - // Get rid of the bit that appears above the clouds - GameObject.Destroy(top.transform.Find("Effects_GD_TornadoCloudCap_Large")?.gameObject); - GameObject.Destroy(top.transform.Find("Effects_GD_TornadoCloudCap_Medium")?.gameObject); - GameObject.Destroy(top.transform.Find("Effects_GD_TornadoCloudCap_Small")?.gameObject); - - var top_objects = new GameObject[3]; - top_objects[0] = GameObject.Instantiate(top.transform.Find("Effects_GD_TornadoCloudBlend_Large").gameObject, top.transform); - top_objects[1] = GameObject.Instantiate(top.transform.Find("Effects_GD_TornadoCloudBlend_Medium").gameObject, top.transform); - top_objects[2] = GameObject.Instantiate(top.transform.Find("Effects_GD_TornadoCloudBlend_Small").gameObject, top.transform); - - foreach(var obj in top_objects) + var colour = info.tint.ToColor(); + foreach(var renderer in tornadoGO.GetComponentsInChildren()) { - obj.transform.localPosition = new Vector3(0, -20, 0); - obj.transform.localRotation = Quaternion.Euler(180, 0, 0); + renderer.material.color = colour; + renderer.material.SetColor("_DetailColor", colour); + renderer.material.SetColor("_TintColor", colour); } } - */ + + if(info.wanderRate != 0) + { + var wanderer = tornadoGO.AddComponent(); + wanderer.wanderRate = info.wanderRate; + wanderer.wanderDegreesX = info.wanderDegreesX; + wanderer.wanderDegreesZ = info.wanderDegreesZ; + wanderer.sector = sector; + } tornadoGO.SetActive(true); } diff --git a/NewHorizons/Components/NHTornadoWanderController.cs b/NewHorizons/Components/NHTornadoWanderController.cs new file mode 100644 index 00000000..abb59c2e --- /dev/null +++ b/NewHorizons/Components/NHTornadoWanderController.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using Random = UnityEngine.Random; + +namespace NewHorizons.Components +{ + public class NHTornadoWanderController : MonoBehaviour + { + public float wanderRate; + public float wanderDegreesX; + public float wanderDegreesZ; + public Sector sector; + + private float noiseOffset; + private float startDegreesX; + private float startDegreesZ; + + private float elevation; + + public void Awake() + { + noiseOffset = Random.value; + + var x = transform.localPosition.x; + var y = transform.localPosition.y; + var z = transform.localPosition.z; + + elevation = Mathf.Sqrt(x * x + y * y + z * z); + + startDegreesX = Mathf.Rad2Deg * Mathf.Atan2(y, x); //theta + startDegreesZ = Mathf.Rad2Deg * Mathf.Acos(z / elevation); //phi + } + + public void Update() + { + float num = Mathf.PerlinNoise(Time.time * wanderRate + noiseOffset, 0f) * 2f - 1f; + float num2 = Mathf.PerlinNoise(Time.time * wanderRate + noiseOffset, 5f) * 2f - 1f; + + var newDegreesX = startDegreesX + num * wanderDegreesX; + var newDegreesZ = startDegreesZ + num2 * wanderDegreesZ; + + var newX = elevation * Mathf.Sin(Mathf.Deg2Rad * newDegreesZ) * Mathf.Cos(Mathf.Deg2Rad * newDegreesX); + var newY = elevation * Mathf.Sin(Mathf.Deg2Rad * newDegreesZ) * Mathf.Sin(Mathf.Deg2Rad * newDegreesX); + var newZ = elevation * Mathf.Cos(Mathf.Deg2Rad * newDegreesZ); + + var newPos = new Vector3(newX, newY, newZ); + + transform.localPosition = newPos; + transform.rotation = Quaternion.FromToRotation(Vector3.up, sector.transform.TransformDirection(newPos.normalized)); + } + } +} diff --git a/NewHorizons/External/PropModule.cs b/NewHorizons/External/PropModule.cs index 6d2c631e..ab95efd6 100644 --- a/NewHorizons/External/PropModule.cs +++ b/NewHorizons/External/PropModule.cs @@ -57,11 +57,14 @@ namespace NewHorizons.External public class TornadoInfo { + public MVector3 position; public float elevation; - public MVector3 position = null; public float height; - public float width; public MColor tint; + public bool downwards; + public float wanderRate; + public float wanderDegreesX = 45; + public float wanderDegreesZ = 45; } public class VolcanoInfo From 21ab007efd19f79c0597ea4ebf4e2d4b596323ef Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 5 May 2022 22:46:19 -0400 Subject: [PATCH 13/15] Allow making copies of the stock system --- NewHorizons/External/Configs/StarSystemConfig.cs | 1 + NewHorizons/Handlers/PlanetCreationHandler.cs | 2 +- NewHorizons/Main.cs | 3 +++ NewHorizons/star_system_schema.json | 4 ++++ 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/NewHorizons/External/Configs/StarSystemConfig.cs b/NewHorizons/External/Configs/StarSystemConfig.cs index 76e43702..29f117ce 100644 --- a/NewHorizons/External/Configs/StarSystemConfig.cs +++ b/NewHorizons/External/Configs/StarSystemConfig.cs @@ -11,6 +11,7 @@ namespace NewHorizons.External.Configs { public bool canEnterViaWarpDrive = true; public bool startHere = false; + public bool destroyStockPlanets = true; public string factRequiredForWarp; public NomaiCoordinates coords; diff --git a/NewHorizons/Handlers/PlanetCreationHandler.cs b/NewHorizons/Handlers/PlanetCreationHandler.cs index 8a362255..a79cee0b 100644 --- a/NewHorizons/Handlers/PlanetCreationHandler.cs +++ b/NewHorizons/Handlers/PlanetCreationHandler.cs @@ -104,7 +104,7 @@ namespace NewHorizons.Handlers // I don't know what these do but they look really weird from a distance Main.Instance.ModHelper.Events.Unity.FireOnNextUpdate(PlanetDestroyer.RemoveAllProxies); - if (Main.Instance.CurrentStarSystem != "SolarSystem") PlanetDestroyer.RemoveSolarSystem(); + if (Main.SystemDict[Main.Instance.CurrentStarSystem].Config.destroyStockPlanets) PlanetDestroyer.RemoveSolarSystem(); } public static bool LoadBody(NewHorizonsBody body, bool defaultPrimaryToSun = false) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 5c4a3b73..30367959 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -110,9 +110,12 @@ namespace NewHorizons GlobalMessenger.AddListener("PlayerDeath", OnDeath); GlobalMessenger.AddListener("WakeUp", new Callback(OnWakeUp)); ShaderBundle = Main.Instance.ModHelper.Assets.LoadBundle("AssetBundle/shader"); + BodyDict["SolarSystem"] = new List(); BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(null), this); + SystemDict["SolarSystem"].Config.destroyStockPlanets = false; Logger.Log("Begin load of config files...", Logger.LogType.Log); diff --git a/NewHorizons/star_system_schema.json b/NewHorizons/star_system_schema.json index a10d191a..b31179ed 100644 --- a/NewHorizons/star_system_schema.json +++ b/NewHorizons/star_system_schema.json @@ -15,6 +15,10 @@ "factRequiredForWarp": { "type": "string", "description": "Set to the FactID that must be revealed before it can be warped to. Don't set `CanEnterViaWarpDrive` to false if you're using this, that would make no sense." + }, + "destroyStockPlanets": { + "type": "bool", + "description": "Do you want a clean slate for this star system? Or will it be a modified version of the original." } } } From b6789d6ded7e7f11bb747d5ddb54e79b56cd843c Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 6 May 2022 00:59:12 -0400 Subject: [PATCH 14/15] Add sounds to tornado --- NewHorizons/Builder/Props/RaftBuilder.cs | 2 +- NewHorizons/Builder/Props/TornadoBuilder.cs | 36 ++++++++++++++++- NewHorizons/Components/NHPlanetaryRaftFix.cs | 41 -------------------- 3 files changed, 36 insertions(+), 43 deletions(-) delete mode 100644 NewHorizons/Components/NHPlanetaryRaftFix.cs diff --git a/NewHorizons/Builder/Props/RaftBuilder.cs b/NewHorizons/Builder/Props/RaftBuilder.cs index 7e661295..0765df42 100644 --- a/NewHorizons/Builder/Props/RaftBuilder.cs +++ b/NewHorizons/Builder/Props/RaftBuilder.cs @@ -51,7 +51,7 @@ namespace NewHorizons.Builder.Props fluidDetector._alignmentFluid = waterVolume; // Light sensors - foreach(var lightSensor in raftObject.GetComponentsInChildren()) + foreach (var lightSensor in raftObject.GetComponentsInChildren()) { lightSensor._sector.OnSectorOccupantsUpdated -= lightSensor.OnSectorOccupantsUpdated; lightSensor._sector = sector; diff --git a/NewHorizons/Builder/Props/TornadoBuilder.cs b/NewHorizons/Builder/Props/TornadoBuilder.cs index 64329a21..16c0d11e 100644 --- a/NewHorizons/Builder/Props/TornadoBuilder.cs +++ b/NewHorizons/Builder/Props/TornadoBuilder.cs @@ -17,6 +17,7 @@ namespace NewHorizons.Builder.Props { private static GameObject upPrefab; private static GameObject downPrefab; + private static GameObject soundPrefab; public static void Make(GameObject go, Sector sector, PropModule.TornadoInfo info, bool hasClouds) { @@ -29,7 +30,11 @@ namespace NewHorizons.Builder.Props { downPrefab = GameObject.Find("BrittleHollow_Body/Sector_BH/Sector_SouthHemisphere/Sector_SouthPole/Sector_Observatory/Interactables_Observatory/MockDownTornado").InstantiateInactive(); downPrefab.name = "Tornado_Down_Prefab"; - downPrefab.name = "Tornado_Down_Prefab"; + } + if(soundPrefab == null) + { + soundPrefab = GameObject.Find("GiantsDeep_Body/Sector_GD/Sector_GDInterior/Tornadoes_GDInterior/SouthernTornadoes/DownTornado_Pivot/DownTornado/AudioRail").InstantiateInactive(); + soundPrefab.name = "AudioRail_Prefab"; } float elevation; @@ -55,13 +60,41 @@ namespace NewHorizons.Builder.Props tornadoGO.transform.localPosition = position; tornadoGO.transform.rotation = Quaternion.FromToRotation(Vector3.up, sector.transform.TransformDirection(position.normalized)); + // Add the sound thing before changing the scale + var soundGO = soundPrefab.InstantiateInactive(); + soundGO.name = "AudioRail"; + soundGO.transform.parent = tornadoGO.transform; + soundGO.transform.localPosition = Vector3.zero; + soundGO.transform.localRotation = Quaternion.identity; + + // Height of the tornado is 10 by default + var audioRail = soundGO.GetComponent(); + audioRail.SetSector(sector); + audioRail._railPointsRoot.GetChild(0).transform.localPosition = Vector3.zero; + audioRail._railPointsRoot.GetChild(1).transform.localPosition = Vector3.up * 10; + audioRail._railPoints = new Vector3[] + { + Vector3.zero, + Vector3.up * 10 + }; + + var audioSpreadController = soundGO.GetComponentInChildren(); + audioSpreadController.SetSector(sector); + + var audioSource = audioRail._audioTransform.GetComponent(); + audioSource.playOnAwake = true; + var scale = info.height == 0 ? 1 : info.height / 10f; tornadoGO.transform.localScale = Vector3.one * scale; + // Resize the distance it can be heard from to match roughly with the size + audioSource.maxDistance = 100 * scale; + var controller = tornadoGO.GetComponent(); controller.SetSector(sector); + // Found these values by messing around in unity explorer until it looked right controller._bottomStartPos = Vector3.up * -20; controller._midStartPos = Vector3.up * 150; controller._topStartPos = Vector3.up * 300; @@ -95,6 +128,7 @@ namespace NewHorizons.Builder.Props wanderer.sector = sector; } + soundGO.SetActive(true); tornadoGO.SetActive(true); } } diff --git a/NewHorizons/Components/NHPlanetaryRaftFix.cs b/NewHorizons/Components/NHPlanetaryRaftFix.cs deleted file mode 100644 index 4e5a9408..00000000 --- a/NewHorizons/Components/NHPlanetaryRaftFix.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using UnityEngine; -using Logger = NewHorizons.Utility.Logger; - -namespace NewHorizons.Components -{ - public class NHPlanetaryRaftFix : MonoBehaviour - { - private RaftController _raftController; - private RaftFluidDetector _fluidDetector; - private FluidVolume _fluidVolume; - private RaftEffectsController _effectsController; - - public void Awake() - { - _raftController = gameObject.GetComponent(); - _fluidDetector = _raftController._fluidDetector; - _fluidVolume = _fluidDetector._alignmentFluid; - _effectsController = _raftController._effectsController; - } - - public void FixedUpdate() - { - if (_raftController._raftBody.IsSuspended()) return; - if (!_raftController._playerInEffectsRange) return; - - // Normally this part won't get called because in RaftController it checks how submerged we are in the Ringworld river - // Just copy pasted it here using the actual fluid volume instead of making an ugly patch - float num = _fluidDetector.InFluidType(FluidVolume.Type.WATER) ? _fluidVolume.GetFractionSubmerged(_fluidDetector) : 0f; - bool allowMovement = num > 0.25f && num < 1f; - Logger.Log($"AllowMovement? [{allowMovement}]"); - allowMovement = true; - _effectsController.UpdateMovementAudio(allowMovement, _raftController._lightSensors); - _effectsController.UpdateGroundedAudio(_fluidDetector); - } - } -} From 1158ddcdc7b0db4e0ec8f942691238c41da96c72 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 6 May 2022 01:11:17 -0400 Subject: [PATCH 15/15] Add docs for tornado and raft --- NewHorizons/schema.json | 62 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/NewHorizons/schema.json b/NewHorizons/schema.json index 2641380f..cc2e8357 100644 --- a/NewHorizons/schema.json +++ b/NewHorizons/schema.json @@ -149,7 +149,7 @@ "type": "boolean", "description": "Should this planet ever be shown on the title screen", "default": "true" - } + }, "Base": { "type": "object", "additionalProperties": false, @@ -992,6 +992,66 @@ } } } + }, + "tornados": { + "type": "array", + "description": "Like those on Giant's Deep", + "items": { + "type": "object", + "additionalProperties": "false", + "properties": { + "position": { + "$ref": "#/$defs/vector3", + "description": "The position of this tornado." + }, + "elevation": { + "type": "number", + "description": "Alternative to setting the position. Will choose a random place at this elevation." + }, + "height": { + "type": "number", + "description": "The height of this tornado.", + "default": 30 + }, + "tint": { + "$ref": "#/$defs/color", + "description": "The colour of the tornado." + }, + "downwards": { + "type": "boolean", + "description": "Should it pull things downwards? Will push them upwards by default." + }, + "wanderRate": { + "type": "number", + "description": "The rate at which the tornado will wander around the planet. Set to 0 for it to be stationary. Should be around 0.1.", + "default": 0 + }, + "wanderDegreesX": { + "type": "number", + "description": "Angular distance from the starting position that it will wander, in terms of the angle around the x-axis.", + "default": 45 + }, + "wanderDegreesZ": { + "type": "number", + "description": "Angular distance from the starting position that it will wander, in terms of the angle around the z-axis.", + "default": 45 + } + } + } + }, + "rafts": { + "type": "array", + "description": "Like those in the DLC", + "items": { + "type": "object", + "additionalProperties": "false", + "properties": { + "position": { + "$ref": "#/$defs/vector3", + "description": "The position of this raft." + } + } + } } } },