From 0dfe9bf769a3c8c24ede2221a96c4cfd67b0b95f Mon Sep 17 00:00:00 2001 From: FreezeDriedMangoes Date: Sat, 21 May 2022 22:26:13 -0400 Subject: [PATCH] chore: fixed merge conflict with main --- NewHorizons/Builder/Props/DetailBuilder.cs | 10 +- NewHorizons/Main.cs | 946 ++++++++++----------- NewHorizons/Utility/DebugMenu.cs | 46 +- NewHorizons/Utility/DebugPropPlacer.cs | 6 +- NewHorizons/Utility/DebugRaycaster.cs | 82 +- NewHorizons/Utility/NewHorizonBody.cs | 42 +- 6 files changed, 586 insertions(+), 546 deletions(-) diff --git a/NewHorizons/Builder/Props/DetailBuilder.cs b/NewHorizons/Builder/Props/DetailBuilder.cs index 7dcf20f1..a87f216d 100644 --- a/NewHorizons/Builder/Props/DetailBuilder.cs +++ b/NewHorizons/Builder/Props/DetailBuilder.cs @@ -11,9 +11,9 @@ using Logger = NewHorizons.Utility.Logger; namespace NewHorizons.Builder.Props { public static class DetailBuilder - { - private static Dictionary detailInfoToCorrespondingSpawnedGameObject = new Dictionary(); - + { + private static Dictionary detailInfoToCorrespondingSpawnedGameObject = new Dictionary(); + public static GameObject GetSpawnedGameObjectByDetailInfo(PropModule.DetailInfo detail) { if (!detailInfoToCorrespondingSpawnedGameObject.ContainsKey(detail)) return null; @@ -74,8 +74,8 @@ namespace NewHorizons.Builder.Props GameObject.Destroy(detailGO); detailGO = newDetailGO; } - - detailInfoToCorrespondingSpawnedGameObject[detail] = detailGO; + + detailInfoToCorrespondingSpawnedGameObject[detail] = detailGO; } public static GameObject MakeDetail(GameObject go, Sector sector, string propToClone, MVector3 position, MVector3 rotation, float scale, bool alignWithNormal) diff --git a/NewHorizons/Main.cs b/NewHorizons/Main.cs index 311c0ad6..691621c6 100644 --- a/NewHorizons/Main.cs +++ b/NewHorizons/Main.cs @@ -1,473 +1,473 @@ -using HarmonyLib; -using NewHorizons.Builder.Props; -using NewHorizons.Components; -using NewHorizons.External.Configs; -using NewHorizons.External; -using NewHorizons.Handlers; -using NewHorizons.Utility; -using OWML.Common; -using OWML.ModHelper; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.SceneManagement; -using Logger = NewHorizons.Utility.Logger; -namespace NewHorizons -{ - public class Main : ModBehaviour - { - public static AssetBundle NHAssetBundle { get; private set; } - public static Main Instance { get; private set; } - - // Settings - public static bool Debug { get; private set; } - private static bool _useCustomTitleScreen; - private static bool _wasConfigured = false; - private static string _defaultSystemOverride; - - public static Dictionary SystemDict = new Dictionary(); - public static Dictionary> BodyDict = new Dictionary>(); - public static List MountedAddons = new List(); - - public static float SecondsLeftInLoop = -1; - - public static bool IsSystemReady { get; private set; } - public static float FurthestOrbit { get; set; } = 50000f; - - public string CurrentStarSystem { get { return Instance._currentStarSystem; } } - public bool IsWarping { get; private set; } = false; - public bool WearingSuit { get; private set; } = false; - - public static bool HasWarpDrive { get; private set; } = false; - - private string _defaultStarSystem = "SolarSystem"; - private string _currentStarSystem = "SolarSystem"; - private bool _isChangingStarSystem = false; - private bool _firstLoad = true; - private ShipWarpController _shipWarpController; - - // API events - public class StarSystemEvent : UnityEvent { } - public StarSystemEvent OnChangeStarSystem; - public StarSystemEvent OnStarSystemLoaded; - - // For warping to the eye system - private GameObject _ship; - - public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } - - public override object GetApi() - { - return new NewHorizonsApi(); - } - - 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); - - _defaultSystemOverride = config.GetSettingsValue("Default System Override"); - - 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 static void ResetConfigs(bool resetTranslation = true) - { - BodyDict.Clear(); - SystemDict.Clear(); - - BodyDict["SolarSystem"] = new List(); - BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr - SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) - { - Config = - { - destroyStockPlanets = false - } - }; - - if (!resetTranslation) return; - TranslationHandler.ClearTables(); - TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); - } - - public void Start() - { - // Patches - Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); - - OnChangeStarSystem = new StarSystemEvent(); - OnStarSystemLoaded = new StarSystemEvent(); - - SceneManager.sceneLoaded += OnSceneLoaded; - SceneManager.sceneUnloaded += OnSceneUnloaded; - - Instance = this; - GlobalMessenger.AddListener("PlayerDeath", OnDeath); - GlobalMessenger.AddListener("WakeUp", new Callback(OnWakeUp)); - NHAssetBundle = ModHelper.Assets.LoadBundle("AssetBundle/xen.newhorizons"); - - ResetConfigs(resetTranslation: false); - - Logger.Log("Begin load of config files...", Logger.LogType.Log); - - try - { - LoadConfigs(this); - } - catch (Exception) - { - Logger.LogWarning("Couldn't find planets folder"); - } - - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); - Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); - Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; - } - - public void OnDestroy() - { - Logger.Log($"Destroying NewHorizons"); - SceneManager.sceneLoaded -= OnSceneLoaded; - GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); - GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); - } - - private static void OnWakeUp() - { - IsSystemReady = true; - Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); - } - - private void OnSceneUnloaded(Scene scene) - { - SearchUtilities.ClearCache(); - ImageUtilities.ClearCache(); - AudioUtilities.ClearCache(); - AssetBundleUtilities.ClearCache(); - IsSystemReady = false; - } - - private void OnSceneLoaded(Scene scene, LoadSceneMode mode) - { - Logger.Log($"Scene Loaded: {scene.name} {mode}"); - - // Set time loop stuff if its enabled and if we're warping to a new place - if (_isChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) - { - TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); - // Prevent the OPC from firing - var launchController = GameObject.FindObjectOfType(); - if (launchController != null) - { - GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); - foreach (var fakeDebris in launchController._fakeDebrisBodies) - { - fakeDebris.gameObject.SetActive(false); - } - launchController.enabled = false; - } - var nomaiProbe = GameObject.Find("NomaiProbe_Body"); - if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); - } - - // Reset this - SecondsLeftInLoop = -1; - - _isChangingStarSystem = false; - - if (scene.name == "TitleScreen" && _useCustomTitleScreen) - { - TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); - } - - if (scene.name == "EyeOfTheUniverse" && IsWarping) - { - if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); - _ship.transform.position = new Vector3(50, 0, 0); - _ship.SetActive(true); - } - - if (scene.name == "SolarSystem") - { - foreach (var body in GameObject.FindObjectsOfType()) - { - Logger.Log($"{body.name}, {body.transform.rotation}"); - } - - if (_ship != null) - { - _ship = GameObject.Find("Ship_Body").InstantiateInactive(); - DontDestroyOnLoad(_ship); - } - - IsSystemReady = false; - - NewHorizonsData.Load(); - SignalBuilder.Init(); - AstroObjectLocator.Init(); - OWAssetHandler.Init(); - PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); - SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); - LoadTranslations(ModHelper.Manifest.ModFolderPath + "AssetBundle/", this); - // Warp drive - StarChartHandler.Init(SystemDict.Values.ToArray()); - HasWarpDrive = StarChartHandler.CanWarp(); - _shipWarpController = GameObject.Find("Ship_Body").AddComponent(); - _shipWarpController.Init(); - if (HasWarpDrive == true) EnableWarpDrive(); - - var shouldWarpIn = IsWarping && _shipWarpController != null; - Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpIn)); - - IsWarping = false; - - var map = GameObject.FindObjectOfType(); - if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; - - // Fix the map satellite - GameObject.Find("HearthianMapSatellite_Body").AddComponent(); - } - else - { - // Reset back to original solar system after going to main menu. - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarping = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - } - } - - // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here - private void OnSystemReady(bool shouldWarpIn) - { - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - Locator.GetPlayerBody().gameObject.AddComponent(); - - - if (shouldWarpIn) _shipWarpController.WarpIn(WearingSuit); - else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); - } - - public void EnableWarpDrive() - { - Logger.Log("Setting up warp drive"); - PlanetCreationHandler.LoadBody(LoadConfig(this, "AssetBundle/WarpDriveConfig.json")); - HasWarpDrive = true; - } - - - #region Load - public void LoadConfigs(IModBehaviour mod) - { - try - { - if (_firstLoad) - { - MountedAddons.Add(mod); - } - var folder = mod.ModHelper.Manifest.ModFolderPath; - - // Load systems first so that when we load bodies later we can check for missing ones - if (Directory.Exists(folder + @"systems\")) - { - foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json", SearchOption.AllDirectories)) - { - var name = Path.GetFileNameWithoutExtension(file); - - Logger.Log($"Loading system {name}"); - - var relativePath = file.Replace(folder, ""); - var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); - - if (starSystemConfig.startHere) - { - // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around - if (name != "SolarSystem") SetDefaultSystem(name); - } - - var system = new NewHorizonsSystem(name, starSystemConfig, mod); - SystemDict[name] = system; - } - } - if (Directory.Exists(folder + "planets")) - { - foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json", SearchOption.AllDirectories)) - { - var relativeDirectory = file.Replace(folder, ""); - var body = LoadConfig(mod, relativeDirectory); - - if (body != null) - { - // Wanna track the spawn point of each system - if (body.Config.Spawn != null) SystemDict[body.Config.StarSystem].Spawn = body.Config.Spawn; - - // Add the new planet to the planet dictionary - if (!BodyDict.ContainsKey(body.Config.StarSystem)) BodyDict[body.Config.StarSystem] = new List(); - BodyDict[body.Config.StarSystem].Add(body); - } - } - } - if (Directory.Exists(folder + @"translations\")) - { - LoadTranslations(folder, mod); - } - } - catch (Exception ex) - { - Logger.LogError($"{ex.Message}, {ex.StackTrace}"); - } - } - - private void LoadTranslations(string folder, IModBehaviour mod) - { - var foundFile = false; - foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) - { - if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; - - var relativeFile = $"translations/{language.ToString().ToLower()}.json"; - - if (File.Exists($"{folder}{relativeFile}")) - { - Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); - - var config = new TranslationConfig($"{folder}{relativeFile}"); - if (config == null) - { - Logger.Log($"Found {folder}{relativeFile} but couldn't load it"); - continue; - } - - foundFile = true; - - TranslationHandler.RegisterTranslation(language, config); - } - } - if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); - } - - public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativeDirectory) - { - NewHorizonsBody body = null; - try - { - var config = mod.ModHelper.Storage.Load(relativeDirectory); - config.Validate(); - - Logger.Log($"Loaded {config.Name}"); - - if (!SystemDict.ContainsKey(config.StarSystem)) - { - // Since we didn't load it earlier there shouldn't be a star system config - var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.StarSystem}.json"); - if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); - else Logger.LogWarning($"Loaded system config for {config.StarSystem}. Why wasn't this loaded earlier?"); - - var system = new NewHorizonsSystem(config.StarSystem, starSystemConfig, mod); - - SystemDict.Add(config.StarSystem, system); - - BodyDict.Add(config.StarSystem, new List()); - } - - body = new NewHorizonsBody(config, mod, relativeDirectory); - } - catch (Exception e) - { - Logger.LogError($"Couldn't load {relativeDirectory}: {e.Message}, is your Json formatted correctly?"); - } - - return body; - } - - public void SetDefaultSystem(string defaultSystem) - { - _defaultStarSystem = defaultSystem; - _currentStarSystem = defaultSystem; - } - - #endregion Load - - #region Change star system - public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false) - { - if (_isChangingStarSystem) return; - - OnChangeStarSystem?.Invoke(newStarSystem); - - Logger.Log($"Warping to {newStarSystem}"); - if (warp && _shipWarpController) _shipWarpController.WarpOut(); - _isChangingStarSystem = true; - IsWarping = warp; - WearingSuit = PlayerState.IsWearingSuit(); - - // We kill them so they don't move as much - Locator.GetDeathManager().KillPlayer(DeathType.Meditation); - - OWScene sceneToLoad; - - if (newStarSystem == "EyeOfTheUniverse") - { - PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); - sceneToLoad = OWScene.EyeOfTheUniverse; - } - else - { - if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); - else SecondsLeftInLoop = -1; - - sceneToLoad = OWScene.SolarSystem; - } - - _currentStarSystem = newStarSystem; - - LoadManager.LoadSceneAsync(sceneToLoad, true, LoadManager.FadeType.ToBlack, 0.1f, true); - } - - void OnDeath(DeathType _) - { - // We reset the solar system on death (unless we just killed the player) - if (!_isChangingStarSystem) - { - // If the override is a valid system then we go there - if (SystemDict.Keys.Contains(_defaultSystemOverride)) - { - _currentStarSystem = _defaultSystemOverride; - IsWarping = true; // always do this else sometimes the spawn gets messed up - } - else - { - _currentStarSystem = _defaultStarSystem; - } - - IsWarping = false; - } - } - #endregion Change star system - } -} +using HarmonyLib; +using NewHorizons.Builder.Props; +using NewHorizons.Components; +using NewHorizons.External.Configs; +using NewHorizons.External; +using NewHorizons.Handlers; +using NewHorizons.Utility; +using OWML.Common; +using OWML.ModHelper; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; +using Logger = NewHorizons.Utility.Logger; +namespace NewHorizons +{ + public class Main : ModBehaviour + { + public static AssetBundle NHAssetBundle { get; private set; } + public static Main Instance { get; private set; } + + // Settings + public static bool Debug { get; private set; } + private static bool _useCustomTitleScreen; + private static bool _wasConfigured = false; + private static string _defaultSystemOverride; + + public static Dictionary SystemDict = new Dictionary(); + public static Dictionary> BodyDict = new Dictionary>(); + public static List MountedAddons = new List(); + + public static float SecondsLeftInLoop = -1; + + public static bool IsSystemReady { get; private set; } + public static float FurthestOrbit { get; set; } = 50000f; + + public string CurrentStarSystem { get { return Instance._currentStarSystem; } } + public bool IsWarping { get; private set; } = false; + public bool WearingSuit { get; private set; } = false; + + public static bool HasWarpDrive { get; private set; } = false; + + private string _defaultStarSystem = "SolarSystem"; + private string _currentStarSystem = "SolarSystem"; + private bool _isChangingStarSystem = false; + private bool _firstLoad = true; + private ShipWarpController _shipWarpController; + + // API events + public class StarSystemEvent : UnityEvent { } + public StarSystemEvent OnChangeStarSystem; + public StarSystemEvent OnStarSystemLoaded; + + // For warping to the eye system + private GameObject _ship; + + public static bool HasDLC { get => EntitlementsManager.IsDlcOwned() == EntitlementsManager.AsyncOwnershipStatus.Owned; } + + public override object GetApi() + { + return new NewHorizonsApi(); + } + + 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); + + _defaultSystemOverride = config.GetSettingsValue("Default System Override"); + + 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 static void ResetConfigs(bool resetTranslation = true) + { + BodyDict.Clear(); + SystemDict.Clear(); + + BodyDict["SolarSystem"] = new List(); + BodyDict["EyeOfTheUniverse"] = new List(); // Keep this empty tho fr + SystemDict["SolarSystem"] = new NewHorizonsSystem("SolarSystem", new StarSystemConfig(), Instance) + { + Config = + { + destroyStockPlanets = false + } + }; + + if (!resetTranslation) return; + TranslationHandler.ClearTables(); + TextTranslation.Get().SetLanguage(TextTranslation.Get().GetLanguage()); + } + + public void Start() + { + // Patches + Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly()); + + OnChangeStarSystem = new StarSystemEvent(); + OnStarSystemLoaded = new StarSystemEvent(); + + SceneManager.sceneLoaded += OnSceneLoaded; + SceneManager.sceneUnloaded += OnSceneUnloaded; + + Instance = this; + GlobalMessenger.AddListener("PlayerDeath", OnDeath); + GlobalMessenger.AddListener("WakeUp", new Callback(OnWakeUp)); + NHAssetBundle = ModHelper.Assets.LoadBundle("AssetBundle/xen.newhorizons"); + + ResetConfigs(resetTranslation: false); + + Logger.Log("Begin load of config files...", Logger.LogType.Log); + + try + { + LoadConfigs(this); + } + catch (Exception) + { + Logger.LogWarning("Couldn't find planets folder"); + } + + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => OnSceneLoaded(SceneManager.GetActiveScene(), LoadSceneMode.Single)); + Instance.ModHelper.Events.Unity.FireOnNextUpdate(() => _firstLoad = false); + Instance.ModHelper.Menus.PauseMenu.OnInit += DebugReload.InitializePauseMenu; + } + + public void OnDestroy() + { + Logger.Log($"Destroying NewHorizons"); + SceneManager.sceneLoaded -= OnSceneLoaded; + GlobalMessenger.RemoveListener("PlayerDeath", OnDeath); + GlobalMessenger.RemoveListener("WakeUp", new Callback(OnWakeUp)); + } + + private static void OnWakeUp() + { + IsSystemReady = true; + Instance.OnStarSystemLoaded?.Invoke(Instance.CurrentStarSystem); + } + + private void OnSceneUnloaded(Scene scene) + { + SearchUtilities.ClearCache(); + ImageUtilities.ClearCache(); + AudioUtilities.ClearCache(); + AssetBundleUtilities.ClearCache(); + IsSystemReady = false; + } + + private void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + Logger.Log($"Scene Loaded: {scene.name} {mode}"); + + // Set time loop stuff if its enabled and if we're warping to a new place + if (_isChangingStarSystem && (SystemDict[_currentStarSystem].Config.enableTimeLoop || _currentStarSystem == "SolarSystem") && SecondsLeftInLoop > 0f) + { + TimeLoop.SetSecondsRemaining(SecondsLeftInLoop); + // Prevent the OPC from firing + var launchController = GameObject.FindObjectOfType(); + if (launchController != null) + { + GlobalMessenger.RemoveListener("StartOfTimeLoop", launchController.OnStartOfTimeLoop); + foreach (var fakeDebris in launchController._fakeDebrisBodies) + { + fakeDebris.gameObject.SetActive(false); + } + launchController.enabled = false; + } + var nomaiProbe = GameObject.Find("NomaiProbe_Body"); + if (nomaiProbe != null) nomaiProbe.gameObject.SetActive(false); + } + + // Reset this + SecondsLeftInLoop = -1; + + _isChangingStarSystem = false; + + if (scene.name == "TitleScreen" && _useCustomTitleScreen) + { + TitleSceneHandler.DisplayBodyOnTitleScreen(BodyDict.Values.ToList().SelectMany(x => x).ToList()); + } + + if (scene.name == "EyeOfTheUniverse" && IsWarping) + { + if (_ship != null) SceneManager.MoveGameObjectToScene(_ship, SceneManager.GetActiveScene()); + _ship.transform.position = new Vector3(50, 0, 0); + _ship.SetActive(true); + } + + if (scene.name == "SolarSystem") + { + foreach (var body in GameObject.FindObjectsOfType()) + { + Logger.Log($"{body.name}, {body.transform.rotation}"); + } + + if (_ship != null) + { + _ship = GameObject.Find("Ship_Body").InstantiateInactive(); + DontDestroyOnLoad(_ship); + } + + IsSystemReady = false; + + NewHorizonsData.Load(); + SignalBuilder.Init(); + AstroObjectLocator.Init(); + OWAssetHandler.Init(); + PlanetCreationHandler.Init(BodyDict[CurrentStarSystem]); + SystemCreationHandler.LoadSystem(SystemDict[CurrentStarSystem]); + LoadTranslations(ModHelper.Manifest.ModFolderPath + "AssetBundle/", this); + // Warp drive + StarChartHandler.Init(SystemDict.Values.ToArray()); + HasWarpDrive = StarChartHandler.CanWarp(); + _shipWarpController = GameObject.Find("Ship_Body").AddComponent(); + _shipWarpController.Init(); + if (HasWarpDrive == true) EnableWarpDrive(); + + var shouldWarpIn = IsWarping && _shipWarpController != null; + Instance.ModHelper.Events.Unity.RunWhen(() => IsSystemReady, () => OnSystemReady(shouldWarpIn)); + + IsWarping = false; + + var map = GameObject.FindObjectOfType(); + if (map != null) map._maxPanDistance = FurthestOrbit * 1.5f; + + // Fix the map satellite + GameObject.Find("HearthianMapSatellite_Body").AddComponent(); + } + else + { + // Reset back to original solar system after going to main menu. + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarping = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + } + } + + // Had a bunch of separate unity things firing stuff when the system is ready so I moved it all to here + private void OnSystemReady(bool shouldWarpIn) + { + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + Locator.GetPlayerBody().gameObject.AddComponent(); + + + if (shouldWarpIn) _shipWarpController.WarpIn(WearingSuit); + else FindObjectOfType().DebugWarp(SystemDict[_currentStarSystem].SpawnPoint); + } + + public void EnableWarpDrive() + { + Logger.Log("Setting up warp drive"); + PlanetCreationHandler.LoadBody(LoadConfig(this, "AssetBundle/WarpDriveConfig.json")); + HasWarpDrive = true; + } + + + #region Load + public void LoadConfigs(IModBehaviour mod) + { + try + { + if (_firstLoad) + { + MountedAddons.Add(mod); + } + var folder = mod.ModHelper.Manifest.ModFolderPath; + + // Load systems first so that when we load bodies later we can check for missing ones + if (Directory.Exists(folder + @"systems\")) + { + foreach (var file in Directory.GetFiles(folder + @"systems\", "*.json", SearchOption.AllDirectories)) + { + var name = Path.GetFileNameWithoutExtension(file); + + Logger.Log($"Loading system {name}"); + + var relativePath = file.Replace(folder, ""); + var starSystemConfig = mod.ModHelper.Storage.Load(relativePath); + + if (starSystemConfig.startHere) + { + // We always want to allow mods to overwrite setting the main SolarSystem as default but not the other way around + if (name != "SolarSystem") SetDefaultSystem(name); + } + + var system = new NewHorizonsSystem(name, starSystemConfig, mod); + SystemDict[name] = system; + } + } + if (Directory.Exists(folder + "planets")) + { + foreach (var file in Directory.GetFiles(folder + @"planets\", "*.json", SearchOption.AllDirectories)) + { + var relativeDirectory = file.Replace(folder, ""); + var body = LoadConfig(mod, relativeDirectory); + + if (body != null) + { + // Wanna track the spawn point of each system + if (body.Config.Spawn != null) SystemDict[body.Config.StarSystem].Spawn = body.Config.Spawn; + + // Add the new planet to the planet dictionary + if (!BodyDict.ContainsKey(body.Config.StarSystem)) BodyDict[body.Config.StarSystem] = new List(); + BodyDict[body.Config.StarSystem].Add(body); + } + } + } + if (Directory.Exists(folder + @"translations\")) + { + LoadTranslations(folder, mod); + } + } + catch (Exception ex) + { + Logger.LogError($"{ex.Message}, {ex.StackTrace}"); + } + } + + private void LoadTranslations(string folder, IModBehaviour mod) + { + var foundFile = false; + foreach (TextTranslation.Language language in Enum.GetValues(typeof(TextTranslation.Language))) + { + if (language == TextTranslation.Language.UNKNOWN || language == TextTranslation.Language.TOTAL) continue; + + var relativeFile = $"translations/{language.ToString().ToLower()}.json"; + + if (File.Exists($"{folder}{relativeFile}")) + { + Logger.Log($"Registering {language} translation from {mod.ModHelper.Manifest.Name} from {relativeFile}"); + + var config = new TranslationConfig($"{folder}{relativeFile}"); + if (config == null) + { + Logger.Log($"Found {folder}{relativeFile} but couldn't load it"); + continue; + } + + foundFile = true; + + TranslationHandler.RegisterTranslation(language, config); + } + } + if (!foundFile) Logger.LogWarning($"{mod.ModHelper.Manifest.Name} has a folder for translations but none were loaded"); + } + + public NewHorizonsBody LoadConfig(IModBehaviour mod, string relativeDirectory) + { + NewHorizonsBody body = null; + try + { + var config = mod.ModHelper.Storage.Load(relativeDirectory); + config.Validate(); + + Logger.Log($"Loaded {config.Name}"); + + if (!SystemDict.ContainsKey(config.StarSystem)) + { + // Since we didn't load it earlier there shouldn't be a star system config + var starSystemConfig = mod.ModHelper.Storage.Load($"systems/{config.StarSystem}.json"); + if (starSystemConfig == null) starSystemConfig = new StarSystemConfig(); + else Logger.LogWarning($"Loaded system config for {config.StarSystem}. Why wasn't this loaded earlier?"); + + var system = new NewHorizonsSystem(config.StarSystem, starSystemConfig, mod); + + SystemDict.Add(config.StarSystem, system); + + BodyDict.Add(config.StarSystem, new List()); + } + + body = new NewHorizonsBody(config, mod, relativeDirectory); + } + catch (Exception e) + { + Logger.LogError($"Couldn't load {relativeDirectory}: {e.Message}, is your Json formatted correctly?"); + } + + return body; + } + + public void SetDefaultSystem(string defaultSystem) + { + _defaultStarSystem = defaultSystem; + _currentStarSystem = defaultSystem; + } + + #endregion Load + + #region Change star system + public void ChangeCurrentStarSystem(string newStarSystem, bool warp = false) + { + if (_isChangingStarSystem) return; + + OnChangeStarSystem?.Invoke(newStarSystem); + + Logger.Log($"Warping to {newStarSystem}"); + if (warp && _shipWarpController) _shipWarpController.WarpOut(); + _isChangingStarSystem = true; + IsWarping = warp; + WearingSuit = PlayerState.IsWearingSuit(); + + // We kill them so they don't move as much + Locator.GetDeathManager().KillPlayer(DeathType.Meditation); + + OWScene sceneToLoad; + + if (newStarSystem == "EyeOfTheUniverse") + { + PlayerData.SaveWarpedToTheEye(TimeLoop.GetSecondsRemaining()); + sceneToLoad = OWScene.EyeOfTheUniverse; + } + else + { + if (SystemDict[_currentStarSystem].Config.enableTimeLoop) SecondsLeftInLoop = TimeLoop.GetSecondsRemaining(); + else SecondsLeftInLoop = -1; + + sceneToLoad = OWScene.SolarSystem; + } + + _currentStarSystem = newStarSystem; + + LoadManager.LoadSceneAsync(sceneToLoad, true, LoadManager.FadeType.ToBlack, 0.1f, true); + } + + void OnDeath(DeathType _) + { + // We reset the solar system on death (unless we just killed the player) + if (!_isChangingStarSystem) + { + // If the override is a valid system then we go there + if (SystemDict.Keys.Contains(_defaultSystemOverride)) + { + _currentStarSystem = _defaultSystemOverride; + IsWarping = true; // always do this else sometimes the spawn gets messed up + } + else + { + _currentStarSystem = _defaultStarSystem; + } + + IsWarping = false; + } + } + #endregion Change star system + } +} diff --git a/NewHorizons/Utility/DebugMenu.cs b/NewHorizons/Utility/DebugMenu.cs index 3b9478d0..f4482da1 100644 --- a/NewHorizons/Utility/DebugMenu.cs +++ b/NewHorizons/Utility/DebugMenu.cs @@ -1,5 +1,6 @@ using NewHorizons.External; using NewHorizons.External.Configs; +using NewHorizons.External.Modules; using OWML.Common; using System; using System.Collections.Generic; @@ -11,6 +12,13 @@ using UnityEngine.InputSystem; namespace NewHorizons.Utility { + + // + // + // TODO: split this into two separate classes "DebugMenu" and "DebugPropPlacerMenu" + // + // + [RequireComponent(typeof(DebugRaycaster))] [RequireComponent(typeof(DebugPropPlacer))] class DebugMenu : MonoBehaviour @@ -18,8 +26,8 @@ namespace NewHorizons.Utility GUIStyle _editorMenuStyle; Vector2 EditorMenuSize = new Vector2(600, 900); bool menuOpen = false; - static bool openMenuOnPause = false; - static bool staticInitialized = false; + static bool openMenuOnPause; + static bool staticInitialized; DebugPropPlacer _dpp; DebugRaycaster _drc; @@ -36,12 +44,19 @@ namespace NewHorizons.Utility private bool saveButtonUnlocked = false; private Vector2 recentModListScrollPosition = Vector2.zero; + + + private double debugcountA = 0; + private double debugcountB = 0; + private double debugcountC = 0; + private double debugcountD = 0; + + private void Awake() { _dpp = this.GetRequiredComponent(); _drc = this.GetRequiredComponent(); LoadFavoriteProps(); - } private void Start() { @@ -59,6 +74,10 @@ namespace NewHorizons.Utility PauseMenuInitHook(); Main.Instance.OnChangeStarSystem.AddListener((string s) => SaveLoadedConfigsForRecentSystem()); + } + else + { + InitMenu(); } if (loadedMod != null) @@ -70,12 +89,13 @@ namespace NewHorizons.Utility private void PauseMenuInitHook() { + Logger.Log("PAUSE MENU INIT HOOK"); InitMenu(); var editorButton = Main.Instance.ModHelper.Menus.PauseMenu.OptionsButton.Duplicate("Toggle Prop Placer Menu".ToUpper()); editorButton.OnClick += ToggleMenu; } - private void RestoreMenuOpennessState() { menuOpen = openMenuOnPause; } - private void ToggleMenu() { menuOpen = !menuOpen; openMenuOnPause = !openMenuOnPause; } + private void RestoreMenuOpennessState() { Logger.Log("RESTORING MENU OPENNESS STATE: " + openMenuOnPause); menuOpen = openMenuOnPause; } + private void ToggleMenu() { Logger.Log($"oMY MENU BUTTON WAS CLICKED! debug counts: {debugcountA}, {debugcountB}, {debugcountC}, {debugcountD}"); menuOpen = !menuOpen; openMenuOnPause = !openMenuOnPause; } private void CloseMenu() { menuOpen = false; } @@ -95,13 +115,19 @@ namespace NewHorizons.Utility private void OnGUI() { + debugcountA ++; + if (!menuOpen) return; if (!Main.Debug) return; + debugcountB ++; + Vector2 menuPosition = new Vector2(10, 40); GUILayout.BeginArea(new Rect(menuPosition.x, menuPosition.y, EditorMenuSize.x, EditorMenuSize.y), _editorMenuStyle); + debugcountC++; + // // DebugPropPlacer // @@ -190,6 +216,8 @@ namespace NewHorizons.Utility } GUILayout.EndArea(); + + debugcountD++; } private void LoadMod(IModBehaviour mod) @@ -269,7 +297,7 @@ namespace NewHorizons.Utility if (!newDetails.ContainsKey(astroObjectName)) continue; - if (loadedConfigFiles[filePath].Props == null) loadedConfigFiles[filePath].Props = new External.PropModule(); + if (loadedConfigFiles[filePath].Props == null) loadedConfigFiles[filePath].Props = new External.Modules.PropModule(); loadedConfigFiles[filePath].Props.Details = newDetails[astroObjectName]; Logger.Log("successfully updated copy of config file for " + astroObjectName); @@ -282,7 +310,7 @@ namespace NewHorizons.Utility Logger.Log("Fabricating new config file for " + astroObjectName); var filepath = "planets/" + Main.Instance.CurrentStarSystem + "/" + astroObjectName + ".json"; - PlanetConfig c = new PlanetConfig(null); + PlanetConfig c = new PlanetConfig(); c.StarSystem = Main.Instance.CurrentStarSystem; c.Name = astroObjectName; c.Props = new PropModule(); @@ -294,8 +322,12 @@ namespace NewHorizons.Utility private void InitMenu() { + Logger.Log("Maybe Initing menu"); + if (_editorMenuStyle != null) return; + Logger.Log("Initing menu"); + _dpp = this.GetRequiredComponent(); _drc = this.GetRequiredComponent(); diff --git a/NewHorizons/Utility/DebugPropPlacer.cs b/NewHorizons/Utility/DebugPropPlacer.cs index abea8aba..603b49ed 100644 --- a/NewHorizons/Utility/DebugPropPlacer.cs +++ b/NewHorizons/Utility/DebugPropPlacer.cs @@ -7,7 +7,7 @@ using System.Text; using System.Threading.Tasks; using UnityEngine; using UnityEngine.InputSystem; -using static NewHorizons.External.PropModule; +using static NewHorizons.External.Modules.PropModule; namespace NewHorizons.Utility { @@ -46,7 +46,7 @@ namespace NewHorizons.Utility if (!Main.Debug) return; if (!active) return; - if (Keyboard.current[Key.X].wasReleasedThisFrame) + if (Keyboard.current[Key.G].wasReleasedThisFrame) { PlaceObject(); } @@ -143,7 +143,7 @@ namespace NewHorizons.Utility return astroObjectName; } - public void FindAndRegisterPropsFromConfig(IPlanetConfig config) + public void FindAndRegisterPropsFromConfig(PlanetConfig config) { if (config.StarSystem != Main.Instance.CurrentStarSystem) return; diff --git a/NewHorizons/Utility/DebugRaycaster.cs b/NewHorizons/Utility/DebugRaycaster.cs index ad648dd7..e73808c4 100644 --- a/NewHorizons/Utility/DebugRaycaster.cs +++ b/NewHorizons/Utility/DebugRaycaster.cs @@ -14,53 +14,61 @@ namespace NewHorizons.Utility { _rb = this.GetRequiredComponent(); } - - + + private void Update() { - if (!Main.Debug) return; - if (Keyboard.current == null) return; - - if (Keyboard.current[Key.P].wasReleasedThisFrame) + if (!Main.Debug) return; + if (Keyboard.current == null) return; + + if (Keyboard.current[Key.P].wasReleasedThisFrame) { - PrintRaycast(); - } - } - + PrintRaycast(); + } + } + + + internal void PrintRaycast() - { - DebugRaycastData data = Raycast(); - var posText = $"{{\"x\": {data.pos.x}, \"y\": {data.pos.y}, \"z\": {data.pos.z}}}"; - var normText = $"{{\"x\": {data.norm.x}, \"y\": {data.norm.y}, \"z\": {data.norm.z}}}"; + { + DebugRaycastData data = Raycast(); + var posText = $"{{\"x\": {data.pos.x}, \"y\": {data.pos.y}, \"z\": {data.pos.z}}}"; + var normText = $"{{\"x\": {data.norm.x}, \"y\": {data.norm.y}, \"z\": {data.norm.z}}}"; - if (_surfaceSphere != null) GameObject.Destroy(_surfaceSphere); - if (_normalSphere1 != null) GameObject.Destroy(_normalSphere1); - if (_normalSphere2 != null) GameObject.Destroy(_normalSphere2); + if(_surfaceSphere != null) GameObject.Destroy(_surfaceSphere); + if(_normalSphere1 != null) GameObject.Destroy(_normalSphere1); + if(_normalSphere2 != null) GameObject.Destroy(_normalSphere2); - _surfaceSphere = AddDebugShape.AddSphere(hitInfo.transform.gameObject, 0.1f, Color.green); - _normalSphere1 = AddDebugShape.AddSphere(hitInfo.transform.gameObject, 0.01f, Color.red); - _normalSphere2 = AddDebugShape.AddSphere(hitInfo.transform.gameObject, 0.01f, Color.red); + _surfaceSphere = AddDebugShape.AddSphere(data.hitObject, 0.1f, Color.green); + _normalSphere1 = AddDebugShape.AddSphere(data.hitObject, 0.01f, Color.red); + _normalSphere2 = AddDebugShape.AddSphere(data.hitObject, 0.01f, Color.red); + _surfaceSphere.transform.localPosition = data.pos; + _normalSphere1.transform.localPosition = data.pos + data.norm * 0.5f; + _normalSphere2.transform.localPosition = data.pos + data.norm; + + Logger.Log($"Raycast hit \"position\": {posText}, \"normal\": {normText} on [{data.bodyName}] at [{data.bodyPath}]"); + } internal DebugRaycastData Raycast() { - DebugRaycastData data = new DebugRaycastData(); - - _rb.DisableCollisionDetection(); - int layerMask = OWLayerMask.physicalMask; - var origin = Locator.GetActiveCamera().transform.position; - var direction = Locator.GetActiveCamera().transform.TransformDirection(Vector3.forward); - - data.hit = Physics.Raycast(origin, direction, out RaycastHit hitInfo, 100f, layerMask); - if (data.hit) - { - data.pos = hitInfo.transform.InverseTransformPoint(hitInfo.point); - data.norm = hitInfo.transform.InverseTransformDirection(hitInfo.normal); - var o = hitInfo.transform.gameObject; + DebugRaycastData data = new DebugRaycastData(); - data.bodyName = o.name; - data.bodyPath = SearchUtilities.GetPath(o.transform); - data.hitObject = hitInfo.transform.gameObject; - } + _rb.DisableCollisionDetection(); + int layerMask = OWLayerMask.physicalMask; + var origin = Locator.GetActiveCamera().transform.position; + var direction = Locator.GetActiveCamera().transform.TransformDirection(Vector3.forward); + + data.hit = Physics.Raycast(origin, direction, out RaycastHit hitInfo, 100f, layerMask); + if (data.hit) + { + data.pos = hitInfo.transform.InverseTransformPoint(hitInfo.point); + data.norm = hitInfo.transform.InverseTransformDirection(hitInfo.normal); + var o = hitInfo.transform.gameObject; + + data.bodyName = o.name; + data.bodyPath = SearchUtilities.GetPath(o.transform); + data.hitObject = hitInfo.transform.gameObject; + } _rb.EnableCollisionDetection(); return data; diff --git a/NewHorizons/Utility/NewHorizonBody.cs b/NewHorizons/Utility/NewHorizonBody.cs index fbbc7de6..48c9d81d 100644 --- a/NewHorizons/Utility/NewHorizonBody.cs +++ b/NewHorizons/Utility/NewHorizonBody.cs @@ -1,21 +1,21 @@ -using NewHorizons.External.Configs; -using OWML.Common; -using UnityEngine; -namespace NewHorizons.Utility -{ - public class NewHorizonsBody - { - public NewHorizonsBody(PlanetConfig config, IModBehaviour mod, string relativePath = null) - { - Config = config; - Mod = mod; - RelativePath = relativePath; - } - - public PlanetConfig Config; - public IModBehaviour Mod; - public string RelativePath; - - public GameObject Object; - } -} +using NewHorizons.External.Configs; +using OWML.Common; +using UnityEngine; +namespace NewHorizons.Utility +{ + public class NewHorizonsBody + { + public NewHorizonsBody(PlanetConfig config, IModBehaviour mod, string relativePath = null) + { + Config = config; + Mod = mod; + RelativePath = relativePath; + } + + public PlanetConfig Config; + public IModBehaviour Mod; + public string RelativePath; + + public GameObject Object; + } +}