Version 0.14.3 0.14.3
Version 0.14.3

// VOID // VOID
// //
// AssemblyInfo.cs // AssemblyInfo.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
   
[assembly: KSPAssemblyDependency("ToadicusTools", 0, 0)] [assembly: KSPAssemblyDependency("ToadicusTools", 0, 0)]
[assembly: KSPAssemblyDependency("VesselSimulator", 0, 0)] [assembly: KSPAssemblyDependency("VesselSimulator", 0, 0)]
   
// Information about this assembly is defined by the following attributes. // Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project. // Change them to the values specific to your project.
[assembly: AssemblyTitle("VOID")] [assembly: AssemblyTitle("VOID")]
[assembly: AssemblyDescription("A KSP mod that provides at-a-glance information about Vessels, Orbits, and their states.")] [assembly: AssemblyDescription("A KSP mod that provides at-a-glance information about Vessels, Orbits, and their states.")]
[assembly: AssemblyCopyright("toadicus")] [assembly: AssemblyCopyright("toadicus")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision, // The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision. // and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.14.2.*")] [assembly: AssemblyVersion("0.14.3.*")]
// The following attributes are used to specify the signing key for the assembly, // The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing. // if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")] //[assembly: AssemblyKeyFile("")]
   
   
// VOID // VOID
// //
// VOID_Core.cs // VOID_Core.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
using Engineer.VesselSimulator; using Engineer.VesselSimulator;
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_Core : VOID_Module, IVOID_Module public class VOID_Core : VOID_Module, IVOID_Module
{ {
#region Singleton Members #region Singleton Members
/* /*
* Static Members * Static Members
* */ * */
protected static bool _initialized = false; protected static bool _initialized = false;
   
public static bool Initialized public static bool Initialized
{ {
get get
{ {
return _initialized; return _initialized;
} }
} }
   
protected static VOID_Core _instance; protected static VOID_Core _instance;
   
public static VOID_Core Instance public static VOID_Core Instance
{ {
get get
{ {
if (_instance == null) if (_instance == null)
{ {
_instance = new VOID_Core(); _instance = new VOID_Core();
_initialized = true; _initialized = true;
} }
return _instance; return _instance;
} }
} }
   
public static void Reset() public static void Reset()
{ {
_instance.StopGUI(); _instance.StopGUI();
_instance.Dispose(); _instance.Dispose();
_instance = null; _instance = null;
_initialized = false; _initialized = false;
} }
#endregion #endregion
   
public static readonly double Constant_G = 6.674e-11; public static readonly double Constant_G = 6.674e-11;
   
/* /*
* Fields * Fields
* */ * */
protected string VoidName = "VOID"; protected string VoidName = "VOID";
protected string VoidVersion; protected string VoidVersion;
   
protected bool _factoryReset = false; protected bool _factoryReset = false;
   
[AVOID_SaveValue("configValue")] [AVOID_SaveValue("configValue")]
protected VOID_SaveValue<int> configVersion = 1; protected VOID_SaveValue<int> configVersion = 1;
   
protected List<IVOID_Module> _modules = new List<IVOID_Module>(); protected List<IVOID_Module> _modules = new List<IVOID_Module>();
protected bool _modulesLoaded = false; protected bool _modulesLoaded = false;
   
[AVOID_SaveValue("mainWindowPos")] [AVOID_SaveValue("mainWindowPos")]
protected VOID_SaveValue<Rect> mainWindowPos = new Rect(475, 575, 10f, 10f); protected VOID_SaveValue<Rect> mainWindowPos = new Rect(475, 575, 10f, 10f);
[AVOID_SaveValue("mainGuiMinimized")] [AVOID_SaveValue("mainGuiMinimized")]
protected VOID_SaveValue<bool> mainGuiMinimized = false; protected VOID_SaveValue<bool> mainGuiMinimized = false;
   
[AVOID_SaveValue("configWindowPos")] [AVOID_SaveValue("configWindowPos")]
protected VOID_SaveValue<Rect> configWindowPos = new Rect(825, 625, 10f, 10f); protected VOID_SaveValue<Rect> configWindowPos = new Rect(825, 625, 10f, 10f);
[AVOID_SaveValue("configWindowMinimized")] [AVOID_SaveValue("configWindowMinimized")]
   
protected VOID_SaveValue<bool> configWindowMinimized = true; protected VOID_SaveValue<bool> configWindowMinimized = true;
[AVOID_SaveValue("VOIDIconPos")] [AVOID_SaveValue("VOIDIconPos")]
protected VOID_SaveValue<Rect> VOIDIconPos = new Rect(Screen.width / 2 - 200, Screen.height - 32, 32f, 32f); protected VOID_SaveValue<Rect> VOIDIconPos = new Rect(Screen.width / 2 - 200, Screen.height - 32, 32f, 32f);
   
protected Texture2D VOIDIconTexture; protected Texture2D VOIDIconTexture;
protected string VOIDIconOnActivePath; protected string VOIDIconOnActivePath;
protected string VOIDIconOnInactivePath; protected string VOIDIconOnInactivePath;
protected string VOIDIconOffActivePath; protected string VOIDIconOffActivePath;
protected string VOIDIconOffInactivePath; protected string VOIDIconOffInactivePath;
   
protected bool VOIDIconLocked = true; protected bool VOIDIconLocked = true;
   
protected GUIStyle iconStyle; protected GUIStyle iconStyle;
   
protected int windowBaseID = -96518722; protected int windowBaseID = -96518722;
protected int _windowID = 0; protected int _windowID = 0;
   
protected bool GUIStylesLoaded = false; protected bool GUIStylesLoaded = false;
protected Dictionary<string, GUIStyle> _LabelStyles = new Dictionary<string, GUIStyle>(); protected Dictionary<string, GUIStyle> _LabelStyles = new Dictionary<string, GUIStyle>();
   
protected CelestialBody _Kerbin; protected CelestialBody _Kerbin;
   
[AVOID_SaveValue("togglePower")] [AVOID_SaveValue("togglePower")]
public VOID_SaveValue<bool> togglePower = true; public VOID_SaveValue<bool> togglePower = true;
public bool powerAvailable = true; public bool powerAvailable = true;
   
[AVOID_SaveValue("consumeResource")] [AVOID_SaveValue("consumeResource")]
protected VOID_SaveValue<bool> consumeResource = false; protected VOID_SaveValue<bool> consumeResource = false;
   
[AVOID_SaveValue("resourceName")] [AVOID_SaveValue("resourceName")]
protected VOID_SaveValue<string> resourceName = "ElectricCharge"; protected VOID_SaveValue<string> resourceName = "ElectricCharge";
   
[AVOID_SaveValue("resourceRate")] [AVOID_SaveValue("resourceRate")]
protected VOID_SaveValue<float> resourceRate = 0.2f; protected VOID_SaveValue<float> resourceRate = 0.2f;
   
[AVOID_SaveValue("updatePeriod")] [AVOID_SaveValue("updatePeriod")]
protected VOID_SaveValue<double> _updatePeriod = 1001f / 15000f; protected VOID_SaveValue<double> _updatePeriod = 1001f / 15000f;
protected float _updateTimer = 0f; protected float _updateTimer = 0f;
protected string stringFrequency; protected string stringFrequency;
   
[AVOID_SaveValue("vesselSimActive")] [AVOID_SaveValue("vesselSimActive")]
protected VOID_SaveValue<bool> vesselSimActive; protected VOID_SaveValue<bool> vesselSimActive;
   
// Vessel Type Housekeeping // Vessel Type Housekeeping
protected List<VesselType> _allVesselTypes = new List<VesselType>(); protected List<VesselType> _allVesselTypes = new List<VesselType>();
protected bool vesselTypesLoaded = false; protected bool vesselTypesLoaded = false;
public float saveTimer = 0; public float saveTimer = 0;
   
protected string defaultSkin = "KSP window 2"; protected string defaultSkin = "KSP window 2";
   
[AVOID_SaveValue("defaultSkin")] [AVOID_SaveValue("defaultSkin")]
protected VOID_SaveValue<string> _skinName; protected VOID_SaveValue<string> _skinName;
protected int _skinIdx; protected int _skinIdx;
   
protected Dictionary<string, GUISkin> validSkins; protected Dictionary<string, GUISkin> validSkins;
protected string[] skinNames; protected string[] skinNames;
protected string[] forbiddenSkins = protected string[] forbiddenSkins =
{ {
"PlaqueDialogSkin", "PlaqueDialogSkin",
"FlagBrowserSkin", "FlagBrowserSkin",
"SSUITextAreaDefault", "SSUITextAreaDefault",
"ExperimentsDialogSkin", "ExperimentsDialogSkin",
"ExpRecoveryDialogSkin", "ExpRecoveryDialogSkin",
"KSP window 5", "KSP window 5",
"KSP window 6", "KSP window 6",
"PartTooltipSkin" "PartTooltipSkin"
}; };
protected bool skinsLoaded = false; protected bool skinsLoaded = false;
   
public bool configDirty; public bool configDirty;
   
[AVOID_SaveValue("UseBlizzyToolbar")] [AVOID_SaveValue("UseBlizzyToolbar")]
protected VOID_SaveValue<bool> _UseToolbarManager; protected VOID_SaveValue<bool> _UseToolbarManager;
internal IButton ToolbarButton; internal IButton ToolbarButton;
   
internal ApplicationLauncherButton AppLauncherButton; internal ApplicationLauncherButton AppLauncherButton;
   
/* /*
* Properties * Properties
* */ * */
public bool factoryReset public bool factoryReset
{ {
get get
{ {
return this._factoryReset; return this._factoryReset;
} }
} }
   
public List<IVOID_Module> Modules public List<IVOID_Module> Modules
{ {
get get
{ {
return this._modules; return this._modules;
} }
} }
   
public GUISkin Skin public GUISkin Skin
{ {
get get
{ {
if (this.skinsLoaded) if (this.skinsLoaded)
{ {
try try
{ {
return this.validSkins[this._skinName]; return this.validSkins[this._skinName];
} }
catch catch
{ {
} }
} }
   
return AssetBase.GetGUISkin(this.defaultSkin); return AssetBase.GetGUISkin(this.defaultSkin);
} }
} }
   
public int windowID public int windowID
{ {
get get
{ {
if (this._windowID == 0) if (this._windowID == 0)
{ {
this._windowID = this.windowBaseID; this._windowID = this.windowBaseID;
} }
return this._windowID++; return this._windowID++;
} }
} }
   
public Dictionary<string, GUIStyle> LabelStyles public Dictionary<string, GUIStyle> LabelStyles
{ {
get get
{ {
return this._LabelStyles; return this._LabelStyles;
} }
} }
   
public List<CelestialBody> allBodies public List<CelestialBody> allBodies
{ {
get get
{ {
return FlightGlobals.Bodies; return FlightGlobals.Bodies;
} }
} }
   
public CelestialBody Kerbin public CelestialBody Kerbin
{ {
get get
{ {
if (this._Kerbin == null) if (this._Kerbin == null)
{ {
if (FlightGlobals.Bodies != null) if (FlightGlobals.Bodies != null)
{ {
this._Kerbin = FlightGlobals.Bodies.First(b => b.name == "Kerbin"); this._Kerbin = FlightGlobals.Bodies.First(b => b.name == "Kerbin");
} }
} }
   
return this._Kerbin; return this._Kerbin;
} }
} }
   
public List<VesselType> allVesselTypes public List<VesselType> allVesselTypes
{ {
get get
{ {
return this._allVesselTypes; return this._allVesselTypes;
} }
} }
   
public float updateTimer public float updateTimer
{ {
get get
{ {
return this._updateTimer; return this._updateTimer;
} }
} }
   
public double updatePeriod public double updatePeriod
{ {
get get
{ {
return this._updatePeriod; return this._updatePeriod;
} }
} }
   
public Stage[] Stages public Stage[] Stages
{ {
get; get;
protected set; protected set;
} }
   
public Stage LastStage public Stage LastStage
{ {
get; get;
protected set; protected set;
} }
   
protected IconState powerState protected IconState powerState
{ {
get get
{ {
if (this.togglePower && this.powerAvailable) if (this.togglePower && this.powerAvailable)
{ {
return IconState.PowerOn; return IconState.PowerOn;
} }
else else
{ {
return IconState.PowerOff; return IconState.PowerOff;
} }
   
} }
} }
   
protected IconState activeState protected IconState activeState
{ {
get get
{ {
if (this.mainGuiMinimized) if (this.mainGuiMinimized)
{ {
return IconState.Inactive; return IconState.Inactive;
} }
else else
{ {
return IconState.Active; return IconState.Active;
} }
   
} }
} }
   
protected bool UseToolbarManager protected bool UseToolbarManager
{ {
get get
{ {
return _UseToolbarManager & ToolbarManager.ToolbarAvailable; return _UseToolbarManager & ToolbarManager.ToolbarAvailable;
} }
set set
{ {
if (this._UseToolbarManager == value) if (this._UseToolbarManager == value)
{ {
return; return;
} }
   
if (value == false && this.ToolbarButton != null) if (value == false && this.ToolbarButton != null)
{ {
this.ToolbarButton.Destroy(); this.ToolbarButton.Destroy();
this.ToolbarButton = null; this.ToolbarButton = null;
} }
if (value == true) if (value == true)
{ {
if (this.AppLauncherButton != null) if (this.AppLauncherButton != null)
{ {
ApplicationLauncher.Instance.RemoveModApplication(this.AppLauncherButton); ApplicationLauncher.Instance.RemoveModApplication(this.AppLauncherButton);
this.AppLauncherButton = null; this.AppLauncherButton = null;
} }
   
this.InitializeToolbarButton(); this.InitializeToolbarButton();
} }
   
_UseToolbarManager.value = value; _UseToolbarManager.value = value;
} }
} }
   
protected virtual ApplicationLauncher.AppScenes appIconVisibleScenes protected virtual ApplicationLauncher.AppScenes appIconVisibleScenes
{ {
get get
{ {
return ApplicationLauncher.AppScenes.FLIGHT; return ApplicationLauncher.AppScenes.FLIGHT;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public override void DrawGUI() public override void DrawGUI()
{ {
this._windowID = this.windowBaseID; this._windowID = this.windowBaseID;
   
if (!this._modulesLoaded) if (!this._modulesLoaded)
{ {
this.LoadModulesOfType<IVOID_Module>(); this.LoadModulesOfType<IVOID_Module>();
} }
   
if (!this.skinsLoaded) if (!this.skinsLoaded)
{ {
this.LoadSkins(); this.LoadSkins();
} }
   
GUI.skin = this.Skin; GUI.skin = this.Skin;
   
if (!this.GUIStylesLoaded) if (!this.GUIStylesLoaded)
{ {
this.LoadGUIStyles(); this.LoadGUIStyles();
   
  Tools.PostDebugMessage(
  this,
  "ToolbarAvailable: {0}, UseToobarManager: {1}",
  ToolbarManager.ToolbarAvailable,
  this.UseToolbarManager);
} }
   
if (!this.UseToolbarManager) if (!this.UseToolbarManager)
{ {
if (this.AppLauncherButton == null) if (this.AppLauncherButton == null)
{ {
  Tools.PostDebugMessage(this,
  "UseToolbarManager = false (ToolbarAvailable = {0}) and " +
  "AppLauncherButton is null, making AppLauncher button.",
  ToolbarManager.ToolbarAvailable
  );
this.InitializeAppLauncherButton(); this.InitializeAppLauncherButton();
} }
} }
else if (this.ToolbarButton == null) else if (this.ToolbarButton == null)
{ {
  Tools.PostDebugMessage(this,
  "UseToolbarManager = true (ToolbarAvailable = {0}) and " +
  "ToolbarButton is null, making Toolbar button.",
  ToolbarManager.ToolbarAvailable
  );
this.InitializeToolbarButton(); this.InitializeToolbarButton();
} }
   
if (!this.mainGuiMinimized) if (!this.mainGuiMinimized)
{ {
   
Rect _mainWindowPos = this.mainWindowPos; Rect _mainWindowPos = this.mainWindowPos;
   
_mainWindowPos = GUILayout.Window( _mainWindowPos = GUILayout.Window(
this.windowID, this.windowID,
_mainWindowPos, _mainWindowPos,
VOID_Tools.GetWindowHandler(this.VOIDMainWindow), VOID_Tools.GetWindowHandler(this.VOIDMainWindow),
string.Join(" ", new string[] { this.VoidName, this.VoidVersion }), string.Join(" ", new string[] { this.VoidName, this.VoidVersion }),
GUILayout.Width(250), GUILayout.Width(250),
GUILayout.Height(50) GUILayout.Height(50)
); );
   
_mainWindowPos = Tools.ClampRectToScreen(_mainWindowPos); _mainWindowPos = Tools.ClampRectToScreen(_mainWindowPos);
   
if (_mainWindowPos != this.mainWindowPos) if (_mainWindowPos != this.mainWindowPos)
{ {
this.mainWindowPos = _mainWindowPos; this.mainWindowPos = _mainWindowPos;
} }
} }
   
if (!this.configWindowMinimized && !this.mainGuiMinimized) if (!this.configWindowMinimized && !this.mainGuiMinimized)
{ {
Rect _configWindowPos = this.configWindowPos; Rect _configWindowPos = this.configWindowPos;
   
_configWindowPos = GUILayout.Window( _configWindowPos = GUILayout.Window(
this.windowID, this.windowID,
_configWindowPos, _configWindowPos,
VOID_Tools.GetWindowHandler(this.VOIDConfigWindow), VOID_Tools.GetWindowHandler(this.VOIDConfigWindow),
string.Join(" ", new string[] { this.VoidName, "Configuration" }), string.Join(" ", new string[] { this.VoidName, "Configuration" }),
GUILayout.Width(250), GUILayout.Width(250),
GUILayout.Height(50) GUILayout.Height(50)
); );
   
_configWindowPos = Tools.ClampRectToScreen(_configWindowPos); _configWindowPos = Tools.ClampRectToScreen(_configWindowPos);
   
if (_configWindowPos != this.configWindowPos) if (_configWindowPos != this.configWindowPos)
{ {
this.configWindowPos = _configWindowPos; this.configWindowPos = _configWindowPos;
} }
} }
} }
   
public virtual void OnGUI() public virtual void OnGUI()
{ {
if (Event.current.type == EventType.Repaint) if (Event.current.type == EventType.Repaint)
{ {
return; return;
} }
   
/* /*
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"Event.current.type: {0}" + "Event.current.type: {0}" +
"\nthis.VOIDIconLocked: {1}" + "\nthis.VOIDIconLocked: {1}" +
"\nEvent.current.mousePosition: {2}" + "\nEvent.current.mousePosition: {2}" +
"\nVOIDIconPos: ({3}, {4}),({5}, {6})", "\nVOIDIconPos: ({3}, {4}),({5}, {6})",
Event.current.type, Event.current.type,
this.VOIDIconLocked, this.VOIDIconLocked,
Event.current.mousePosition, Event.current.mousePosition,
this.VOIDIconPos.value.xMin, this.VOIDIconPos.value.xMin,
this.VOIDIconPos.value.yMin, this.VOIDIconPos.value.yMin,
this.VOIDIconPos.value.xMax, this.VOIDIconPos.value.xMax,
this.VOIDIconPos.value.yMax this.VOIDIconPos.value.yMax
)); ));
*/ */
   
if (!this.VOIDIconLocked && if (!this.VOIDIconLocked &&
VOIDIconPos.value.Contains(Event.current.mousePosition) VOIDIconPos.value.Contains(Event.current.mousePosition)
&& Event.current.type == EventType.mouseDrag) && Event.current.type == EventType.mouseDrag)
{ {
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"Event.current.type: {0}" + "Event.current.type: {0}" +
"\ndelta.x: {1}; delta.y: {2}", "\ndelta.x: {1}; delta.y: {2}",
Event.current.type, Event.current.type,
Event.current.delta.x, Event.current.delta.x,
Event.current.delta.y Event.current.delta.y
)); ));
   
Rect tmp = new Rect(VOIDIconPos); Rect tmp = new Rect(VOIDIconPos);
   
tmp.x = Event.current.mousePosition.x - tmp.width / 2; tmp.x = Event.current.mousePosition.x - tmp.width / 2;
tmp.y = Event.current.mousePosition.y - tmp.height / 2; tmp.y = Event.current.mousePosition.y - tmp.height / 2;
   
if (tmp.x > Screen.width - tmp.width) if (tmp.x > Screen.width - tmp.width)
{ {
tmp.x = Screen.width - tmp.width; tmp.x = Screen.width - tmp.width;
} }
   
if (tmp.y > Screen.height - tmp.height) if (tmp.y > Screen.height - tmp.height)
{ {
tmp.y = Screen.height - tmp.height; tmp.y = Screen.height - tmp.height;
} }
   
VOIDIconPos = tmp; VOIDIconPos = tmp;
} }
} }
   
public virtual void Update() public virtual void Update()
{ {
this.LoadBeforeUpdate(); this.LoadBeforeUpdate();
   
if (this.vessel != null && this.vesselSimActive) if (this.vessel != null && this.vesselSimActive)
{ {
Tools.PostDebugMessage(this, "Updating SimManager."); Tools.PostDebugMessage(this, "Updating SimManager.");
this.UpdateSimManager(); this.UpdateSimManager();
} }
   
if (!this.guiRunning) if (!this.guiRunning)
{ {
this.StartGUI(); this.StartGUI();
} }
   
if (!HighLogic.LoadedSceneIsFlight && this.guiRunning) if (!HighLogic.LoadedSceneIsFlight && this.guiRunning)
{ {
this.StopGUI(); this.StopGUI();
} }
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.Modules)
{ {
if (!module.guiRunning && module.toggleActive) if (!module.guiRunning && module.toggleActive)
{ {
module.StartGUI(); module.StartGUI();
} }
if (module.guiRunning && !module.toggleActive || if (module.guiRunning && !module.toggleActive ||
!this.togglePower || !this.togglePower ||
!HighLogic.LoadedSceneIsFlight || !HighLogic.LoadedSceneIsFlight ||
this.factoryReset) this.factoryReset)
{ {
module.StopGUI(); module.StopGUI();
} }
   
if (module is IVOID_BehaviorModule) if (module is IVOID_BehaviorModule)
{ {
((IVOID_BehaviorModule)module).Update(); ((IVOID_BehaviorModule)module).Update();
} }
} }
   
this.CheckAndSave(); this.CheckAndSave();
this._updateTimer += Time.deltaTime; this._updateTimer += Time.deltaTime;
} }
   
public virtual void FixedUpdate() public virtual void FixedUpdate()
{ {
bool newPowerState = this.powerAvailable; bool newPowerState = this.powerAvailable;
   
if (this.togglePower && this.consumeResource && if (this.togglePower && this.consumeResource &&
this.vessel.vesselType != VesselType.EVA && this.vessel.vesselType != VesselType.EVA &&
TimeWarp.deltaTime != 0) TimeWarp.deltaTime != 0)
{ {
float powerReceived = this.vessel.rootPart.RequestResource( float powerReceived = this.vessel.rootPart.RequestResource(
this.resourceName, this.resourceName,
this.resourceRate * TimeWarp.fixedDeltaTime this.resourceRate * TimeWarp.fixedDeltaTime
); );
   
if (powerReceived > 0) if (powerReceived > 0)
{ {
newPowerState = true; newPowerState = true;
} }
else else
{ {
newPowerState = false; newPowerState = false;
} }
   
if (this.powerAvailable != newPowerState) if (this.powerAvailable != newPowerState)
{ {
this.powerAvailable = newPowerState; this.powerAvailable = newPowerState;
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
} }
} }
   
foreach (IVOID_BehaviorModule module in foreach (IVOID_BehaviorModule module in
this._modules.OfType<IVOID_BehaviorModule>().Where(m => !m.GetType().IsAbstract)) this._modules.OfType<IVOID_BehaviorModule>().Where(m => !m.GetType().IsAbstract))
{ {
module.FixedUpdate(); module.FixedUpdate();
} }
} }
   
public void ResetGUI() public void ResetGUI()
{ {
this.StopGUI(); this.StopGUI();
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.Modules)
{ {
module.StopGUI(); module.StopGUI();
module.StartGUI(); module.StartGUI();
} }
   
this.StartGUI(); this.StartGUI();
} }
   
public void VOIDMainWindow(int _) public void VOIDMainWindow(int _)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
if (this.powerAvailable || HighLogic.LoadedSceneIsEditor) if (this.powerAvailable || HighLogic.LoadedSceneIsEditor)
{ {
if (!HighLogic.LoadedSceneIsEditor) if (!HighLogic.LoadedSceneIsEditor)
{ {
string str = string.Intern("ON"); string str = string.Intern("ON");
if (togglePower) if (togglePower)
str = string.Intern("OFF"); str = string.Intern("OFF");
if (GUILayout.Button("Power " + str)) if (GUILayout.Button("Power " + str))
{ {
togglePower.value = !togglePower; togglePower.value = !togglePower;
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
} }
} }
   
if (togglePower || HighLogic.LoadedSceneIsEditor) if (togglePower || HighLogic.LoadedSceneIsEditor)
{ {
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.Modules)
{ {
module.toggleActive = GUILayout.Toggle(module.toggleActive, module.Name); module.toggleActive = GUILayout.Toggle(module.toggleActive, module.Name);
} }
} }
} }
else else
{ {
GUILayout.Label("-- POWER LOST --", this.LabelStyles["red"]); GUILayout.Label("-- POWER LOST --", this.LabelStyles["red"]);
} }
   
this.configWindowMinimized.value = !GUILayout.Toggle(!this.configWindowMinimized, "Configuration"); this.configWindowMinimized.value = !GUILayout.Toggle(!this.configWindowMinimized, "Configuration");
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow(); GUI.DragWindow();
} }
   
public void VOIDConfigWindow(int _) public void VOIDConfigWindow(int _)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
this.DrawConfigurables(); this.DrawConfigurables();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow(); GUI.DragWindow();
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
GUIContent _content; GUIContent _content;
   
if (HighLogic.LoadedSceneIsFlight) if (HighLogic.LoadedSceneIsFlight)
{ {
this.consumeResource.value = GUILayout.Toggle(this.consumeResource, "Consume Resources"); this.consumeResource.value = GUILayout.Toggle(this.consumeResource, "Consume Resources");
   
this.VOIDIconLocked = GUILayout.Toggle(this.VOIDIconLocked, "Lock Icon Position"); this.VOIDIconLocked = GUILayout.Toggle(this.VOIDIconLocked, "Lock Icon Position");
} }
   
this.UseToolbarManager = GUILayout.Toggle(this.UseToolbarManager, "Use Blizzy's Toolbar If Available"); this.UseToolbarManager = GUILayout.Toggle(this.UseToolbarManager, "Use Blizzy's Toolbar If Available");
   
this.vesselSimActive.value = GUILayout.Toggle(this.vesselSimActive.value, this.vesselSimActive.value = GUILayout.Toggle(this.vesselSimActive.value,
"Enable Engineering Calculations"); "Enable Engineering Calculations");
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
GUILayout.Label("Skin:", GUILayout.ExpandWidth(false)); GUILayout.Label("Skin:", GUILayout.ExpandWidth(false));
   
_content = new GUIContent(); _content = new GUIContent();
   
_content.text = "◄"; _content.text = "◄";
_content.tooltip = "Select previous skin"; _content.tooltip = "Select previous skin";
if (GUILayout.Button(_content, GUILayout.ExpandWidth(true))) if (GUILayout.Button(_content, GUILayout.ExpandWidth(true)))
{ {
this.GUIStylesLoaded = false; this.GUIStylesLoaded = false;
this._skinIdx--; this._skinIdx--;
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: new this._skinIdx = {1} :: skin_list.Count = {2}", "{0}: new this._skinIdx = {1} :: skin_list.Count = {2}",
this.GetType().Name, this.GetType().Name,
this._skinName, this._skinName,
this.validSkins.Count this.validSkins.Count
)); ));
} }
   
_content.text = this.Skin.name; _content.text = this.Skin.name;
_content.tooltip = "Current skin"; _content.tooltip = "Current skin";
GUILayout.Label(_content, this.LabelStyles["center"], GUILayout.ExpandWidth(true)); GUILayout.Label(_content, this.LabelStyles["center"], GUILayout.ExpandWidth(true));
   
_content.text = "►"; _content.text = "►";
_content.tooltip = "Select next skin"; _content.tooltip = "Select next skin";
if (GUILayout.Button(_content, GUILayout.ExpandWidth(true))) if (GUILayout.Button(_content, GUILayout.ExpandWidth(true)))
{ {
this.GUIStylesLoaded = false; this.GUIStylesLoaded = false;
this._skinIdx++; this._skinIdx++;
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: new this._skinIdx = {1} :: skin_list.Count = {2}", "{0}: new this._skinIdx = {1} :: skin_list.Count = {2}",
this.GetType().Name, this.GetType().Name,
this._skinName, this._skinName,
this.validSkins.Count this.validSkins.Count
)); ));
} }
   
this._skinIdx %= this.skinNames.Length; this._skinIdx %= this.skinNames.Length;
if (this._skinIdx < 0) if (this._skinIdx < 0)
{ {
this._skinIdx += this.skinNames.Length; this._skinIdx += this.skinNames.Length;
} }
   
if (this._skinName != skinNames[this._skinIdx]) if (this._skinName != skinNames[this._skinIdx])
{ {
this._skinName.value = skinNames[this._skinIdx]; this._skinName.value = skinNames[this._skinIdx];
} }
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
GUILayout.Label("Update Rate (Hz):"); GUILayout.Label("Update Rate (Hz):");
if (this.stringFrequency == null) if (this.stringFrequency == null)
{ {
this.stringFrequency = (1f / this.updatePeriod).ToString(); this.stringFrequency = (1f / this.updatePeriod).ToString();
} }
this.stringFrequency = GUILayout.TextField(this.stringFrequency.ToString(), 5, GUILayout.ExpandWidth(true)); this.stringFrequency = GUILayout.TextField(this.stringFrequency.ToString(), 5, GUILayout.ExpandWidth(true));
   
if (GUILayout.Button("Apply")) if (GUILayout.Button("Apply"))
{ {
double updateFreq = 1f / this.updatePeriod; double updateFreq = 1f / this.updatePeriod;
double.TryParse(stringFrequency, out updateFreq); double.TryParse(stringFrequency, out updateFreq);
this._updatePeriod = 1 / updateFreq; this._updatePeriod = 1 / updateFreq;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
foreach (IVOID_Module mod in this.Modules) foreach (IVOID_Module mod in this.Modules)
{ {
mod.DrawConfigurables(); mod.DrawConfigurables();
} }
   
this._factoryReset = GUILayout.Toggle(this._factoryReset, "Factory Reset"); this._factoryReset = GUILayout.Toggle(this._factoryReset, "Factory Reset");
} }
   
protected void UpdateSimManager() protected void UpdateSimManager()
{ {
if (SimManager.ResultsReady()) if (SimManager.ResultsReady())
{ {
Tools.PostDebugMessage(this, "VesselSimulator results ready, setting Stages."); Tools.PostDebugMessage(this, "VesselSimulator results ready, setting Stages.");
   
this.Stages = SimManager.Stages; this.Stages = SimManager.Stages;
   
if (this.Stages != null) if (this.Stages != null)
{ {
this.LastStage = this.Stages.Last(); this.LastStage = this.Stages.Last();
} }
   
if (HighLogic.LoadedSceneIsEditor) if (HighLogic.LoadedSceneIsEditor)
{ {
SimManager.Gravity = VOID_Data.KerbinGee; SimManager.Gravity = VOID_Data.KerbinGee;
} }
else else
{ {
double radius = this.vessel.Radius(); double radius = this.vessel.Radius();
SimManager.Gravity = this.vessel.mainBody.gravParameter / (radius * radius); SimManager.Gravity = this.vessel.mainBody.gravParameter / (radius * radius);
} }
   
SimManager.minSimTime = (long)(this.updatePeriod * 1000); SimManager.minSimTime = (long)(this.updatePeriod * 1000);
   
SimManager.TryStartSimulation(); SimManager.TryStartSimulation();
} }
#if DEBUG #if DEBUG
else else
{ {
Tools.PostDebugMessage(this, "VesselSimulator results not ready."); Tools.PostDebugMessage(this, "VesselSimulator results not ready.");
} }
#endif #endif
} }
   
protected void LoadModulesOfType<T>() protected void LoadModulesOfType<T>()
{ {
StringBuilder sb = new StringBuilder("Loading modules..."); StringBuilder sb = new StringBuilder("Loading modules...");
sb.AppendLine(); sb.AppendLine();
   
foreach (AssemblyLoader.LoadedAssembly assy in AssemblyLoader.loadedAssemblies) foreach (AssemblyLoader.LoadedAssembly assy in AssemblyLoader.loadedAssemblies)
{ {
foreach (Type loadedType in assy.assembly.GetExportedTypes()) foreach (Type loadedType in assy.assembly.GetExportedTypes())
{ {
if ( if (
loadedType.IsInterface || loadedType.IsInterface ||
loadedType.IsAbstract || loadedType.IsAbstract ||
!typeof(T).IsAssignableFrom(loadedType) || !typeof(T).IsAssignableFrom(loadedType) ||
this.GetType().IsAssignableFrom(loadedType) this.GetType().IsAssignableFrom(loadedType)
) )
{ {
continue; continue;
} }
   
// HACK: This stops editor modules from loading in flight. It is a dirty hack and should be fixed. // HACK: This stops editor modules from loading in flight. It is a dirty hack and should be fixed.
if (!HighLogic.LoadedSceneIsEditor && typeof(IVOID_EditorModule).IsAssignableFrom(loadedType)) if (!HighLogic.LoadedSceneIsEditor && typeof(IVOID_EditorModule).IsAssignableFrom(loadedType))
{ {
continue; continue;
} }
   
sb.AppendFormat("Loading IVOID_Module type {0}...", loadedType.Name); sb.AppendFormat("Loading IVOID_Module type {0}...", loadedType.Name);
   
try try
{ {
this.LoadModule(loadedType); this.LoadModule(loadedType);
sb.AppendLine("Success."); sb.AppendLine("Success.");
} }
catch (Exception ex) catch (Exception ex)
{ {
sb.AppendFormat("Failed, caught {0}", ex.GetType().Name); sb.AppendFormat("Failed, caught {0}", ex.GetType().Name);
sb.AppendLine(); sb.AppendLine();
   
#if DEBUG #if DEBUG
Debug.LogException(ex); Debug.LogException(ex);
#endif #endif
} }
} }
} }
   
this._modulesLoaded = true; this._modulesLoaded = true;
   
sb.AppendFormat("Loaded {0} modules.", this.Modules.Count); sb.AppendFormat("Loaded {0} modules.", this.Modules.Count);
sb.AppendLine(); sb.AppendLine();
} }
   
protected void LoadModule(Type T) protected void LoadModule(Type T)
{ {
var existingModules = this._modules.Where(mod => mod.GetType().Name == T.Name); var existingModules = this._modules.Where(mod => mod.GetType().Name == T.Name);
if (existingModules.Any()) if (existingModules.Any())
{ {
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: refusing to load {1}: already loaded", "{0}: refusing to load {1}: already loaded",
this.GetType().Name, this.GetType().Name,
T.Name T.Name
)); ));
return; return;
} }
IVOID_Module module = Activator.CreateInstance(T) as IVOID_Module; IVOID_Module module = Activator.CreateInstance(T) as IVOID_Module;
module.LoadConfig(); module.LoadConfig();
this._modules.Add(module); this._modules.Add(module);
   
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: loaded module {1}.", "{0}: loaded module {1}.",
this.GetType().Name, this.GetType().Name,
T.Name T.Name
)); ));
} }
   
protected void LoadSkins() protected void LoadSkins()
{ {
Tools.PostDebugMessage("AssetBase has skins: \n" + Tools.PostDebugMessage("AssetBase has skins: \n" +
string.Join("\n\t", string.Join("\n\t",
Resources.FindObjectsOfTypeAll(typeof(GUISkin)) Resources.FindObjectsOfTypeAll(typeof(GUISkin))
.Select(s => s.ToString()) .Select(s => s.ToString())
.ToArray() .ToArray()
) )
); );
   
this.validSkins = Resources.FindObjectsOfTypeAll(typeof(GUISkin)) this.validSkins = Resources.FindObjectsOfTypeAll(typeof(GUISkin))
.Where(s => !this.forbiddenSkins.Contains(s.name)) .Where(s => !this.forbiddenSkins.Contains(s.name))
.Select(s => s as GUISkin) .Select(s => s as GUISkin)
.GroupBy(s => s.name) .GroupBy(s => s.name)
.Select(g => g.First()) .Select(g => g.First())
.ToDictionary(s => s.name); .ToDictionary(s => s.name);
   
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: loaded {1} GUISkins.", "{0}: loaded {1} GUISkins.",
this.GetType().Name, this.GetType().Name,
this.validSkins.Count this.validSkins.Count
)); ));
   
this.skinNames = this.validSkins.Keys.ToArray(); this.skinNames = this.validSkins.Keys.ToArray();
Array.Sort(this.skinNames); Array.Sort(this.skinNames);
   
int defaultIdx = int.MinValue; int defaultIdx = int.MinValue;
   
for (int i = 0; i < this.skinNames.Length; i++) for (int i = 0; i < this.skinNames.Length; i++)
{ {
if (this.skinNames[i] == this._skinName) if (this.skinNames[i] == this._skinName)
{ {
this._skinIdx = i; this._skinIdx = i;
} }
if (this.skinNames[i] == this.defaultSkin) if (this.skinNames[i] == this.defaultSkin)
{ {
defaultIdx = i; defaultIdx = i;
} }
if (this._skinIdx != int.MinValue && defaultIdx != int.MinValue) if (this._skinIdx != int.MinValue && defaultIdx != int.MinValue)
{ {
break; break;
} }
} }
   
if (this._skinIdx == int.MinValue) if (this._skinIdx == int.MinValue)
{ {
this._skinIdx = defaultIdx; this._skinIdx = defaultIdx;
} }
   
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: _skinIdx = {1}.", "{0}: _skinIdx = {1}.",
this.GetType().Name, this.GetType().Name,
this._skinName.ToString() this._skinName.ToString()
)); ));
   
this.skinsLoaded = true; this.skinsLoaded = true;
} }
   
protected void LoadGUIStyles() protected void LoadGUIStyles()
{ {
this.LabelStyles["link"] = new GUIStyle(GUI.skin.label); this.LabelStyles["link"] = new GUIStyle(GUI.skin.label);
this.LabelStyles["link"].fontStyle = FontStyle.Bold; this.LabelStyles["link"].fontStyle = FontStyle.Bold;
   
this.LabelStyles["center"] = new GUIStyle(GUI.skin.label); this.LabelStyles["center"] = new GUIStyle(GUI.skin.label);
this.LabelStyles["center"].normal.textColor = Color.white; this.LabelStyles["center"].normal.textColor = Color.white;
this.LabelStyles["center"].alignment = TextAnchor.UpperCenter; this.LabelStyles["center"].alignment = TextAnchor.UpperCenter;
   
this.LabelStyles["center_bold"] = new GUIStyle(GUI.skin.label); this.LabelStyles["center_bold"] = new GUIStyle(GUI.skin.label);
this.LabelStyles["center_bold"].normal.textColor = Color.white; this.LabelStyles["center_bold"].normal.textColor = Color.white;
this.LabelStyles["center_bold"].alignment = TextAnchor.UpperCenter; this.LabelStyles["center_bold"].alignment = TextAnchor.UpperCenter;
this.LabelStyles["center_bold"].fontStyle = FontStyle.Bold; this.LabelStyles["center_bold"].fontStyle = FontStyle.Bold;
   
this.LabelStyles["right"] = new GUIStyle(GUI.skin.label); this.LabelStyles["right"] = new GUIStyle(GUI.skin.label);
this.LabelStyles["right"].normal.textColor = Color.white; this.LabelStyles["right"].normal.textColor = Color.white;
this.LabelStyles["right"].alignment = TextAnchor.UpperRight; this.LabelStyles["right"].alignment = TextAnchor.UpperRight;
   
this.LabelStyles["red"] = new GUIStyle(GUI.skin.label); this.LabelStyles["red"] = new GUIStyle(GUI.skin.label);
this.LabelStyles["red"].normal.textColor = Color.red; this.LabelStyles["red"].normal.textColor = Color.red;
this.LabelStyles["red"].alignment = TextAnchor.MiddleCenter; this.LabelStyles["red"].alignment = TextAnchor.MiddleCenter;
   
this.iconStyle = new GUIStyle(GUI.skin.button); this.iconStyle = new GUIStyle(GUI.skin.button);
this.iconStyle.padding = new RectOffset(0, 0, 0, 0); this.iconStyle.padding = new RectOffset(0, 0, 0, 0);
this.iconStyle.overflow = new RectOffset(0, 0, 0, 0); this.iconStyle.overflow = new RectOffset(0, 0, 0, 0);
   
this.GUIStylesLoaded = true; this.GUIStylesLoaded = true;
} }
   
protected void LoadVesselTypes() protected void LoadVesselTypes()
{ {
this._allVesselTypes = Enum.GetValues(typeof(VesselType)).OfType<VesselType>().ToList(); this._allVesselTypes = Enum.GetValues(typeof(VesselType)).OfType<VesselType>().ToList();
this.vesselTypesLoaded = true; this.vesselTypesLoaded = true;
} }
   
protected void LoadBeforeUpdate() protected void LoadBeforeUpdate()
{ {
if (!this.vesselTypesLoaded) if (!this.vesselTypesLoaded)
{ {
this.LoadVesselTypes(); this.LoadVesselTypes();
} }
} }
   
protected void InitializeToolbarButton() protected void InitializeToolbarButton()
{ {
// Do nothing if (the Toolbar is not available. // Do nothing if (the Toolbar is not available.
if (!ToolbarManager.ToolbarAvailable) if (!ToolbarManager.ToolbarAvailable)
{ {
  Tools.PostDebugMessage(this, "Refusing to make a ToolbarButton: ToolbarAvailable = false");
return; return;
} }
   
this.ToolbarButton = ToolbarManager.Instance.add(this.VoidName, "coreToggle"); this.ToolbarButton = ToolbarManager.Instance.add(this.VoidName, "coreToggle");
this.ToolbarButton.Text = this.VoidName; this.ToolbarButton.Text = this.VoidName;
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
   
this.ToolbarButton.Visibility = new GameScenesVisibility(GameScenes.EDITOR, GameScenes.FLIGHT, GameScenes.SPH); this.ToolbarButton.Visibility = new GameScenesVisibility(GameScenes.EDITOR, GameScenes.FLIGHT, GameScenes.SPH);
   
this.ToolbarButton.OnClick += this.ToolbarButton.OnClick +=
(e) => (e) =>
{ {
this.ToggleMainWindow(); this.ToggleMainWindow();
}; };
   
Tools.PostDebugMessage(string.Format("{0}: Toolbar Button initialized.", this.GetType().Name)); Tools.PostDebugMessage(string.Format("{0}: Toolbar Button initialized.", this.GetType().Name));
} }
   
protected void InitializeAppLauncherButton() protected void InitializeAppLauncherButton()
{ {
if (ApplicationLauncher.Ready) if (ApplicationLauncher.Ready)
{ {
this.AppLauncherButton = ApplicationLauncher.Instance.AddModApplication( this.AppLauncherButton = ApplicationLauncher.Instance.AddModApplication(
this.ToggleMainWindow, this.ToggleMainWindow, this.ToggleMainWindow, this.ToggleMainWindow,
this.appIconVisibleScenes, this.appIconVisibleScenes,
this.VOIDIconTexture this.VOIDIconTexture
); );
   
Tools.PostDebugMessage( Tools.PostDebugMessage(
this, this,
"AppLauncherButton initialized in {0}", "AppLauncherButton initialized in {0}",
Enum.GetName( Enum.GetName(
typeof(GameScenes), typeof(GameScenes),
HighLogic.LoadedScene HighLogic.LoadedScene
) )
); );
} }
} }
   
protected void ToggleMainWindow() protected void ToggleMainWindow()
{ {
this.mainGuiMinimized = !this.mainGuiMinimized; this.mainGuiMinimized = !this.mainGuiMinimized;
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
} }
   
protected void SetIconTexture(IconState state) protected void SetIconTexture(IconState state)
{ {
switch (state) switch (state)
{ {
case (IconState.PowerOff | IconState.Inactive): case (IconState.PowerOff | IconState.Inactive):
this.SetIconTexture(this.VOIDIconOffInactivePath); this.SetIconTexture(this.VOIDIconOffInactivePath);
break; break;
case (IconState.PowerOff | IconState.Active): case (IconState.PowerOff | IconState.Active):
this.SetIconTexture(this.VOIDIconOffActivePath); this.SetIconTexture(this.VOIDIconOffActivePath);
break; break;
case (IconState.PowerOn | IconState.Inactive): case (IconState.PowerOn | IconState.Inactive):
this.SetIconTexture(this.VOIDIconOnInactivePath); this.SetIconTexture(this.VOIDIconOnInactivePath);
break; break;
case (IconState.PowerOn | IconState.Active): case (IconState.PowerOn | IconState.Active):
this.SetIconTexture(this.VOIDIconOnActivePath); this.SetIconTexture(this.VOIDIconOnActivePath);
break; break;
default: default:
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
   
protected void SetIconTexture(string texturePath) protected void SetIconTexture(string texturePath)
{ {
if (this.ToolbarButton != null) if (this.ToolbarButton != null)
{ {
this.ToolbarButton.TexturePath = texturePath; this.ToolbarButton.TexturePath = texturePath;
} }
   
this.VOIDIconTexture = GameDatabase.Instance.GetTexture(texturePath.Replace("icon", "appIcon"), false); this.VOIDIconTexture = GameDatabase.Instance.GetTexture(texturePath.Replace("icon", "appIcon"), false);
   
if (this.AppLauncherButton != null) if (this.AppLauncherButton != null)
{ {
this.AppLauncherButton.SetTexture(VOIDIconTexture); this.AppLauncherButton.SetTexture(VOIDIconTexture);
} }
} }
   
protected void CheckAndSave() protected void CheckAndSave()
{ {
this.saveTimer += Time.deltaTime; this.saveTimer += Time.deltaTime;
   
if (this.saveTimer > 2f) if (this.saveTimer > 2f)
{ {
if (!this.configDirty) if (!this.configDirty)
{ {
return; return;
} }
   
Tools.PostDebugMessage(string.Format( Tools.PostDebugMessage(string.Format(
"{0}: Time to save, checking if configDirty: {1}", "{0}: Time to save, checking if configDirty: {1}",
this.GetType().Name, this.GetType().Name,
this.configDirty this.configDirty
)); ));
   
this.SaveConfig(); this.SaveConfig();
this.saveTimer = 0; this.saveTimer = 0;
} }
} }
   
public override void LoadConfig() public override void LoadConfig()
{ {
base.LoadConfig(); base.LoadConfig();
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.Modules)
{ {
module.LoadConfig(); module.LoadConfig();
} }
} }
   
public void SaveConfig() public void SaveConfig()
{ {
var config = KSP.IO.PluginConfiguration.CreateForType<VOID_Core>(); var config = KSP.IO.PluginConfiguration.CreateForType<VOID_Core>();
config.load(); config.load();
   
this._SaveToConfig(config); this._SaveToConfig(config);
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.Modules)
{ {
module._SaveToConfig(config); module._SaveToConfig(config);
} }
   
config.save(); config.save();
   
this.configDirty = false; this.configDirty = false;
} }
   
protected VOID_Core() protected VOID_Core()
{ {
this._Name = "VOID Core"; this._Name = "VOID Core";
   
System.Version version = this.GetType().Assembly.GetName().Version; System.Version version = this.GetType().Assembly.GetName().Version;
   
this.VoidVersion = string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.MajorRevision); this.VoidVersion = string.Format("{0}.{1}.{2}", version.Major, version.Minor, version.MajorRevision);
   
this.toggleActive = true; this.toggleActive = true;
   
this._skinName = this.defaultSkin; this._skinName = this.defaultSkin;
this._skinIdx = int.MinValue; this._skinIdx = int.MinValue;
   
this.VOIDIconOnInactivePath = "VOID/Textures/void_icon_light_glow"; this.VOIDIconOnInactivePath = "VOID/Textures/void_icon_light_glow";
this.VOIDIconOnActivePath = "VOID/Textures/void_icon_dark_glow"; this.VOIDIconOnActivePath = "VOID/Textures/void_icon_dark_glow";
this.VOIDIconOffInactivePath = "VOID/Textures/void_icon_light"; this.VOIDIconOffInactivePath = "VOID/Textures/void_icon_light";
this.VOIDIconOffActivePath = "VOID/Textures/void_icon_dark"; this.VOIDIconOffActivePath = "VOID/Textures/void_icon_dark";
   
this.vesselSimActive = true; this.vesselSimActive = true;
   
this.UseToolbarManager = false; this.UseToolbarManager = false;
   
this.LoadConfig(); this.LoadConfig();
   
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
} }
   
public virtual void Dispose() public virtual void Dispose()
{ {
if (this.AppLauncherButton != null) if (this.AppLauncherButton != null)
{ {
ApplicationLauncher.Instance.RemoveModApplication(this.AppLauncherButton); ApplicationLauncher.Instance.RemoveModApplication(this.AppLauncherButton);
this.AppLauncherButton = null; this.AppLauncherButton = null;
} }
if (this.ToolbarButton != null) if (this.ToolbarButton != null)
{ {
this.ToolbarButton.Destroy(); this.ToolbarButton.Destroy();
this.ToolbarButton = null; this.ToolbarButton = null;
} }
} }
   
protected enum IconState protected enum IconState
{ {
PowerOff = 1, PowerOff = 1,
PowerOn = 2, PowerOn = 2,
Inactive = 4, Inactive = 4,
Active = 8 Active = 8
} }
} }
   
public static partial class VOID_Data public static partial class VOID_Data
{ {
public static VOID_Core core public static VOID_Core core
{ {
get get
{ {
if (HighLogic.LoadedSceneIsEditor) if (HighLogic.LoadedSceneIsEditor)
{ {
return VOID_EditorCore.Instance; return VOID_EditorCore.Instance;
} }
else else
{ {
return VOID_Core.Instance; return VOID_Core.Instance;
} }
} }
} }
   
public static double KerbinGee public static double KerbinGee
{ {
get get
{ {
if (kerbinGee == default(double)) if (kerbinGee == default(double))
{ {
kerbinGee = core.Kerbin.gravParameter / (core.Kerbin.Radius * core.Kerbin.Radius); kerbinGee = core.Kerbin.gravParameter / (core.Kerbin.Radius * core.Kerbin.Radius);
} }
   
return kerbinGee; return kerbinGee;
} }
} }
   
private static double kerbinGee; private static double kerbinGee;
} }
} }
   
   
// VOID // VOID
// //
// VOID_DataLogger.cs // VOID_DataLogger.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_DataLogger : VOID_WindowModule, IVOID_BehaviorModule public class VOID_DataLogger : VOID_WindowModule, IVOID_BehaviorModule
{ {
/* /*
* Fields * Fields
* */ * */
protected bool stopwatch1_running; protected bool stopwatch1_running;
   
protected bool csv_logging; protected bool csv_logging;
protected bool first_write; protected bool first_write;
   
protected double stopwatch1; protected double stopwatch1;
   
protected string csv_log_interval_str; protected string csv_log_interval_str;
   
protected float csv_log_interval; protected float csv_log_interval;
   
protected double csvWriteTimer; protected double csvWriteTimer;
protected double csvCollectTimer; protected double csvCollectTimer;
   
protected List<string> csvList = new List<string>(); protected List<string> csvList = new List<string>();
   
/* /*
* Properties * Properties
* */ * */
   
   
/* /*
* Methods * Methods
* */ * */
public VOID_DataLogger() public VOID_DataLogger()
{ {
this._Name = "CSV Data Logger"; this._Name = "CSV Data Logger";
   
this.stopwatch1_running = false; this.stopwatch1_running = false;
   
this.csv_logging = false; this.csv_logging = false;
this.first_write = true; this.first_write = true;
   
this.stopwatch1 = 0; this.stopwatch1 = 0;
this.csv_log_interval_str = "0.5"; this.csv_log_interval_str = "0.5";
   
this.csvWriteTimer = 0; this.csvWriteTimer = 0;
this.csvCollectTimer = 0; this.csvCollectTimer = 0;
   
this.WindowPos.x = Screen.width - 520; this.WindowPos.x = Screen.width - 520;
this.WindowPos.y = 85; this.WindowPos.y = 85;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int _)
{ {
GUIStyle txt_white = new GUIStyle(GUI.skin.label); GUIStyle txt_white = new GUIStyle(GUI.skin.label);
txt_white.normal.textColor = txt_white.focused.textColor = Color.white; txt_white.normal.textColor = txt_white.focused.textColor = Color.white;
txt_white.alignment = TextAnchor.UpperRight; txt_white.alignment = TextAnchor.UpperRight;
GUIStyle txt_green = new GUIStyle(GUI.skin.label); GUIStyle txt_green = new GUIStyle(GUI.skin.label);
txt_green.normal.textColor = txt_green.focused.textColor = Color.green; txt_green.normal.textColor = txt_green.focused.textColor = Color.green;
txt_green.alignment = TextAnchor.UpperRight; txt_green.alignment = TextAnchor.UpperRight;
GUIStyle txt_yellow = new GUIStyle(GUI.skin.label); GUIStyle txt_yellow = new GUIStyle(GUI.skin.label);
txt_yellow.normal.textColor = txt_yellow.focused.textColor = Color.yellow; txt_yellow.normal.textColor = txt_yellow.focused.textColor = Color.yellow;
txt_yellow.alignment = TextAnchor.UpperRight; txt_yellow.alignment = TextAnchor.UpperRight;
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.Label("System time: " + DateTime.Now.ToString("HH:mm:ss")); GUILayout.Label("System time: " + DateTime.Now.ToString("HH:mm:ss"));
GUILayout.Label(VOID_Tools.ConvertInterval(stopwatch1)); GUILayout.Label(VOID_Tools.ConvertInterval(stopwatch1));
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("Start")) if (GUILayout.Button("Start"))
{ {
if (stopwatch1_running == false) stopwatch1_running = true; if (stopwatch1_running == false) stopwatch1_running = true;
} }
if (GUILayout.Button("Stop")) if (GUILayout.Button("Stop"))
{ {
if (stopwatch1_running == true) stopwatch1_running = false; if (stopwatch1_running == true) stopwatch1_running = false;
} }
if (GUILayout.Button("Reset")) if (GUILayout.Button("Reset"))
{ {
if (stopwatch1_running == true) stopwatch1_running = false; if (stopwatch1_running == true) stopwatch1_running = false;
stopwatch1 = 0; stopwatch1 = 0;
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUIStyle label_style = txt_white; GUIStyle label_style = txt_white;
string log_label = "Inactive"; string log_label = "Inactive";
if (csv_logging && vessel.situation.ToString() == "PRELAUNCH") if (csv_logging && vessel.situation.ToString() == "PRELAUNCH")
{ {
log_label = "Awaiting launch"; log_label = "Awaiting launch";
label_style = txt_yellow; label_style = txt_yellow;
} }
if (csv_logging && vessel.situation.ToString() != "PRELAUNCH") if (csv_logging && vessel.situation.ToString() != "PRELAUNCH")
{ {
log_label = "Active"; log_label = "Active";
label_style = txt_green; label_style = txt_green;
} }
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
csv_logging = GUILayout.Toggle(csv_logging, "Data logging: ", GUILayout.ExpandWidth(false)); csv_logging = GUILayout.Toggle(csv_logging, "Data logging: ", GUILayout.ExpandWidth(false));
GUILayout.Label(log_label, label_style, GUILayout.ExpandWidth(true)); GUILayout.Label(log_label, label_style, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Interval: ", GUILayout.ExpandWidth(false)); GUILayout.Label("Interval: ", GUILayout.ExpandWidth(false));
csv_log_interval_str = GUILayout.TextField(csv_log_interval_str, GUILayout.ExpandWidth(true)); csv_log_interval_str = GUILayout.TextField(csv_log_interval_str, GUILayout.ExpandWidth(true));
GUILayout.Label("s", GUILayout.ExpandWidth(false)); GUILayout.Label("s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
float new_log_interval; float new_log_interval;
if (float.TryParse(csv_log_interval_str, out new_log_interval)) if (float.TryParse(csv_log_interval_str, out new_log_interval))
{ {
csv_log_interval = new_log_interval; csv_log_interval = new_log_interval;
} }
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow(); GUI.DragWindow();
} }
   
public void Update() public void Update()
{ {
// CSV Logging // CSV Logging
// from ISA MapSat // from ISA MapSat
if (csv_logging) if (csv_logging)
{ {
//data logging is on //data logging is on
//increment timers //increment timers
csvWriteTimer += Time.deltaTime; csvWriteTimer += Time.deltaTime;
csvCollectTimer += Time.deltaTime; csvCollectTimer += Time.deltaTime;
   
if (csvCollectTimer >= csv_log_interval && vessel.situation != Vessel.Situations.PRELAUNCH) if (csvCollectTimer >= csv_log_interval && vessel.situation != Vessel.Situations.PRELAUNCH)
{ {
//data logging is on, vessel is not prelaunch, and interval has passed //data logging is on, vessel is not prelaunch, and interval has passed
//write a line to the list //write a line to the list
line_to_csvList(); //write to the csv line_to_csvList(); //write to the csv
} }
   
if (csvList.Count != 0 && csvWriteTimer >= 15f) if (csvList.Count != 0 && csvWriteTimer >= 15f)
{ {
// csvList is not empty and interval between writings to file has elapsed // csvList is not empty and interval between writings to file has elapsed
//write it //write it
string[] csvData; string[] csvData;
csvData = (string[])csvList.ToArray(); csvData = (string[])csvList.ToArray();
Innsewerants_writeData(csvData); Innsewerants_writeData(csvData);
csvList.Clear(); csvList.Clear();
csvWriteTimer = 0f; csvWriteTimer = 0f;
} }
} }
else else
{ {
//data logging is off //data logging is off
//reset any timers and clear anything from csvList //reset any timers and clear anything from csvList
csvWriteTimer = 0f; csvWriteTimer = 0f;
csvCollectTimer = 0f; csvCollectTimer = 0f;
if (csvList.Count > 0) csvList.Clear(); if (csvList.Count > 0) csvList.Clear();
} }
   
if (stopwatch1_running) if (stopwatch1_running)
{ {
stopwatch1 += Time.deltaTime; stopwatch1 += Time.deltaTime;
} }
} }
   
public void FixedUpdate() {} public void FixedUpdate() {}
   
private void Innsewerants_writeData(string[] csvArray) private void Innsewerants_writeData(string[] csvArray)
{ {
var efile = KSP.IO.File.AppendText<VOID_Core>(vessel.vesselName + "_data.csv", null); var efile = KSP.IO.File.AppendText<VOID_Core>(vessel.vesselName + "_data.csv", null);
foreach (string line in csvArray) foreach (string line in csvArray)
{ {
efile.Write(line); efile.Write(line);
} }
efile.Close(); efile.Close();
} }
   
private void line_to_csvList() private void line_to_csvList()
{ {
//called if logging is on and interval has passed //called if logging is on and interval has passed
//writes one line to the csvList //writes one line to the csvList
   
StringBuilder line = new StringBuilder(); StringBuilder line = new StringBuilder();
   
if (first_write && !KSP.IO.File.Exists<VOID_Core>(vessel.vesselName + "_data.csv", null)) if (first_write && !KSP.IO.File.Exists<VOID_Core>(vessel.vesselName + "_data.csv", null))
{ {
first_write = false; first_write = false;
line.Append( line.Append(
"Mission Elapsed Time (s);" + "Mission Elapsed Time (s);" +
"Altitude ASL (m);" + "Altitude ASL (m);" +
"Altitude above terrain (m);" + "Altitude above terrain (m);" +
"Surface Latitude (°);" + "Surface Latitude (°);" +
"Surface Longitude (°);" + "Surface Longitude (°);" +
"Orbital Velocity (m/s);" + "Orbital Velocity (m/s);" +
"Surface Velocity (m/s);" + "Surface Velocity (m/s);" +
"Vertical Speed (m/s);" + "Vertical Speed (m/s);" +
"Horizontal Speed (m/s);" + "Horizontal Speed (m/s);" +
"Gee Force (gees);" + "Gee Force (gees);" +
"Temperature (°C);" + "Temperature (°C);" +
"Gravity (m/s²);" + "Gravity (m/s²);" +
"Atmosphere Density (g/m³);" + "Atmosphere Density (g/m³);" +
  "Downrange Distance (m);" +
"\n" "\n"
); );
} }
   
//Mission time //Mission time
line.Append(vessel.missionTime.ToString("F3")); line.Append(vessel.missionTime.ToString("F3"));
line.Append(';'); line.Append(';');
   
//Altitude ASL //Altitude ASL
line.Append(vessel.orbit.altitude.ToString("F3")); line.Append(vessel.orbit.altitude.ToString("F3"));
line.Append(';'); line.Append(';');
   
//Altitude (true) //Altitude (true)
double alt_true = vessel.orbit.altitude - vessel.terrainAltitude; double alt_true = vessel.orbit.altitude - vessel.terrainAltitude;
if (vessel.terrainAltitude < 0) alt_true = vessel.orbit.altitude; if (vessel.terrainAltitude < 0) alt_true = vessel.orbit.altitude;
line.Append(alt_true.ToString("F3")); line.Append(alt_true.ToString("F3"));
line.Append(';'); line.Append(';');
   
// Surface Latitude // Surface Latitude
line.Append(VOID_Data.surfLatitude.Value); line.Append(VOID_Data.surfLatitude.Value);
line.Append(';'); line.Append(';');
   
// Surface Longitude // Surface Longitude
line.Append(VOID_Data.surfLongitude.Value); line.Append(VOID_Data.surfLongitude.Value);
line.Append(';'); line.Append(';');
   
//Orbital velocity //Orbital velocity
line.Append(vessel.orbit.vel.magnitude.ToString("F3")); line.Append(vessel.orbit.vel.magnitude.ToString("F3"));
line.Append(';'); line.Append(';');
   
//surface velocity //surface velocity
line.Append(vessel.srf_velocity.magnitude.ToString("F3")); line.Append(vessel.srf_velocity.magnitude.ToString("F3"));
line.Append(';'); line.Append(';');
   
//vertical speed //vertical speed
line.Append(vessel.verticalSpeed.ToString("F3")); line.Append(vessel.verticalSpeed.ToString("F3"));
line.Append(';'); line.Append(';');
   
//horizontal speed //horizontal speed
line.Append(vessel.horizontalSrfSpeed.ToString("F3")); line.Append(vessel.horizontalSrfSpeed.ToString("F3"));
line.Append(';'); line.Append(';');
   
//gee force //gee force
line.Append(vessel.geeForce.ToString("F3")); line.Append(vessel.geeForce.ToString("F3"));
line.Append(';'); line.Append(';');
   
//temperature //temperature
line.Append(vessel.flightIntegrator.getExternalTemperature().ToString("F2")); line.Append(vessel.flightIntegrator.getExternalTemperature().ToString("F2"));
line.Append(';'); line.Append(';');
   
//gravity //gravity
double r_vessel = vessel.mainBody.Radius + vessel.mainBody.GetAltitude(vessel.findWorldCenterOfMass()); double r_vessel = vessel.mainBody.Radius + vessel.mainBody.GetAltitude(vessel.findWorldCenterOfMass());
double g_vessel = (VOID_Core.Constant_G * vessel.mainBody.Mass) / (r_vessel * r_vessel); double g_vessel = (VOID_Core.Constant_G * vessel.mainBody.Mass) / (r_vessel * r_vessel);
line.Append(g_vessel.ToString("F3")); line.Append(g_vessel.ToString("F3"));
line.Append(';'); line.Append(';');
   
//atm density //atm density
line.Append((vessel.atmDensity * 1000).ToString("F3")); line.Append((vessel.atmDensity * 1000).ToString("F3"));
line.Append(';'); line.Append(';');
   
  // Downrange Distance
  line.Append((VOID_Data.downrangeDistance.Value.ToString("G3")));
  line.Append(';');
   
line.Append('\n'); line.Append('\n');
   
csvList.Add(line.ToString()); csvList.Add(line.ToString());
   
csvCollectTimer = 0f; csvCollectTimer = 0f;
} }
} }
} }
   
   
// VOID // VOID
// //
// VOID_HUD.cs // VOID_HUD.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
using Engineer.VesselSimulator; using Engineer.VesselSimulator;
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_HUD : VOID_Module, IVOID_Module public class VOID_HUD : VOID_Module, IVOID_Module
{ {
/* /*
* Fields * Fields
* */ * */
[AVOID_SaveValue("colorIndex")] [AVOID_SaveValue("colorIndex")]
protected VOID_SaveValue<int> _colorIndex; protected VOID_SaveValue<int> _colorIndex;
   
protected List<Color> textColors; protected List<Color> textColors;
   
protected Rect leftHUDdefaultPos; protected Rect leftHUDdefaultPos;
protected Rect rightHUDdefaultPos; protected Rect rightHUDdefaultPos;
   
[AVOID_SaveValue("leftHUDPos")] [AVOID_SaveValue("leftHUDPos")]
protected VOID_SaveValue<Rect> leftHUDPos; protected VOID_SaveValue<Rect> leftHUDPos;
[AVOID_SaveValue("rightHUDPos")] [AVOID_SaveValue("rightHUDPos")]
protected VOID_SaveValue<Rect> rightHUDPos; protected VOID_SaveValue<Rect> rightHUDPos;
   
[AVOID_SaveValue("positionsLocked")] [AVOID_SaveValue("positionsLocked")]
protected VOID_SaveValue<bool> positionsLocked; protected VOID_SaveValue<bool> positionsLocked;
   
/* /*
* Properties * Properties
* */ * */
public int ColorIndex public int ColorIndex
{ {
get get
{ {
return this._colorIndex; return this._colorIndex;
} }
set set
{ {
if (this._colorIndex >= this.textColors.Count - 1) if (this._colorIndex >= this.textColors.Count - 1)
{ {
this._colorIndex = 0; this._colorIndex = 0;
return; return;
} }
   
this._colorIndex = value; this._colorIndex = value;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public VOID_HUD() : base() public VOID_HUD() : base()
{ {
this._Name = "Heads-Up Display"; this._Name = "Heads-Up Display";
   
this.toggleActive = true; this.toggleActive = true;
   
this._colorIndex = 0; this._colorIndex = 0;
   
this.textColors = new List<Color>(); this.textColors = new List<Color>();
   
this.textColors.Add(Color.green); this.textColors.Add(Color.green);
this.textColors.Add(Color.black); this.textColors.Add(Color.black);
this.textColors.Add(Color.white); this.textColors.Add(Color.white);
this.textColors.Add(Color.red); this.textColors.Add(Color.red);
this.textColors.Add(Color.blue); this.textColors.Add(Color.blue);
this.textColors.Add(Color.yellow); this.textColors.Add(Color.yellow);
this.textColors.Add(Color.gray); this.textColors.Add(Color.gray);
this.textColors.Add(Color.cyan); this.textColors.Add(Color.cyan);
this.textColors.Add(Color.magenta); this.textColors.Add(Color.magenta);
   
this.leftHUDdefaultPos = new Rect(Screen.width * .375f - 300f, 0f, 300f, 90f); this.leftHUDdefaultPos = new Rect(Screen.width * .375f - 300f, 0f, 300f, 90f);
this.leftHUDPos = new Rect(this.leftHUDdefaultPos); this.leftHUDPos = new Rect(this.leftHUDdefaultPos);
   
this.rightHUDdefaultPos = new Rect(Screen.width * .625f, 0f, 300f, 90f); this.rightHUDdefaultPos = new Rect(Screen.width * .625f, 0f, 300f, 90f);
this.rightHUDPos = new Rect(this.rightHUDdefaultPos); this.rightHUDPos = new Rect(this.rightHUDdefaultPos);
   
this.positionsLocked = true; this.positionsLocked = true;
   
Tools.PostDebugMessage ("VOID_HUD: Constructed."); Tools.PostDebugMessage ("VOID_HUD: Constructed.");
} }
   
protected void leftHUDWindow(int id) protected void leftHUDWindow(int id)
{ {
StringBuilder leftHUD; StringBuilder leftHUD;
   
leftHUD = new StringBuilder(); leftHUD = new StringBuilder();
   
this.core.LabelStyles["hud"].alignment = TextAnchor.UpperRight; this.core.LabelStyles["hud"].alignment = TextAnchor.UpperRight;
   
if (this.core.powerAvailable) if (this.core.powerAvailable)
{ {
leftHUD.AppendFormat("Primary: {0} Inc: {1}", leftHUD.AppendFormat("Primary: {0} Inc: {1}",
VOID_Data.primaryName.ValueUnitString(), VOID_Data.primaryName.ValueUnitString(),
VOID_Data.orbitInclination.ValueUnitString("F3") VOID_Data.orbitInclination.ValueUnitString("F3")
); );
leftHUD.AppendFormat("\nObt Alt: {0} Obt Vel: {1}", leftHUD.AppendFormat("\nObt Alt: {0} Obt Vel: {1}",
VOID_Data.orbitAltitude.ToSIString(), VOID_Data.orbitAltitude.ToSIString(),
VOID_Data.orbitVelocity.ToSIString() VOID_Data.orbitVelocity.ToSIString()
); );
leftHUD.AppendFormat("\nAp: {0} ETA {1}", leftHUD.AppendFormat("\nAp: {0} ETA {1}",
VOID_Data.orbitApoAlt.ToSIString(), VOID_Data.orbitApoAlt.ToSIString(),
VOID_Data.timeToApo.ValueUnitString() VOID_Data.timeToApo.ValueUnitString()
); );
leftHUD.AppendFormat("\nPe: {0} ETA {1}", leftHUD.AppendFormat("\nPe: {0} ETA {1}",
VOID_Data.oribtPeriAlt.ToSIString(), VOID_Data.oribtPeriAlt.ToSIString(),
VOID_Data.timeToPeri.ValueUnitString() VOID_Data.timeToPeri.ValueUnitString()
); );
leftHUD.AppendFormat("\nTot Δv: {0} Stg Δv: {1}", leftHUD.AppendFormat("\nTot Δv: {0} Stg Δv: {1}",
VOID_Data.totalDeltaV.ToSIString(2), VOID_Data.totalDeltaV.ToSIString(2),
VOID_Data.stageDeltaV.ToSIString(2) VOID_Data.stageDeltaV.ToSIString(2)
); );
} }
else else
{ {
this.core.LabelStyles["hud"].normal.textColor = Color.red; this.core.LabelStyles["hud"].normal.textColor = Color.red;
leftHUD.Append(string.Intern("-- POWER LOST --")); leftHUD.Append(string.Intern("-- POWER LOST --"));
} }
   
GUILayout.Label(leftHUD.ToString(), this.core.LabelStyles["hud"], GUILayout.ExpandWidth(true)); GUILayout.Label(leftHUD.ToString(), this.core.LabelStyles["hud"], GUILayout.ExpandWidth(true));
   
if (!this.positionsLocked) if (!this.positionsLocked)
{ {
GUI.DragWindow(); GUI.DragWindow();
} }
   
GUI.BringWindowToBack(id); GUI.BringWindowToBack(id);
} }
   
protected void rightHUDWindow(int id) protected void rightHUDWindow(int id)
{ {
StringBuilder rightHUD; StringBuilder rightHUD;
   
rightHUD = new StringBuilder(); rightHUD = new StringBuilder();
   
this.core.LabelStyles["hud"].alignment = TextAnchor.UpperLeft; this.core.LabelStyles["hud"].alignment = TextAnchor.UpperLeft;
   
if (this.core.powerAvailable) if (this.core.powerAvailable)
{ {
rightHUD.AppendFormat("Biome: {0} Sit: {1}", rightHUD.AppendFormat("Biome: {0} Sit: {1}",
VOID_Data.currBiome.ValueUnitString(), VOID_Data.currBiome.ValueUnitString(),
VOID_Data.expSituation.ValueUnitString() VOID_Data.expSituation.ValueUnitString()
); );
rightHUD.AppendFormat("\nSrf Alt: {0} Srf Vel: {1}", rightHUD.AppendFormat("\nSrf Alt: {0} Srf Vel: {1}",
VOID_Data.trueAltitude.ToSIString(), VOID_Data.trueAltitude.ToSIString(),
VOID_Data.surfVelocity.ToSIString() VOID_Data.surfVelocity.ToSIString()
); );
rightHUD.AppendFormat("\nVer: {0} Hor: {1}", rightHUD.AppendFormat("\nVer: {0} Hor: {1}",
VOID_Data.vertVelocity.ToSIString(), VOID_Data.vertVelocity.ToSIString(),
VOID_Data.horzVelocity.ToSIString() VOID_Data.horzVelocity.ToSIString()
); );
rightHUD.AppendFormat("\nLat: {0} Lon: {1}", rightHUD.AppendFormat("\nLat: {0} Lon: {1}",
VOID_Data.surfLatitude.ValueUnitString(), VOID_Data.surfLatitude.ValueUnitString(),
VOID_Data.surfLongitude.ValueUnitString() VOID_Data.surfLongitude.ValueUnitString()
); );
rightHUD.AppendFormat("\nHdg: {0} Pit: {1}", rightHUD.AppendFormat("\nHdg: {0} Pit: {1}",
VOID_Data.vesselHeading.ValueUnitString(), VOID_Data.vesselHeading.ValueUnitString(),
VOID_Data.vesselPitch.ToSIString(2) VOID_Data.vesselPitch.ToSIString(2)
); );
   
  if (
  this.core.vessel.mainBody == this.core.Kerbin &&
  (
  this.core.vessel.situation == Vessel.Situations.FLYING ||
  this.core.vessel.situation == Vessel.Situations.SUB_ORBITAL ||
  this.core.vessel.situation == Vessel.Situations.LANDED ||
  this.core.vessel.situation == Vessel.Situations.SPLASHED
  )
  )
  {
  rightHUD.AppendFormat("\nRange to KSC: {0}", VOID_Data.downrangeDistance.ValueUnitString(2));
  }
} }
else else
{ {
this.core.LabelStyles["hud"].normal.textColor = Color.red; this.core.LabelStyles["hud"].normal.textColor = Color.red;
rightHUD.Append(string.Intern("-- POWER LOST --")); rightHUD.Append(string.Intern("-- POWER LOST --"));
} }
   
   
GUILayout.Label(rightHUD.ToString(), this.core.LabelStyles["hud"], GUILayout.ExpandWidth(true)); GUILayout.Label(rightHUD.ToString(), this.core.LabelStyles["hud"], GUILayout.ExpandWidth(true));
   
if (!this.positionsLocked) if (!this.positionsLocked)
{ {
GUI.DragWindow(); GUI.DragWindow();
} }
   
GUI.BringWindowToBack(id); GUI.BringWindowToBack(id);
} }
   
public override void DrawGUI() public override void DrawGUI()
{ {
if (!this.core.LabelStyles.ContainsKey("hud")) if (!this.core.LabelStyles.ContainsKey("hud"))
{ {
this.core.LabelStyles["hud"] = new GUIStyle(GUI.skin.label); this.core.LabelStyles["hud"] = new GUIStyle(GUI.skin.label);
} }
   
this.core.LabelStyles["hud"].normal.textColor = textColors [ColorIndex]; this.core.LabelStyles["hud"].normal.textColor = textColors [ColorIndex];
   
GUI.skin = this.core.Skin; GUI.skin = this.core.Skin;
   
if ((TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate)) if ((TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate))
{ {
SimManager.RequestSimulation(); SimManager.RequestSimulation();
} }
   
this.leftHUDPos.value = GUI.Window( this.leftHUDPos.value = GUI.Window(
this.core.windowID, this.core.windowID,
this.leftHUDPos, this.leftHUDPos,
this.leftHUDWindow, VOID_Tools.GetWindowHandler(this.leftHUDWindow),
GUIContent.none, GUIContent.none,
GUIStyle.none GUIStyle.none
); );
   
this.rightHUDPos.value = GUI.Window( this.rightHUDPos.value = GUI.Window(
this.core.windowID, this.core.windowID,
this.rightHUDPos, this.rightHUDPos,
this.rightHUDWindow, VOID_Tools.GetWindowHandler(this.rightHUDWindow),
GUIContent.none, GUIContent.none,
GUIStyle.none GUIStyle.none
); );
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
if (GUILayout.Button (string.Intern("Change HUD color"), GUILayout.ExpandWidth (false))) if (GUILayout.Button (string.Intern("Change HUD color"), GUILayout.ExpandWidth (false)))
{ {
++this.ColorIndex; ++this.ColorIndex;
} }
   
if (GUILayout.Button(string.Intern("Reset HUD Positions"), GUILayout.ExpandWidth(false))) if (GUILayout.Button(string.Intern("Reset HUD Positions"), GUILayout.ExpandWidth(false)))
{ {
this.leftHUDPos = new Rect(this.leftHUDdefaultPos); this.leftHUDPos = new Rect(this.leftHUDdefaultPos);
this.rightHUDPos = new Rect(this.rightHUDdefaultPos); this.rightHUDPos = new Rect(this.rightHUDdefaultPos);
} }
   
this.positionsLocked = GUILayout.Toggle(this.positionsLocked, this.positionsLocked = GUILayout.Toggle(this.positionsLocked,
string.Intern("Lock HUD Positions"), string.Intern("Lock HUD Positions"),
GUILayout.ExpandWidth(false)); GUILayout.ExpandWidth(false));
} }
} }
   
public static partial class VOID_Data public static partial class VOID_Data
{ {
public static readonly VOID_StrValue expSituation = new VOID_StrValue( public static readonly VOID_StrValue expSituation = new VOID_StrValue(
"Situation", "Situation",
new Func<string> (() => core.vessel.GetExperimentSituation().HumanString()) new Func<string> (() => core.vessel.GetExperimentSituation().HumanString())
); );
   
public static readonly VOID_DoubleValue vesselPitch = new VOID_DoubleValue( public static readonly VOID_DoubleValue vesselPitch = new VOID_DoubleValue(
"Pitch", "Pitch",
() => core.vessel.getSurfacePitch(), () => core.vessel.getSurfacePitch(),
"°" "°"
); );
   
  public static readonly VOID_DoubleValue downrangeDistance = new VOID_DoubleValue(
  "Downrange Distance",
  delegate() {
   
  if (core.vessel == null ||
  Planetarium.fetch == null ||
  core.vessel.mainBody != Planetarium.fetch.Home
  )
  {
  return double.NaN;
  }
   
  double vesselLongitude = core.vessel.longitude * Math.PI / 180d;
  double vesselLatitude = core.vessel.latitude * Math.PI / 180d;
   
  const double kscLongitude = 285.442323427289 * Math.PI / 180d;
  const double kscLatitude = -0.0972112860655246 * Math.PI / 180d;
   
  double diffLon = vesselLongitude - kscLongitude;
  double diffLat = vesselLatitude - kscLatitude;
   
  double sinHalfDiffLat = Math.Sin(diffLat / 2d);
  double sinHalfDiffLon = Math.Sin(diffLon / 2d);
   
  double cosVesselLon = Math.Cos(vesselLongitude);
  double cosKSCLon = Math.Cos(kscLongitude);
   
  double haversine =
  sinHalfDiffLat * sinHalfDiffLat +
  cosVesselLon * cosKSCLon * sinHalfDiffLon * sinHalfDiffLon;
   
  double arc = 2d * Math.Atan2(Math.Sqrt(haversine), Math.Sqrt(1d - haversine));
   
  return core.vessel.mainBody.Radius * arc;
  },
  "m"
  );
} }
} }
   
// VOID // VOID
// //
// VOID_SurfAtmo.cs // VOID_SurfAtmo.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
using KSP; using KSP;
using System; using System;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_SurfAtmo : VOID_WindowModule public class VOID_SurfAtmo : VOID_WindowModule
{ {
[AVOID_SaveValue("precisionValues")] [AVOID_SaveValue("precisionValues")]
protected long _precisionValues = 230584300921369395; protected long _precisionValues = 230584300921369395;
protected IntCollection precisionValues; protected IntCollection precisionValues;
   
public VOID_SurfAtmo() public VOID_SurfAtmo()
{ {
this._Name = "Surface & Atmospheric Information"; this._Name = "Surface & Atmospheric Information";
   
this.WindowPos.x = Screen.width - 260f; this.WindowPos.x = Screen.width - 260f;
this.WindowPos.y = 85; this.WindowPos.y = 85;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int _)
{ {
int idx = 0; int idx = 0;
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
this.precisionValues [idx]= (ushort)VOID_Data.trueAltitude.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.trueAltitude.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
VOID_Data.surfLatitude.DoGUIHorizontal (); VOID_Data.surfLatitude.DoGUIHorizontal ();
   
VOID_Data.surfLongitude.DoGUIHorizontal (); VOID_Data.surfLongitude.DoGUIHorizontal ();
   
VOID_Data.vesselHeading.DoGUIHorizontal (); VOID_Data.vesselHeading.DoGUIHorizontal ();
   
this.precisionValues [idx]= (ushort)VOID_Data.terrainElevation.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.terrainElevation.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
  this.precisionValues[idx] = (ushort)VOID_Data.downrangeDistance.DoGUIHorizontal(this.precisionValues[idx]);
  idx++;
   
this.precisionValues [idx]= (ushort)VOID_Data.surfVelocity.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.surfVelocity.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
this.precisionValues [idx]= (ushort)VOID_Data.vertVelocity.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.vertVelocity.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
this.precisionValues [idx]= (ushort)VOID_Data.horzVelocity.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.horzVelocity.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
VOID_Data.temperature.DoGUIHorizontal ("F2"); VOID_Data.temperature.DoGUIHorizontal ("F2");
   
VOID_Data.atmDensity.DoGUIHorizontal (3); this.precisionValues [idx]= (ushort)VOID_Data.atmDensity.DoGUIHorizontal (this.precisionValues [idx]);
  idx++;
   
VOID_Data.atmPressure.DoGUIHorizontal ("F2"); VOID_Data.atmPressure.DoGUIHorizontal ("F2");
   
this.precisionValues [idx]= (ushort)VOID_Data.atmLimit.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.atmLimit.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
// Toadicus edit: added Biome // Toadicus edit: added Biome
VOID_Data.currBiome.DoGUIHorizontal (); VOID_Data.currBiome.DoGUIHorizontal ();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow(); GUI.DragWindow();
} }
   
public override void LoadConfig () public override void LoadConfig ()
{ {
base.LoadConfig (); base.LoadConfig ();
   
this.precisionValues = new IntCollection (4, this._precisionValues); this.precisionValues = new IntCollection (4, this._precisionValues);
} }
   
public override void _SaveToConfig (KSP.IO.PluginConfiguration config) public override void _SaveToConfig (KSP.IO.PluginConfiguration config)
{ {
this._precisionValues = this.precisionValues.collection; this._precisionValues = this.precisionValues.collection;
   
base._SaveToConfig (config); base._SaveToConfig (config);
} }
} }
   
public static partial class VOID_Data public static partial class VOID_Data
{ {
public static readonly VOID_DoubleValue trueAltitude = new VOID_DoubleValue( public static readonly VOID_DoubleValue trueAltitude = new VOID_DoubleValue(
"Altitude (true)", "Altitude (true)",
delegate() delegate()
{ {
double alt_true = core.vessel.orbit.altitude - core.vessel.terrainAltitude; double alt_true = core.vessel.orbit.altitude - core.vessel.terrainAltitude;
// HACK: This assumes that on worlds with oceans, all water is fixed at 0 m, // HACK: This assumes that on worlds with oceans, all water is fixed at 0 m,
// and water covers the whole surface at 0 m. // and water covers the whole surface at 0 m.
if (core.vessel.terrainAltitude < 0 && core.vessel.mainBody.ocean ) if (core.vessel.terrainAltitude < 0 && core.vessel.mainBody.ocean )
alt_true = core.vessel.orbit.altitude; alt_true = core.vessel.orbit.altitude;
return alt_true; return alt_true;
}, },
"m" "m"
); );
   
public static readonly VOID_StrValue surfLatitude = new VOID_StrValue( public static readonly VOID_StrValue surfLatitude = new VOID_StrValue(
"Latitude", "Latitude",
new Func<string> (() => VOID_Tools.GetLatitudeString(core.vessel)) new Func<string> (() => VOID_Tools.GetLatitudeString(core.vessel))
); );
   
public static readonly VOID_StrValue surfLongitude = new VOID_StrValue( public static readonly VOID_StrValue surfLongitude = new VOID_StrValue(
"Longitude", "Longitude",
new Func<string> (() => VOID_Tools.GetLongitudeString(core.vessel)) new Func<string> (() => VOID_Tools.GetLongitudeString(core.vessel))
); );
   
public static readonly VOID_StrValue vesselHeading = new VOID_StrValue( public static readonly VOID_StrValue vesselHeading = new VOID_StrValue(
"Heading", "Heading",
delegate() delegate()
{ {
double heading = core.vessel.getSurfaceHeading(); double heading = core.vessel.getSurfaceHeading();
string cardinal = VOID_Tools.get_heading_text(heading); string cardinal = VOID_Tools.get_heading_text(heading);
   
return string.Format( return string.Format(
"{0}° {1}", "{0}° {1}",
heading.ToString("F2"), heading.ToString("F2"),
cardinal cardinal
); );
} }
); );
   
public static readonly VOID_DoubleValue terrainElevation = new VOID_DoubleValue( public static readonly VOID_DoubleValue terrainElevation = new VOID_DoubleValue(
"Terrain elevation", "Terrain elevation",
new Func<double> (() => core.vessel.terrainAltitude), new Func<double> (() => core.vessel.terrainAltitude),
"m" "m"
); );
   
public static readonly VOID_DoubleValue surfVelocity = new VOID_DoubleValue( public static readonly VOID_DoubleValue surfVelocity = new VOID_DoubleValue(
"Surface velocity", "Surface velocity",
new Func<double> (() => core.vessel.srf_velocity.magnitude), new Func<double> (() => core.vessel.srf_velocity.magnitude),
"m/s" "m/s"
); );
   
public static readonly VOID_DoubleValue vertVelocity = new VOID_DoubleValue( public static readonly VOID_DoubleValue vertVelocity = new VOID_DoubleValue(
"Vertical speed", "Vertical speed",
new Func<double> (() => core.vessel.verticalSpeed), new Func<double> (() => core.vessel.verticalSpeed),
"m/s" "m/s"
); );
   
public static readonly VOID_DoubleValue horzVelocity = new VOID_DoubleValue( public static readonly VOID_DoubleValue horzVelocity = new VOID_DoubleValue(
"Horizontal speed", "Horizontal speed",
new Func<double> (() => core.vessel.horizontalSrfSpeed), new Func<double> (() => core.vessel.horizontalSrfSpeed),
"m/s" "m/s"
); );
   
public static readonly VOID_FloatValue temperature = new VOID_FloatValue( public static readonly VOID_FloatValue temperature = new VOID_FloatValue(
"Temperature", "Temperature",
new Func<float> (() => core.vessel.flightIntegrator.getExternalTemperature()), new Func<float> (() => core.vessel.flightIntegrator.getExternalTemperature()),
"°C" "°C"
); );
   
public static readonly VOID_DoubleValue atmDensity = new VOID_DoubleValue ( public static readonly VOID_DoubleValue atmDensity = new VOID_DoubleValue (
"Atmosphere Density", "Atmosphere Density",
new Func<double> (() => core.vessel.atmDensity * 1000f), new Func<double> (() => core.vessel.atmDensity * 1000f),
"g/m³" "g/m³"
); );
   
public static readonly VOID_DoubleValue atmPressure = new VOID_DoubleValue ( public static readonly VOID_DoubleValue atmPressure = new VOID_DoubleValue (
"Pressure", "Pressure",
new Func<double> (() => core.vessel.staticPressure), new Func<double> (() => core.vessel.staticPressure),
"atm" "atm"
); );
   
public static readonly VOID_FloatValue atmLimit = new VOID_FloatValue( public static readonly VOID_FloatValue atmLimit = new VOID_FloatValue(
"Atmosphere Limit", "Atmosphere Limit",
new Func<float> (() => core.vessel.mainBody.maxAtmosphereAltitude), new Func<float> (() => core.vessel.mainBody.maxAtmosphereAltitude),
"m" "m"
); );
   
public static readonly VOID_StrValue currBiome = new VOID_StrValue( public static readonly VOID_StrValue currBiome = new VOID_StrValue(
"Biome", "Biome",
new Func<string> (() => VOID_Tools.GetBiome(core.vessel).name) new Func<string> (() => VOID_Tools.GetBiome(core.vessel).name)
); );
   
} }
} }
// VOID // VOID
// //
// VOID_Tools.cs // VOID_Tools.cs
// //
// Copyright © 2014, toadicus // Copyright © 2014, toadicus
// All rights reserved. // All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without modification, // Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met: // are permitted provided that the following conditions are met:
// //
// 1. Redistributions of source code must retain the above copyright notice, // 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer. // this list of conditions and the following disclaimer.
// //
// 2. Redistributions in binary form must reproduce the above copyright notice, // 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or other // this list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution. // materials provided with the distribution.
// //
// 3. Neither the name of the copyright holder nor the names of its contributors may be used // 3. Neither the name of the copyright holder nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior written permission. // to endorse or promote products derived from this software without specific prior written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public static partial class VOID_Tools public static partial class VOID_Tools
{ {
#region CelestialBody Utilities #region CelestialBody Utilities
public static bool hasAncestor(this CelestialBody bodyA, CelestialBody bodyB) public static bool hasAncestor(this CelestialBody bodyA, CelestialBody bodyB)
{ {
if (bodyA == null || bodyB == null) if (bodyA == null || bodyB == null)
{ {
return false; return false;
} }
   
while (bodyA.orbitDriver != null) while (bodyA.orbitDriver != null)
{ {
if (bodyA.orbit.referenceBody == bodyB) if (bodyA.orbit.referenceBody == bodyB)
{ {
return true; return true;
} }
   
bodyA = bodyA.orbit.referenceBody; bodyA = bodyA.orbit.referenceBody;
} }
   
return false; return false;
} }
   
public static bool NearestRelatedParents(ref CelestialBody bodyA, ref CelestialBody bodyB) public static bool NearestRelatedParents(ref CelestialBody bodyA, ref CelestialBody bodyB)
{ {
if (bodyA == null || bodyB == null || bodyA.orbitDriver == null || bodyB.orbitDriver == null) if (bodyA == null || bodyB == null || bodyA.orbitDriver == null || bodyB.orbitDriver == null)
{ {
throw new ArgumentException(string.Concat( throw new ArgumentException(string.Concat(
"CelestialBody::FindRelatedParents: ", "CelestialBody::FindRelatedParents: ",
"Neither body may be null, and both bodies must have orbits." "Neither body may be null, and both bodies must have orbits."
)); ));
} }
   
CelestialBody a, b; CelestialBody a, b;
   
a = bodyA; a = bodyA;
   
while (bodyA.orbitDriver != null) while (bodyA.orbitDriver != null)
{ {
b = bodyB; b = bodyB;
   
while (b.orbitDriver != null) while (b.orbitDriver != null)
{ {
if (a.orbit.referenceBody == b.orbit.referenceBody) if (a.orbit.referenceBody == b.orbit.referenceBody)
{ {
bodyA = a; bodyA = a;
bodyB = b; bodyB = b;
return true; return true;
} }
   
b = b.orbit.referenceBody; b = b.orbit.referenceBody;
} }
   
a = a.orbit.referenceBody; a = a.orbit.referenceBody;
} }
   
return false; return false;
} }
#endregion #endregion
   
#region VESSEL_EXTENSIONS_SCIENCE #region VESSEL_EXTENSIONS_SCIENCE
public static CBAttributeMap.MapAttribute GetBiome(this Vessel vessel) public static CBAttributeMap.MapAttribute GetBiome(this Vessel vessel)
{ {
CBAttributeMap.MapAttribute mapAttribute; CBAttributeMap.MapAttribute mapAttribute;
   
try try
{ {
CBAttributeMap BiomeMap = vessel.mainBody.BiomeMap; CBAttributeMap BiomeMap = vessel.mainBody.BiomeMap;
   
double lat = vessel.latitude * Math.PI / 180d; double lat = vessel.latitude * Math.PI / 180d;
double lon = vessel.longitude * Math.PI / 180d; double lon = vessel.longitude * Math.PI / 180d;
   
mapAttribute = BiomeMap.GetAtt(lat, lon); mapAttribute = BiomeMap.GetAtt(lat, lon);
   
/* /*
lon -= Math.PI / 2d; lon -= Math.PI / 2d;
   
if (lon < 0d) if (lon < 0d)
{ {
lon += 2d * Math.PI; lon += 2d * Math.PI;
} }
   
float v = (float)(lat / Math.PI) + 0.5f; float v = (float)(lat / Math.PI) + 0.5f;
float u = (float)(lon / (2d * Math.PI)); float u = (float)(lon / (2d * Math.PI));
   
Color pixelBilinear = BiomeMap.Map.GetPixelBilinear(u, v); Color pixelBilinear = BiomeMap.Map.GetPixelBilinear(u, v);
mapAttribute = BiomeMap.defaultAttribute; mapAttribute = BiomeMap.defaultAttribute;
   
if (BiomeMap.Map != null) if (BiomeMap.Map != null)
{ {
if (BiomeMap.exactSearch) if (BiomeMap.exactSearch)
{ {
for (int i = 0; i < BiomeMap.Attributes.Length; ++i) for (int i = 0; i < BiomeMap.Attributes.Length; ++i)
{ {
if (pixelBilinear == BiomeMap.Attributes[i].mapColor) if (pixelBilinear == BiomeMap.Attributes[i].mapColor)
{ {
mapAttribute = BiomeMap.Attributes[i]; mapAttribute = BiomeMap.Attributes[i];
} }
} }
} }
else else
{ {
float zero = 0; float zero = 0;
float num = 1 / zero; float num = 1 / zero;
for (int j = 0; j < BiomeMap.Attributes.Length; ++j) for (int j = 0; j < BiomeMap.Attributes.Length; ++j)
{ {
Color mapColor = BiomeMap.Attributes[j].mapColor; Color mapColor = BiomeMap.Attributes[j].mapColor;
float sqrMagnitude = ((Vector4)(mapColor - pixelBilinear)).sqrMagnitude; float sqrMagnitude = ((Vector4)(mapColor - pixelBilinear)).sqrMagnitude;
if (sqrMagnitude < num) if (sqrMagnitude < num)
{ {
bool testCase = true; bool testCase = true;
if (BiomeMap.nonExactThreshold != -1) if (BiomeMap.nonExactThreshold != -1)
{ {
testCase = (sqrMagnitude < BiomeMap.nonExactThreshold); testCase = (sqrMagnitude < BiomeMap.nonExactThreshold);
} }
if (testCase) if (testCase)
{ {
mapAttribute = BiomeMap.Attributes[j]; mapAttribute = BiomeMap.Attributes[j];
num = sqrMagnitude; num = sqrMagnitude;
} }
} }
} }
} }
} }
*/ */
} }
catch (NullReferenceException) catch (NullReferenceException)
{ {
mapAttribute = new CBAttributeMap.MapAttribute(); mapAttribute = new CBAttributeMap.MapAttribute();
mapAttribute.name = "N/A"; mapAttribute.name = "N/A";
} }
   
return mapAttribute; return mapAttribute;
} }
   
public static ExperimentSituations GetExperimentSituation(this Vessel vessel) public static ExperimentSituations GetExperimentSituation(this Vessel vessel)
{ {
if (vessel == null) if (vessel == null)
{ {
return ExperimentSituations.SrfSplashed; return ExperimentSituations.SrfSplashed;
} }
   
Vessel.Situations situation = vessel.situation; Vessel.Situations situation = vessel.situation;
   
switch (situation) switch (situation)
{ {
case Vessel.Situations.PRELAUNCH: case Vessel.Situations.PRELAUNCH:
case Vessel.Situations.LANDED: case Vessel.Situations.LANDED:
return ExperimentSituations.SrfLanded; return ExperimentSituations.SrfLanded;
case Vessel.Situations.SPLASHED: case Vessel.Situations.SPLASHED:
return ExperimentSituations.SrfSplashed; return ExperimentSituations.SrfSplashed;
case Vessel.Situations.FLYING: case Vessel.Situations.FLYING:
if (vessel.altitude < (double)vessel.mainBody.scienceValues.flyingAltitudeThreshold) if (vessel.altitude < (double)vessel.mainBody.scienceValues.flyingAltitudeThreshold)
{ {
return ExperimentSituations.FlyingLow; return ExperimentSituations.FlyingLow;
} }
else else
{ {
return ExperimentSituations.FlyingHigh; return ExperimentSituations.FlyingHigh;
} }
} }
   
if (vessel.altitude < (double)vessel.mainBody.scienceValues.spaceAltitudeThreshold) if (vessel.altitude < (double)vessel.mainBody.scienceValues.spaceAltitudeThreshold)
{ {
return ExperimentSituations.InSpaceLow; return ExperimentSituations.InSpaceLow;
} }
else else
{ {
return ExperimentSituations.InSpaceHigh; return ExperimentSituations.InSpaceHigh;
} }
} }
   
public static string HumanString(this ExperimentSituations situation) public static string HumanString(this ExperimentSituations situation)
{ {
switch (situation) switch (situation)
{ {
case ExperimentSituations.FlyingHigh: case ExperimentSituations.FlyingHigh:
return "Upper Atmosphere"; return "Upper Atmosphere";
case ExperimentSituations.FlyingLow: case ExperimentSituations.FlyingLow:
return "Flying"; return "Flying";
case ExperimentSituations.SrfLanded: case ExperimentSituations.SrfLanded:
return "Surface"; return "Surface";
case ExperimentSituations.InSpaceLow: case ExperimentSituations.InSpaceLow:
return "Near in Space"; return "Near in Space";
case ExperimentSituations.InSpaceHigh: case ExperimentSituations.InSpaceHigh:
return "High in Space"; return "High in Space";
case ExperimentSituations.SrfSplashed: case ExperimentSituations.SrfSplashed:
return "Splashed Down"; return "Splashed Down";
default: default:
return "Unknown"; return "Unknown";
} }
} }
#endregion #endregion
   
#region VESSEL_EXTENSIONS_LAT_LONG #region VESSEL_EXTENSIONS_LAT_LONG
public static string GetLongitudeString(this Vessel vessel, string format = "F4") public static string GetLongitudeString(this Vessel vessel, string format = "F4")
{ {
string dir_long = "W"; string dir_long = "W";
double v_long = vessel.longitude; double v_long = vessel.longitude;
   
v_long = FixDegreeDomain(v_long); v_long = FixDegreeDomain(v_long);
   
if (v_long < -180d) if (v_long < -180d)
{ {
v_long += 360d; v_long += 360d;
} }
if (v_long >= 180) if (v_long >= 180)
{ {
v_long -= 360d; v_long -= 360d;
} }
   
if (v_long > 0) if (v_long > 0)
dir_long = "E"; dir_long = "E";
   
return string.Format("{0}° {1}", Math.Abs(v_long).ToString(format), dir_long); return string.Format("{0}° {1}", Math.Abs(v_long).ToString(format), dir_long);
} }
   
public static string GetLatitudeString(this Vessel vessel, string format = "F4") public static string GetLatitudeString(this Vessel vessel, string format = "F4")
{ {
string dir_lat = "S"; string dir_lat = "S";
double v_lat = vessel.latitude; double v_lat = vessel.latitude;
if (v_lat > 0) if (v_lat > 0)
dir_lat = "N"; dir_lat = "N";
   
return string.Format("{0}° {1}", Math.Abs(v_lat).ToString(format), dir_lat); return string.Format("{0}° {1}", Math.Abs(v_lat).ToString(format), dir_lat);
} }
#endregion #endregion
   
#region VESSEL_EXTENSIONS_GENERAL #region VESSEL_EXTENSIONS_GENERAL
public static double TrueAltitude(Vessel vessel) public static double TrueAltitude(Vessel vessel)
{ {
double trueAltitude = vessel.orbit.altitude - vessel.terrainAltitude; double trueAltitude = vessel.orbit.altitude - vessel.terrainAltitude;
   
// HACK: This assumes that on worlds with oceans, all water is fixed at 0 m, // HACK: This assumes that on worlds with oceans, all water is fixed at 0 m,
// and water covers the whole surface at 0 m. // and water covers the whole surface at 0 m.
if (vessel.terrainAltitude < 0 && vessel.mainBody.ocean) if (vessel.terrainAltitude < 0 && vessel.mainBody.ocean)
{ {
trueAltitude = vessel.orbit.altitude; trueAltitude = vessel.orbit.altitude;
} }
   
return trueAltitude; return trueAltitude;
} }
   
public static double Radius(this Vessel vessel) public static double Radius(this Vessel vessel)
{ {
double radius; double radius;
   
radius = vessel.altitude; radius = vessel.altitude;
   
if (vessel.mainBody != null) if (vessel.mainBody != null)
{ {
radius += vessel.mainBody.Radius; radius += vessel.mainBody.Radius;
} }
   
return radius; return radius;
} }
#endregion #endregion
   
#region GEOMETRY_UTILS #region GEOMETRY_UTILS
public static double FixAngleDomain(double Angle, bool Degrees = false) public static double FixAngleDomain(double Angle, bool Degrees = false)
{ {
double Extent = 2d * Math.PI; double Extent = 2d * Math.PI;
if (Degrees) if (Degrees)
{ {
Extent = 360d; Extent = 360d;
} }
   
Angle = Angle % (Extent); Angle = Angle % (Extent);
if (Angle < 0d) if (Angle < 0d)
{ {
Angle += Extent; Angle += Extent;
} }
   
return Angle; return Angle;
} }
   
public static double FixDegreeDomain(double Angle) public static double FixDegreeDomain(double Angle)
{ {
return FixAngleDomain(Angle, true); return FixAngleDomain(Angle, true);
} }
#endregion #endregion
   
private static Dictionary<int, GUI.WindowFunction> functionCache; private static Dictionary<int, GUI.WindowFunction> functionCache;
public static UnityEngine.GUI.WindowFunction GetWindowHandler(Action<int> func) public static UnityEngine.GUI.WindowFunction GetWindowHandler(Action<int> func)
{ {
if (functionCache == null) if (functionCache == null)
{ {
functionCache = new Dictionary<int, GUI.WindowFunction>(); functionCache = new Dictionary<int, GUI.WindowFunction>();
} }
   
int hashCode = func.GetHashCode(); int hashCode = func.GetHashCode();
   
if (!functionCache.ContainsKey(hashCode)) if (!functionCache.ContainsKey(hashCode))
{ {
functionCache[hashCode] = delegate (int id) functionCache[hashCode] = delegate (int id)
{ {
try try
{ {
func(id); func(id);
} }
#if DEBUG #if DEBUG
catch (ArgumentException ex) catch (ArgumentException ex)
#else #else
catch (ArgumentException) catch (ArgumentException)
#endif #endif
{ {
Debug.LogWarning( Debug.LogWarning(
string.Format("[{0}]: ArgumentException caught during window call.", func.Target.GetType().Name) string.Format("[{0}]: ArgumentException caught during window call. This is not a bug.",
); func.Target.GetType().Name
  ));
   
/*#if DEBUG /*#if DEBUG
Debug.LogException(ex); Debug.LogException(ex);
#endif*/ #endif*/
  }
  catch (Exception ex)
  {
  Debug.LogError(
  string.Format("[{0}]: {1} caught during window call.\nMessage:\n{2}\nStackTrace:\n{3}",
  func.Target.GetType().Name,
  ex.GetType().Name,
  ex.Message,
  ex.StackTrace
  ));
} }
}; };
} }
   
return functionCache[hashCode]; return functionCache[hashCode];
} }
   
/// <summary> /// <summary>
/// Converts the interval given in seconds to a human-friendly /// Converts the interval given in seconds to a human-friendly
/// time period in [years], [days], hours, minutes, and seconds. /// time period in [years], [days], hours, minutes, and seconds.
/// ///
/// Uses sidereal days, since "6 hours per day" is the Kerbal standard. /// Uses sidereal days, since "6 hours per day" is the Kerbal standard.
/// </summary> /// </summary>
/// <returns>Human readable interval</returns> /// <returns>Human readable interval</returns>
/// <param name="seconds"></param> /// <param name="seconds"></param>
public static string ConvertInterval(double seconds) public static string ConvertInterval(double seconds)
{ {
double SecondsPerMinute = 60d; double SecondsPerMinute = 60d;
double SecondsPerHour = 3600d; double SecondsPerHour = 3600d;
double SecondsPerDay; double SecondsPerDay;
double SecondsPerYear; double SecondsPerYear;
   
if (GameSettings.KERBIN_TIME) if (GameSettings.KERBIN_TIME)
{ {
SecondsPerDay = 21600d; SecondsPerDay = 21600d;
SecondsPerYear = 9203545d; SecondsPerYear = 9203545d;
} }
else else
{ {
SecondsPerDay = 86164.1d; SecondsPerDay = 86164.1d;
SecondsPerYear = 31558149d; SecondsPerYear = 31558149d;
} }
   
int years; int years;
int days; int days;
int hours; int hours;
int minutes; int minutes;
   
years = (int)(seconds / SecondsPerYear); years = (int)(seconds / SecondsPerYear);
   
seconds %= SecondsPerYear; seconds %= SecondsPerYear;
   
days = (int)(seconds / SecondsPerDay); days = (int)(seconds / SecondsPerDay);
   
seconds %= SecondsPerDay; seconds %= SecondsPerDay;
   
hours = (int)(seconds / SecondsPerHour); hours = (int)(seconds / SecondsPerHour);
   
seconds %= SecondsPerHour; seconds %= SecondsPerHour;
   
minutes = (int)(seconds / SecondsPerMinute); minutes = (int)(seconds / SecondsPerMinute);
   
seconds %= SecondsPerMinute; seconds %= SecondsPerMinute;
   
string format_1 = string.Intern("{0:D1}y {1:D1}d {2:D2}h {3:D2}m {4:00.0}s"); string format_1 = string.Intern("{0:D1}y {1:D1}d {2:D2}h {3:D2}m {4:00.0}s");
string format_2 = string.Intern("{0:D1}d {1:D2}h {2:D2}m {3:00.0}s"); string format_2 = string.Intern("{0:D1}d {1:D2}h {2:D2}m {3:00.0}s");
string format_3 = string.Intern("{0:D2}h {1:D2}m {2:00.0}s"); string format_3 = string.Intern("{0:D2}h {1:D2}m {2:00.0}s");
string format_4 = string.Intern("{0:D2}m {1:00.0}s"); string format_4 = string.Intern("{0:D2}m {1:00.0}s");
string format_5 = string.Intern("{0:00.0}s"); string format_5 = string.Intern("{0:00.0}s");
   
if (years > 0) if (years > 0)
{ {
return string.Format(format_1, years, days, hours, minutes, seconds); return string.Format(format_1, years, days, hours, minutes, seconds);
} }
else if (days > 0) else if (days > 0)
{ {
return string.Format(format_2, days, hours, minutes, seconds); return string.Format(format_2, days, hours, minutes, seconds);
} }
else if (hours > 0) else if (hours > 0)
{ {
return string.Format(format_3, hours, minutes, seconds); return string.Format(format_3, hours, minutes, seconds);
} }
else if (minutes > 0) else if (minutes > 0)
{ {
return string.Format(format_4, minutes, seconds); return string.Format(format_4, minutes, seconds);
} }
else else
{ {
return string.Format(format_5, seconds); return string.Format(format_5, seconds);
} }
} }
   
public static string UppercaseFirst(string s) public static string UppercaseFirst(string s)
{ {
if (string.IsNullOrEmpty(s)) if (string.IsNullOrEmpty(s))
{ {
return string.Empty; return string.Empty;
} }
char[] a = s.ToCharArray(); char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]); a[0] = char.ToUpper(a[0]);
return new string(a); return new string(a);
} }
   
//transfer angles //transfer angles
public static double Nivvy_CalcTransferPhaseAngle(double r_current, double r_target, double grav_param) public static double Nivvy_CalcTransferPhaseAngle(double r_current, double r_target, double grav_param)
{ {
r_target /= 1000; r_target /= 1000;
r_current /= 1000; r_current /= 1000;
grav_param /= 1000000000; grav_param /= 1000000000;
   
double midpoint = (r_target + r_current) / 2; double midpoint = (r_target + r_current) / 2;
   
double T_target = (2 * Math.PI) * Math.Sqrt((r_target * r_target * r_target) / grav_param); double T_target = (2 * Math.PI) * Math.Sqrt((r_target * r_target * r_target) / grav_param);
double T_transfer = (2 * Math.PI) * Math.Sqrt((midpoint * midpoint * midpoint) / grav_param); double T_transfer = (2 * Math.PI) * Math.Sqrt((midpoint * midpoint * midpoint) / grav_param);
return 360 * (0.5 - (T_transfer / (2 * T_target))); return 360 * (0.5 - (T_transfer / (2 * T_target)));
} }
   
public static double Younata_DeltaVToGetToOtherBody(double mu, double r1, double r2) public static double Younata_DeltaVToGetToOtherBody(double mu, double r1, double r2)
{ {
/* /*
def deltaVToGetToOtherBody(mu, r1, r2): def deltaVToGetToOtherBody(mu, r1, r2):
# mu = gravity param of common orbiting body of r1 and r2 # mu = gravity param of common orbiting body of r1 and r2
# (e.g. for mun to minmus, mu is kerbin's gravity param # (e.g. for mun to minmus, mu is kerbin's gravity param
# r1 = initial body's orbit radius # r1 = initial body's orbit radius
# r2 = target body's orbit radius # r2 = target body's orbit radius
# return value is km/s # return value is km/s
sur1 = math.sqrt(mu / r1) sur1 = math.sqrt(mu / r1)
sr1r2 = math.sqrt(float(2*r2)/float(r1+r2)) sr1r2 = math.sqrt(float(2*r2)/float(r1+r2))
mult = sr1r2 - 1 mult = sr1r2 - 1
return sur1 * mult return sur1 * mult
*/ */
double sur1, sr1r2, mult; double sur1, sr1r2, mult;
sur1 = Math.Sqrt(mu / r1); sur1 = Math.Sqrt(mu / r1);
sr1r2 = Math.Sqrt((2 * r2) / (r1 + r2)); sr1r2 = Math.Sqrt((2 * r2) / (r1 + r2));
mult = sr1r2 - 1; mult = sr1r2 - 1;
return sur1 * mult; return sur1 * mult;
} }
   
public static double Younata_DeltaVToExitSOI(double mu, double r1, double r2, double v) public static double Younata_DeltaVToExitSOI(double mu, double r1, double r2, double v)
{ {
/* /*
def deltaVToExitSOI(mu, r1, r2, v): def deltaVToExitSOI(mu, r1, r2, v):
# mu = gravity param of current body # mu = gravity param of current body
# r1 = current orbit radius # r1 = current orbit radius
# r2 = SOI radius # r2 = SOI radius
# v = SOI exit velocity # v = SOI exit velocity
foo = r2 * (v**2) - 2 * mu foo = r2 * (v**2) - 2 * mu
bar = r1 * foo + (2 * r2 * mu) bar = r1 * foo + (2 * r2 * mu)
r = r1*r2 r = r1*r2
return math.sqrt(bar / r) return math.sqrt(bar / r)
*/ */
double foo = r2 * (v * v) - 2 * mu; double foo = r2 * (v * v) - 2 * mu;
double bar = r1 * foo + (2 * r2 * mu); double bar = r1 * foo + (2 * r2 * mu);
double r = r1 * r2; double r = r1 * r2;
return Math.Sqrt(bar / r); return Math.Sqrt(bar / r);
} }
   
public static double Younata_TransferBurnPoint(double r, double v, double angle, double mu) public static double Younata_TransferBurnPoint(double r, double v, double angle, double mu)
{ {
/* /*
def transferBurnPoint(r, v, angle, mu): def transferBurnPoint(r, v, angle, mu):
# r = parking orbit radius # r = parking orbit radius
# v = ejection velocity # v = ejection velocity
# angle = phase angle (from function phaseAngle()) # angle = phase angle (from function phaseAngle())
# mu = gravity param of current body. # mu = gravity param of current body.
epsilon = ((v**2)/2) - (mu / r) epsilon = ((v**2)/2) - (mu / r)
h = r * v * math.sin(angle) h = r * v * math.sin(angle)
e = math.sqrt(1 + ((2 * epsilon * h**2)/(mu**2))) e = math.sqrt(1 + ((2 * epsilon * h**2)/(mu**2)))
theta = math.acos(1.0 / e) theta = math.acos(1.0 / e)
degrees = theta * (180.0 / math.pi) degrees = theta * (180.0 / math.pi)
return 180 - degrees return 180 - degrees
*/ */
double epsilon, h, ee, theta, degrees; double epsilon, h, ee, theta, degrees;
epsilon = ((v * v) / 2) - (mu / r); epsilon = ((v * v) / 2) - (mu / r);
h = r * v * Math.Sin(angle); h = r * v * Math.Sin(angle);
ee = Math.Sqrt(1 + ((2 * epsilon * (h * h)) / (mu * mu))); ee = Math.Sqrt(1 + ((2 * epsilon * (h * h)) / (mu * mu)));
theta = Math.Acos(1.0 / ee); theta = Math.Acos(1.0 / ee);
degrees = theta * (180.0 / Math.PI); degrees = theta * (180.0 / Math.PI);
return 180 - degrees; return 180 - degrees;
// returns the ejection angle // returns the ejection angle
} }
   
public static double Adammada_CurrrentPhaseAngle( public static double Adammada_CurrrentPhaseAngle(
double body_LAN, double body_LAN,
double body_orbitPct, double body_orbitPct,
double origin_LAN, double origin_LAN,
double origin_orbitPct double origin_orbitPct
) )
{ {
double angle = (body_LAN / 360 + body_orbitPct) - (origin_LAN / 360 + origin_orbitPct); double angle = (body_LAN / 360 + body_orbitPct) - (origin_LAN / 360 + origin_orbitPct);
if (angle > 1) if (angle > 1)
angle = angle - 1; angle = angle - 1;
if (angle < 0) if (angle < 0)
angle = angle + 1; angle = angle + 1;
if (angle > 0.5) if (angle > 0.5)
angle = angle - 1; angle = angle - 1;
angle = angle * 360; angle = angle * 360;
return angle; return angle;
} }
   
public static double Adammada_CurrentEjectionAngle( public static double Adammada_CurrentEjectionAngle(
double vessel_long, double vessel_long,
double origin_rotAngle, double origin_rotAngle,
double origin_LAN, double origin_LAN,
double origin_orbitPct double origin_orbitPct
) )
{ {
//double eangle = ((FlightGlobals.ActiveVOID.vessel.longitude + orbiting.rotationAngle) - (orbiting.orbit.LAN / 360 + orbiting.orbit.orbitPercent) * 360); //double eangle = ((FlightGlobals.ActiveVOID.vessel.longitude + orbiting.rotationAngle) - (orbiting.orbit.LAN / 360 + orbiting.orbit.orbitPercent) * 360);
double eangle = ((vessel_long + origin_rotAngle) - (origin_LAN / 360 + origin_orbitPct) * 360); double eangle = ((vessel_long + origin_rotAngle) - (origin_LAN / 360 + origin_orbitPct) * 360);
   
while (eangle < 0) while (eangle < 0)
eangle = eangle + 360; eangle = eangle + 360;
while (eangle > 360) while (eangle > 360)
eangle = eangle - 360; eangle = eangle - 360;
if (eangle < 270) if (eangle < 270)
eangle = 90 - eangle; eangle = 90 - eangle;
else else
eangle = 450 - eangle; eangle = 450 - eangle;
return eangle; return eangle;
} }
   
public static double mrenigma03_calcphase(Vessel vessel, CelestialBody target) //calculates phase angle between the current body and target body public static double mrenigma03_calcphase(Vessel vessel, CelestialBody target) //calculates phase angle between the current body and target body
{ {
Vector3d vecthis = new Vector3d(); Vector3d vecthis = new Vector3d();
Vector3d vectarget = new Vector3d(); Vector3d vectarget = new Vector3d();
vectarget = target.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()); vectarget = target.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime());
   
if ((vessel.mainBody.name == "Sun") || (vessel.mainBody.referenceBody.referenceBody.name == "Sun")) if ((vessel.mainBody.name == "Sun") || (vessel.mainBody.referenceBody.referenceBody.name == "Sun"))
{ {
vecthis = vessel.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()); vecthis = vessel.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime());
} }
else else
{ {
vecthis = vessel.mainBody.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()); vecthis = vessel.mainBody.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime());
} }
   
vecthis = Vector3d.Project(new Vector3d(vecthis.x, 0, vecthis.z), vecthis); vecthis = Vector3d.Project(new Vector3d(vecthis.x, 0, vecthis.z), vecthis);
vectarget = Vector3d.Project(new Vector3d(vectarget.x, 0, vectarget.z), vectarget); vectarget = Vector3d.Project(new Vector3d(vectarget.x, 0, vectarget.z), vectarget);
   
Vector3d prograde = new Vector3d(); Vector3d prograde = new Vector3d();
prograde = Quaternion.AngleAxis(90, Vector3d.forward) * vecthis; prograde = Quaternion.AngleAxis(90, Vector3d.forward) * vecthis;
   
double phase = Vector3d.Angle(vecthis, vectarget); double phase = Vector3d.Angle(vecthis, vectarget);
   
if (Vector3d.Angle(prograde, vectarget) > 90) if (Vector3d.Angle(prograde, vectarget) > 90)
phase = 360 - phase; phase = 360 - phase;
   
return (phase + 360) % 360; return (phase + 360) % 360;
} }
   
public static double adjustCurrPhaseAngle(double transfer_angle, double curr_phase) public static double adjustCurrPhaseAngle(double transfer_angle, double curr_phase)
{ {
if (transfer_angle < 0) if (transfer_angle < 0)
{ {
if (curr_phase > 0) if (curr_phase > 0)
return (-1 * (360 - curr_phase)); return (-1 * (360 - curr_phase));
else if (curr_phase < 0) else if (curr_phase < 0)
return curr_phase; return curr_phase;
} }
else if (transfer_angle > 0) else if (transfer_angle > 0)
{ {
if (curr_phase > 0) if (curr_phase > 0)
return curr_phase; return curr_phase;
else if (curr_phase < 0) else if (curr_phase < 0)
return (360 + curr_phase); return (360 + curr_phase);
} }
return curr_phase; return curr_phase;
} }
   
public static double adjust_current_ejection_angle(double curr_ejection) public static double adjust_current_ejection_angle(double curr_ejection)
{ {
//curr_ejection WILL need to be adjusted once for all transfers as it returns values ranging -180 to 180 //curr_ejection WILL need to be adjusted once for all transfers as it returns values ranging -180 to 180
// need 0-360 instead // need 0-360 instead
// //
// ie i have -17 in the screenshot // ie i have -17 in the screenshot
// need it to show 343 // need it to show 343
// //
// do this // do this
// //
// if < 0, add curr to 360 // 360 + (-17) = 343 // if < 0, add curr to 360 // 360 + (-17) = 343
// else its good as it is // else its good as it is
   
if (curr_ejection < 0) if (curr_ejection < 0)
return 360 + curr_ejection; return 360 + curr_ejection;
else else
return curr_ejection; return curr_ejection;
   
} }
   
public static double adjust_transfer_ejection_angle(double trans_ejection, double trans_phase) public static double adjust_transfer_ejection_angle(double trans_ejection, double trans_phase)
{ {
// if transfer_phase_angle < 0 its a lower transfer // if transfer_phase_angle < 0 its a lower transfer
//180 + curr_ejection //180 + curr_ejection
// else if transfer_phase_angle > 0 its good as it is // else if transfer_phase_angle > 0 its good as it is
   
if (trans_phase < 0) if (trans_phase < 0)
return 180 + trans_ejection; return 180 + trans_ejection;
else else
return trans_ejection; return trans_ejection;
   
} }
   
public static void display_transfer_angles_SUN2PLANET(CelestialBody body, Vessel vessel) public static void display_transfer_angles_SUN2PLANET(CelestialBody body, Vessel vessel)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Phase angle (curr/trans):"); GUILayout.Label("Phase angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
VOID_Tools.mrenigma03_calcphase(vessel, body).ToString("F3") + "° / " + VOID_Tools.Nivvy_CalcTransferPhaseAngle( VOID_Tools.mrenigma03_calcphase(vessel, body).ToString("F3") + "° / " + VOID_Tools.Nivvy_CalcTransferPhaseAngle(
vessel.orbit.semiMajorAxis, vessel.orbit.semiMajorAxis,
body.orbit.semiMajorAxis, body.orbit.semiMajorAxis,
vessel.mainBody.gravParameter vessel.mainBody.gravParameter
).ToString("F3") + "°", ).ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Transfer velocity:"); GUILayout.Label("Transfer velocity:");
GUILayout.Label( GUILayout.Label(
(VOID_Tools.Younata_DeltaVToGetToOtherBody( (VOID_Tools.Younata_DeltaVToGetToOtherBody(
(vessel.mainBody.gravParameter / 1000000000), (vessel.mainBody.gravParameter / 1000000000),
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
(body.orbit.semiMajorAxis / 1000) (body.orbit.semiMajorAxis / 1000)
) * 1000).ToString("F2") + "m/s", ) * 1000).ToString("F2") + "m/s",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
public static void display_transfer_angles_PLANET2PLANET(CelestialBody body, Vessel vessel) public static void display_transfer_angles_PLANET2PLANET(CelestialBody body, Vessel vessel)
{ {
double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody( double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody(
(vessel.mainBody.referenceBody.gravParameter / 1000000000), (vessel.mainBody.referenceBody.gravParameter / 1000000000),
(vessel.mainBody.orbit.semiMajorAxis / 1000), (vessel.mainBody.orbit.semiMajorAxis / 1000),
(body.orbit.semiMajorAxis / 1000) (body.orbit.semiMajorAxis / 1000)
); );
double dv2 = VOID_Tools.Younata_DeltaVToExitSOI( double dv2 = VOID_Tools.Younata_DeltaVToExitSOI(
(vessel.mainBody.gravParameter / 1000000000), (vessel.mainBody.gravParameter / 1000000000),
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
(vessel.mainBody.sphereOfInfluence / 1000), (vessel.mainBody.sphereOfInfluence / 1000),
Math.Abs(dv1) Math.Abs(dv1)
); );
   
double trans_ejection_angle = VOID_Tools.Younata_TransferBurnPoint( double trans_ejection_angle = VOID_Tools.Younata_TransferBurnPoint(
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
dv2, dv2,
(Math.PI / 2.0), (Math.PI / 2.0),
(vessel.mainBody.gravParameter / 1000000000) (vessel.mainBody.gravParameter / 1000000000)
); );
double curr_ejection_angle = VOID_Tools.Adammada_CurrentEjectionAngle( double curr_ejection_angle = VOID_Tools.Adammada_CurrentEjectionAngle(
FlightGlobals.ActiveVessel.longitude, FlightGlobals.ActiveVessel.longitude,
FlightGlobals.ActiveVessel.orbit.referenceBody.rotationAngle, FlightGlobals.ActiveVessel.orbit.referenceBody.rotationAngle,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN, FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent
); );
   
double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle( double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle(
vessel.mainBody.orbit.semiMajorAxis, vessel.mainBody.orbit.semiMajorAxis,
body.orbit.semiMajorAxis, body.orbit.semiMajorAxis,
vessel.mainBody.referenceBody.gravParameter vessel.mainBody.referenceBody.gravParameter
) % 360; ) % 360;
double curr_phase_angle = VOID_Tools.Adammada_CurrrentPhaseAngle( double curr_phase_angle = VOID_Tools.Adammada_CurrrentPhaseAngle(
body.orbit.LAN, body.orbit.LAN,
body.orbit.orbitPercent, body.orbit.orbitPercent,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN, FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent
); );
   
double adj_phase_angle = VOID_Tools.adjustCurrPhaseAngle(trans_phase_angle, curr_phase_angle); double adj_phase_angle = VOID_Tools.adjustCurrPhaseAngle(trans_phase_angle, curr_phase_angle);
double adj_trans_ejection_angle = VOID_Tools.adjust_transfer_ejection_angle(trans_ejection_angle, trans_phase_angle); double adj_trans_ejection_angle = VOID_Tools.adjust_transfer_ejection_angle(trans_ejection_angle, trans_phase_angle);
double adj_curr_ejection_angle = VOID_Tools.adjust_current_ejection_angle(curr_ejection_angle); double adj_curr_ejection_angle = VOID_Tools.adjust_current_ejection_angle(curr_ejection_angle);
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Phase angle (curr/trans):"); GUILayout.Label("Phase angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
adj_phase_angle.ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°", adj_phase_angle.ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Ejection angle (curr/trans):"); GUILayout.Label("Ejection angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
adj_curr_ejection_angle.ToString("F3") + "° / " + adj_trans_ejection_angle.ToString("F3") + "°", adj_curr_ejection_angle.ToString("F3") + "° / " + adj_trans_ejection_angle.ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Transfer velocity:"); GUILayout.Label("Transfer velocity:");
GUILayout.Label((dv2 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false)); GUILayout.Label((dv2 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
public static void display_transfer_angles_PLANET2MOON(CelestialBody body, Vessel vessel) public static void display_transfer_angles_PLANET2MOON(CelestialBody body, Vessel vessel)
{ {
double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody( double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody(
(vessel.mainBody.gravParameter / 1000000000), (vessel.mainBody.gravParameter / 1000000000),
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
(body.orbit.semiMajorAxis / 1000) (body.orbit.semiMajorAxis / 1000)
); );
   
double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle( double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle(
vessel.orbit.semiMajorAxis, vessel.orbit.semiMajorAxis,
body.orbit.semiMajorAxis, body.orbit.semiMajorAxis,
vessel.mainBody.gravParameter vessel.mainBody.gravParameter
); );
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Phase angle (curr/trans):"); GUILayout.Label("Phase angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
VOID_Tools.mrenigma03_calcphase(vessel, body).ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°", VOID_Tools.mrenigma03_calcphase(vessel, body).ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Transfer velocity:"); GUILayout.Label("Transfer velocity:");
GUILayout.Label((dv1 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false)); GUILayout.Label((dv1 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
public static void display_transfer_angles_MOON2MOON(CelestialBody body, Vessel vessel) public static void display_transfer_angles_MOON2MOON(CelestialBody body, Vessel vessel)
{ {
double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody( double dv1 = VOID_Tools.Younata_DeltaVToGetToOtherBody(
(vessel.mainBody.referenceBody.gravParameter / 1000000000), (vessel.mainBody.referenceBody.gravParameter / 1000000000),
(vessel.mainBody.orbit.semiMajorAxis / 1000), (vessel.mainBody.orbit.semiMajorAxis / 1000),
(body.orbit.semiMajorAxis / 1000) (body.orbit.semiMajorAxis / 1000)
); );
double dv2 = VOID_Tools.Younata_DeltaVToExitSOI( double dv2 = VOID_Tools.Younata_DeltaVToExitSOI(
(vessel.mainBody.gravParameter / 1000000000), (vessel.mainBody.gravParameter / 1000000000),
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
(vessel.mainBody.sphereOfInfluence / 1000), (vessel.mainBody.sphereOfInfluence / 1000),
Math.Abs(dv1) Math.Abs(dv1)
); );
double trans_ejection_angle = VOID_Tools.Younata_TransferBurnPoint( double trans_ejection_angle = VOID_Tools.Younata_TransferBurnPoint(
(vessel.orbit.semiMajorAxis / 1000), (vessel.orbit.semiMajorAxis / 1000),
dv2, dv2,
(Math.PI / 2.0), (Math.PI / 2.0),
(vessel.mainBody.gravParameter / 1000000000) (vessel.mainBody.gravParameter / 1000000000)
); );
   
double curr_phase_angle = VOID_Tools.Adammada_CurrrentPhaseAngle( double curr_phase_angle = VOID_Tools.Adammada_CurrrentPhaseAngle(
body.orbit.LAN, body.orbit.LAN,
body.orbit.orbitPercent, body.orbit.orbitPercent,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN, FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent
); );
double curr_ejection_angle = VOID_Tools.Adammada_CurrentEjectionAngle( double curr_ejection_angle = VOID_Tools.Adammada_CurrentEjectionAngle(
FlightGlobals.ActiveVessel.longitude, FlightGlobals.ActiveVessel.longitude,
FlightGlobals.ActiveVessel.orbit.referenceBody.rotationAngle, FlightGlobals.ActiveVessel.orbit.referenceBody.rotationAngle,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN, FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.LAN,
FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent FlightGlobals.ActiveVessel.orbit.referenceBody.orbit.orbitPercent
); );
   
double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle( double trans_phase_angle = VOID_Tools.Nivvy_CalcTransferPhaseAngle(
vessel.mainBody.orbit.semiMajorAxis, vessel.mainBody.orbit.semiMajorAxis,
body.orbit.semiMajorAxis, body.orbit.semiMajorAxis,
vessel.mainBody.referenceBody.gravParameter vessel.mainBody.referenceBody.gravParameter
) % 360; ) % 360;
   
double adj_phase_angle = VOID_Tools.adjustCurrPhaseAngle(trans_phase_angle, curr_phase_angle); double adj_phase_angle = VOID_Tools.adjustCurrPhaseAngle(trans_phase_angle, curr_phase_angle);
//double adj_ejection_angle = adjustCurrEjectionAngle(trans_phase_angle, curr_ejection_angle); //double adj_ejection_angle = adjustCurrEjectionAngle(trans_phase_angle, curr_ejection_angle);
   
//new stuff //new stuff
// //
double adj_trans_ejection_angle = VOID_Tools.adjust_transfer_ejection_angle(trans_ejection_angle, trans_phase_angle); double adj_trans_ejection_angle = VOID_Tools.adjust_transfer_ejection_angle(trans_ejection_angle, trans_phase_angle);
double adj_curr_ejection_angle = VOID_Tools.adjust_current_ejection_angle(curr_ejection_angle); double adj_curr_ejection_angle = VOID_Tools.adjust_current_ejection_angle(curr_ejection_angle);
// //
// //
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Phase angle (curr/trans):"); GUILayout.Label("Phase angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
adj_phase_angle.ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°", adj_phase_angle.ToString("F3") + "° / " + trans_phase_angle.ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Ejection angle (curr/trans):"); GUILayout.Label("Ejection angle (curr/trans):");
GUILayout.Label( GUILayout.Label(
adj_curr_ejection_angle.ToString("F3") + "° / " + adj_trans_ejection_angle.ToString("F3") + "°", adj_curr_ejection_angle.ToString("F3") + "° / " + adj_trans_ejection_angle.ToString("F3") + "°",
GUILayout.ExpandWidth(false) GUILayout.ExpandWidth(false)
); );
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Transfer velocity:"); GUILayout.Label("Transfer velocity:");
GUILayout.Label((dv2 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false)); GUILayout.Label((dv2 * 1000).ToString("F2") + "m/s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
public static string get_heading_text(double heading) public static string get_heading_text(double heading)
{ {
if (heading > 348.75 || heading <= 11.25) if (heading > 348.75 || heading <= 11.25)
return "N"; return "N";
else if (heading > 11.25 && heading <= 33.75) else if (heading > 11.25 && heading <= 33.75)
return "NNE"; return "NNE";
else if (heading > 33.75 && heading <= 56.25) else if (heading > 33.75 && heading <= 56.25)
return "NE"; return "NE";
else if (heading > 56.25 && heading <= 78.75) else if (heading > 56.25 && heading <= 78.75)
return "ENE"; return "ENE";
else if (heading > 78.75 && heading <= 101.25) else if (heading > 78.75 && heading <= 101.25)
return "E"; return "E";
else if (heading > 101.25 && heading <= 123.75) else if (heading > 101.25 && heading <= 123.75)
return "ESE"; return "ESE";
else if (heading > 123.75 && heading <= 146.25) else if (heading > 123.75 && heading <= 146.25)
return "SE"; return "SE";
else if (heading > 146.25 && heading <= 168.75) else if (heading > 146.25 && heading <= 168.75)
return "SSE"; return "SSE";
else if (heading > 168.75 && heading <= 191.25) else if (heading > 168.75 && heading <= 191.25)
return "S"; return "S";
else if (heading > 191.25 && heading <= 213.75) else if (heading > 191.25 && heading <= 213.75)
return "SSW"; return "SSW";
else if (heading > 213.75 && heading <= 236.25) else if (heading > 213.75 && heading <= 236.25)
return "SW"; return "SW";
else if (heading > 236.25 && heading <= 258.75) else if (heading > 236.25 && heading <= 258.75)
return "WSW"; return "WSW";
else if (heading > 258.75 && heading <= 281.25) else if (heading > 258.75 && heading <= 281.25)
return "W"; return "W";
else if (heading > 281.25 && heading <= 303.75) else if (heading > 281.25 && heading <= 303.75)
return "WNW"; return "WNW";
else if (heading > 303.75 && heading <= 326.25) else if (heading > 303.75 && heading <= 326.25)
return "NW"; return "NW";
else if (heading > 326.25 && heading <= 348.75) else if (heading > 326.25 && heading <= 348.75)
return "NNW"; return "NNW";
else else
return ""; return "";
} }
} }
   
public class CBListComparer : IComparer<CelestialBody> public class CBListComparer : IComparer<CelestialBody>
{ {
public int Compare(CelestialBody bodyA, CelestialBody bodyB) public int Compare(CelestialBody bodyA, CelestialBody bodyB)
{ {
Tools.PostDebugMessage(this, "got bodyA: {0} & bodyB: {1}", bodyA, bodyB); Tools.PostDebugMessage(this, "got bodyA: {0} & bodyB: {1}", bodyA, bodyB);
   
if (bodyA == null && bodyB == null) if (bodyA == null && bodyB == null)
{ {
Tools.PostDebugMessage(this, "both bodies are null, returning 0"); Tools.PostDebugMessage(this, "both bodies are null, returning 0");
return 0; return 0;
} }
if (bodyA == null) if (bodyA == null)
{ {
Tools.PostDebugMessage(this, "bodyA is null, returning -1"); Tools.PostDebugMessage(this, "bodyA is null, returning -1");
return -1; return -1;
} }
if (bodyB == null) if (bodyB == null)
{ {
Tools.PostDebugMessage(this, "bodyB is null, returning 1"); Tools.PostDebugMessage(this, "bodyB is null, returning 1");
return 1; return 1;
} }
   
Tools.PostDebugMessage(this, "bodies are not null, carrying on"); Tools.PostDebugMessage(this, "bodies are not null, carrying on");
   
if (object.ReferenceEquals(bodyA, bodyB)) if (object.ReferenceEquals(bodyA, bodyB))
{ {
Tools.PostDebugMessage(this, "bodies are equal, returning 0"); Tools.PostDebugMessage(this, "bodies are equal, returning 0");
return 0; return 0;
} }
   
Tools.PostDebugMessage(this, "bodies are not equal, carrying on"); Tools.PostDebugMessage(this, "bodies are not equal, carrying on");
   
if (bodyA.orbitDriver == null) if (bodyA.orbitDriver == null)
{ {
Tools.PostDebugMessage(this, "bodyA.orbit is null (bodyA is the sun, returning 1"); Tools.PostDebugMessage(this, "bodyA.orbit is null (bodyA is the sun, returning 1");
return 1; return 1;
} }
if (bodyB.orbitDriver == null) if (bodyB.orbitDriver == null)
{ {
Tools.PostDebugMessage(this, "bodyB.orbit is null (bodyB is the sun, returning -1"); Tools.PostDebugMessage(this, "bodyB.orbit is null (bodyB is the sun, returning -1");
return -1; return -1;
} }
   
Tools.PostDebugMessage(this, "orbits are not null, carrying on"); Tools.PostDebugMessage(this, "orbits are not null, carrying on");
   
if (bodyA.orbit.referenceBody == bodyB.orbit.referenceBody) if (bodyA.orbit.referenceBody == bodyB.orbit.referenceBody)
{ {
Tools.PostDebugMessage(this, "bodies share a parent, comparing SMAs"); Tools.PostDebugMessage(this, "bodies share a parent, comparing SMAs");
return -bodyA.orbit.semiMajorAxis.CompareTo(bodyB.orbit.semiMajorAxis); return -bodyA.orbit.semiMajorAxis.CompareTo(bodyB.orbit.semiMajorAxis);
} }
   
Tools.PostDebugMessage(this, "orbits do not share a parent, carrying on"); Tools.PostDebugMessage(this, "orbits do not share a parent, carrying on");
   
if (bodyA.hasAncestor(bodyB)) if (bodyA.hasAncestor(bodyB))
{ {
Tools.PostDebugMessage(this, "bodyA is a moon or sub-moon of bodyB, returning -1"); Tools.PostDebugMessage(this, "bodyA is a moon or sub-moon of bodyB, returning -1");
return -1; return -1;
} }
if (bodyB.hasAncestor(bodyA)) if (bodyB.hasAncestor(bodyA))
{ {
Tools.PostDebugMessage(this, "bodyA is a moon or sub-moon of bodyB, returning 1"); Tools.PostDebugMessage(this, "bodyA is a moon or sub-moon of bodyB, returning 1");
return 1; return 1;
} }
   
Tools.PostDebugMessage(this, "bodies do not have an obvious relationship, searching for one"); Tools.PostDebugMessage(this, "bodies do not have an obvious relationship, searching for one");
   
if (VOID_Tools.NearestRelatedParents(ref bodyA, ref bodyB)) if (VOID_Tools.NearestRelatedParents(ref bodyA, ref bodyB))
{ {
Tools.PostDebugMessage(this, "good relation {0} and {1}, comparing", bodyA.bodyName, bodyB.bodyName); Tools.PostDebugMessage(this, "good relation {0} and {1}, comparing", bodyA.bodyName, bodyB.bodyName);
return this.Compare(bodyA, bodyB); return this.Compare(bodyA, bodyB);
} }
   
Tools.PostDebugMessage(this, "bad relation {0} and {1}, giving up", bodyA.bodyName, bodyB.bodyName); Tools.PostDebugMessage(this, "bad relation {0} and {1}, giving up", bodyA.bodyName, bodyB.bodyName);
   
return 0; return 0;
} }
} }
} }