VOIDCore_Generic: Basic cleanup removing underscores, fixing some naming conventions, etc.
VOIDCore_Generic: Basic cleanup removing underscores, fixing some naming conventions, etc.

// VOID // VOID
// //
// IVOID_Module.cs // IVOID_Module.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; using System;
   
namespace VOID namespace VOID
{ {
public interface IVOID_Module public interface IVOID_Module
{ {
string Name { get; } string Name { get; }
bool toggleActive { get; set; } bool toggleActive { get; set; }
bool guiRunning { get; } bool guiRunning { get; }
bool inValidScene { get; } bool inValidScene { get; }
bool inValidGame { get; } bool inValidGame { get; }
   
void DrawGUI(); void DrawGUI();
void StartGUI(); void StartGUI();
void StopGUI(); void StopGUI();
   
void DrawConfigurables(); void DrawConfigurables();
   
void LoadConfig(); void LoadConfig();
   
void _SaveToConfig(KSP.IO.PluginConfiguration config); void Save(KSP.IO.PluginConfiguration config);
} }
   
public interface IVOID_BehaviorModule : IVOID_Module public interface IVOID_BehaviorModule : IVOID_Module
{ {
void Update(); void Update();
void FixedUpdate(); void FixedUpdate();
void OnDestroy(); void OnDestroy();
} }
} }
   
// VOID // VOID
// //
// IVOID_Core.cs // IVOID_Core.cs
// //
// Copyright © 2015, toadicus // Copyright © 2015, 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 KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
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 abstract class VOIDCore : VOID_Module, IVOID_Module public abstract class VOIDCore : VOID_WindowModule, IVOID_Module
{ {
public const double Constant_G = 6.674e-11; public const double Constant_G = 6.674e-11;
public const int CONFIG_VERSION = 2; public const int CONFIG_VERSION = 2;
   
public static bool useToolbarManager; public abstract int ConfigVersion { get; }
   
public abstract int configVersion { get; }  
public virtual bool configNeedsUpdate { get; set; } public virtual bool configNeedsUpdate { get; set; }
   
public abstract int windowID { get; } public abstract int WindowID { get; }
public abstract bool configDirty { get; set; } public abstract bool configDirty { get; set; }
public abstract bool powerAvailable { get; protected set; } public abstract bool powerAvailable { get; protected set; }
   
public abstract List<IVOID_Module> Modules { get; } public abstract IList<IVOID_Module> Modules { get; }
   
public abstract float updateTimer { get; protected set; } public abstract float UpdateTimer { get; protected set; }
public abstract double updatePeriod { get; } public abstract double UpdatePeriod { get; }
   
public virtual float saveTimer { get; protected set; } public virtual float saveTimer { get; protected set; }
   
public abstract GUISkin Skin { get; } public abstract GUISkin Skin { get; }
   
public abstract CelestialBody HomeBody { get; } public abstract CelestialBody HomeBody { get; }
public abstract List<CelestialBody> allBodies { get; } public abstract IList<CelestialBody> AllBodies { get; }
public abstract List<CelestialBody> sortedBodyList { get; protected set; } public abstract List<CelestialBody> SortedBodyList { get; protected set; }
   
public abstract List<VesselType> allVesselTypes { get; } public abstract VesselType[] AllVesselTypes { get; protected set; }
   
public abstract Stage LastStage { get; protected set; } public abstract Stage LastStage { get; protected set; }
public abstract Stage[] Stages { get; protected set; } public abstract Stage[] Stages { get; protected set; }
   
public abstract event VOIDEventHandler onApplicationQuit; public abstract event VOIDEventHandler onApplicationQuit;
public abstract event VOIDEventHandler onSkinChanged; public abstract event VOIDEventHandler onSkinChanged;
   
public virtual void OnGUI() {} public virtual void OnGUI() {}
   
public override void LoadConfig() public override void LoadConfig()
{ {
var config = KSP.IO.PluginConfiguration.CreateForType<VOIDCore>(null);  
   
useToolbarManager = config.GetValue("UseToolbarManager", useToolbarManager);  
   
base.LoadConfig(); base.LoadConfig();
} }
   
public abstract void SaveConfig(); public abstract void SaveConfig();
   
public override void _SaveToConfig(KSP.IO.PluginConfiguration config) public override void Save(KSP.IO.PluginConfiguration config)
{ {
config.SetValue("UseToolbarManager", useToolbarManager); base.Save(config);
   
base._SaveToConfig(config);  
} }
} }
   
public delegate void VOIDEventHandler(object sender); public delegate void VOIDEventHandler(object sender);
} }
   
   
// VOID // VOID
// //
// VOIDMaster.cs // VOIDMaster.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.
// //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// //
// Much, much credit to Younata, Adammada, Nivvydaskrl and to all the authors // Much, much credit to Younata, Adammada, Nivvydaskrl and to all the authors
// behind MechJeb, RemoteTech Relay Network, ISA MapSat, and Protractor for some // behind MechJeb, RemoteTech Relay Network, ISA MapSat, and Protractor for some
// invaluable functions and making your nicely written code available to learn from. // invaluable functions and making your nicely written code available to learn from.
// //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// //
// This software uses VesselSimulator and Engineer.Extensions from Engineer Redux. // This software uses VesselSimulator and Engineer.Extensions from Engineer Redux.
// Engineer Redux (c) 2013 cybutek // Engineer Redux (c) 2013 cybutek
// Used by permission. // Used by permission.
// //
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
   
using System; using System;
using UnityEngine; using UnityEngine;
using KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
using ToadicusTools; using ToadicusTools;
   
namespace VOID namespace VOID
{ {
public abstract class VOIDMaster<T> : MonoBehaviour public abstract class VOIDMaster<T> : MonoBehaviour
where T : VOIDCore_Generic<T>, new() where T : VOIDCore_Generic<T>, new()
{ {
protected T Core; protected T Core;
   
public abstract void Awake(); public abstract void Awake();
   
public virtual void Update() public virtual void Update()
{ {
if (this.Core != null && !this.InValidScene()) if (this.Core != null && !this.InValidScene())
{ {
this.LogDebug("We have a Core but the scene is not valid for this master. Saving and disposing."); this.LogDebug("We have a Core but the scene is not valid for this master. Saving and disposing.");
   
this.Core.SaveConfig (); this.Core.SaveConfig ();
this.Core.Dispose(); this.Core.Dispose();
this.Core = null; this.Core = null;
return; return;
} }
   
if (this.Core == null && this.InValidScene()) if (this.Core == null && this.InValidScene())
{ {
this.LogDebug("We have no Core and the scene is valid for this master; re-trying Awake."); this.LogDebug("We have no Core and the scene is valid for this master; re-trying Awake.");
this.Awake(); this.Awake();
return; return;
} }
   
this.Core.Update (); this.Core.Update ();
   
if (this.Core.factoryReset) if (this.Core.FactoryReset)
{ {
this.LogDebug("Factory reset is true; deleting config and disposing!"); this.LogDebug("Factory reset is true; deleting config and disposing!");
   
KSP.IO.File.Delete<T>("config.xml"); KSP.IO.File.Delete<T>("config.xml");
this.Core.Dispose(); this.Core.Dispose();
this.Core = null; this.Core = null;
} }
} }
   
public virtual void FixedUpdate() public virtual void FixedUpdate()
{ {
if (this.Core == null) if (this.Core == null)
{ {
return; return;
} }
   
this.Core.FixedUpdate (); this.Core.FixedUpdate ();
} }
   
public virtual void OnGUI() public virtual void OnGUI()
{ {
if (this.Core == null) if (this.Core == null)
{ {
return; return;
} }
   
this.Core.OnGUI(); this.Core.OnGUI();
} }
   
public virtual void OnDestroy() public virtual void OnDestroy()
{ {
if (this.Core == null) if (this.Core == null)
{ {
return; return;
} }
   
this.Core.OnDestroy(); this.Core.OnDestroy();
} }
   
public virtual void OnApplicationQuit() public virtual void OnApplicationQuit()
{ {
if (this.Core == null) if (this.Core == null)
{ {
return; return;
} }
   
this.Core.OnApplicationQuit(); this.Core.OnApplicationQuit();
} }
   
protected virtual bool InValidScene() protected virtual bool InValidScene()
{ {
foreach (var attr in this.GetType().GetCustomAttributes(true)) foreach (var attr in this.GetType().GetCustomAttributes(true))
{ {
if (attr is KSPAddon) if (attr is KSPAddon)
{ {
KSPAddon addonAttr = (KSPAddon)attr; KSPAddon addonAttr = (KSPAddon)attr;
   
switch (addonAttr.startup) switch (addonAttr.startup)
{ {
case KSPAddon.Startup.EveryScene: case KSPAddon.Startup.EveryScene:
return true; return true;
case KSPAddon.Startup.EditorAny: case KSPAddon.Startup.EditorAny:
return HighLogic.LoadedSceneIsEditor; return HighLogic.LoadedSceneIsEditor;
case KSPAddon.Startup.Flight: case KSPAddon.Startup.Flight:
return HighLogic.LoadedSceneIsFlight; return HighLogic.LoadedSceneIsFlight;
case KSPAddon.Startup.MainMenu: case KSPAddon.Startup.MainMenu:
return HighLogic.LoadedScene == GameScenes.MAINMENU; return HighLogic.LoadedScene == GameScenes.MAINMENU;
case KSPAddon.Startup.SpaceCentre: case KSPAddon.Startup.SpaceCentre:
return HighLogic.LoadedScene == GameScenes.SPACECENTER; return HighLogic.LoadedScene == GameScenes.SPACECENTER;
case KSPAddon.Startup.TrackingStation: case KSPAddon.Startup.TrackingStation:
return HighLogic.LoadedScene == GameScenes.TRACKSTATION; return HighLogic.LoadedScene == GameScenes.TRACKSTATION;
default: default:
return false; return false;
} }
} }
} }
   
return false; return false;
} }
} }
} }
   
// VOID // VOID
// //
// VOID_HUDModule.cs // VOID_HUDModule.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 KerbalEngineer.VesselSimulator; using KerbalEngineer.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 abstract class VOID_HUDModule : VOID_Module public abstract class VOID_HUDModule : VOID_Module
{ {
[AVOID_SaveValue("colorIndex")] [AVOID_SaveValue("colorIndex")]
protected VOID_SaveValue<int> _colorIndex; protected VOID_SaveValue<int> _colorIndex;
   
protected List<Color> textColors; protected List<Color> textColors;
   
[AVOID_SaveValue("positionsLocked")] [AVOID_SaveValue("positionsLocked")]
protected VOID_SaveValue<bool> positionsLocked; protected VOID_SaveValue<bool> positionsLocked;
   
public virtual int ColorIndex public virtual 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.value = 0;
return; return;
} }
   
this._colorIndex = value; this._colorIndex.value = value;
} }
} }
   
public virtual List<HUDWindow> Windows public virtual List<HUDWindow> Windows
{ {
get; get;
protected set; protected set;
} }
   
public VOID_HUDModule() : base() public VOID_HUDModule() : base()
{ {
this._colorIndex = 0; this._colorIndex = (VOID_SaveValue<int>)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.positionsLocked = true; this.positionsLocked = (VOID_SaveValue<bool>)true;
   
this.Windows = new List<HUDWindow>(); this.Windows = new List<HUDWindow>();
} }
   
public override void DrawGUI() public override void DrawGUI()
{ {
VOID_Styles.labelHud.normal.textColor = textColors [ColorIndex]; VOID_Styles.labelHud.normal.textColor = textColors [ColorIndex];
   
GUI.skin = this.core.Skin; GUI.skin = this.core.Skin;
   
if (HighLogic.LoadedSceneIsEditor || if (HighLogic.LoadedSceneIsEditor ||
(TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate) (TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate)
) )
{ {
SimManager.RequestSimulation(); SimManager.RequestSimulation();
} }
   
foreach (HUDWindow window in this.Windows) foreach (HUDWindow window in this.Windows)
{ {
window.WindowPos = GUILayout.Window( window.WindowPos = GUILayout.Window(
this.core.windowID, this.core.WindowID,
window.WindowPos, window.WindowPos,
VOID_Tools.GetWindowHandler(window.WindowFunction), VOID_Tools.GetWindowHandler(window.WindowFunction),
GUIContent.none, GUIContent.none,
GUIStyle.none GUIStyle.none
); );
} }
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
base.DrawConfigurables(); base.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)))
{ {
foreach (HUDWindow window in this.Windows) foreach (HUDWindow window in this.Windows)
{ {
window.WindowPos = new Rect(window.defaultWindowPos); window.WindowPos = new Rect(window.defaultWindowPos);
} }
} }
   
this.positionsLocked = GUITools.Toggle(this.positionsLocked, "Lock HUD Positions"); this.positionsLocked.value = GUITools.Toggle(this.positionsLocked, "Lock HUD Positions");
} }
   
public override void LoadConfig() public override void LoadConfig()
{ {
base.LoadConfig(); base.LoadConfig();
   
var config = KSP.IO.PluginConfiguration.CreateForType<VOID_HUDModule>(); var config = KSP.IO.PluginConfiguration.CreateForType<VOID_HUDModule>();
config.load(); config.load();
   
foreach (HUDWindow window in this.Windows) foreach (HUDWindow window in this.Windows)
{ {
string saveName = string.Format("{0}_{1}", this.GetType().Name, window.WindowName); string saveName = string.Format("{0}_{1}", this.GetType().Name, window.WindowName);
Rect loadedPos = config.GetValue(saveName, window.defaultWindowPos); Rect loadedPos = config.GetValue(saveName, window.defaultWindowPos);
   
window.WindowPos = loadedPos; window.WindowPos = loadedPos;
} }
} }
   
public override void _SaveToConfig(KSP.IO.PluginConfiguration config) public override void Save(KSP.IO.PluginConfiguration config)
{ {
base._SaveToConfig(config); base.Save(config);
   
foreach (HUDWindow window in this.Windows) foreach (HUDWindow window in this.Windows)
{ {
string saveName = string.Format("{0}_{1}", this.GetType().Name, window.WindowName); string saveName = string.Format("{0}_{1}", this.GetType().Name, window.WindowName);
config.SetValue(saveName, window.WindowPos); config.SetValue(saveName, window.WindowPos);
} }
} }
} }
   
public class HUDWindow public class HUDWindow
{ {
public readonly Rect defaultWindowPos; public readonly Rect defaultWindowPos;
   
private Rect _windowPos; private Rect _windowPos;
   
public Action<int> WindowFunction public Action<int> WindowFunction
{ {
get; get;
private set; private set;
} }
   
public Rect WindowPos public Rect WindowPos
{ {
get get
{ {
return this._windowPos; return this._windowPos;
} }
set set
{ {
if (value != this._windowPos) if (value != this._windowPos)
{ {
this._windowPos = value; this._windowPos = value;
   
if (VOID_Data.Core != null) if (VOID_Data.Core != null)
{ {
VOID_Data.Core.configDirty = true; VOID_Data.Core.configDirty = true;
} }
} }
} }
} }
   
public string WindowName public string WindowName
{ {
get; get;
private set; private set;
} }
   
private HUDWindow() {} private HUDWindow() {}
   
public HUDWindow(string name, Action<int> windowFunc, Rect defaultPos) public HUDWindow(string name, Action<int> windowFunc, Rect defaultPos)
{ {
this.WindowName = name; this.WindowName = name;
this.WindowFunction = windowFunc; this.WindowFunction = windowFunc;
this.defaultWindowPos = defaultPos; this.defaultWindowPos = defaultPos;
this.WindowPos = new Rect(this.defaultWindowPos); this.WindowPos = new Rect(this.defaultWindowPos);
} }
} }
} }
   
   
// VOID // VOID
// //
// VOID_Module.cs // VOID_Module.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; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public abstract class VOID_Module : IVOID_Module public abstract class VOID_Module : IVOID_Module
{ {
/* /*
* Fields * Fields
* */ * */
[AVOID_SaveValue("Active")] [AVOID_SaveValue("Active")]
protected VOID_SaveValue<bool> _Active = false; protected VOID_SaveValue<bool> _Active = (VOID_SaveValue<bool>)false;
private GameScenes[] validScenes; private GameScenes[] validScenes;
private Game.Modes[] validModes; private Game.Modes[] validModes;
   
protected float lastUpdate = 0; protected float lastUpdate = 0;
   
/* /*
* Properties * Properties
* */ * */
protected virtual VOIDCore core protected virtual VOIDCore core
{ {
get get
{ {
return VOID_Data.Core; return VOID_Data.Core;
} }
} }
   
protected virtual bool timeToUpdate protected virtual bool timeToUpdate
{ {
get get
{ {
return ( return (
(this.core.updateTimer - this.lastUpdate) > this.core.updatePeriod || (this.core.UpdateTimer - this.lastUpdate) > this.core.UpdatePeriod ||
this.lastUpdate > this.core.updateTimer this.lastUpdate > this.core.UpdateTimer
); );
} }
} }
   
public virtual bool toggleActive public virtual bool toggleActive
{ {
get get
{ {
return this._Active && this.inValidGame && this.inValidScene; return this._Active && this.inValidGame && this.inValidScene;
} }
set set
{ {
this._Active = value && this.inValidGame && this.inValidScene; this._Active.value = value && this.inValidGame && this.inValidScene;
} }
} }
   
public virtual bool guiRunning public virtual bool guiRunning
{ {
get get
{ {
if ( if (
RenderingManager.fetch == null || RenderingManager.fetch == null ||
RenderingManager.fetch.postDrawQueue == null || RenderingManager.fetch.postDrawQueue == null ||
RenderingManager.fetch.postDrawQueue.Length < 4 RenderingManager.fetch.postDrawQueue.Length < 4
) )
{ {
return false; return false;
} }
else else
{ {
Delegate callback = RenderingManager.fetch.postDrawQueue[3]; Delegate callback = RenderingManager.fetch.postDrawQueue[3];
if (callback == null) if (callback == null)
{ {
return false; return false;
} }
   
return callback.GetInvocationList().Contains((Callback)this.DrawGUI); return callback.GetInvocationList().Contains((Callback)this.DrawGUI);
} }
} }
} }
   
public virtual GameScenes[] ValidScenes public virtual GameScenes[] ValidScenes
{ {
get get
{ {
if (this.validScenes == null) if (this.validScenes == null)
{ {
Tools.PostDebugMessage(this, "validScenes is null when checking inValidScene; fetching attribute."); Tools.PostDebugMessage(this, "validScenes is null when checking inValidScene; fetching attribute.");
foreach (var attr in this.GetType().GetCustomAttributes(false)) foreach (var attr in this.GetType().GetCustomAttributes(false))
{ {
if (attr is VOID_ScenesAttribute) if (attr is VOID_ScenesAttribute)
{ {
VOID_ScenesAttribute addonAttr = (VOID_ScenesAttribute)attr; VOID_ScenesAttribute addonAttr = (VOID_ScenesAttribute)attr;
   
this.validScenes = addonAttr.ValidScenes; this.validScenes = addonAttr.ValidScenes;
   
Tools.PostDebugMessage("Found VOID_ScenesAttribute; validScenes set."); Tools.PostDebugMessage("Found VOID_ScenesAttribute; validScenes set.");
   
break; break;
} }
} }
   
if (this.validScenes == null) if (this.validScenes == null)
{ {
this.validScenes = new GameScenes[] { GameScenes.FLIGHT }; this.validScenes = new GameScenes[] { GameScenes.FLIGHT };
Tools.PostDebugMessage("No VOID_ScenesAttribute found; validScenes defaulted to flight."); Tools.PostDebugMessage("No VOID_ScenesAttribute found; validScenes defaulted to flight.");
} }
} }
   
return this.validScenes; return this.validScenes;
} }
} }
   
public virtual bool inValidScene public virtual bool inValidScene
{ {
get get
{ {
return this.ValidScenes.Contains(HighLogic.LoadedScene); return this.ValidScenes.Contains(HighLogic.LoadedScene);
} }
} }
   
public virtual Game.Modes[] ValidModes public virtual Game.Modes[] ValidModes
{ {
get get
{ {
if (this.validModes == null) if (this.validModes == null)
{ {
Tools.PostDebugMessage(this, "validModes is null when checking inValidGame; fetching attribute."); Tools.PostDebugMessage(this, "validModes is null when checking inValidGame; fetching attribute.");
foreach (var attr in this.GetType().GetCustomAttributes(false)) foreach (var attr in this.GetType().GetCustomAttributes(false))
{ {
if (attr is VOID_GameModesAttribute) if (attr is VOID_GameModesAttribute)
{ {
VOID_GameModesAttribute addonAttr = (VOID_GameModesAttribute)attr; VOID_GameModesAttribute addonAttr = (VOID_GameModesAttribute)attr;
   
this.validModes = addonAttr.ValidModes; this.validModes = addonAttr.ValidModes;
   
Tools.PostDebugMessage("Found VOID_GameModesAttribute; validScenes set."); Tools.PostDebugMessage("Found VOID_GameModesAttribute; validScenes set.");
   
break; break;
} }
} }
   
if (this.validModes == null) if (this.validModes == null)
{ {
this.validModes = new Game.Modes[] this.validModes = new Game.Modes[]
{ {
Game.Modes.CAREER, Game.Modes.CAREER,
Game.Modes.SANDBOX, Game.Modes.SANDBOX,
Game.Modes.SCENARIO, Game.Modes.SCENARIO,
Game.Modes.SCENARIO_NON_RESUMABLE, Game.Modes.SCENARIO_NON_RESUMABLE,
Game.Modes.SCIENCE_SANDBOX Game.Modes.SCIENCE_SANDBOX
}; };
   
Tools.PostDebugMessage("No VOID_GameModesAttribute found; validScenes defaulted to flight."); Tools.PostDebugMessage("No VOID_GameModesAttribute found; validScenes defaulted to flight.");
} }
} }
   
return this.validModes; return this.validModes;
} }
} }
   
public virtual bool inValidGame public virtual bool inValidGame
{ {
get get
{ {
return this.ValidModes.Contains(HighLogic.CurrentGame.Mode); return this.ValidModes.Contains(HighLogic.CurrentGame.Mode);
} }
} }
   
public virtual string Name public virtual string Name
{ {
get; get;
protected set; protected set;
} }
   
public virtual Vessel vessel public virtual Vessel vessel
{ {
get get
{ {
return FlightGlobals.ActiveVessel; return FlightGlobals.ActiveVessel;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public void StartGUI() public virtual void StartGUI()
{ {
if (!this.toggleActive || this.guiRunning) if (!this.toggleActive || this.guiRunning)
{ {
return; return;
} }
   
Tools.PostDebugMessage (string.Format("Adding {0} to the draw queue.", this.GetType().Name)); Tools.PostDebugMessage (string.Format("Adding {0} to the draw queue.", this.GetType().Name));
RenderingManager.AddToPostDrawQueue (3, this.DrawGUI); RenderingManager.AddToPostDrawQueue (3, this.DrawGUI);
} }
   
public void StopGUI() public virtual void StopGUI()
{ {
if (!this.guiRunning) if (!this.guiRunning)
{ {
return; return;
} }
Tools.PostDebugMessage (string.Format("Removing {0} from the draw queue.", this.GetType().Name)); Tools.PostDebugMessage (string.Format("Removing {0} from the draw queue.", this.GetType().Name));
RenderingManager.RemoveFromPostDrawQueue (3, this.DrawGUI); RenderingManager.RemoveFromPostDrawQueue (3, this.DrawGUI);
} }
   
public abstract void DrawGUI(); public abstract void DrawGUI();
   
public virtual void DrawConfigurables() {} public virtual void DrawConfigurables() {}
   
public virtual void LoadConfig() public virtual void LoadConfig()
{ {
var config = KSP.IO.PluginConfiguration.CreateForType<VOID_Module> (); var config = KSP.IO.PluginConfiguration.CreateForType<VOID_Module> ();
config.load (); config.load ();
   
if (this is VOIDCore) if (this is VOIDCore)
{ {
int configVersion = config.GetValue("VOID_Core_configValue", 2); int configVersion = config.GetValue("VOID_Core_configValue", 2);
   
if (configVersion < VOIDCore.CONFIG_VERSION) if (configVersion < VOIDCore.CONFIG_VERSION)
{ {
((VOIDCore)this).configNeedsUpdate = true; ((VOIDCore)this).configNeedsUpdate = true;
} }
} }
   
foreach (var field in this.GetType().GetMembers( foreach (var field in this.GetType().GetMembers(
BindingFlags.NonPublic | BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Public |
BindingFlags.Instance | BindingFlags.Instance |
BindingFlags.FlattenHierarchy BindingFlags.FlattenHierarchy
)) ))
{ {
if (!(field is FieldInfo || field is PropertyInfo)) if (!(field is FieldInfo || field is PropertyInfo))
{ {
continue; continue;
} }
   
if (field is PropertyInfo && (field as PropertyInfo).GetIndexParameters().Length > 0) if (field is PropertyInfo && (field as PropertyInfo).GetIndexParameters().Length > 0)
{ {
continue; continue;
} }
   
object[] attrs = field.GetCustomAttributes(typeof(AVOID_SaveValue), false); object[] attrs = field.GetCustomAttributes(typeof(AVOID_SaveValue), false);
   
if (attrs.Length == 0) { if (attrs.Length == 0) {
continue; continue;
} }
   
AVOID_SaveValue attr = attrs.FirstOrDefault () as AVOID_SaveValue; AVOID_SaveValue attr = attrs.FirstOrDefault () as AVOID_SaveValue;
   
string fieldName = string.Empty; string fieldName = string.Empty;
   
if (this is VOIDCore || this.core.configNeedsUpdate) if (this is VOIDCore || this.core.configNeedsUpdate)
{ {
string typeName = this.GetType().Name;; string typeName = this.GetType().Name;;
   
if (this is VOIDCore && ((VOIDCore)this).configNeedsUpdate) if (this is VOIDCore && ((VOIDCore)this).configNeedsUpdate)
{ {
if (this is VOIDCore_Flight) if (this is VOIDCore_Flight)
{ {
typeName = "VOID_Core"; typeName = "VOID_Core";
} }
else if (this is VOIDCore_Editor) else if (this is VOIDCore_Editor)
{ {
typeName = "VOID_EditorCore"; typeName = "VOID_EditorCore";
} }
} }
   
fieldName = string.Format("{0}_{1}", typeName, attr.Name); fieldName = string.Format("{0}_{1}", typeName, attr.Name);
} }
else else
{ {
fieldName = string.Format( fieldName = string.Format(
"{0}_{1}_{2}", "{0}_{1}_{2}",
this.GetType().Name, this.GetType().Name,
Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene), Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene),
attr.Name attr.Name
); );
} }
   
Tools.PostDebugMessage(string.Format("{0}: Loading field {1}.", this.GetType().Name, fieldName)); Tools.PostDebugMessage(string.Format("{0}: Loading field {1}.", this.GetType().Name, fieldName));
   
object fieldValue; object fieldValue;
   
if (field is FieldInfo) if (field is FieldInfo)
{ {
fieldValue = (field as FieldInfo).GetValue(this); fieldValue = (field as FieldInfo).GetValue(this);
} }
else else
{ {
fieldValue = (field as PropertyInfo).GetValue(this, null); fieldValue = (field as PropertyInfo).GetValue(this, null);
} }
   
bool convertBack = false; bool convertBack = false;
if (fieldValue is IVOID_SaveValue) if (fieldValue is IVOID_SaveValue)
{ {
fieldValue = (fieldValue as IVOID_SaveValue).value; fieldValue = (fieldValue as IVOID_SaveValue).value;
convertBack = true; convertBack = true;
} }
   
fieldValue = config.GetValue(fieldName, fieldValue); fieldValue = config.GetValue(fieldName, fieldValue);
   
if (convertBack) if (convertBack)
{ {
Type type = typeof(VOID_SaveValue<>).MakeGenericType (fieldValue.GetType ()); Type type = typeof(VOID_SaveValue<>).MakeGenericType (fieldValue.GetType ());
IVOID_SaveValue convertValue = Activator.CreateInstance (type) as IVOID_SaveValue; IVOID_SaveValue convertValue = Activator.CreateInstance (type) as IVOID_SaveValue;
convertValue.SetValue (fieldValue); convertValue.SetValue (fieldValue);
fieldValue = convertValue; fieldValue = convertValue;
} }
   
if (field is FieldInfo) if (field is FieldInfo)
{ {
(field as FieldInfo).SetValue(this, fieldValue); (field as FieldInfo).SetValue(this, fieldValue);
} }
else else
{ {
(field as PropertyInfo).SetValue(this, fieldValue, null); (field as PropertyInfo).SetValue(this, fieldValue, null);
} }
   
Tools.PostDebugMessage(string.Format("{0}: Loaded field {1}.", this.GetType().Name, fieldName)); Tools.PostDebugMessage(string.Format("{0}: Loaded field {1}.", this.GetType().Name, fieldName));
} }
} }
   
public virtual void _SaveToConfig(KSP.IO.PluginConfiguration config) public virtual void Save(KSP.IO.PluginConfiguration config)
{ {
foreach (var field in this.GetType().GetMembers( foreach (var field in this.GetType().GetMembers(
BindingFlags.Instance | BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Public |
BindingFlags.FlattenHierarchy BindingFlags.FlattenHierarchy
)) ))
{ {
object[] attrs = field.GetCustomAttributes(typeof(AVOID_SaveValue), false); object[] attrs = field.GetCustomAttributes(typeof(AVOID_SaveValue), false);
   
if (attrs.Length == 0) { if (attrs.Length == 0) {
continue; continue;
} }
   
AVOID_SaveValue attr = attrs.FirstOrDefault () as AVOID_SaveValue; AVOID_SaveValue attr = attrs.FirstOrDefault () as AVOID_SaveValue;
   
string fieldName; string fieldName;
   
if (this is VOIDCore) if (this is VOIDCore)
{ {
fieldName = string.Format("{0}_{1}", this.GetType().Name, attr.Name); fieldName = string.Format("{0}_{1}", this.GetType().Name, attr.Name);
} }
else else
{ {
fieldName = string.Format( fieldName = string.Format(
"{0}_{1}_{2}", "{0}_{1}_{2}",
this.GetType().Name, this.GetType().Name,
Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene), Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene),
attr.Name attr.Name
); );
} }
   
object fieldValue; object fieldValue;
   
if (field is FieldInfo) if (field is FieldInfo)
{ {
fieldValue = (field as FieldInfo).GetValue(this); fieldValue = (field as FieldInfo).GetValue(this);
} }
else else
{ {
fieldValue = (field as PropertyInfo).GetValue(this, null); fieldValue = (field as PropertyInfo).GetValue(this, null);
} }
   
if (fieldValue is IVOID_SaveValue) if (fieldValue is IVOID_SaveValue)
{ {
fieldValue = (fieldValue as IVOID_SaveValue).value; fieldValue = (fieldValue as IVOID_SaveValue).value;
} }
   
config.SetValue(fieldName, fieldValue); config.SetValue(fieldName, fieldValue);
   
Tools.PostDebugMessage(string.Format("{0}: Saved field {1}.", this.GetType().Name, fieldName)); Tools.PostDebugMessage(string.Format("{0}: Saved field {1}.", this.GetType().Name, fieldName));
} }
} }
} }
   
public abstract class VOID_WindowModule : VOID_Module public abstract class VOID_WindowModule : VOID_Module
{ {
protected static GUIContent closeButton;  
   
protected static Dictionary<int, Action<int>> DecoratedWindows;  
   
[AVOID_SaveValue("WindowPos")] [AVOID_SaveValue("WindowPos")]
protected Rect WindowPos; protected Rect WindowPos;
protected float defWidth; protected float defWidth;
protected float defHeight; protected float defHeight;
   
  protected bool decorateWindow;
   
protected string inputLockName; protected string inputLockName;
   
protected virtual Action<int> DecoratedWindow  
{  
get  
{  
return VOID_WindowModule.DecorateWindow(  
this.ModuleWindow,  
this.WindowPos,  
(bool active) => { this.toggleActive = active; }  
);  
}  
}  
   
public VOID_WindowModule() : base() public VOID_WindowModule() : base()
{ {
this.defWidth = 250f; this.defWidth = 250f;
this.defHeight = 50f; this.defHeight = 50f;
   
  this.decorateWindow = true;
   
this.inputLockName = string.Concat(this.Name, "_edlock"); this.inputLockName = string.Concat(this.Name, "_edlock");
   
this.WindowPos = new Rect(Screen.width / 2, Screen.height / 2, this.defWidth, this.defHeight); this.WindowPos = new Rect(Screen.width / 2, Screen.height / 2, this.defWidth, this.defHeight);
} }
   
public abstract void ModuleWindow(int _); public virtual void ModuleWindow(int id)
  {
  GUIStyle buttonStyle = this.core.Skin.button;
  RectOffset padding = buttonStyle.padding;
  RectOffset border = buttonStyle.border;
   
  Rect closeRect = new Rect(
  0f,
  0f,
  border.left + border.right,
  border.top + border.bottom
  );
   
  closeRect.width = Mathf.Max(closeRect.width, 16f);
  closeRect.height = Mathf.Max(closeRect.height, 16f);
   
  closeRect.x = this.WindowPos.width - closeRect.width - 2f;
  closeRect.y = 2f;
   
  GUI.Button(closeRect, GUIContent.none, buttonStyle);
   
  if (Event.current.type == EventType.repaint && Input.GetMouseButtonUp(0))
  {
  if (closeRect.Contains(Event.current.mousePosition))
  {
  this.toggleActive = false;
  }
  }
   
  GUI.DragWindow();
  }
   
public override void DrawGUI() public override void DrawGUI()
{ {
GUI.skin = this.core.Skin; GUI.skin = this.core.Skin;
   
Rect _Pos = this.WindowPos; Rect _Pos = this.WindowPos;
   
_Pos = GUILayout.Window( _Pos = GUILayout.Window(
this.core.windowID, this.core.WindowID,
_Pos, _Pos,
VOID_Tools.GetWindowHandler(this.DecoratedWindow), VOID_Tools.GetWindowHandler(this.ModuleWindow),
this.Name, this.Name,
GUILayout.Width(this.defWidth), GUILayout.Width(this.defWidth),
GUILayout.Height(this.defHeight), GUILayout.Height(this.defHeight)
GUILayout.ExpandWidth(true),  
GUILayout.ExpandHeight(true)  
); );
   
bool cursorInWindow = _Pos.Contains(Mouse.screenPos); bool cursorInWindow = _Pos.Contains(Mouse.screenPos);
   
switch (HighLogic.LoadedScene) switch (HighLogic.LoadedScene)
{ {
case GameScenes.EDITOR: case GameScenes.EDITOR:
if (cursorInWindow) if (cursorInWindow)
{ {
InputLockManager.SetControlLock( InputLockManager.SetControlLock(
ControlTypes.EDITOR_ICON_HOVER | ControlTypes.EDITOR_ICON_PICK | ControlTypes.EDITOR_ICON_HOVER | ControlTypes.EDITOR_ICON_PICK |
ControlTypes.EDITOR_PAD_PICK_COPY | ControlTypes.EDITOR_PAD_PICK_COPY, ControlTypes.EDITOR_PAD_PICK_COPY | ControlTypes.EDITOR_PAD_PICK_COPY,
this.inputLockName this.inputLockName
); );
EditorLogic.fetch.Lock(false, false, false, this.inputLockName); EditorLogic.fetch.Lock(false, false, false, this.inputLockName);
} }
else else
{ {
EditorLogic.fetch.Unlock(this.inputLockName); EditorLogic.fetch.Unlock(this.inputLockName);
} }
break; break;
case GameScenes.FLIGHT: case GameScenes.FLIGHT:
if (cursorInWindow) if (cursorInWindow)
{ {
InputLockManager.SetControlLock(ControlTypes.CAMERACONTROLS, this.inputLockName); InputLockManager.SetControlLock(ControlTypes.CAMERACONTROLS, this.inputLockName);
} }
else if (InputLockManager.GetControlLock(this.inputLockName) != ControlTypes.None) else if (InputLockManager.GetControlLock(this.inputLockName) != ControlTypes.None)
{ {
InputLockManager.RemoveControlLock(this.inputLockName); InputLockManager.RemoveControlLock(this.inputLockName);
} }
break; break;
case GameScenes.SPACECENTER: case GameScenes.SPACECENTER:
if (cursorInWindow) if (cursorInWindow)
{ {
InputLockManager.SetControlLock( InputLockManager.SetControlLock(
ControlTypes.KSC_FACILITIES | ControlTypes.CAMERACONTROLS, ControlTypes.KSC_FACILITIES | ControlTypes.CAMERACONTROLS,
this.inputLockName this.inputLockName
); );
} }
else if (InputLockManager.GetControlLock(this.inputLockName) != ControlTypes.None) else if (InputLockManager.GetControlLock(this.inputLockName) != ControlTypes.None)
{ {
InputLockManager.RemoveControlLock(this.inputLockName); InputLockManager.RemoveControlLock(this.inputLockName);
} }
break; break;
} }
   
if (HighLogic.LoadedSceneIsEditor) if (HighLogic.LoadedSceneIsEditor)
{ {
_Pos = Tools.ClampRectToEditorPad(_Pos); _Pos = Tools.ClampRectToEditorPad(_Pos);
} }
else else
{ {
_Pos = Tools.ClampRectToScreen(_Pos); _Pos = Tools.ClampRectToScreen(_Pos);
} }
   
if (_Pos != this.WindowPos) if (_Pos != this.WindowPos)
{ {
this.WindowPos = _Pos; this.WindowPos = _Pos;
this.core.configDirty = true; this.core.configDirty = true;
} }
} }
   
public static Action<int> DecorateWindow(Action<int> func, Rect windowRect, Callback<bool> callBack, bool useCache)  
{  
if (DecoratedWindows == null)  
{  
DecoratedWindows = new Dictionary<int, Action<int>>();  
}  
   
int hashCode = func.GetHashCode();  
   
if (!useCache || !DecoratedWindows.ContainsKey(hashCode))  
{  
DecoratedWindows[hashCode] = delegate(int id)  
{  
func(id);  
   
if (closeButton == null)  
{  
closeButton = new GUIContent("X");  
}  
   
Rect closeRect = GUILayoutUtility.GetRect(  
closeButton,  
VOID_Data.Core.Skin.button,  
GUILayout.ExpandWidth(false)  
);  
   
closeRect.x = windowRect.width - closeRect.width - VOID_Data.Core.Skin.button.margin.right;  
closeRect.y = VOID_Data.Core.Skin.button.margin.top;  
   
GUI.Button(closeRect, closeButton, VOID_Data.Core.Skin.button);  
   
if (Event.current.type == EventType.repaint && Input.GetMouseButtonUp(0))  
{  
if (closeRect.Contains(Event.current.mousePosition))  
{  
callBack(false);  
}  
}  
};  
}  
   
return DecoratedWindows[hashCode];  
}  
   
public static Action<int> DecorateWindow(Action<int> func, Rect windowRect, Callback<bool> callBack)  
{  
return DecorateWindow(func, windowRect, callBack, true);  
}  
   
public static void UncacheWindow(Action<int> func)  
{  
if (DecoratedWindows != null)  
{  
int hashCode = func.GetHashCode();  
   
if (DecoratedWindows.ContainsKey(hashCode))  
{  
VOID_Tools.UncacheWindow(DecoratedWindows[hashCode]);  
   
DecoratedWindows.Remove(hashCode);  
}  
}  
}  
} }
} }
   
   
// VOID // VOID
// //
// VOID_DataValue.cs // VOID_DataValue.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; using System;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_DataValue<T> : IVOID_DataValue public class VOID_DataValue<T> : IVOID_DataValue
{ {
/* /*
* Static Members * Static Members
* */ * */
public static implicit operator T(VOID_DataValue<T> v) public static implicit operator T(VOID_DataValue<T> v)
{ {
return (T)v.Value; return (T)v.Value;
} }
   
/* /*
* Instance Members * Instance Members
* */ * */
/* /*
* Fields * Fields
* */ * */
protected T cache; protected T cache;
protected Func<T> ValueFunc; protected Func<T> ValueFunc;
protected float lastUpdate; protected float lastUpdate;
   
/* /*
* Properties * Properties
* */ * */
public string Label { get; protected set; } public string Label { get; protected set; }
public string Units { get; protected set; } public string Units { get; protected set; }
   
object IVOID_DataValue.Value object IVOID_DataValue.Value
{ {
get get
{ {
return this.Value; return this.Value;
} }
} }
   
public T Value public T Value
{ {
get get
{ {
if ( if (
(VOID_Data.Core.updateTimer - this.lastUpdate > VOID_Data.Core.updatePeriod) || (VOID_Data.Core.UpdateTimer - this.lastUpdate > VOID_Data.Core.UpdatePeriod) ||
(this.lastUpdate > VOID_Data.Core.updateTimer) (this.lastUpdate > VOID_Data.Core.UpdateTimer)
) )
{ {
this.Refresh(); this.Refresh();
} }
return (T)this.cache; return (T)this.cache;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public VOID_DataValue(string Label, Func<T> ValueFunc, string Units = "") public VOID_DataValue(string Label, Func<T> ValueFunc, string Units = "")
{ {
this.Label = Label; this.Label = Label;
this.Units = Units; this.Units = Units;
this.ValueFunc = ValueFunc; this.ValueFunc = ValueFunc;
this.lastUpdate = 0; this.lastUpdate = 0;
   
VOID_Data.DataValues[this.GetHashCode()] = this; VOID_Data.DataValues[this.GetHashCode()] = this;
} }
   
public void Refresh() public void Refresh()
{ {
this.cache = this.ValueFunc.Invoke (); this.cache = this.ValueFunc.Invoke ();
this.lastUpdate = VOID_Data.Core.updateTimer; this.lastUpdate = VOID_Data.Core.UpdateTimer;
} }
   
public T GetFreshValue() public T GetFreshValue()
{ {
this.Refresh (); this.Refresh ();
return (T)this.cache; return (T)this.cache;
} }
   
public virtual string ValueUnitString() { public virtual string ValueUnitString() {
return this.Value.ToString() + this.Units; return this.Value.ToString() + this.Units;
} }
   
public virtual void DoGUIHorizontal() public virtual void DoGUIHorizontal()
{ {
GUILayout.BeginHorizontal (GUILayout.ExpandWidth (true)); GUILayout.BeginHorizontal (GUILayout.ExpandWidth (true));
GUILayout.Label (this.Label + ":"); GUILayout.Label (this.Label + ":");
GUILayout.FlexibleSpace (); GUILayout.FlexibleSpace ();
GUILayout.Label (this.ValueUnitString(), GUILayout.ExpandWidth (false)); GUILayout.Label (this.ValueUnitString(), GUILayout.ExpandWidth (false));
GUILayout.EndHorizontal (); GUILayout.EndHorizontal ();
} }
   
public override int GetHashCode() public override int GetHashCode()
{ {
int hash; int hash;
unchecked unchecked
{ {
hash = 79999; hash = 79999;
   
hash = hash * 104399 + this.Label.GetHashCode(); hash = hash * 104399 + this.Label.GetHashCode();
hash = hash * 104399 + this.ValueFunc.GetHashCode(); hash = hash * 104399 + this.ValueFunc.GetHashCode();
hash = hash * 104399 + this.Units.GetHashCode(); hash = hash * 104399 + this.Units.GetHashCode();
} }
   
return hash; return hash;
} }
   
public override string ToString() public override string ToString()
{ {
return string.Format ( return string.Format (
"{0}: {1}{2}", "{0}: {1}{2}",
this.Label, this.Label,
this.Value.ToString (), this.Value.ToString (),
this.Units this.Units
); );
} }
} }
   
public abstract class VOID_NumValue<T> : VOID_DataValue<T>, IFormattable public abstract class VOID_NumValue<T> : VOID_DataValue<T>, IFormattable
where T : IFormattable, IConvertible, IComparable where T : IFormattable, IConvertible, IComparable
{ {
public static IFormatProvider formatProvider = Tools.SIFormatter; public static IFormatProvider formatProvider = Tools.SIFormatter;
   
public static implicit operator Double(VOID_NumValue<T> v) public static implicit operator Double(VOID_NumValue<T> v)
{ {
return v.ToDouble(); return v.ToDouble();
} }
   
public static implicit operator Int32(VOID_NumValue<T> v) public static implicit operator Int32(VOID_NumValue<T> v)
{ {
return v.ToInt32(); return v.ToInt32();
} }
   
public static implicit operator Single(VOID_NumValue<T> v) public static implicit operator Single(VOID_NumValue<T> v)
{ {
return v.ToSingle(); return v.ToSingle();
} }
   
public VOID_NumValue(string Label, Func<T> ValueFunc, string Units = "") : base(Label, ValueFunc, Units) public VOID_NumValue(string Label, Func<T> ValueFunc, string Units = "") : base(Label, ValueFunc, Units)
{ {
   
} }
   
public virtual double ToDouble(IFormatProvider provider) public virtual double ToDouble(IFormatProvider provider)
{ {
return this.Value.ToDouble(provider); return this.Value.ToDouble(provider);
} }
   
public virtual double ToDouble() public virtual double ToDouble()
{ {
return this.ToDouble(formatProvider); return this.ToDouble(formatProvider);
} }
   
public virtual int ToInt32(IFormatProvider provider) public virtual int ToInt32(IFormatProvider provider)
{ {
return this.Value.ToInt32(provider); return this.Value.ToInt32(provider);
} }
   
public virtual int ToInt32() public virtual int ToInt32()
{ {
return this.ToInt32(formatProvider); return this.ToInt32(formatProvider);
} }
   
public virtual float ToSingle(IFormatProvider provider) public virtual float ToSingle(IFormatProvider provider)
{ {
return this.Value.ToSingle(provider); return this.Value.ToSingle(provider);
} }
   
public virtual float ToSingle() public virtual float ToSingle()
{ {
return this.ToSingle(formatProvider); return this.ToSingle(formatProvider);
} }
   
public virtual string ToString(string format) public virtual string ToString(string format)
{ {
return this.ToString(format, formatProvider); return this.ToString(format, formatProvider);
} }
   
public virtual string ToString(string format, IFormatProvider provider) public virtual string ToString(string format, IFormatProvider provider)
{ {
return string.Format ( return string.Format (
"{0}{1}", "{0}{1}",
this.Value.ToString(format, provider), this.Value.ToString(format, provider),
this.Units this.Units
); );
} }
   
public virtual string ToSIString(int digits = 3, int MinMagnitude = 0, int MaxMagnitude = int.MaxValue) public virtual string ToSIString(int digits = 3, int MinMagnitude = 0, int MaxMagnitude = int.MaxValue)
{ {
return string.Format ( return string.Format (
"{0}{1}", "{0}{1}",
Tools.MuMech_ToSI (this, digits, MinMagnitude, MaxMagnitude), Tools.MuMech_ToSI (this, digits, MinMagnitude, MaxMagnitude),
this.Units this.Units
); );
} }
   
public virtual string ValueUnitString(string format) public virtual string ValueUnitString(string format)
{ {
return this.Value.ToString(format, formatProvider) + this.Units; return this.Value.ToString(format, formatProvider) + this.Units;
} }
public virtual string ValueUnitString(int digits) { public virtual string ValueUnitString(int digits) {
return Tools.MuMech_ToSI(this, digits) + this.Units; return Tools.MuMech_ToSI(this, digits) + this.Units;
} }
   
public virtual string ValueUnitString(int digits, int MinMagnitude, int MaxMagnitude) public virtual string ValueUnitString(int digits, int MinMagnitude, int MaxMagnitude)
{ {
return Tools.MuMech_ToSI(this, digits, MinMagnitude, MaxMagnitude) + this.Units; return Tools.MuMech_ToSI(this, digits, MinMagnitude, MaxMagnitude) + this.Units;
} }
   
public virtual void DoGUIHorizontal(string format) public virtual void DoGUIHorizontal(string format)
{ {
GUILayout.BeginHorizontal (GUILayout.ExpandWidth (true)); GUILayout.BeginHorizontal (GUILayout.ExpandWidth (true));
GUILayout.Label (this.Label + ":"); GUILayout.Label (this.Label + ":");
GUILayout.FlexibleSpace (); GUILayout.FlexibleSpace ();
GUILayout.Label (this.ValueUnitString(format), GUILayout.ExpandWidth (false)); GUILayout.Label (this.ValueUnitString(format), GUILayout.ExpandWidth (false));
GUILayout.EndHorizontal (); GUILayout.EndHorizontal ();
} }
   
public virtual int DoGUIHorizontal(int digits, bool precisionButton = true) public virtual int DoGUIHorizontal(int digits, bool precisionButton = true)
{ {
if (precisionButton) if (precisionButton)
{ {
return this.DoGUIHorizontalPrec(digits); return this.DoGUIHorizontalPrec(digits);
} }
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(this.Label + ":", GUILayout.ExpandWidth(true)); GUILayout.Label(this.Label + ":", GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.Label(this.ValueUnitString(digits), GUILayout.ExpandWidth(false)); GUILayout.Label(this.ValueUnitString(digits), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
return digits; return digits;
} }
   
public virtual int DoGUIHorizontalPrec(int digits) public virtual int DoGUIHorizontalPrec(int digits)
{ {
double magnitude; double magnitude;
double magLimit; double magLimit;
   
magnitude = Math.Log10(Math.Abs((double)this)); magnitude = Math.Log10(Math.Abs((double)this));
   
magLimit = Math.Max(Math.Abs(magnitude), 3d) + 3d; magLimit = Math.Max(Math.Abs(magnitude), 3d) + 3d;
magLimit = Math.Round(Math.Ceiling(magLimit / 3f)) * 3d; magLimit = Math.Round(Math.Ceiling(magLimit / 3f)) * 3d;
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(this.Label + "ⁱ:", GUILayout.ExpandWidth(true)); GUILayout.Label(this.Label + "ⁱ:", GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
   
if (magnitude >= 0) if (magnitude >= 0)
{ {
GUILayout.Label(this.ValueUnitString(3, int.MinValue, (int)magnitude - digits), GUILayout.ExpandWidth(false)); GUILayout.Label(this.ValueUnitString(3, int.MinValue, (int)magnitude - digits), GUILayout.ExpandWidth(false));
} }
else else
{ {
GUILayout.Label(this.ValueUnitString(3, (int)magnitude + digits, int.MaxValue), GUILayout.ExpandWidth(false)); GUILayout.Label(this.ValueUnitString(3, (int)magnitude + digits, int.MaxValue), GUILayout.ExpandWidth(false));
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (Event.current.type == EventType.mouseUp) if (Event.current.type == EventType.mouseUp)
{ {
Rect lastRect = GUILayoutUtility.GetLastRect(); Rect lastRect = GUILayoutUtility.GetLastRect();
if (lastRect.Contains(Event.current.mousePosition)) if (lastRect.Contains(Event.current.mousePosition))
{ {
Tools.PostDebugMessage(string.Format("{0}: Changing digits from {1} within magLimit {2}.", Tools.PostDebugMessage(string.Format("{0}: Changing digits from {1} within magLimit {2}.",
this.GetType().Name, this.GetType().Name,
digits, digits,
magLimit)); magLimit));
   
if (Event.current.button == 0) if (Event.current.button == 0)
{ {
digits = (digits + 3) % (int)magLimit; digits = (digits + 3) % (int)magLimit;
} }
else if (Event.current.button == 1) else if (Event.current.button == 1)
{ {
digits = (digits - 3) % (int)magLimit; digits = (digits - 3) % (int)magLimit;
} }
   
if (digits < 0) if (digits < 0)
{ {
digits += (int)magLimit; digits += (int)magLimit;
} }
   
Tools.PostDebugMessage(string.Format("{0}: Changed digits to {1}." + Tools.PostDebugMessage(string.Format("{0}: Changed digits to {1}." +
"\n\tNew minMagnitude: {2}, maxMagnitude: {3}" + "\n\tNew minMagnitude: {2}, maxMagnitude: {3}" +
"\n\tMagnitude: {4}", "\n\tMagnitude: {4}",
this.GetType().Name, this.GetType().Name,
digits, digits,
magnitude >= 0 ? int.MinValue : (int)magnitude - 4 + digits, magnitude >= 0 ? int.MinValue : (int)magnitude - 4 + digits,
magnitude >= 0 ? (int)magnitude - digits : int.MaxValue, magnitude >= 0 ? (int)magnitude - digits : int.MaxValue,
magnitude magnitude
)); ));
} }
} }
   
return digits; return digits;
} }
} }
   
public class VOID_DoubleValue : VOID_NumValue<double> public class VOID_DoubleValue : VOID_NumValue<double>
{ {
public VOID_DoubleValue(string Label, Func<double> ValueFunc, string Units) : base(Label, ValueFunc, Units) {} public VOID_DoubleValue(string Label, Func<double> ValueFunc, string Units) : base(Label, ValueFunc, Units) {}
} }
   
public class VOID_FloatValue : VOID_NumValue<float> public class VOID_FloatValue : VOID_NumValue<float>
{ {
public VOID_FloatValue(string Label, Func<float> ValueFunc, string Units) : base(Label, ValueFunc, Units) {} public VOID_FloatValue(string Label, Func<float> ValueFunc, string Units) : base(Label, ValueFunc, Units) {}
} }
   
public class VOID_IntValue : VOID_NumValue<int> public class VOID_IntValue : VOID_NumValue<int>
{ {
public VOID_IntValue(string Label, Func<int> ValueFunc, string Units) : base(Label, ValueFunc, Units) {} public VOID_IntValue(string Label, Func<int> ValueFunc, string Units) : base(Label, ValueFunc, Units) {}
} }
   
public class VOID_StrValue : VOID_DataValue<string> public class VOID_StrValue : VOID_DataValue<string>
{ {
public VOID_StrValue(string Label, Func<string> ValueFunc) : base(Label, ValueFunc, "") {} public VOID_StrValue(string Label, Func<string> ValueFunc) : base(Label, ValueFunc, "") {}
} }
   
public class VOID_Vector3dValue : VOID_DataValue<Vector3d> public class VOID_Vector3dValue : VOID_DataValue<Vector3d>
{ {
public VOID_Vector3dValue(string Label, Func<Vector3d> ValueFunc, string Units) public VOID_Vector3dValue(string Label, Func<Vector3d> ValueFunc, string Units)
: base(Label, ValueFunc, Units) : base(Label, ValueFunc, Units)
{} {}
   
public string ToString(string format) public string ToString(string format)
{ {
return string.Format("{0}: {1}{2}", return string.Format("{0}: {1}{2}",
this.Label, this.Label,
this.Value.ToString(format), this.Value.ToString(format),
this.Units this.Units
); );
} }
   
public string ValueUnitString(string format) { public string ValueUnitString(string format) {
return this.Value.ToString(format) + this.Units; return this.Value.ToString(format) + this.Units;
} }
} }
} }
   
   
  // VOID
  //
  // VOID_Localization.cs
  //
  // Copyright © 2014, toadicus
  // All rights reserved.
  //
  // Redistribution and use in source and binary forms, with or without modification,
  // are permitted provided that the following conditions are met:
  //
  // 1. Redistributions of source code must retain the above copyright notice,
  // this list of conditions and the following disclaimer.
  //
  // 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
  // materials provided with the distribution.
  //
  // 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.
  //
  // 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
  // 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
  // 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
  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  public static class VOID_Localization
  {
  public static string void_primary = "Primary";
  public static string void_altitude_asl = "Altitude (ASL)";
  public static string void_velocity = "Velocity";
  public static string void_apoapsis = "Apoapsis";
  public static string void_periapsis = "Periapsis";
  }
// VOID // VOID
// //
// VOID_SaveValue.cs // VOID_SaveValue.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 struct VOID_SaveValue<T> : IVOID_SaveValue public struct VOID_SaveValue<T> : IVOID_SaveValue
{ {
private T _value; private T _value;
private Type _type; private Type _type;
   
private VOIDCore Core private VOIDCore Core
{ {
get get
{ {
return VOID_Data.Core; return VOID_Data.Core;
} }
} }
   
object IVOID_SaveValue.value object IVOID_SaveValue.value
{ {
get get
{ {
return this.value; return this.value;
} }
} }
   
public T value public T value
{ {
get get
{ {
return this._value; return this._value;
} }
set set
{ {
if (this.Core != null && !System.Object.Equals(this._value, value)) if (this.Core != null && !System.Object.Equals(this._value, value))
{ {
Tools.PostDebugMessage (string.Format ( Tools.PostDebugMessage (string.Format (
"VOID: Dirtying config for type {0} in method {1}." + "VOID: Dirtying config for type {0}." +
"\n\t Old Value: {2}, New Value: {3}" + "\n\t Old Value: {2}, New Value: {3}" +
"\n\t Object.Equals(New, Old): {4}", "\n\t Object.Equals(New, Old): {4}\n" +
  "{1}",
this._type, this._type,
new System.Diagnostics.StackTrace().GetFrame(1).GetMethod(), new System.Diagnostics.StackTrace().ToString(),
this._value, this._value,
value, value,
System.Object.Equals(this._value, value) System.Object.Equals(this._value, value)
)); ));
this.Core.configDirty = true; this.Core.configDirty = true;
} }
this._value = value; this._value = value;
} }
} }
   
public Type type public Type type
{ {
get get
{ {
if (this._type == null && this._value != null) if (this._type == null && this._value != null)
{ {
this._type = this._value.GetType (); this._type = this._value.GetType ();
} }
return this._type; return this._type;
} }
set set
{ {
this._type = value; this._type = value;
} }
} }
   
public void SetValue(object v) public void SetValue(object v)
{ {
this.value = (T)v; this.value = (T)v;
} }
   
public static implicit operator T(VOID_SaveValue<T> v) public static implicit operator T(VOID_SaveValue<T> v)
{ {
return (T)v.value; return (T)v.value;
} }
   
public static implicit operator VOID_SaveValue<T>(T v) public static explicit operator VOID_SaveValue<T>(T v)
{ {
VOID_SaveValue<T> r = new VOID_SaveValue<T>(); VOID_SaveValue<T> r = new VOID_SaveValue<T>();
r.type = v.GetType(); r.type = v.GetType();
r.value = v; r.value = v;
   
return r; return r;
} }
   
public override string ToString() public override string ToString()
{ {
return this.value.ToString(); return this.value.ToString();
} }
} }
} }
   
   
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug_win</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug_win</Configuration>
<ProductVersion>8.0.30703</ProductVersion> <ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{45ACC1CC-942C-4A66-BFC7-8BE375938B18}</ProjectGuid> <ProjectGuid>{45ACC1CC-942C-4A66-BFC7-8BE375938B18}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<RootNamespace>VOID</RootNamespace> <RootNamespace>VOID</RootNamespace>
<AssemblyName>VOID</AssemblyName> <AssemblyName>VOID</AssemblyName>
<CodePage>65001</CodePage> <CodePage>65001</CodePage>
<UseMSBuildEngine>False</UseMSBuildEngine> <UseMSBuildEngine>False</UseMSBuildEngine>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ReleaseVersion>0.11</ReleaseVersion> <ReleaseVersion>0.11</ReleaseVersion>
<SynchReleaseVersion>false</SynchReleaseVersion> <SynchReleaseVersion>false</SynchReleaseVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug_win|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug_win|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath> <OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG; TRACE</DefineConstants> <DefineConstants>DEBUG; TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
<CustomCommands> <CustomCommands>
<CustomCommands> <CustomCommands>
<Command type="AfterBuild" command="xcopy /Y ${TargetFile} ${ProjectDir}\GameData\VOID\Plugins\" /> <Command type="AfterBuild" command="xcopy /Y ${TargetFile} ${ProjectDir}\GameData\VOID\Plugins\" />
</CustomCommands> </CustomCommands>
</CustomCommands> </CustomCommands>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release_win|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release_win|AnyCPU' ">
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath> <OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<CustomCommands> <CustomCommands>
<CustomCommands> <CustomCommands>
<Command type="AfterBuild" command="xcopy /Y ${TargetFile} ${ProjectDir}\GameData\VOID\Plugins\" /> <Command type="AfterBuild" command="xcopy /Y ${TargetFile} ${ProjectDir}\GameData\VOID\Plugins\" />
</CustomCommands> </CustomCommands>
</CustomCommands> </CustomCommands>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug_linux|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug_linux|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath> <OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG; TRACE</DefineConstants> <DefineConstants>DEBUG; TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
<CustomCommands> <CustomCommands>
<CustomCommands> <CustomCommands>
<Command type="AfterBuild" command="cp -afv ${TargetFile} ${ProjectDir}/GameData/${ProjectName}/Plugins/" /> <Command type="AfterBuild" command="cp -afv ${TargetFile} ${ProjectDir}/GameData/${ProjectName}/Plugins/" />
</CustomCommands> </CustomCommands>
</CustomCommands> </CustomCommands>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release_linux|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release_linux|AnyCPU' ">
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath> <OutputPath>bin\Release</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
<CustomCommands> <CustomCommands>
<CustomCommands> <CustomCommands>
<Command type="AfterBuild" command="cp -afv ${TargetFile} ${ProjectDir}/GameData/${ProjectName}/Plugins/" /> <Command type="AfterBuild" command="cp -afv ${TargetFile} ${ProjectDir}/GameData/${ProjectName}/Plugins/" />
</CustomCommands> </CustomCommands>
</CustomCommands> </CustomCommands>
</PropertyGroup> </PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup> <ItemGroup>
<Compile Include="VOID_HUD.cs" /> <Compile Include="VOID_HUD.cs" />
<Compile Include="VOID_Orbital.cs" /> <Compile Include="VOID_Orbital.cs" />
<Compile Include="VOID_SurfAtmo.cs" /> <Compile Include="VOID_SurfAtmo.cs" />
<Compile Include="VOID_VesselInfo.cs" /> <Compile Include="VOID_VesselInfo.cs" />
<Compile Include="VOID_Transfer.cs" /> <Compile Include="VOID_Transfer.cs" />
<Compile Include="VOID_CBInfoBrowser.cs" /> <Compile Include="VOID_CBInfoBrowser.cs" />
<Compile Include="VOID_Rendezvous.cs" /> <Compile Include="VOID_Rendezvous.cs" />
<Compile Include="VOID_VesselRegister.cs" /> <Compile Include="VOID_VesselRegister.cs" />
<Compile Include="VOID_DataLogger.cs" /> <Compile Include="VOID_DataLogger.cs" />
<Compile Include="VOID_EditorHUD.cs" /> <Compile Include="VOID_EditorHUD.cs" />
<Compile Include="VOID_Localization.cs" />  
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="VOID_HUDAdvanced.cs" /> <Compile Include="VOID_HUDAdvanced.cs" />
<Compile Include="VOID_TWR.cs" /> <Compile Include="VOID_TWR.cs" />
<Compile Include="VOID_CareerStatus.cs" /> <Compile Include="VOID_CareerStatus.cs" />
<Compile Include="VOID_StageInfo.cs" /> <Compile Include="VOID_StageInfo.cs" />
<Compile Include="VOID_Styles.cs" /> <Compile Include="VOID_Styles.cs" />
<Compile Include="VOID_Data.cs" /> <Compile Include="VOID_Data.cs" />
<Compile Include="VOIDMaster_Flight.cs" /> <Compile Include="VOIDMaster_Flight.cs" />
<Compile Include="VOIDMaster_Editor.cs" /> <Compile Include="VOIDMaster_Editor.cs" />
<Compile Include="VOIDMaster_SpaceCentre.cs" /> <Compile Include="VOIDMaster_SpaceCentre.cs" />
<Compile Include="VOIDCore_SpaceCentre.cs" /> <Compile Include="VOIDCore_SpaceCentre.cs" />
<Compile Include="VOIDCore_Flight.cs" /> <Compile Include="VOIDCore_Flight.cs" />
<Compile Include="VOIDCore_Editor.cs" /> <Compile Include="VOIDCore_Editor.cs" />
<Compile Include="VOIDCore_Generic.cs" /> <Compile Include="VOIDCore_Generic.cs" />
<Compile Include="API\IVOID_Module.cs" /> <Compile Include="API\IVOID_Module.cs" />
<Compile Include="API\VOIDCore.cs" /> <Compile Include="API\VOIDCore.cs" />
<Compile Include="API\IVOID_SaveValue.cs" /> <Compile Include="API\IVOID_SaveValue.cs" />
<Compile Include="API\IVOID_DataValue.cs" /> <Compile Include="API\IVOID_DataValue.cs" />
<Compile Include="API\VOID_Module.cs" /> <Compile Include="API\VOID_Module.cs" />
<Compile Include="Tools\VOID_Tools.cs" /> <Compile Include="Tools\VOID_Tools.cs" />
<Compile Include="Tools\VOID_DataValue.cs" /> <Compile Include="Tools\VOID_DataValue.cs" />
<Compile Include="Tools\VOID_SaveValue.cs" /> <Compile Include="Tools\VOID_SaveValue.cs" />
<Compile Include="API\VOID_HUDModule.cs" /> <Compile Include="API\VOID_HUDModule.cs" />
<Compile Include="API\VOID_SingletonModule.cs" /> <Compile Include="API\VOID_SingletonModule.cs" />
<Compile Include="API\Attributes\VOID_ScenesAttribute.cs" /> <Compile Include="API\Attributes\VOID_ScenesAttribute.cs" />
<Compile Include="API\Attributes\AVOID_SaveValue.cs" /> <Compile Include="API\Attributes\AVOID_SaveValue.cs" />
<Compile Include="API\VOIDMaster.cs" /> <Compile Include="API\VOIDMaster.cs" />
<Compile Include="API\Attributes\VOID_GameModesAttribute.cs" /> <Compile Include="API\Attributes\VOID_GameModesAttribute.cs" />
  <Compile Include="VOID_ConfigWindow.cs" />
  <Compile Include="Tools\VOID_Localization.cs" />
</ItemGroup> </ItemGroup>
<ProjectExtensions> <ProjectExtensions>
<MonoDevelop> <MonoDevelop>
<Properties> <Properties>
<Policies> <Policies>
<TextStylePolicy FileWidth="120" TabsToSpaces="False" EolMarker="Unix" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" /> <TextStylePolicy FileWidth="120" TabsToSpaces="False" EolMarker="Unix" inheritsSet="VisualStudio" inheritsScope="text/plain" scope="text/plain" />
</Policies> </Policies>
</Properties> </Properties>
</MonoDevelop> </MonoDevelop>
</ProjectExtensions> </ProjectExtensions>
<ItemGroup> <ItemGroup>
<Reference Include="System"> <Reference Include="System">
<HintPath>..\_KSPAssemblies\System.dll</HintPath> <HintPath>..\_KSPAssemblies\System.dll</HintPath>
</Reference> </Reference>
<Reference Include="Assembly-CSharp"> <Reference Include="Assembly-CSharp">
<HintPath>..\_KSPAssemblies\Assembly-CSharp.dll</HintPath> <HintPath>..\_KSPAssemblies\Assembly-CSharp.dll</HintPath>
</Reference> </Reference>
<Reference Include="UnityEngine"> <Reference Include="UnityEngine">
<HintPath>..\_KSPAssemblies\UnityEngine.dll</HintPath> <HintPath>..\_KSPAssemblies\UnityEngine.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ToadicusTools\ToadicusTools.csproj"> <ProjectReference Include="..\ToadicusTools\ToadicusTools.csproj">
<Project>{D48A5542-6655-4149-BC27-B27DF0466F1C}</Project> <Project>{D48A5542-6655-4149-BC27-B27DF0466F1C}</Project>
<Name>ToadicusTools</Name> <Name>ToadicusTools</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\VesselSimulator\VesselSimulator.csproj"> <ProjectReference Include="..\VesselSimulator\VesselSimulator.csproj">
<Project>{30FD6C0B-D36E-462F-B0FF-F0FAC9C666CF}</Project> <Project>{30FD6C0B-D36E-462F-B0FF-F0FAC9C666CF}</Project>
<Name>VesselSimulator</Name> <Name>VesselSimulator</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="GameData\VOID\Textures\ATM_VOID.cfg" /> <None Include="GameData\VOID\Textures\ATM_VOID.cfg" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="API\" /> <Folder Include="API\" />
<Folder Include="Tools\" /> <Folder Include="Tools\" />
<Folder Include="API\Attributes\" /> <Folder Include="API\Attributes\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
   
// VOID // VOID
// //
// VOID_EditorCore.cs // VOID_EditorCore.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 KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.EDITOR)] [VOID_Scenes(GameScenes.EDITOR)]
public class VOIDCore_Editor : VOIDCore_Generic<VOIDCore_Editor> public class VOIDCore_Editor : VOIDCore_Generic<VOIDCore_Editor>
{ {
public VOIDCore_Editor() : base()  
{  
this.Name = "VOID Core: Editor";  
}  
   
public override void FixedUpdate() {} public override void FixedUpdate() {}
} }
} }
   
   
// VOID // VOID
// //
// VOIDCore_Flight.cs // VOIDCore_Flight.cs
// //
// Copyright © 2015, toadicus // Copyright © 2015, 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 UnityEngine; using UnityEngine;
using ToadicusTools; using ToadicusTools;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.FLIGHT)] [VOID_Scenes(GameScenes.FLIGHT)]
public class VOIDCore_Flight : VOIDCore_Generic<VOIDCore_Flight> public class VOIDCore_Flight : VOIDCore_Generic<VOIDCore_Flight>
{ {
public VOIDCore_Flight()  
{  
base.Name = "VOID Core: Flight";  
}  
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
if (HighLogic.LoadedSceneIsFlight) if (HighLogic.LoadedSceneIsFlight)
{ {
this.consumeResource.value = GUITools.Toggle(this.consumeResource, "Consume Resources"); this.consumeResource.value = GUITools.Toggle(this.consumeResource, "Consume Resources");
} }
   
base.DrawConfigurables(); base.DrawConfigurables();
} }
} }
} }
   
   
// VOID // VOID
// //
// VOIDCore_Generic.cs // VOIDCore_Generic.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 KerbalEngineer.VesselSimulator; using KerbalEngineer.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 abstract class VOIDCore_Generic<T> : VOID_SingletonModule<T>, IVOID_Module, IDisposable public abstract class VOIDCore_Generic<T> : VOID_SingletonModule<T>, IVOID_Module, IDisposable
where T : VOID_Module, new() where T : VOID_Module, new()
{ {
/* /*
* Fields * Fields
* */ * */
protected string VoidName = "VOID"; protected string VoidName = "VOID";
protected string VoidVersion; protected string VoidVersion;
   
[AVOID_SaveValue("configValue")] [AVOID_SaveValue("configValue")]
protected VOID_SaveValue<int> _configVersion = VOIDCore.CONFIG_VERSION; protected VOID_SaveValue<int> configVersion = (VOID_SaveValue<int>)VOIDCore.CONFIG_VERSION;
   
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")]  
protected VOID_SaveValue<Rect> mainWindowPos = new Rect(475, 575, 10f, 10f);  
[AVOID_SaveValue("mainGuiMinimized")]  
protected VOID_SaveValue<bool> mainGuiMinimized = false;  
   
[AVOID_SaveValue("configWindowPos")]  
protected VOID_SaveValue<Rect> configWindowPos = new Rect(825, 625, 10f, 10f);  
[AVOID_SaveValue("configWindowMinimized")]  
   
protected VOID_SaveValue<bool> configWindowMinimized = true;  
   
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;
   
  private bool _useToolbarManager;
   
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 CelestialBody _homeBody; protected CelestialBody homeBody;
   
[AVOID_SaveValue("togglePower")] [AVOID_SaveValue("togglePower")]
public VOID_SaveValue<bool> togglePower = true; public VOID_SaveValue<bool> togglePower = (VOID_SaveValue<bool>)true;
   
public override bool powerAvailable { get; protected set; } public override bool powerAvailable { get; protected set; }
   
[AVOID_SaveValue("consumeResource")] [AVOID_SaveValue("consumeResource")]
protected VOID_SaveValue<bool> consumeResource = false; protected VOID_SaveValue<bool> consumeResource = (VOID_SaveValue<bool>)false;
   
[AVOID_SaveValue("resourceName")] [AVOID_SaveValue("resourceName")]
protected VOID_SaveValue<string> resourceName = "ElectricCharge"; protected VOID_SaveValue<string> resourceName = (VOID_SaveValue<string>)"ElectricCharge";
   
[AVOID_SaveValue("resourceRate")] [AVOID_SaveValue("resourceRate")]
protected VOID_SaveValue<float> resourceRate = 0.2f; protected VOID_SaveValue<float> resourceRate = (VOID_SaveValue<float>)0.2f;
   
[AVOID_SaveValue("updatePeriod")] [AVOID_SaveValue("updatePeriod")]
protected VOID_SaveValue<double> _updatePeriod = 1001f / 15000f; protected VOID_SaveValue<double> updatePeriod = (VOID_SaveValue<double>)(1001f / 15000f);
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 bool vesselTypesLoaded = false; protected bool vesselTypesLoaded = false;
   
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 1", "KSP window 1",
  "KSP window 3",
"KSP window 5", "KSP window 5",
"KSP window 6", "KSP window 6",
"PartTooltipSkin", "PartTooltipSkin",
"KSCContextMenuSkin" "KSCContextMenuSkin"
}; };
protected bool skinsLoaded = false; protected bool skinsLoaded = false;
   
public override bool configDirty { get; set; } public override bool configDirty { get; set; }
   
internal IButton ToolbarButton; internal IButton ToolbarButton;
   
internal ApplicationLauncherButton AppLauncherButton; internal ApplicationLauncherButton AppLauncherButton;
   
/* /*
* Properties * Properties
* */ * */
public override int configVersion  
  public override IList<CelestialBody> AllBodies
{ {
get get
{ {
return this._configVersion; return FlightGlobals.Bodies.AsReadOnly();
} }
} }
   
public bool factoryReset public override VesselType[] AllVesselTypes
{ {
get; get;
protected set; protected set;
} }
   
public override List<IVOID_Module> Modules public override int ConfigVersion
{ {
get get
{ {
return this._modules; return this.configVersion;
  }
  }
   
  public bool FactoryReset
  {
  get;
  protected set;
  }
   
  public override CelestialBody HomeBody
  {
  get
  {
  if (this.homeBody == null)
  {
  if (Planetarium.fetch != null)
  {
  this.homeBody = Planetarium.fetch.Home;
  }
  }
   
  return this.homeBody;
  }
  }
   
  public override IList<IVOID_Module> Modules
  {
  get
  {
  return this.modules.AsReadOnly();
} }
} }
   
public override GUISkin Skin public override 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 override int windowID public override List<CelestialBody> SortedBodyList
{  
get  
{  
if (this._windowID == 0)  
{  
this._windowID = this.windowBaseID;  
}  
return this._windowID++;  
}  
}  
   
public override List<CelestialBody> allBodies  
{  
get  
{  
return FlightGlobals.Bodies;  
}  
}  
   
public override List<CelestialBody> sortedBodyList  
{ {
get; get;
protected set; protected set;
} }
   
public override CelestialBody HomeBody public override double UpdatePeriod
{ {
get get
{ {
if (this._homeBody == null) return this.updatePeriod;
{ }
if (Planetarium.fetch != null) }
{  
this._homeBody = Planetarium.fetch.Home; public override float UpdateTimer
}  
}  
   
return this._homeBody;  
}  
}  
   
public override List<VesselType> allVesselTypes  
{  
get  
{  
return this._allVesselTypes;  
}  
}  
   
public override float updateTimer  
{ {
get; get;
protected set; protected set;
} }
   
  public override int WindowID
public override double updatePeriod  
{ {
get get
{ {
return this._updatePeriod; if (this.windowID == 0)
  {
  this.windowID = this.windowBaseID;
  }
  return this.windowID++;
} }
} }
   
public override Stage[] Stages public override Stage[] Stages
{ {
get; get;
protected set; protected set;
} }
   
public override Stage LastStage public override Stage LastStage
{ {
get; get;
protected set; protected set;
} }
   
  protected IconState activeState
  {
  get
  {
  if (this.toggleActive)
  {
  return IconState.Inactive;
  }
  else
  {
  return IconState.Active;
  }
   
  }
  }
   
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 virtual ApplicationLauncher.AppScenes appIconVisibleScenes
{ {
get get
{ {
if (this.mainGuiMinimized) return HighLogic.LoadedScene.ToAppScenes();
{ }
return IconState.Inactive; }
}  
else protected bool useToolbarManager
{  
return IconState.Active;  
}  
   
}  
}  
   
protected bool UseToolbarManager  
{ {
get get
{ {
return useToolbarManager & ToolbarManager.ToolbarAvailable; return _useToolbarManager & ToolbarManager.ToolbarAvailable;
} }
set set
{ {
if (useToolbarManager == value) if (_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; _useToolbarManager = value;
}  
}  
   
protected virtual ApplicationLauncher.AppScenes appIconVisibleScenes  
{  
get  
{  
return HighLogic.LoadedScene.ToAppScenes();  
} }
} }
   
/* /*
* Events * Events
* */ * */
public override event VOIDEventHandler onApplicationQuit; public override event VOIDEventHandler onApplicationQuit;
public override event VOIDEventHandler onSkinChanged; public override event VOIDEventHandler onSkinChanged;
   
/* /*
* 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( Tools.PostDebugMessage(
this, this,
"ToolbarAvailable: {0}, UseToobarManager: {1}", "ToolbarAvailable: {0}, UseToobarManager: {1}",
ToolbarManager.ToolbarAvailable, ToolbarManager.ToolbarAvailable,
this.UseToolbarManager); this.useToolbarManager);
} }
   
if (!this.UseToolbarManager) if (!this.useToolbarManager)
{ {
if (this.AppLauncherButton == null) if (this.AppLauncherButton == null)
{ {
Tools.PostDebugMessage(this, Tools.PostDebugMessage(this,
"UseToolbarManager = false (ToolbarAvailable = {0}) and " + "UseToolbarManager = false (ToolbarAvailable = {0}) and " +
"AppLauncherButton is null, making AppLauncher button.", "AppLauncherButton is null, making AppLauncher button.",
ToolbarManager.ToolbarAvailable ToolbarManager.ToolbarAvailable
); );
this.InitializeAppLauncherButton(); this.InitializeAppLauncherButton();
} }
} }
else if (this.ToolbarButton == null) else if (this.ToolbarButton == null)
{ {
Tools.PostDebugMessage(this, Tools.PostDebugMessage(this,
"UseToolbarManager = true (ToolbarAvailable = {0}) and " + "UseToolbarManager = true (ToolbarAvailable = {0}) and " +
"ToolbarButton is null, making Toolbar button.", "ToolbarButton is null, making Toolbar button.",
ToolbarManager.ToolbarAvailable ToolbarManager.ToolbarAvailable
); );
this.InitializeToolbarButton(); this.InitializeToolbarButton();
} }
   
if (!this.mainGuiMinimized) if (this.toggleActive)
{ {
  base.DrawGUI();
Rect _mainWindowPos = this.mainWindowPos;  
   
_mainWindowPos = GUILayout.Window(  
this.windowID,  
_mainWindowPos,  
VOID_Tools.GetWindowHandler(  
VOID_WindowModule.DecorateWindow(  
this.VOIDMainWindow,  
_mainWindowPos,  
(bool active) => { this.mainGuiMinimized = !active; }  
)),  
string.Join(" ", new string[] { this.VoidName, this.VoidVersion }),  
GUILayout.Width(250f),  
GUILayout.Height(50f),  
GUILayout.ExpandWidth(true),  
GUILayout.ExpandHeight(true)  
);  
   
if (HighLogic.LoadedSceneIsEditor)  
{  
_mainWindowPos = Tools.ClampRectToEditorPad(_mainWindowPos);  
}  
else  
{  
_mainWindowPos = Tools.ClampRectToScreen(_mainWindowPos);  
}  
   
if (_mainWindowPos != this.mainWindowPos)  
{  
this.mainWindowPos = _mainWindowPos;  
}  
}  
   
if (!this.configWindowMinimized && !this.mainGuiMinimized)  
{  
Rect _configWindowPos = this.configWindowPos;  
   
_configWindowPos = GUILayout.Window(  
this.windowID,  
_configWindowPos,  
VOID_Tools.GetWindowHandler(VOID_WindowModule.DecorateWindow(  
this.VOIDConfigWindow,  
_configWindowPos,  
(bool active) => { this.configWindowMinimized = !active; }  
)),  
string.Join(" ", new string[] { this.VoidName, "Configuration" }),  
GUILayout.Width(250),  
GUILayout.Height(50)  
);  
   
if (HighLogic.LoadedSceneIsEditor)  
{  
_configWindowPos = Tools.ClampRectToEditorPad(_configWindowPos);  
}  
else  
{  
_configWindowPos = Tools.ClampRectToScreen(_configWindowPos);  
}  
   
if (_configWindowPos != this.configWindowPos)  
{  
this.configWindowPos = _configWindowPos;  
}  
} }
} }
   
public virtual void Update() public virtual void Update()
{ {
this.LoadBeforeUpdate(); this.LoadBeforeUpdate();
   
if ( if (
this.vesselSimActive && this.vesselSimActive &&
( (
this.vessel != null || this.vessel != null ||
( (
HighLogic.LoadedSceneIsEditor && HighLogic.LoadedSceneIsEditor &&
EditorLogic.RootPart != null && EditorLogic.RootPart != null &&
EditorLogic.SortedShipList.Count > 0 EditorLogic.SortedShipList.Count > 0
) )
) )
) )
{ {
Tools.PostDebugMessage(this, "Updating SimManager."); Tools.PostDebugMessage(this, "Updating SimManager.");
this.UpdateSimManager(); this.UpdateSimManager();
} }
   
if (!this.guiRunning) if (!this.guiRunning)
{ {
this.StartGUI(); this.StartGUI();
} }
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.modules)
{ {
if ( if (
!module.guiRunning && !module.guiRunning &&
module.toggleActive && module.toggleActive &&
module.inValidScene && module.inValidScene &&
( (
!HighLogic.LoadedSceneIsEditor || !HighLogic.LoadedSceneIsEditor ||
(EditorLogic.RootPart != null && EditorLogic.SortedShipList.Count > 0) (EditorLogic.RootPart != null && EditorLogic.SortedShipList.Count > 0)
) )
) )
{ {
module.StartGUI(); module.StartGUI();
} }
if ( if (
module.guiRunning && module.guiRunning &&
( (
!module.toggleActive || !module.toggleActive ||
!this.togglePower || !this.togglePower ||
!module.inValidScene || !module.inValidScene ||
this.factoryReset || this.FactoryReset ||
( (
HighLogic.LoadedSceneIsEditor && HighLogic.LoadedSceneIsEditor &&
(EditorLogic.RootPart == null || EditorLogic.SortedShipList.Count == 0) (EditorLogic.RootPart == null || EditorLogic.SortedShipList.Count == 0)
) )
) )
) )
{ {
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_Module module in this.Modules) foreach (IVOID_Module module in this.modules)
{ {
if (module is IVOID_BehaviorModule) if (module is IVOID_BehaviorModule)
{ {
((IVOID_BehaviorModule)module).FixedUpdate(); ((IVOID_BehaviorModule)module).FixedUpdate();
} }
} }
} }
   
public void OnDestroy() public void OnDestroy()
{ {
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.modules)
{ {
if (module is IVOID_BehaviorModule) if (module is IVOID_BehaviorModule)
{ {
((IVOID_BehaviorModule)module).OnDestroy(); ((IVOID_BehaviorModule)module).OnDestroy();
} }
} }
   
this.Dispose(); this.Dispose();
} }
   
public virtual void OnApplicationQuit() public virtual void OnApplicationQuit()
{ {
if (this.onApplicationQuit != null) if (this.onApplicationQuit != null)
{ {
this.onApplicationQuit(this); this.onApplicationQuit(this);
} }
   
this.OnDestroy(); this.OnDestroy();
} }
   
  public override void StartGUI()
  {
  if (!this.guiRunning)
  {
  RenderingManager.AddToPostDrawQueue(3, this.DrawGUI);
  }
  }
   
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 override void ModuleWindow(int id)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
if (this.powerAvailable || !HighLogic.LoadedSceneIsFlight) if (this.powerAvailable || !HighLogic.LoadedSceneIsFlight)
{ {
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.LoadedSceneIsFlight) if (togglePower || !HighLogic.LoadedSceneIsFlight)
{ {
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.modules)
{ {
  if (module is VOID_ConfigWindow)
  {
  continue;
  }
   
module.toggleActive = GUITools.Toggle(module.toggleActive, module.Name); module.toggleActive = GUITools.Toggle(module.toggleActive, module.Name);
} }
} }
} }
else else
{ {
GUILayout.Label("-- POWER LOST --", VOID_Styles.labelRed); GUILayout.Label("-- POWER LOST --", VOID_Styles.labelRed);
} }
   
this.configWindowMinimized.value = !GUITools.Toggle(!this.configWindowMinimized, "Configuration"); VOID_ConfigWindow.Instance.toggleActive = GUITools.Toggle(
  VOID_ConfigWindow.Instance.toggleActive,
  "Configuration"
  );
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow();  
} base.ModuleWindow(id);
   
public void VOIDConfigWindow(int _)  
{  
GUILayout.BeginVertical();  
   
this.DrawConfigurables();  
   
GUILayout.EndVertical();  
GUI.DragWindow();  
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
GUIContent _content; GUIContent _content;
   
this.UseToolbarManager = GUITools.Toggle(this.UseToolbarManager, "Use Blizzy's Toolbar If Available"); this.useToolbarManager = GUITools.Toggle(this.useToolbarManager, "Use Blizzy's Toolbar If Available");
   
this.vesselSimActive.value = GUITools.Toggle(this.vesselSimActive.value, this.vesselSimActive.value = GUITools.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._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, VOID_Styles.labelCenter, GUILayout.ExpandWidth(true)); GUILayout.Label(_content, VOID_Styles.labelCenter, 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._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];
this.GUIStylesLoaded = false; this.GUIStylesLoaded = false;
} }
   
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.value = 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 = GUITools.Toggle(this.factoryReset, "Factory Reset"); this.FactoryReset = GUITools.Toggle(this.FactoryReset, "Factory Reset");
} }
   
protected void UpdateSimManager() protected void UpdateSimManager()
{ {
if (SimManager.ResultsReady()) if (SimManager.ResultsReady())
{ {
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 = new TimeSpan(0, 0, 0, 0, (int)(this.updatePeriod * 1000d)); SimManager.minSimTime = new TimeSpan(0, 0, 0, 0, (int)(this.UpdatePeriod * 1000d));
   
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 GetSimManagerResults() protected void GetSimManagerResults()
{ {
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();
} }
} }
   
protected void LoadModulesOfType<U>() protected void LoadModulesOfType<U>()
{ {
Tools.DebugLogger sb = Tools.DebugLogger.New(this); Tools.DebugLogger sb = Tools.DebugLogger.New(this);
sb.AppendLine("Loading modules..."); sb.AppendLine("Loading modules...");
   
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(U).IsAssignableFrom(loadedType) || !typeof(U).IsAssignableFrom(loadedType) ||
typeof(VOIDCore).IsAssignableFrom(loadedType) typeof(VOIDCore).IsAssignableFrom(loadedType)
) )
{ {
continue; continue;
} }
   
sb.AppendFormat("Checking IVOID_Module type {0}...", loadedType.Name); sb.AppendFormat("Checking IVOID_Module type {0}...", loadedType.Name);
   
GameScenes[] validScenes = null;  
   
foreach (var attr in loadedType.GetCustomAttributes(true))  
{  
if (attr is VOID_ScenesAttribute)  
{  
validScenes = ((VOID_ScenesAttribute)attr).ValidScenes;  
   
sb.Append("VOID_ScenesAttribute found;");  
   
break;  
}  
}  
   
if (validScenes == null)  
{  
validScenes = new GameScenes[] { GameScenes.FLIGHT };  
   
   
sb.Append("VOID_ScenesAttribute not found;");  
   
}  
   
sb.AppendFormat(  
" validScenes set to {0}.",  
string.Join(  
", ",  
validScenes.Select(s => Enum.GetName(typeof(GameScenes), s)).ToArray()  
)  
);  
   
if (!validScenes.Contains(HighLogic.LoadedScene))  
{  
sb.AppendFormat(" {0} not found in validScenes, skipping.",  
Enum.GetName(typeof(GameScenes), HighLogic.LoadedScene));  
continue;  
}  
   
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}\n", ex.GetType().Name); sb.AppendFormat("Failed, caught {0}\n", ex.GetType().Name);
   
#if DEBUG #if DEBUG
Debug.LogException(ex); Debug.LogException(ex);
#endif #endif
} }
} }
} }
   
this._modulesLoaded = true; this.modulesLoaded = true;
   
sb.AppendFormat("Loaded {0} modules.\n", this.Modules.Count); sb.AppendFormat("Loaded {0} modules.\n", this.Modules.Count);
   
sb.Print(); sb.Print();
} }
   
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;
} }
   
var InstanceProperty = T.GetProperty( var InstanceProperty = T.GetProperty(
"Instance", "Instance",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public
); );
   
object modInstance = null; object modInstance = null;
IVOID_Module module; IVOID_Module module;
   
if (InstanceProperty != null) if (InstanceProperty != null)
{ {
modInstance = InstanceProperty.GetValue(null, null); modInstance = InstanceProperty.GetValue(null, null);
} }
   
if (modInstance != null) if (modInstance != null)
{ {
module = modInstance as IVOID_Module; module = modInstance as IVOID_Module;
} }
else else
{ {
module = Activator.CreateInstance(T) as IVOID_Module; module = Activator.CreateInstance(T) as IVOID_Module;
} }
   
module.LoadConfig(); if (module.inValidGame && module.inValidScene)
this._modules.Add(module); {
  module.LoadConfig();
Tools.PostDebugMessage(string.Format( this.modules.Add(module);
"{0}: loaded module {1}.",  
this.GetType().Name, Tools.PostDebugMessage(string.Format(
T.Name "{0}: loaded module {1}.",
)); this.GetType().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()
{ {
VOID_Styles.OnSkinChanged(); VOID_Styles.OnSkinChanged();
   
if (this.onSkinChanged != null) if (this.onSkinChanged != null)
{ {
this.onSkinChanged(this); this.onSkinChanged(this);
} }
   
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>().ToArray();
this.vesselTypesLoaded = true; this.vesselTypesLoaded = true;
} }
   
protected void LoadBeforeUpdate() protected void LoadBeforeUpdate()
{ {
if (!this.vesselTypesLoaded) if (!this.vesselTypesLoaded)
{ {
this.LoadVesselTypes(); this.LoadVesselTypes();
} }
   
if (this.sortedBodyList == null && FlightGlobals.Bodies != null && FlightGlobals.Bodies.Count > 0) if (this.SortedBodyList == null && FlightGlobals.Bodies != null && FlightGlobals.Bodies.Count > 0)
{ {
this.sortedBodyList = new List<CelestialBody>(FlightGlobals.Bodies); this.SortedBodyList = new List<CelestialBody>(FlightGlobals.Bodies);
this.sortedBodyList.Sort(new CBListComparer()); this.SortedBodyList.Sort(new CBListComparer());
this.sortedBodyList.Reverse(); this.SortedBodyList.Reverse();
   
Debug.Log(string.Format("sortedBodyList: {0}", string.Join("\n\t", this.sortedBodyList.Select(b => b.bodyName).ToArray()))); Debug.Log(string.Format("sortedBodyList: {0}", string.Join("\n\t", this.SortedBodyList.Select(b => b.bodyName).ToArray())));
} }
   
} }
   
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"); 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.Visible = true; this.ToolbarButton.Visible = true;
   
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.toggleActive = !this.toggleActive;
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 virtual void CheckAndSave() protected virtual 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 override void SaveConfig() public override void SaveConfig()
{ {
if (this.configNeedsUpdate && this is VOIDCore_Flight) if (this.configNeedsUpdate && this is VOIDCore_Flight)
{ {
KSP.IO.File.Delete<T>("config.xml"); KSP.IO.File.Delete<T>("config.xml");
} }
   
var config = KSP.IO.PluginConfiguration.CreateForType<T>(); var config = KSP.IO.PluginConfiguration.CreateForType<T>();
   
config.load(); config.load();
   
this._SaveToConfig(config); this.Save(config);
   
foreach (IVOID_Module module in this.Modules) foreach (IVOID_Module module in this.modules)
{ {
module._SaveToConfig(config); module.Save(config);
} }
   
config.save(); config.save();
   
this.configDirty = false; this.configDirty = false;
} }
   
public VOIDCore_Generic() public VOIDCore_Generic()
{ {
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.Name = string.Format("VOID {0}", this.VoidVersion.ToString());
   
this.powerAvailable = true; this.powerAvailable = true;
   
this.toggleActive = true; this.toggleActive = true;
   
this._skinName = this.defaultSkin; this.skinName = (VOID_SaveValue<string>)this.defaultSkin;
this._skinIdx = int.MinValue; this.skinIdx = int.MinValue;
   
this.VOIDIconOnActivePath = "VOID/Textures/void_icon_light_glow"; this.VOIDIconOnActivePath = "VOID/Textures/void_icon_light_glow";
this.VOIDIconOnInactivePath = "VOID/Textures/void_icon_dark_glow"; this.VOIDIconOnInactivePath = "VOID/Textures/void_icon_dark_glow";
this.VOIDIconOffActivePath = "VOID/Textures/void_icon_light"; this.VOIDIconOffActivePath = "VOID/Textures/void_icon_light";
this.VOIDIconOffInactivePath = "VOID/Textures/void_icon_dark"; this.VOIDIconOffInactivePath = "VOID/Textures/void_icon_dark";
   
this.saveTimer = 0f; this.saveTimer = 0f;
this.updateTimer = 0f; this.UpdateTimer = 0f;
   
this.vesselSimActive = true; this.vesselSimActive = (VOID_SaveValue<bool>)true;
SimManager.Atmosphere = 0d; SimManager.Atmosphere = 0d;
SimManager.OnReady += this.GetSimManagerResults; SimManager.OnReady += this.GetSimManagerResults;
   
this.UseToolbarManager = ToolbarManager.ToolbarAvailable; this.useToolbarManager = ToolbarManager.ToolbarAvailable;
   
this.LoadConfig(); this.LoadConfig();
   
this._configVersion = VOIDCore.CONFIG_VERSION; this.configVersion = (VOID_SaveValue<int>)VOIDCore.CONFIG_VERSION;
this.SetIconTexture(this.powerState | this.activeState); this.SetIconTexture(this.powerState | this.activeState);
   
this.factoryReset = false; this.FactoryReset = false;
} }
   
public virtual void Dispose() public virtual void Dispose()
{ {
this.StopGUI(); this.StopGUI();
   
  this.onSkinChanged(this);
   
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;
} }
   
_instance = null; _instance = null;
_initialized = false; _initialized = false;
} }
   
protected enum IconState protected enum IconState
{ {
PowerOff = 1, PowerOff = 1,
PowerOn = 2, PowerOn = 2,
Inactive = 4, Inactive = 4,
Active = 8 Active = 8
} }
} }
} }
   
   
// VOID // VOID
// //
// VOIDCore_SpaceCentre.cs // VOIDCore_SpaceCentre.cs
// //
// Copyright © 2015, toadicus // Copyright © 2015, 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; using System;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.SPACECENTER)] [VOID_Scenes(GameScenes.SPACECENTER)]
public class VOIDCore_SpaceCentre : VOIDCore_Generic<VOIDCore_SpaceCentre> public class VOIDCore_SpaceCentre : VOIDCore_Generic<VOIDCore_SpaceCentre>
{ {
public VOIDCore_SpaceCentre() : base()  
{  
base.Name = "VOID Core: SpaceCentre";  
}  
   
public override void FixedUpdate() {} public override void FixedUpdate() {}
} }
} }
   
   
// VOID // VOID
// //
// VOID_CBInfoBrowser.cs // VOID_CBInfoBrowser.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 class VOID_CBInfoBrowser : VOID_WindowModule public class VOID_CBInfoBrowser : VOID_WindowModule
{ {
[AVOID_SaveValue("selectedBodyIdx1")] [AVOID_SaveValue("selectedBodyIdx1")]
protected VOID_SaveValue<int> selectedBodyIdx1 = 1; protected VOID_SaveValue<int> selectedBodyIdx1;
   
[AVOID_SaveValue("selectedBodyIdx2")] [AVOID_SaveValue("selectedBodyIdx2")]
protected VOID_SaveValue<int> selectedBodyIdx2 = 2; protected VOID_SaveValue<int> selectedBodyIdx2;
   
protected CelestialBody selectedBody1; protected CelestialBody selectedBody1;
protected CelestialBody selectedBody2; protected CelestialBody selectedBody2;
   
[AVOID_SaveValue("toggleOrbital")] [AVOID_SaveValue("toggleOrbital")]
protected VOID_SaveValue<bool> toggleOrbital = false; protected VOID_SaveValue<bool> toggleOrbital;
   
[AVOID_SaveValue("togglePhysical")] [AVOID_SaveValue("togglePhysical")]
protected VOID_SaveValue<bool> togglePhysical = false; protected VOID_SaveValue<bool> togglePhysical;
   
[AVOID_SaveValue("toggleScience")] [AVOID_SaveValue("toggleScience")]
protected VOID_SaveValue<bool> toggleScience = false; protected VOID_SaveValue<bool> toggleScience;
   
public VOID_CBInfoBrowser() public VOID_CBInfoBrowser()
{ {
this.Name = "Celestial Body Information Browser"; this.Name = "Celestial Body Information Browser";
   
this.WindowPos.x = 10; this.WindowPos.x = 10;
this.WindowPos.y = 85; this.WindowPos.y = 85;
   
  this.selectedBodyIdx1 = (VOID_SaveValue<int>)1;
  this.selectedBodyIdx2 = (VOID_SaveValue<int>)2;
   
  this.toggleOrbital = (VOID_SaveValue<bool>)false;
  this.togglePhysical = (VOID_SaveValue<bool>)false;
  this.toggleScience = (VOID_SaveValue<bool>)false;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("", GUILayout.ExpandWidth(true)); GUILayout.Label("", GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
selectedBody1 = this.core.allBodies[selectedBodyIdx1]; selectedBody1 = this.core.AllBodies[selectedBodyIdx1];
selectedBody2 = this.core.allBodies[selectedBodyIdx2]; selectedBody2 = this.core.AllBodies[selectedBodyIdx2];
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("<", GUILayout.ExpandWidth(false))) if (GUILayout.Button("<", GUILayout.ExpandWidth(false)))
{ {
selectedBodyIdx1--; selectedBodyIdx1.value--;
if (selectedBodyIdx1 < 0) selectedBodyIdx1 = this.core.allBodies.Count - 1; if (selectedBodyIdx1 < 0)
} {
GUILayout.Label(this.core.allBodies[selectedBodyIdx1].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true)); selectedBodyIdx1.value = this.core.AllBodies.Count - 1;
  }
  }
  GUILayout.Label(this.core.AllBodies[selectedBodyIdx1].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true));
if (GUILayout.Button(">", GUILayout.ExpandWidth(false))) if (GUILayout.Button(">", GUILayout.ExpandWidth(false)))
{ {
selectedBodyIdx1++; selectedBodyIdx1.value++;
if (selectedBodyIdx1 > this.core.allBodies.Count - 1) selectedBodyIdx1 = 0; if (selectedBodyIdx1 > this.core.AllBodies.Count - 1)
  {
  selectedBodyIdx1.value = 0;
  }
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("<", GUILayout.ExpandWidth(false))) if (GUILayout.Button("<", GUILayout.ExpandWidth(false)))
{ {
selectedBodyIdx2--; selectedBodyIdx2.value--;
if (selectedBodyIdx2 < 0) selectedBodyIdx2 = this.core.allBodies.Count - 1; if (selectedBodyIdx2 < 0)
} {
GUILayout.Label(this.core.allBodies[selectedBodyIdx2].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true)); selectedBodyIdx2.value = this.core.AllBodies.Count - 1;
  }
  }
  GUILayout.Label(this.core.AllBodies[selectedBodyIdx2].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true));
if (GUILayout.Button(">", GUILayout.ExpandWidth(false))) if (GUILayout.Button(">", GUILayout.ExpandWidth(false)))
{ {
selectedBodyIdx2++; selectedBodyIdx2.value++;
if (selectedBodyIdx2 > this.core.allBodies.Count - 1) selectedBodyIdx2 = 0; if (selectedBodyIdx2 > this.core.AllBodies.Count - 1)
  {
  selectedBodyIdx2.value = 0;
  }
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
//toggle for orbital info chunk //toggle for orbital info chunk
if (GUILayout.Button("Orbital Characteristics", GUILayout.ExpandWidth(true))) toggleOrbital.value = !toggleOrbital; if (GUILayout.Button("Orbital Characteristics", GUILayout.ExpandWidth(true))) toggleOrbital.value = !toggleOrbital;
   
if (toggleOrbital) if (toggleOrbital)
{ {
//begin orbital into horizontal chunk //begin orbital into horizontal chunk
//print("begin orbital info section..."); //print("begin orbital info section...");
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
//begin orbital value labels column //begin orbital value labels column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
//print("printing row labels..."); //print("printing row labels...");
   
GUILayout.Label("Apoapsis:"); GUILayout.Label("Apoapsis:");
GUILayout.Label("Time to Ap:"); GUILayout.Label("Time to Ap:");
GUILayout.Label("Periapsis:"); GUILayout.Label("Periapsis:");
GUILayout.Label("Time to Pe:"); GUILayout.Label("Time to Pe:");
GUILayout.Label("Semi-major axis:"); GUILayout.Label("Semi-major axis:");
GUILayout.Label("Eccentricity:"); GUILayout.Label("Eccentricity:");
GUILayout.Label("Orbital period:"); GUILayout.Label("Orbital period:");
GUILayout.Label("Rotational period:"); GUILayout.Label("Rotational period:");
GUILayout.Label("Velocity:"); GUILayout.Label("Velocity:");
GUILayout.Label("Mean anomaly:"); GUILayout.Label("Mean anomaly:");
GUILayout.Label("True anomaly:"); GUILayout.Label("True anomaly:");
GUILayout.Label("Eccentric anomaly:"); GUILayout.Label("Eccentric anomaly:");
GUILayout.Label("Inclination:"); GUILayout.Label("Inclination:");
GUILayout.Label("Long. ascending node:"); GUILayout.Label("Long. ascending node:");
GUILayout.Label("Arg. of periapsis:"); GUILayout.Label("Arg. of periapsis:");
GUILayout.Label("Tidally locked:"); GUILayout.Label("Tidally locked:");
   
//end orbital value labels column //end orbital value labels column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin primary orbital values column //begin primary orbital values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
body_OP_show_orbital_info(selectedBody1); body_OP_show_orbital_info(selectedBody1);
   
//end primary orbital values column //end primary orbital values column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin secondary orbital values column //begin secondary orbital values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
body_OP_show_orbital_info(selectedBody2); body_OP_show_orbital_info(selectedBody2);
   
//end secondary orbital values column //end secondary orbital values column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//end orbital info horizontal chunk //end orbital info horizontal chunk
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
//toggle for physical info chunk //toggle for physical info chunk
if (GUILayout.Button("Physical Characteristics", GUILayout.ExpandWidth(true))) togglePhysical.value = !togglePhysical; if (GUILayout.Button("Physical Characteristics", GUILayout.ExpandWidth(true))) togglePhysical.value = !togglePhysical;
   
if (togglePhysical) if (togglePhysical)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
//begin physical info value label column //begin physical info value label column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
GUILayout.Label("Radius:"); GUILayout.Label("Radius:");
GUILayout.Label("Surface area:"); GUILayout.Label("Surface area:");
GUILayout.Label("Volume:"); GUILayout.Label("Volume:");
GUILayout.Label("Mass:"); GUILayout.Label("Mass:");
GUILayout.Label("Density:"); GUILayout.Label("Density:");
GUILayout.Label("Sphere of influence:"); GUILayout.Label("Sphere of influence:");
GUILayout.Label("Natural satellites:"); GUILayout.Label("Natural satellites:");
GUILayout.Label("Artificial satellites:"); GUILayout.Label("Artificial satellites:");
GUILayout.Label("Surface gravity:"); GUILayout.Label("Surface gravity:");
GUILayout.Label("Atmosphere altitude:"); GUILayout.Label("Atmosphere altitude:");
GUILayout.Label("Atmospheric O\u2082:"); GUILayout.Label("Atmospheric O\u2082:");
GUILayout.Label("Has ocean:"); GUILayout.Label("Has ocean:");
   
//end physical info value label column //end physical info value label column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin primary physical values column //begin primary physical values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
body_OP_show_physical_info(selectedBody1); body_OP_show_physical_info(selectedBody1);
   
//end primary physical column //end primary physical column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin secondary physical values column //begin secondary physical values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
body_OP_show_physical_info(selectedBody2); body_OP_show_physical_info(selectedBody2);
   
//end target physical values column //end target physical values column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//end physical value horizontal chunk //end physical value horizontal chunk
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
if (GUILayout.Button("Scientific Parameters", GUILayout.ExpandWidth(true))) if (GUILayout.Button("Scientific Parameters", GUILayout.ExpandWidth(true)))
{ {
toggleScience.value = !toggleScience; toggleScience.value = !toggleScience;
} }
   
if (toggleScience) if (toggleScience)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
//begin physical info value label column //begin physical info value label column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
   
/* /*
* public float RecoveryValue = 1f; * public float RecoveryValue = 1f;
   
public float InSpaceHighDataValue = 1f; public float InSpaceHighDataValue = 1f;
   
public float spaceAltitudeThreshold = 250000f; public float spaceAltitudeThreshold = 250000f;
   
public float flyingAltitudeThreshold = 18000f; public float flyingAltitudeThreshold = 18000f;
   
public float InSpaceLowDataValue = 1f; public float InSpaceLowDataValue = 1f;
   
public float SplashedDataValue = 1f; public float SplashedDataValue = 1f;
   
public float LandedDataValue = 1f; public float LandedDataValue = 1f;
   
public float FlyingHighDataValue = 1f; public float FlyingHighDataValue = 1f;
   
public float FlyingLowDataValue = 1f; public float FlyingLowDataValue = 1f;
*/ */
   
GUILayout.Label("Surface Multiplier:"); GUILayout.Label("Surface Multiplier:");
GUILayout.Label("Ocean Multiplier:"); GUILayout.Label("Ocean Multiplier:");
GUILayout.Label("Flying-Low Multiplier:"); GUILayout.Label("Flying-Low Multiplier:");
GUILayout.Label("Flying-High Multiplier:"); GUILayout.Label("Flying-High Multiplier:");
GUILayout.Label("Low Orbit Multiplier:"); GUILayout.Label("Low Orbit Multiplier:");
GUILayout.Label("High Orbit Multiplier:"); GUILayout.Label("High Orbit Multiplier:");
GUILayout.Label("'Flying-High' Altitude:"); GUILayout.Label("'Flying-High' Altitude:");
GUILayout.Label("'High Orbit' Altitude:"); GUILayout.Label("'High Orbit' Altitude:");
GUILayout.Label("Recovery Multiplier:"); GUILayout.Label("Recovery Multiplier:");
   
//end physical info value label column //end physical info value label column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin primary physical values column //begin primary physical values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
this.cbColumnScience(selectedBody1); this.cbColumnScience(selectedBody1);
   
//end primary physical column //end primary physical column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//begin secondary physical values column //begin secondary physical values column
GUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.BeginVertical(GUILayout.Width(150));
   
this.cbColumnScience(selectedBody2); this.cbColumnScience(selectedBody2);
   
//end target physical values column //end target physical values column
GUILayout.EndVertical(); GUILayout.EndVertical();
   
//end physical value horizontal chunk //end physical value horizontal chunk
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
   
private void body_OP_show_orbital_info(CelestialBody body) private void body_OP_show_orbital_info(CelestialBody body)
{ {
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.ApA / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.ApA / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.timeToAp), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.timeToAp), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.PeA / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.PeA / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.timeToPe), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.timeToPe), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.semiMajorAxis / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.semiMajorAxis / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(body.orbit.eccentricity.ToString("F4") + "", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(body.orbit.eccentricity.ToString("F4") + "", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.period), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(VOID_Tools.FormatInterval(body.orbit.period), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(VOID_Tools.FormatInterval(body.rotationPeriod), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(VOID_Tools.FormatInterval(body.rotationPeriod), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.orbitalSpeed / 1000).ToString("F2") + "km/s", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.orbitalSpeed / 1000).ToString("F2") + "km/s", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
// Toadicus edit: convert mean anomaly into degrees. // Toadicus edit: convert mean anomaly into degrees.
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.meanAnomaly * 180d / Math.PI).ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.meanAnomaly * 180d / Math.PI).ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(body.orbit.trueAnomaly.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(body.orbit.trueAnomaly.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
// Toadicus edit: convert eccentric anomaly into degrees. // Toadicus edit: convert eccentric anomaly into degrees.
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label((body.orbit.eccentricAnomaly * 180d / Math.PI).ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label((body.orbit.eccentricAnomaly * 180d / Math.PI).ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(body.orbit.inclination.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(body.orbit.inclination.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(body.orbit.LAN.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(body.orbit.LAN.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(body.orbit.argumentOfPeriapsis.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(body.orbit.argumentOfPeriapsis.ToString("F3") + "°", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else else
{ {
string body_tidally_locked = "No"; string body_tidally_locked = "No";
if (body.tidallyLocked) body_tidally_locked = "Yes"; if (body.tidallyLocked) body_tidally_locked = "Yes";
GUILayout.Label(body_tidally_locked, VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(body_tidally_locked, VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
} }
} }
   
private void body_OP_show_physical_info(CelestialBody body) private void body_OP_show_physical_info(CelestialBody body)
{ {
   
GUILayout.Label((body.Radius / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label((body.Radius / 1000).ToString("##,#") + "km", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
GUILayout.Label((((body.Radius * body.Radius) * 4 * Math.PI) / 1000).ToString("0.00e+00") + "km²", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label((((body.Radius * body.Radius) * 4 * Math.PI) / 1000).ToString("0.00e+00") + "km²", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
// divide by 1000 to convert m to km // divide by 1000 to convert m to km
GUILayout.Label((((4d / 3) * Math.PI * (body.Radius * body.Radius * body.Radius)) / 1000).ToString("0.00e+00") + "km³", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label((((4d / 3) * Math.PI * (body.Radius * body.Radius * body.Radius)) / 1000).ToString("0.00e+00") + "km³", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
GUILayout.Label(body.Mass.ToString("0.00e+00") + "kg", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(body.Mass.ToString("0.00e+00") + "kg", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
double p = body.Mass / ((body.Radius * body.Radius * body.Radius) * (4d / 3) * Math.PI); double p = body.Mass / ((body.Radius * body.Radius * body.Radius) * (4d / 3) * Math.PI);
   
GUILayout.Label(p.ToString("##,#") + "kg/m³", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(p.ToString("##,#") + "kg/m³", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.bodyName == "Sun") GUILayout.Label(Tools.MuMech_ToSI(body.sphereOfInfluence), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); if (body.bodyName == "Sun") GUILayout.Label(Tools.MuMech_ToSI(body.sphereOfInfluence), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
else GUILayout.Label(Tools.MuMech_ToSI(body.sphereOfInfluence), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); else GUILayout.Label(Tools.MuMech_ToSI(body.sphereOfInfluence), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
GUILayout.Label(body.orbitingBodies.Count.ToString(), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(body.orbitingBodies.Count.ToString(), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
//show # artificial satellites //show # artificial satellites
int num_art_sats = 0; int num_art_sats = 0;
foreach (Vessel v in FlightGlobals.Vessels) foreach (Vessel v in FlightGlobals.Vessels)
{ {
if (v.mainBody == body && v.situation.ToString() == "ORBITING") num_art_sats++; if (v.mainBody == body && v.situation.ToString() == "ORBITING") num_art_sats++;
} }
   
GUILayout.Label(num_art_sats.ToString(), VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(num_art_sats.ToString(), VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
double g_ASL = (VOIDCore.Constant_G * body.Mass) / (body.Radius * body.Radius); double g_ASL = (VOIDCore.Constant_G * body.Mass) / (body.Radius * body.Radius);
   
GUILayout.Label(Tools.MuMech_ToSI(g_ASL) + "m/s²", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(Tools.MuMech_ToSI(g_ASL) + "m/s²", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
   
if (body.atmosphere) if (body.atmosphere)
{ {
GUILayout.Label("≈ " + Tools.MuMech_ToSI(body.maxAtmosphereAltitude) + "m", GUILayout.Label("≈ " + Tools.MuMech_ToSI(body.maxAtmosphereAltitude) + "m",
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
string O2 = "No"; string O2 = "No";
if (body.atmosphereContainsOxygen == true) O2 = "Yes"; if (body.atmosphereContainsOxygen == true) O2 = "Yes";
GUILayout.Label(O2, VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(O2, VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
} }
else else
{ {
GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label("N/A", VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
} }
   
string ocean = "No"; string ocean = "No";
if (body.ocean == true) ocean = "Yes"; if (body.ocean == true) ocean = "Yes";
GUILayout.Label(ocean, VOID_Styles.labelRight, GUILayout.ExpandWidth(true)); GUILayout.Label(ocean, VOID_Styles.labelRight, GUILayout.ExpandWidth(true));
} }
   
private void cbColumnScience(CelestialBody body) private void cbColumnScience(CelestialBody body)
{ {
/*GUILayout.Label("Surface Science Multiplier:"); /*GUILayout.Label("Surface Science Multiplier:");
GUILayout.Label("Ocean Science Multiplier:"); GUILayout.Label("Ocean Science Multiplier:");
GUILayout.Label("Low-Atmosphere Science Multiplier:"); GUILayout.Label("Low-Atmosphere Science Multiplier:");
GUILayout.Label("High-Atmosphere Science Multiplier:"); GUILayout.Label("High-Atmosphere Science Multiplier:");
GUILayout.Label("Low Orbit Science Multiplier:"); GUILayout.Label("Low Orbit Science Multiplier:");
GUILayout.Label("High Orbit Science Multiplier:"); GUILayout.Label("High Orbit Science Multiplier:");
GUILayout.Label("'In Space' Altitude:"); GUILayout.Label("'In Space' Altitude:");
GUILayout.Label("'Flying' Altitude:"); GUILayout.Label("'Flying' Altitude:");
GUILayout.Label("Recovery Multiplier:");*/ GUILayout.Label("Recovery Multiplier:");*/
   
var scienceValues = body.scienceValues; var scienceValues = body.scienceValues;
   
GUILayout.Label(scienceValues.LandedDataValue.ToString("0.0#"), GUILayout.Label(scienceValues.LandedDataValue.ToString("0.0#"),
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label( GUILayout.Label(
body.ocean ? scienceValues.SplashedDataValue.ToString("0.0#") : "N/A", body.ocean ? scienceValues.SplashedDataValue.ToString("0.0#") : "N/A",
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label( GUILayout.Label(
body.atmosphere ? scienceValues.FlyingLowDataValue.ToString("0.0#") : "N/A", body.atmosphere ? scienceValues.FlyingLowDataValue.ToString("0.0#") : "N/A",
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label( GUILayout.Label(
body.atmosphere ? scienceValues.FlyingHighDataValue.ToString("0.0#") : "N/A", body.atmosphere ? scienceValues.FlyingHighDataValue.ToString("0.0#") : "N/A",
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label(scienceValues.InSpaceLowDataValue.ToString("0.0#"), GUILayout.Label(scienceValues.InSpaceLowDataValue.ToString("0.0#"),
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label(scienceValues.InSpaceHighDataValue.ToString("0.0#"), GUILayout.Label(scienceValues.InSpaceHighDataValue.ToString("0.0#"),
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label( GUILayout.Label(
body.atmosphere ? scienceValues.flyingAltitudeThreshold.ToString("N0") : "N/A", body.atmosphere ? scienceValues.flyingAltitudeThreshold.ToString("N0") : "N/A",
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label( GUILayout.Label(
scienceValues.spaceAltitudeThreshold.ToString("N0"), scienceValues.spaceAltitudeThreshold.ToString("N0"),
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
GUILayout.Label(scienceValues.RecoveryValue.ToString("0.0#"), GUILayout.Label(scienceValues.RecoveryValue.ToString("0.0#"),
VOID_Styles.labelRight, VOID_Styles.labelRight,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
} }
} }
} }
// VOID // VOID
// //
// VOID_CareerStatus.cs // VOID_CareerStatus.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.Text; using System.Text;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.FLIGHT, GameScenes.EDITOR, GameScenes.SPACECENTER)] [VOID_Scenes(GameScenes.FLIGHT, GameScenes.EDITOR, GameScenes.SPACECENTER)]
[VOID_GameModes(Game.Modes.CAREER, Game.Modes.SCIENCE_SANDBOX)] [VOID_GameModes(Game.Modes.CAREER, Game.Modes.SCIENCE_SANDBOX)]
public class VOID_CareerStatus : VOID_WindowModule public class VOID_CareerStatus : VOID_WindowModule
{ {
public static VOID_CareerStatus Instance public static VOID_CareerStatus Instance
{ {
get; get;
private set; private set;
} }
   
public static string formatDelta(double delta, string numberFormat) public static string formatDelta(double delta, string numberFormat)
{ {
if (delta > 0) if (delta > 0)
{ {
return string.Format("<color='lime'>{0}↑</color>", delta.ToString(numberFormat, Tools.SIFormatter)); return string.Format("<color='lime'>{0}↑</color>", delta.ToString(numberFormat, Tools.SIFormatter));
} }
else if (delta < 0) else if (delta < 0)
{ {
return string.Format("<color='red'>{0}↓</color>", delta.ToString(numberFormat, Tools.SIFormatter)); return string.Format("<color='red'>{0}↓</color>", delta.ToString(numberFormat, Tools.SIFormatter));
} }
else else
{ {
return "0"; return "0";
} }
} }
   
public static string formatDelta(double delta) public static string formatDelta(double delta)
{ {
return formatDelta(delta, "#,##0.##"); return formatDelta(delta, "#,##0.##");
} }
   
public static string formatDelta(float delta) public static string formatDelta(float delta)
{ {
return formatDelta((double)delta); return formatDelta((double)delta);
} }
   
private GUIContent fundsContent; private GUIContent fundsContent;
private GUIContent repContent; private GUIContent repContent;
private GUIContent scienceContent; private GUIContent scienceContent;
   
#pragma warning disable 0414 #pragma warning disable 0414
private Texture2D fundsIconGreen; private Texture2D fundsIconGreen;
private Texture2D fundsIconRed; private Texture2D fundsIconRed;
private Texture2D reputationIconGreen; private Texture2D reputationIconGreen;
private Texture2D reputationIconRed; private Texture2D reputationIconRed;
private Texture2D scienceIcon; private Texture2D scienceIcon;
#pragma warning restore 0414 #pragma warning restore 0414
   
public double lastFundsChange public double lastFundsChange
{ {
get; get;
private set; private set;
} }
   
public float lastRepChange public float lastRepChange
{ {
get; get;
private set; private set;
} }
   
public float lastScienceChange public float lastScienceChange
{ {
get; get;
private set; private set;
} }
   
public double currentFunds public double currentFunds
{ {
get; get;
private set; private set;
} }
   
public float currentReputation public float currentReputation
{ {
get; get;
private set; private set;
} }
   
public float currentScience public float currentScience
{ {
get; get;
private set; private set;
} }
   
private bool currenciesInitialized private bool currenciesInitialized
{ {
get get
{ {
Tools.PostDebugMessage( Tools.PostDebugMessage(
this, this,
"Checking init state:" + "Checking init state:" +
"\n\tcurrentFunds={0}" + "\n\tcurrentFunds={0}" +
"\n\tcurrentScience={1}" + "\n\tcurrentScience={1}" +
"\n\tcurrentReputation={2}", "\n\tcurrentReputation={2}",
this.currentFunds, this.currentFunds,
this.currentScience, this.currentScience,
this.currentReputation this.currentReputation
); );
   
return !( return !(
double.IsNaN(this.currentFunds) || double.IsNaN(this.currentFunds) ||
float.IsNaN(this.currentScience) || float.IsNaN(this.currentScience) ||
float.IsNaN(this.currentReputation) float.IsNaN(this.currentReputation)
); );
} }
} }
   
public override void DrawGUI() public override void DrawGUI()
{ {
if (Event.current.type != EventType.Layout && !this.currenciesInitialized) if (Event.current.type != EventType.Layout && !this.currenciesInitialized)
{ {
this.initCurrencies(); this.initCurrencies();
} }
   
base.DrawGUI(); base.DrawGUI();
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(VOID_Data.fundingStatus.Label); GUILayout.Label(VOID_Data.fundingStatus.Label);
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
this.fundsContent.text = VOID_Data.fundingStatus.Value; this.fundsContent.text = VOID_Data.fundingStatus.Value;
GUILayout.Label(this.fundsContent, GUILayout.ExpandWidth(true)); GUILayout.Label(this.fundsContent, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(VOID_Data.reputationStatus.Label); GUILayout.Label(VOID_Data.reputationStatus.Label);
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
this.repContent.text = VOID_Data.reputationStatus.Value; this.repContent.text = VOID_Data.reputationStatus.Value;
GUILayout.Label(this.repContent, GUILayout.ExpandWidth(true)); GUILayout.Label(this.repContent, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(VOID_Data.scienceStatus.Label); GUILayout.Label(VOID_Data.scienceStatus.Label);
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
this.scienceContent.text = VOID_Data.scienceStatus.Value; this.scienceContent.text = VOID_Data.scienceStatus.Value;
GUILayout.Label(this.scienceContent, GUILayout.ExpandWidth(true)); GUILayout.Label(this.scienceContent, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
   
// TODO: Update event handlers to do something useful with the new "reasons" parameter. // TODO: Update event handlers to do something useful with the new "reasons" parameter.
private void onFundsChange(double newValue, TransactionReasons reasons) private void onFundsChange(double newValue, TransactionReasons reasons)
{ {
this.lastFundsChange = newValue - this.currentFunds; this.lastFundsChange = newValue - this.currentFunds;
this.currentFunds = newValue; this.currentFunds = newValue;
} }
   
private void onRepChange(float newValue, TransactionReasons reasons) private void onRepChange(float newValue, TransactionReasons reasons)
{ {
this.lastRepChange = newValue - this.currentReputation; this.lastRepChange = newValue - this.currentReputation;
this.currentReputation = newValue; this.currentReputation = newValue;
} }
   
private void onScienceChange(float newValue, TransactionReasons reasons) private void onScienceChange(float newValue, TransactionReasons reasons)
{ {
this.lastScienceChange = newValue - this.currentScience; this.lastScienceChange = newValue - this.currentScience;
this.currentScience = newValue; this.currentScience = newValue;
} }
   
private void onGameStateLoad(ConfigNode node) private void onGameStateLoad(ConfigNode node)
{ {
this.initCurrencies(); this.initCurrencies();
} }
   
private void initCurrencies() private void initCurrencies()
{ {
Tools.PostDebugMessage( Tools.PostDebugMessage(
this, this,
"Initializing currencies." + "Initializing currencies." +
"\n\tFunding.Instance={0}" + "\n\tFunding.Instance={0}" +
"ResearchAndDevelopment.Instance={1}" + "ResearchAndDevelopment.Instance={1}" +
"Reputation.Instance={2}", "Reputation.Instance={2}",
Funding.Instance == null ? "NULL" : Funding.Instance.ToString(), Funding.Instance == null ? "NULL" : Funding.Instance.ToString(),
ResearchAndDevelopment.Instance == null ? "NULL" : ResearchAndDevelopment.Instance.ToString(), ResearchAndDevelopment.Instance == null ? "NULL" : ResearchAndDevelopment.Instance.ToString(),
Reputation.Instance == null ? "NULL" : Reputation.Instance.ToString() Reputation.Instance == null ? "NULL" : Reputation.Instance.ToString()
); );
   
this.currentFunds = Funding.Instance != null ? Funding.Instance.Funds : double.NaN; this.currentFunds = Funding.Instance != null ? Funding.Instance.Funds : double.NaN;
this.currentReputation = Reputation.Instance != null ? Reputation.Instance.reputation : float.NaN; this.currentReputation = Reputation.Instance != null ? Reputation.Instance.reputation : float.NaN;
this.currentScience = ResearchAndDevelopment.Instance != null ? this.currentScience = ResearchAndDevelopment.Instance != null ?
ResearchAndDevelopment.Instance.Science : float.NaN; ResearchAndDevelopment.Instance.Science : float.NaN;
} }
   
/* /*
* MissionRecoveryDialog::fundsIconGreen.name: UiElements_05 * MissionRecoveryDialog::fundsIconGreen.name: UiElements_05
* MissionRecoveryDialog::fundsIconRed.name: UiElements_06 * MissionRecoveryDialog::fundsIconRed.name: UiElements_06
* MissionRecoveryDialog::reputationIconGreen.name: UiElements_07 * MissionRecoveryDialog::reputationIconGreen.name: UiElements_07
* MissionRecoveryDialog::reputationIconRed.name: UiElements_08 * MissionRecoveryDialog::reputationIconRed.name: UiElements_08
* MissionRecoveryDialog::scienceIcon.name: UiElements_12 * MissionRecoveryDialog::scienceIcon.name: UiElements_12
* */ * */
public VOID_CareerStatus() : base() public VOID_CareerStatus() : base()
{ {
VOID_CareerStatus.Instance = this; if (this.inValidGame && this.inValidScene)
  {
  VOID_CareerStatus.Instance = this;
  }
   
this.Name = "Career Status"; this.Name = "Career Status";
   
GameEvents.OnFundsChanged.Add(this.onFundsChange); GameEvents.OnFundsChanged.Add(this.onFundsChange);
GameEvents.OnReputationChanged.Add(this.onRepChange); GameEvents.OnReputationChanged.Add(this.onRepChange);
GameEvents.OnScienceChanged.Add(this.onScienceChange); GameEvents.OnScienceChanged.Add(this.onScienceChange);
GameEvents.onGameStateLoad.Add(this.onGameStateLoad); GameEvents.onGameStateLoad.Add(this.onGameStateLoad);
   
bool texturesLoaded; bool texturesLoaded;
   
texturesLoaded = IOTools.LoadTexture(out this.fundsIconGreen, "VOID/Textures/fundsgreen.png", 10, 18); texturesLoaded = IOTools.LoadTexture(out this.fundsIconGreen, "VOID/Textures/fundsgreen.png", 10, 18);
texturesLoaded &= IOTools.LoadTexture(out this.fundsIconRed, "VOID/Textures/fundsred.png", 10, 18); texturesLoaded &= IOTools.LoadTexture(out this.fundsIconRed, "VOID/Textures/fundsred.png", 10, 18);
texturesLoaded &= IOTools.LoadTexture(out this.reputationIconGreen, "VOID/Textures/repgreen.png", 16, 18); texturesLoaded &= IOTools.LoadTexture(out this.reputationIconGreen, "VOID/Textures/repgreen.png", 16, 18);
texturesLoaded &= IOTools.LoadTexture(out this.reputationIconRed, "VOID/Textures/repred.png", 16, 18); texturesLoaded &= IOTools.LoadTexture(out this.reputationIconRed, "VOID/Textures/repred.png", 16, 18);
texturesLoaded &= IOTools.LoadTexture(out this.scienceIcon, "VOID/Textures/science.png", 16, 18); texturesLoaded &= IOTools.LoadTexture(out this.scienceIcon, "VOID/Textures/science.png", 16, 18);
   
this.fundsContent = new GUIContent(); this.fundsContent = new GUIContent();
this.repContent = new GUIContent(); this.repContent = new GUIContent();
this.scienceContent = new GUIContent(); this.scienceContent = new GUIContent();
   
if (texturesLoaded) if (texturesLoaded)
{ {
this.fundsContent.image = this.fundsIconGreen; this.fundsContent.image = this.fundsIconGreen;
this.repContent.image = this.reputationIconGreen; this.repContent.image = this.reputationIconGreen;
this.scienceContent.image = this.scienceIcon; this.scienceContent.image = this.scienceIcon;
} }
   
this.currentFunds = double.NaN; this.currentFunds = double.NaN;
this.currentScience = float.NaN; this.currentScience = float.NaN;
this.currentReputation = float.NaN; this.currentReputation = float.NaN;
} }
   
~VOID_CareerStatus() ~VOID_CareerStatus()
{ {
GameEvents.OnFundsChanged.Remove(this.onFundsChange); GameEvents.OnFundsChanged.Remove(this.onFundsChange);
GameEvents.OnReputationChanged.Remove(this.onRepChange); GameEvents.OnReputationChanged.Remove(this.onRepChange);
GameEvents.OnScienceChanged.Remove(this.onScienceChange); GameEvents.OnScienceChanged.Remove(this.onScienceChange);
GameEvents.onGameStateLoad.Remove(this.onGameStateLoad); GameEvents.onGameStateLoad.Remove(this.onGameStateLoad);
   
VOID_CareerStatus.Instance = null; VOID_CareerStatus.Instance = null;
} }
} }
} }
   
   
  // VOID
  //
  // VOID_ConfigModule.cs
  //
  // Copyright © 2015, toadicus
  // All rights reserved.
  //
  // Redistribution and use in source and binary forms, with or without modification,
  // are permitted provided that the following conditions are met:
  //
  // 1. Redistributions of source code must retain the above copyright notice,
  // this list of conditions and the following disclaimer.
  //
  // 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
  // materials provided with the distribution.
  //
  // 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.
  //
  // 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
  // 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
  // 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
  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  using KSP;
  using System;
  using ToadicusTools;
  using UnityEngine;
 
  namespace VOID
  {
  public class VOID_ConfigWindow : VOID_WindowModule
  {
  public static VOID_ConfigWindow Instance
  {
  get;
  private set;
  }
 
  public override bool inValidScene
  {
  get
  {
  return true;
  }
  }
 
  public override bool inValidGame
  {
  get
  {
  return true;
  }
  }
 
  public VOID_ConfigWindow() : base()
  {
  VOID_ConfigWindow.Instance = this;
 
  this.Name = "VOID Configuration";
  }
 
  public override void ModuleWindow(int id)
  {
  GUILayout.BeginVertical();
 
  this.core.DrawConfigurables();
 
  GUILayout.EndVertical();
  GUI.DragWindow();
  }
 
  ~VOID_ConfigWindow()
  {
  VOID_ConfigWindow.Instance = null;
  }
  }
  }
 
// 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.IO; using System.IO;
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
* */ * */
#region Fields #region Fields
   
protected bool _loggingActive; protected bool _loggingActive;
protected bool firstWrite; protected bool firstWrite;
   
[AVOID_SaveValue("waitForLaunch")] [AVOID_SaveValue("waitForLaunch")]
protected VOID_SaveValue<bool> waitForLaunch; protected VOID_SaveValue<bool> waitForLaunch;
   
[AVOID_SaveValue("logInterval")] [AVOID_SaveValue("logInterval")]
protected VOID_SaveValue<float> logInterval; protected VOID_SaveValue<float> logInterval;
protected string logIntervalStr; protected string logIntervalStr;
   
protected float csvCollectTimer; protected float csvCollectTimer;
   
protected List<byte> csvBytes; protected List<byte> csvBytes;
   
protected string _fileName; protected string _fileName;
protected FileStream _outputFile; protected FileStream _outputFile;
   
protected uint outstandingWrites; protected uint outstandingWrites;
   
protected System.Text.UTF8Encoding _utf8Encoding; protected System.Text.UTF8Encoding _utf8Encoding;
   
#endregion #endregion
   
/* /*
* Properties * Properties
* */ * */
   
#region Properties #region Properties
   
// TODO: Add configurable or incremental file names. // TODO: Add configurable or incremental file names.
protected bool loggingActive protected bool loggingActive
{ {
get get
{ {
return this._loggingActive; return this._loggingActive;
} }
set set
{ {
if (value != this._loggingActive) if (value != this._loggingActive)
{ {
if (value) if (value)
{ {
this.csvCollectTimer = 0f; this.csvCollectTimer = 0f;
} }
else else
{ {
this.CloseFileIfOpen(); this.CloseFileIfOpen();
} }
   
this._loggingActive = value; this._loggingActive = value;
} }
} }
} }
   
protected string fileName protected string fileName
{ {
get get
{ {
if (this._fileName == null || this._fileName == string.Empty) if (this._fileName == null || this._fileName == string.Empty)
{ {
this._fileName = KSP.IO.IOUtils.GetFilePathFor( this._fileName = KSP.IO.IOUtils.GetFilePathFor(
typeof(VOIDCore), typeof(VOIDCore),
string.Format( string.Format(
"{0}_{1}", "{0}_{1}",
this.vessel.vesselName, this.vessel.vesselName,
"data.csv" "data.csv"
), ),
null null
); );
} }
   
return this._fileName; return this._fileName;
} }
} }
   
protected FileStream outputFile protected FileStream outputFile
{ {
get get
{ {
if (this._outputFile == null) if (this._outputFile == null)
{ {
Tools.DebugLogger logger = Tools.DebugLogger.New(this); Tools.DebugLogger logger = Tools.DebugLogger.New(this);
logger.AppendFormat("Initializing output file '{0}' with mode ", this.fileName); logger.AppendFormat("Initializing output file '{0}' with mode ", this.fileName);
   
if (File.Exists(this.fileName)) if (File.Exists(this.fileName))
{ {
logger.Append("append"); logger.Append("append");
this._outputFile = new FileStream( this._outputFile = new FileStream(
this.fileName, this.fileName,
FileMode.Append, FileMode.Append,
FileAccess.Write, FileAccess.Write,
FileShare.Read, FileShare.Read,
512, 512,
true true
); );
} }
else else
{ {
logger.Append("create"); logger.Append("create");
this._outputFile = new FileStream( this._outputFile = new FileStream(
this.fileName, this.fileName,
FileMode.Create, FileMode.Create,
FileAccess.Write, FileAccess.Write,
FileShare.Read, FileShare.Read,
512, 512,
true true
); );
   
byte[] byteOrderMark = utf8Encoding.GetPreamble(); byte[] byteOrderMark = utf8Encoding.GetPreamble();
   
logger.Append(" and writing preamble"); logger.Append(" and writing preamble");
this._outputFile.Write(byteOrderMark, 0, byteOrderMark.Length); this._outputFile.Write(byteOrderMark, 0, byteOrderMark.Length);
} }
   
logger.Append('.'); logger.Append('.');
   
logger.AppendFormat(" File is {0}opened asynchronously.", this._outputFile.IsAsync ? "" : "not "); logger.AppendFormat(" File is {0}opened asynchronously.", this._outputFile.IsAsync ? "" : "not ");
   
logger.Print(); logger.Print();
} }
   
return this._outputFile; return this._outputFile;
} }
} }
   
public UTF8Encoding utf8Encoding public UTF8Encoding utf8Encoding
{ {
get get
{ {
if (this._utf8Encoding == null) if (this._utf8Encoding == null)
{ {
this._utf8Encoding = new UTF8Encoding(true); this._utf8Encoding = new UTF8Encoding(true);
} }
   
return this._utf8Encoding; return this._utf8Encoding;
} }
} }
   
#endregion #endregion
   
/* /*
* Methods * Methods
* */ * */
#region Monobehaviour Lifecycle #region Monobehaviour Lifecycle
public void Update() public void Update()
{ {
if (this.csvBytes != null && this.csvBytes.Count > 0) if (this.csvBytes != null && this.csvBytes.Count > 0)
{ {
// csvList is not empty, write it // csvList is not empty, write it
this.AsyncWriteData(); this.AsyncWriteData();
} }
   
// CSV Logging // CSV Logging
// from ISA MapSat // from ISA MapSat
if (loggingActive && (!waitForLaunch || this.vessel.situation != Vessel.Situations.PRELAUNCH)) if (loggingActive && (!waitForLaunch || this.vessel.situation != Vessel.Situations.PRELAUNCH))
{ {
//data logging is on //data logging is on
//increment timers //increment timers
this.csvCollectTimer += Time.deltaTime; this.csvCollectTimer += Time.deltaTime;
   
if (this.csvCollectTimer >= this.logInterval) if (this.csvCollectTimer >= this.logInterval)
{ {
//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
this.CollectLogData(); this.CollectLogData();
} }
} }
} }
   
public void FixedUpdate() {} public void FixedUpdate() {}
   
public void OnDestroy() public void OnDestroy()
{ {
Tools.DebugLogger logger = Tools.DebugLogger.New(this); Tools.DebugLogger logger = Tools.DebugLogger.New(this);
   
logger.Append("Destroying..."); logger.Append("Destroying...");
   
this.CloseFileIfOpen(); this.CloseFileIfOpen();
   
logger.Append(" Done."); logger.Append(" Done.");
logger.Print(false); logger.Print(false);
} }
   
#endregion #endregion
   
#region VOID_Module Overrides #region VOID_Module Overrides
   
public override void LoadConfig() public override void LoadConfig()
{ {
base.LoadConfig(); base.LoadConfig();
   
this.logIntervalStr = this.logInterval.value.ToString("#.0##"); this.logIntervalStr = this.logInterval.value.ToString("#.0##");
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.Label( GUILayout.Label(
string.Format("System time: {0}", DateTime.Now.ToString("HH:mm:ss")), string.Format("System time: {0}", DateTime.Now.ToString("HH:mm:ss")),
GUILayout.ExpandWidth(true) GUILayout.ExpandWidth(true)
); );
GUILayout.Label( GUILayout.Label(
string.Format("Kerbin time: {0}", VOID_Tools.FormatDate(Planetarium.GetUniversalTime())), string.Format("Kerbin time: {0}", VOID_Tools.FormatDate(Planetarium.GetUniversalTime())),
GUILayout.ExpandWidth(true) GUILayout.ExpandWidth(true)
); );
   
GUIStyle activeLabelStyle = VOID_Styles.labelRed; GUIStyle activeLabelStyle = VOID_Styles.labelRed;
string activeLabelText = "Inactive"; string activeLabelText = "Inactive";
if (loggingActive) if (loggingActive)
{ {
activeLabelText = "Active"; activeLabelText = "Active";
activeLabelStyle = VOID_Styles.labelGreen; activeLabelStyle = VOID_Styles.labelGreen;
} }
   
this.loggingActive = GUITools.Toggle( this.loggingActive = GUITools.Toggle(
loggingActive, loggingActive,
string.Format("Data logging: {0}", activeLabelText), string.Format("Data logging: {0}", activeLabelText),
null, null,
activeLabelStyle activeLabelStyle
); );
   
this.waitForLaunch.value = GUITools.Toggle( this.waitForLaunch.value = GUITools.Toggle(
this.waitForLaunch, this.waitForLaunch,
"Wait for launch" "Wait for launch"
); );
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
GUILayout.Label("Interval: ", GUILayout.ExpandWidth(false)); GUILayout.Label("Interval: ", GUILayout.ExpandWidth(false));
   
logIntervalStr = GUILayout.TextField(logIntervalStr, GUILayout.ExpandWidth(true)); logIntervalStr = GUILayout.TextField(logIntervalStr, GUILayout.ExpandWidth(true));
GUILayout.Label("s", GUILayout.ExpandWidth(false)); GUILayout.Label("s", GUILayout.ExpandWidth(false));
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
float newLogInterval; float newLogInterval;
if (float.TryParse(logIntervalStr, out newLogInterval)) if (float.TryParse(logIntervalStr, out newLogInterval))
{ {
logInterval.value = newLogInterval; logInterval.value = newLogInterval;
this.logIntervalStr = this.logInterval.value.ToString("#.0##"); this.logIntervalStr = this.logInterval.value.ToString("#.0##");
} }
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
   
#endregion #endregion
   
#region Data Collection #region Data Collection
   
private void CollectLogData() private void CollectLogData()
{ {
if (this.csvBytes == null) if (this.csvBytes == null)
{ {
this.csvBytes = new List<byte>(); this.csvBytes = new List<byte>();
} }
   
//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 (firstWrite) if (firstWrite)
{ {
firstWrite = false; firstWrite = false;
line.Append( line.Append(
"\"Kerbin Universal Time (s)\"," + "\"Kerbin Universal Time (s)\"," +
"\"Mission Elapsed Time (s)\t\"," + "\"Mission Elapsed Time (s)\t\"," +
"\"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)\"," + "\"Downrange Distance (m)\"," +
"\n" "\n"
); );
} }
   
// Universal time // Universal time
line.Append(Planetarium.GetUniversalTime().ToString("F2")); line.Append(Planetarium.GetUniversalTime().ToString("F2"));
line.Append(','); line.Append(',');
   
//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(VOID_Data.orbitAltitude.Value.ToString("F3")); line.Append(VOID_Data.orbitAltitude.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//Altitude (true) //Altitude (true)
line.Append(VOID_Data.trueAltitude.Value.ToString("F3")); line.Append(VOID_Data.trueAltitude.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
// Surface Latitude // Surface Latitude
line.Append('"'); line.Append('"');
line.Append(VOID_Data.surfLatitude.Value); line.Append(VOID_Data.surfLatitude.Value);
line.Append('"'); line.Append('"');
line.Append(','); line.Append(',');
   
// Surface Longitude // Surface Longitude
line.Append('"'); line.Append('"');
line.Append(VOID_Data.surfLongitude.Value); line.Append(VOID_Data.surfLongitude.Value);
line.Append('"'); line.Append('"');
line.Append(','); line.Append(',');
   
//Orbital velocity //Orbital velocity
line.Append(VOID_Data.orbitVelocity.Value.ToString("F3")); line.Append(VOID_Data.orbitVelocity.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//surface velocity //surface velocity
line.Append(VOID_Data.surfVelocity.Value.ToString("F3")); line.Append(VOID_Data.surfVelocity.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//vertical speed //vertical speed
line.Append(VOID_Data.vertVelocity.Value.ToString("F3")); line.Append(VOID_Data.vertVelocity.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//horizontal speed //horizontal speed
line.Append(VOID_Data.horzVelocity.Value.ToString("F3")); line.Append(VOID_Data.horzVelocity.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//gee force //gee force
line.Append(VOID_Data.geeForce.Value.ToString("F3")); line.Append(VOID_Data.geeForce.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//temperature //temperature
line.Append(VOID_Data.temperature.Value.ToString("F2")); line.Append(VOID_Data.temperature.Value.ToString("F2"));
line.Append(','); line.Append(',');
   
//gravity //gravity
line.Append(VOID_Data.gravityAccel.Value.ToString("F3")); line.Append(VOID_Data.gravityAccel.Value.ToString("F3"));
line.Append(','); line.Append(',');
   
//atm density //atm density
line.Append(VOID_Data.atmDensity.Value.ToString("G3")); line.Append(VOID_Data.atmDensity.Value.ToString("G3"));
line.Append(','); line.Append(',');
   
// Downrange Distance // Downrange Distance
line.Append((VOID_Data.downrangeDistance.Value.ToString("G3"))); line.Append((VOID_Data.downrangeDistance.Value.ToString("G3")));
   
line.Append('\n'); line.Append('\n');
   
csvBytes.AddRange(this.utf8Encoding.GetBytes(line.ToString())); csvBytes.AddRange(this.utf8Encoding.GetBytes(line.ToString()));
   
this.csvCollectTimer = 0f; this.csvCollectTimer = 0f;
} }
   
#endregion #endregion
   
#region File IO Methods #region File IO Methods
   
protected void AsyncWriteCallback(IAsyncResult result) protected void AsyncWriteCallback(IAsyncResult result)
{ {
Tools.PostDebugMessage(this, "Got async callback, IsCompleted = {0}", result.IsCompleted); Tools.PostDebugMessage(this, "Got async callback, IsCompleted = {0}", result.IsCompleted);
   
this.outputFile.EndWrite(result); this.outputFile.EndWrite(result);
this.outstandingWrites--; this.outstandingWrites--;
} }
   
private void AsyncWriteData() private void AsyncWriteData()
{ {
WriteState state = new WriteState(); WriteState state = new WriteState();
   
state.bytes = this.csvBytes.ToArray(); state.bytes = this.csvBytes.ToArray();
state.stream = this.outputFile; state.stream = this.outputFile;
   
this.outstandingWrites++; this.outstandingWrites++;
var writeCallback = new AsyncCallback(this.AsyncWriteCallback); var writeCallback = new AsyncCallback(this.AsyncWriteCallback);
   
this.outputFile.BeginWrite(state.bytes, 0, state.bytes.Length, writeCallback, state); this.outputFile.BeginWrite(state.bytes, 0, state.bytes.Length, writeCallback, state);
   
this.csvBytes.Clear(); this.csvBytes.Clear();
} }
   
private void CloseFileIfOpen() private void CloseFileIfOpen()
{ {
Tools.DebugLogger logger = Tools.DebugLogger.New(this); Tools.DebugLogger logger = Tools.DebugLogger.New(this);
   
logger.AppendFormat("Cleaning up file {0}...", this.fileName); logger.AppendFormat("Cleaning up file {0}...", this.fileName);
   
if (this.csvBytes != null && this.csvBytes.Count > 0) if (this.csvBytes != null && this.csvBytes.Count > 0)
{ {
logger.Append(" Writing remaining data..."); logger.Append(" Writing remaining data...");
this.AsyncWriteData(); this.AsyncWriteData();
} }
   
logger.Append(" Waiting for writes to finish."); logger.Append(" Waiting for writes to finish.");
while (this.outstandingWrites > 0) while (this.outstandingWrites > 0)
{ {
logger.Append('.'); logger.Append('.');
System.Threading.Thread.Sleep(10); System.Threading.Thread.Sleep(10);
} }
   
if (this._outputFile != null) if (this._outputFile != null)
{ {
this._outputFile.Close(); this._outputFile.Close();
this._outputFile = null; this._outputFile = null;
logger.Append(" File closed."); logger.Append(" File closed.");
} }
   
logger.Print(false); logger.Print(false);
} }
   
#endregion #endregion
   
#region Constructors & Destructors #region Constructors & Destructors
   
public VOID_DataLogger() public VOID_DataLogger()
{ {
this.Name = "CSV Data Logger"; this.Name = "CSV Data Logger";
   
this.loggingActive = false; this.loggingActive = false;
this.firstWrite = true; this.firstWrite = true;
   
this.waitForLaunch = true; this.waitForLaunch = (VOID_SaveValue<bool>)true;
   
this.logInterval = 0.5f; this.logInterval = (VOID_SaveValue<float>)0.5f;
this.csvCollectTimer = 0f; this.csvCollectTimer = (VOID_SaveValue<float>)0f;
   
this.outstandingWrites = 0; this.outstandingWrites = 0;
   
this.WindowPos.x = Screen.width - 520f; this.WindowPos.x = Screen.width - 520f;
this.WindowPos.y = 85f; this.WindowPos.y = 85f;
   
this.core.onApplicationQuit += delegate(object sender) this.core.onApplicationQuit += delegate(object sender)
{ {
this.CloseFileIfOpen(); this.CloseFileIfOpen();
}; };
} }
   
~VOID_DataLogger() ~VOID_DataLogger()
{ {
this.OnDestroy(); this.OnDestroy();
} }
   
#endregion #endregion
   
#region Subclasses #region Subclasses
   
private class WriteState private class WriteState
{ {
public byte[] bytes; public byte[] bytes;
public FileStream stream; public FileStream stream;
} }
   
#endregion #endregion
} }
} }
   
   
// VOID // VOID
// //
// VOID_EditorHUD.cs // VOID_EditorHUD.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 KerbalEngineer.VesselSimulator; using KerbalEngineer.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
{ {
[VOID_Scenes(GameScenes.EDITOR)] [VOID_Scenes(GameScenes.EDITOR)]
public class VOID_EditorHUD : VOID_HUDModule public class VOID_EditorHUD : VOID_HUDModule
{ {
/* /*
* Fields * Fields
* */ * */
protected HUDWindow ehudWindow; protected HUDWindow ehudWindow;
protected EditorVesselOverlays _vesselOverlays; protected EditorVesselOverlays _vesselOverlays;
   
[AVOID_SaveValue("snapToLeft")] [AVOID_SaveValue("snapToLeft")]
protected VOID_SaveValue<bool> snapToLeft; protected VOID_SaveValue<bool> snapToLeft;
   
/* /*
* Properties * Properties
* */ * */
protected EditorVesselOverlays vesselOverlays protected EditorVesselOverlays vesselOverlays
{ {
get get
{ {
if (this._vesselOverlays == null) if (this._vesselOverlays == null)
{ {
this._vesselOverlays = (EditorVesselOverlays)Resources this._vesselOverlays = (EditorVesselOverlays)Resources
.FindObjectsOfTypeAll(typeof(EditorVesselOverlays)) .FindObjectsOfTypeAll(typeof(EditorVesselOverlays))
.FirstOrDefault(); .FirstOrDefault();
} }
   
return this._vesselOverlays; return this._vesselOverlays;
} }
} }
   
protected EditorMarker_CoM CoMmarker protected EditorMarker_CoM CoMmarker
{ {
get get
{ {
if (this.vesselOverlays == null) if (this.vesselOverlays == null)
{ {
return null; return null;
} }
   
return this.vesselOverlays.CoMmarker; return this.vesselOverlays.CoMmarker;
} }
} }
   
protected EditorMarker_CoT CoTmarker protected EditorMarker_CoT CoTmarker
{ {
get get
{ {
if (this.vesselOverlays == null) if (this.vesselOverlays == null)
{ {
return null; return null;
} }
   
return this.vesselOverlays.CoTmarker; return this.vesselOverlays.CoTmarker;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public VOID_EditorHUD() : base() public VOID_EditorHUD() : base()
{ {
this.Name = "Heads-Up Display"; this.Name = "Heads-Up Display";
   
this.toggleActive = true; this.toggleActive = true;
   
this.snapToLeft.value = true; this.snapToLeft.value = true;
   
this.ehudWindow = new HUDWindow( this.ehudWindow = new HUDWindow(
"editorHUD", "editorHUD",
this.ehudWindowFunc, this.ehudWindowFunc,
new Rect(EditorPanels.Instance.partsPanelWidth + 10f, 125f, 300f, 64f) new Rect(EditorPanels.Instance.partsPanelWidth + 10f, 125f, 300f, 64f)
); );
this.Windows.Add(this.ehudWindow); this.Windows.Add(this.ehudWindow);
   
Tools.PostDebugMessage (this.GetType().Name + ": Constructed."); Tools.PostDebugMessage (this.GetType().Name + ": Constructed.");
} }
   
public void ehudWindowFunc(int id) public void ehudWindowFunc(int id)
{ {
StringBuilder hudString = new StringBuilder(); StringBuilder hudString = new StringBuilder();
   
if (this.core.LastStage == null) if (this.core.LastStage == null)
{ {
return; return;
} }
   
VOID_Styles.labelHud.alignment = TextAnchor.UpperLeft; VOID_Styles.labelHud.alignment = TextAnchor.UpperLeft;
   
hudString.Append("Total Mass: "); hudString.Append("Total Mass: ");
hudString.Append(this.core.LastStage.totalMass.ToString("F3")); hudString.Append(this.core.LastStage.totalMass.ToString("F3"));
hudString.Append('t'); hudString.Append('t');
   
hudString.Append(' '); hudString.Append(' ');
   
hudString.Append("Part Count: "); hudString.Append("Part Count: ");
hudString.Append(EditorLogic.SortedShipList.Count); hudString.Append(EditorLogic.SortedShipList.Count);
   
hudString.Append('\n'); hudString.Append('\n');
   
hudString.Append("Total Delta-V: "); hudString.Append("Total Delta-V: ");
hudString.Append(Tools.MuMech_ToSI(this.core.LastStage.totalDeltaV)); hudString.Append(Tools.MuMech_ToSI(this.core.LastStage.totalDeltaV));
hudString.Append("m/s"); hudString.Append("m/s");
   
hudString.Append('\n'); hudString.Append('\n');
   
hudString.Append("Bottom Stage Delta-V"); hudString.Append("Bottom Stage Delta-V");
hudString.Append(Tools.MuMech_ToSI(this.core.LastStage.deltaV)); hudString.Append(Tools.MuMech_ToSI(this.core.LastStage.deltaV));
hudString.Append("m/s"); hudString.Append("m/s");
   
hudString.Append('\n'); hudString.Append('\n');
   
hudString.Append("Bottom Stage T/W Ratio: "); hudString.Append("Bottom Stage T/W Ratio: ");
hudString.Append(this.core.LastStage.thrustToWeight.ToString("F3")); hudString.Append(this.core.LastStage.thrustToWeight.ToString("F3"));
   
Tools.PostDebugMessage(this, Tools.PostDebugMessage(this,
"CoMmarker.gameObject.activeInHierarchy: {0};" + "CoMmarker.gameObject.activeInHierarchy: {0};" +
"CoTmarker.gameObject.activeInHierarchy: {1}", "CoTmarker.gameObject.activeInHierarchy: {1}",
this.CoMmarker.gameObject.activeInHierarchy, this.CoMmarker.gameObject.activeInHierarchy,
this.CoTmarker.gameObject.activeInHierarchy this.CoTmarker.gameObject.activeInHierarchy
); );
   
if (this.CoMmarker.gameObject.activeInHierarchy && this.CoTmarker.gameObject.activeInHierarchy) if (this.CoMmarker.gameObject.activeInHierarchy && this.CoTmarker.gameObject.activeInHierarchy)
{ {
Tools.PostDebugMessage(this, "CoM and CoT markers are active, doing thrust offset."); Tools.PostDebugMessage(this, "CoM and CoT markers are active, doing thrust offset.");
hudString.Append('\n'); hudString.Append('\n');
   
hudString.Append("Thrust Offset: "); hudString.Append("Thrust Offset: ");
hudString.Append( hudString.Append(
Vector3.Cross( Vector3.Cross(
this.CoTmarker.dirMarkerObject.transform.forward, this.CoTmarker.dirMarkerObject.transform.forward,
this.CoMmarker.posMarkerObject.transform.position - this.CoTmarker.posMarkerObject.transform.position this.CoMmarker.posMarkerObject.transform.position - this.CoTmarker.posMarkerObject.transform.position
).ToString("F3")); ).ToString("F3"));
} }
#if DEBUG #if DEBUG
else else
{ {
Tools.PostDebugMessage(this, "CoM and CoT markers are not active, thrust offset skipped."); Tools.PostDebugMessage(this, "CoM and CoT markers are not active, thrust offset skipped.");
} }
#endif #endif
   
GUILayout.Label( GUILayout.Label(
hudString.ToString(), hudString.ToString(),
VOID_Styles.labelHud, VOID_Styles.labelHud,
GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true),
GUILayout.ExpandHeight(true) GUILayout.ExpandHeight(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()
{ {
float hudLeft; float hudLeft;
   
if (EditorLogic.fetch.editorScreen == EditorScreen.Parts) if (EditorLogic.fetch.editorScreen == EditorScreen.Parts)
{ {
hudLeft = EditorPanels.Instance.partsPanelWidth + 10f; hudLeft = EditorPanels.Instance.partsPanelWidth + 10f;
hudLeft += EditorPartList.Instance.transformTopLeft.position.x - hudLeft += EditorPartList.Instance.transformTopLeft.position.x -
EditorPartList.Instance.transformTopLeft.parent.parent.position.x - EditorPartList.Instance.transformTopLeft.parent.parent.position.x -
72f; 72f;
} }
else if (EditorLogic.fetch.editorScreen == EditorScreen.Actions) else if (EditorLogic.fetch.editorScreen == EditorScreen.Actions)
{ {
hudLeft = EditorPanels.Instance.actionsPanelWidth + 10f; hudLeft = EditorPanels.Instance.actionsPanelWidth + 10f;
} }
else else
{ {
return; return;
} }
   
Tools.PostDebugMessage(this, Tools.PostDebugMessage(this,
"EditorPartList topLeft.parent.parent.position: {0}\n" + "EditorPartList topLeft.parent.parent.position: {0}\n" +
"EditorPartList topLeft.parent.position: {1}\n" + "EditorPartList topLeft.parent.position: {1}\n" +
"EditorPartList topLeft.position: {2}\n" + "EditorPartList topLeft.position: {2}\n" +
"snapToEdge: {3} (pos.Xmin: {4}; hudLeft: {5})", "snapToEdge: {3} (pos.Xmin: {4}; hudLeft: {5})",
EditorPartList.Instance.transformTopLeft.parent.parent.position, EditorPartList.Instance.transformTopLeft.parent.parent.position,
EditorPartList.Instance.transformTopLeft.parent.position, EditorPartList.Instance.transformTopLeft.parent.position,
EditorPartList.Instance.transformTopLeft.position, EditorPartList.Instance.transformTopLeft.position,
this.snapToLeft, this.ehudWindow.WindowPos.xMin, hudLeft this.snapToLeft, this.ehudWindow.WindowPos.xMin, hudLeft
); );
   
base.DrawGUI(); base.DrawGUI();
   
Rect hudPos = this.ehudWindow.WindowPos; Rect hudPos = this.ehudWindow.WindowPos;
   
if (this.snapToLeft && this.positionsLocked) if (this.snapToLeft && this.positionsLocked)
{ {
hudPos.xMin = hudLeft; hudPos.xMin = hudLeft;
} }
else else
{ {
hudPos.xMin = Mathf.Max(hudLeft, hudPos.xMin); hudPos.xMin = Mathf.Max(hudLeft, hudPos.xMin);
} }
   
hudPos.width = this.ehudWindow.defaultWindowPos.width; hudPos.width = this.ehudWindow.defaultWindowPos.width;
   
this.ehudWindow.WindowPos = hudPos; this.ehudWindow.WindowPos = hudPos;
   
this.snapToLeft = Mathf.Abs(this.ehudWindow.WindowPos.xMin - hudLeft) < 15f; this.snapToLeft.value = Mathf.Abs(this.ehudWindow.WindowPos.xMin - hudLeft) < 15f;
} }
} }
} }
   
// 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 KerbalEngineer.VesselSimulator; using KerbalEngineer.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_HUDAdvanced : VOID_HUDModule, IVOID_Module public class VOID_HUDAdvanced : VOID_HUDModule, IVOID_Module
{ {
/* /*
* Fields * Fields
* */ * */
protected VOID_HUD primaryHUD; protected VOID_HUD primaryHUD;
   
protected HUDWindow leftHUD; protected HUDWindow leftHUD;
protected HUDWindow rightHUD; protected HUDWindow rightHUD;
   
/* /*
* Properties * Properties
* */ * */
public override int ColorIndex public override int ColorIndex
{ {
get get
{ {
if (this.primaryHUD != null) if (this.primaryHUD != null)
{ {
return this.primaryHUD.ColorIndex; return this.primaryHUD.ColorIndex;
} }
   
return base.ColorIndex; return base.ColorIndex;
} }
set set
{ {
base.ColorIndex = value; base.ColorIndex = value;
} }
} }
   
/* /*
* Methods * Methods
* */ * */
public VOID_HUDAdvanced() : base() public VOID_HUDAdvanced() : base()
{ {
this.Name = "Advanced Heads-Up Display"; this.Name = "Advanced Heads-Up Display";
   
this.toggleActive = true; this.toggleActive = true;
   
this.leftHUD = new HUDWindow("leftHUD", this.leftHUD = new HUDWindow("leftHUD",
this.leftHUDWindow, this.leftHUDWindow,
new Rect( new Rect(
Screen.width * .5f - (float)GameSettings.UI_SIZE * .25f - 300f, Screen.width * .5f - (float)GameSettings.UI_SIZE * .25f - 300f,
Screen.height - 200f, Screen.height - 200f,
300f, 90f) 300f, 90f)
); );
this.Windows.Add(this.leftHUD); this.Windows.Add(this.leftHUD);
   
this.rightHUD = new HUDWindow( this.rightHUD = new HUDWindow(
"rightHUD", "rightHUD",
this.rightHUDWindow, this.rightHUDWindow,
new Rect( new Rect(
Screen.width * .5f + (float)GameSettings.UI_SIZE * .25f, Screen.width * .5f + (float)GameSettings.UI_SIZE * .25f,
Screen.height - 200f, Screen.height - 200f,
300f, 90f) 300f, 90f)
); );
this.Windows.Add(this.rightHUD); this.Windows.Add(this.rightHUD);
   
this.positionsLocked = true; this.positionsLocked.value = true;
   
Tools.PostDebugMessage (this, "Constructed."); Tools.PostDebugMessage (this, "Constructed.");
} }
   
protected void leftHUDWindow(int id) protected void leftHUDWindow(int id)
{ {
StringBuilder leftHUD; StringBuilder leftHUD;
   
leftHUD = new StringBuilder(); leftHUD = new StringBuilder();
   
VOID_Styles.labelHud.alignment = TextAnchor.UpperRight; VOID_Styles.labelHud.alignment = TextAnchor.UpperRight;
   
if (this.core.powerAvailable) if (this.core.powerAvailable)
{ {
leftHUD.AppendFormat( leftHUD.AppendFormat(
string.Intern("Mass: {0}\n"), string.Intern("Mass: {0}\n"),
VOID_Data.totalMass.ToSIString(2) VOID_Data.totalMass.ToSIString(2)
); );
   
if (VOID_Data.vesselCrewCapacity > 0) if (VOID_Data.vesselCrewCapacity > 0)
{ {
leftHUD.AppendFormat( leftHUD.AppendFormat(
string.Intern("Crew: {0} / {1}\n"), string.Intern("Crew: {0} / {1}\n"),
VOID_Data.vesselCrewCount.Value, VOID_Data.vesselCrewCount.Value,
VOID_Data.vesselCrewCapacity.Value VOID_Data.vesselCrewCapacity.Value
); );
} }
   
leftHUD.AppendFormat( leftHUD.AppendFormat(
string.Intern("Acc: {0} T:W: {1}\n"), string.Intern("Acc: {0} T:W: {1}\n"),
VOID_Data.vesselAccel.ToSIString(2), VOID_Data.vesselAccel.ToSIString(2),
VOID_Data.currThrustWeight.Value.ToString("f2") VOID_Data.currThrustWeight.Value.ToString("f2")
); );
   
leftHUD.AppendFormat( leftHUD.AppendFormat(
string.Intern("Ang Vel: {0}\n"), string.Intern("Ang Vel: {0}\n"),
VOID_Data.vesselAngularVelocity.ToSIString(2) VOID_Data.vesselAngularVelocity.ToSIString(2)
); );
   
if (VOID_Data.stageNominalThrust != 0d) if (VOID_Data.stageNominalThrust != 0d)
{ {
leftHUD.AppendFormat( leftHUD.AppendFormat(
string.Intern("Thrust Offset: {0}\n"), string.Intern("Thrust Offset: {0}\n"),
VOID_Data.vesselThrustOffset.Value.ToString("F1") VOID_Data.vesselThrustOffset.Value.ToString("F1")
); );
} }
} }
else else
{ {
VOID_Styles.labelHud.normal.textColor = Color.red; VOID_Styles.labelHud.normal.textColor = Color.red;
leftHUD.Append(string.Intern("-- POWER LOST --")); leftHUD.Append(string.Intern("-- POWER LOST --"));
} }
   
GUILayout.Label( GUILayout.Label(
leftHUD.ToString(), leftHUD.ToString(),
VOID_Styles.labelHud, VOID_Styles.labelHud,
GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true),
GUILayout.ExpandHeight(true) GUILayout.ExpandHeight(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();
   
VOID_Styles.labelHud.alignment = TextAnchor.UpperLeft; VOID_Styles.labelHud.alignment = TextAnchor.UpperLeft;
   
if (this.core.powerAvailable) if (this.core.powerAvailable)
{ {
rightHUD.AppendFormat( rightHUD.AppendFormat(
"Burn Δv (Rem/Tot): {0} / {1}\n", "Burn Δv (Rem/Tot): {0} / {1}\n",
VOID_Data.currManeuverDVRemaining.ValueUnitString("f2"), VOID_Data.currManeuverDVRemaining.ValueUnitString("f2"),
VOID_Data.currManeuverDeltaV.ValueUnitString("f2") VOID_Data.currManeuverDeltaV.ValueUnitString("f2")
); );
   
if (VOID_Data.upcomingManeuverNodes > 1) if (VOID_Data.upcomingManeuverNodes > 1)
{ {
rightHUD.AppendFormat("Next Burn Δv: {0}\n", rightHUD.AppendFormat("Next Burn Δv: {0}\n",
VOID_Data.nextManeuverDeltaV.ValueUnitString("f2") VOID_Data.nextManeuverDeltaV.ValueUnitString("f2")
); );
} }
   
rightHUD.AppendFormat("Burn Time (Rem/Total): {0} / {1}\n", rightHUD.AppendFormat("Burn Time (Rem/Total): {0} / {1}\n",
VOID_Tools.FormatInterval(VOID_Data.currentNodeBurnRemaining.Value), VOID_Tools.FormatInterval(VOID_Data.currentNodeBurnRemaining.Value),
VOID_Tools.FormatInterval(VOID_Data.currentNodeBurnDuration.Value) VOID_Tools.FormatInterval(VOID_Data.currentNodeBurnDuration.Value)
); );
   
if (VOID_Data.burnTimeDoneAtNode.Value != string.Empty) if (VOID_Data.burnTimeDoneAtNode.Value != string.Empty)
{ {
rightHUD.AppendFormat("{0} (done @ node)\n", rightHUD.AppendFormat("{0} (done @ node)\n",
VOID_Data.burnTimeDoneAtNode.Value VOID_Data.burnTimeDoneAtNode.Value
); );
   
rightHUD.AppendFormat("{0} (½ done @ node)", rightHUD.AppendFormat("{0} (½ done @ node)",
VOID_Data.burnTimeHalfDoneAtNode.Value VOID_Data.burnTimeHalfDoneAtNode.Value
); );
} }
else else
{ {
rightHUD.Append("Node is past"); rightHUD.Append("Node is past");
} }
} }
else else
{ {
VOID_Styles.labelHud.normal.textColor = Color.red; VOID_Styles.labelHud.normal.textColor = Color.red;
rightHUD.Append(string.Intern("-- POWER LOST --")); rightHUD.Append(string.Intern("-- POWER LOST --"));
} }
   
GUILayout.Label( GUILayout.Label(
rightHUD.ToString(), rightHUD.ToString(),
VOID_Styles.labelHud, VOID_Styles.labelHud,
GUILayout.ExpandWidth(true), GUILayout.ExpandWidth(true),
GUILayout.ExpandHeight(true) GUILayout.ExpandHeight(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.primaryHUD == null) if (this.primaryHUD == null)
{ {
foreach (IVOID_Module module in this.core.Modules) foreach (IVOID_Module module in this.core.Modules)
{ {
if (module is VOID_HUD) if (module is VOID_HUD)
{ {
this.primaryHUD = module as VOID_HUD; this.primaryHUD = module as VOID_HUD;
} }
} }
} }
   
if (VOID_Data.upcomingManeuverNodes < 1 && this.Windows.Contains(this.rightHUD)) if (VOID_Data.upcomingManeuverNodes < 1 && this.Windows.Contains(this.rightHUD))
{ {
this.Windows.Remove(this.rightHUD); this.Windows.Remove(this.rightHUD);
} }
else if (VOID_Data.upcomingManeuverNodes > 0 && !this.Windows.Contains(this.rightHUD)) else if (VOID_Data.upcomingManeuverNodes > 0 && !this.Windows.Contains(this.rightHUD))
{ {
this.Windows.Add(this.rightHUD); this.Windows.Add(this.rightHUD);
} }
   
base.DrawGUI(); base.DrawGUI();
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
base.DrawConfigurables(); base.DrawConfigurables();
   
if (GUILayout.Button(string.Intern("Reset Advanced HUD Positions"), GUILayout.ExpandWidth(false))) if (GUILayout.Button(string.Intern("Reset Advanced HUD Positions"), GUILayout.ExpandWidth(false)))
{ {
foreach (HUDWindow window in this.Windows) foreach (HUDWindow window in this.Windows)
{ {
window.WindowPos = new Rect(window.defaultWindowPos); window.WindowPos = new Rect(window.defaultWindowPos);
} }
} }
   
this.positionsLocked = GUITools.Toggle(this.positionsLocked, string.Intern("Lock Advanced HUD Positions")); this.positionsLocked.value = GUITools.Toggle(this.positionsLocked, string.Intern("Lock Advanced HUD Positions"));
} }
} }
} }
   
file:a/VOID_Localization.cs (deleted)
// VOID  
//  
// VOID_Localization.cs  
//  
// Copyright © 2014, toadicus  
// All rights reserved.  
//  
// Redistribution and use in source and binary forms, with or without modification,  
// are permitted provided that the following conditions are met:  
//  
// 1. Redistributions of source code must retain the above copyright notice,  
// this list of conditions and the following disclaimer.  
//  
// 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  
// materials provided with the distribution.  
//  
// 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.  
//  
// 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  
// 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  
// 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  
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  
 
public static class VOID_Localization  
{  
public static string void_primary = "Primary";  
public static string void_altitude_asl = "Altitude (ASL)";  
public static string void_velocity = "Velocity";  
public static string void_apoapsis = "Apoapsis";  
public static string void_periapsis = "Periapsis";  
}  
// VOID // VOID
// //
// VOID_Orbital.cs // VOID_Orbital.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_Orbital : VOID_WindowModule public class VOID_Orbital : VOID_WindowModule
{ {
[AVOID_SaveValue("toggleExtended")] [AVOID_SaveValue("toggleExtended")]
protected VOID_SaveValue<bool> toggleExtended = false; protected VOID_SaveValue<bool> toggleExtended;
   
[AVOID_SaveValue("precisionValues")] [AVOID_SaveValue("precisionValues")]
protected long _precisionValues = 230584300921369395; protected long _precisionValues;
protected IntCollection precisionValues; protected IntCollection precisionValues;
   
public VOID_Orbital() public VOID_Orbital()
{ {
this.Name = "Orbital Information"; this.Name = "Orbital Information";
   
this.WindowPos.x = Screen.width - 520f; this.WindowPos.x = Screen.width - 520f;
this.WindowPos.y = 250f; this.WindowPos.y = 250f;
   
  this.toggleExtended = (VOID_SaveValue<bool>)false;
   
  this._precisionValues = 230584300921369395;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
int idx = 0; int idx = 0;
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
VOID_Data.primaryName.DoGUIHorizontal (); VOID_Data.primaryName.DoGUIHorizontal ();
   
this.precisionValues [idx]= (ushort)VOID_Data.orbitAltitude.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.orbitAltitude.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
this.precisionValues [idx]= (ushort)VOID_Data.orbitVelocity.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.orbitVelocity.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
this.precisionValues [idx]= (ushort)VOID_Data.orbitApoAlt.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.orbitApoAlt.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
VOID_Data.timeToApo.DoGUIHorizontal(); VOID_Data.timeToApo.DoGUIHorizontal();
   
this.precisionValues [idx]= (ushort)VOID_Data.oribtPeriAlt.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.oribtPeriAlt.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
VOID_Data.timeToPeri.DoGUIHorizontal(); VOID_Data.timeToPeri.DoGUIHorizontal();
   
VOID_Data.orbitInclination.DoGUIHorizontal("F3"); VOID_Data.orbitInclination.DoGUIHorizontal("F3");
   
this.precisionValues [idx]= (ushort)VOID_Data.gravityAccel.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.gravityAccel.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
this.toggleExtended.value = GUITools.Toggle(this.toggleExtended, "Extended info"); this.toggleExtended.value = GUITools.Toggle(this.toggleExtended, "Extended info");
   
if (this.toggleExtended) if (this.toggleExtended)
{ {
VOID_Data.orbitPeriod.DoGUIHorizontal(); VOID_Data.orbitPeriod.DoGUIHorizontal();
   
this.precisionValues [idx]= (ushort)VOID_Data.semiMajorAxis.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.semiMajorAxis.DoGUIHorizontal (this.precisionValues [idx]);
idx++; idx++;
   
VOID_Data.eccentricity.DoGUIHorizontal("F4"); VOID_Data.eccentricity.DoGUIHorizontal("F4");
   
VOID_Data.meanAnomaly.DoGUIHorizontal("F3"); VOID_Data.meanAnomaly.DoGUIHorizontal("F3");
   
VOID_Data.trueAnomaly.DoGUIHorizontal("F3"); VOID_Data.trueAnomaly.DoGUIHorizontal("F3");
   
VOID_Data.eccAnomaly.DoGUIHorizontal("F3"); VOID_Data.eccAnomaly.DoGUIHorizontal("F3");
   
VOID_Data.longitudeAscNode.DoGUIHorizontal("F3"); VOID_Data.longitudeAscNode.DoGUIHorizontal("F3");
   
VOID_Data.timeToAscendingNode.DoGUIHorizontal(); VOID_Data.timeToAscendingNode.DoGUIHorizontal();
   
VOID_Data.timeToDescendingNode.DoGUIHorizontal(); VOID_Data.timeToDescendingNode.DoGUIHorizontal();
   
VOID_Data.argumentPeriapsis.DoGUIHorizontal("F3"); VOID_Data.argumentPeriapsis.DoGUIHorizontal("F3");
   
VOID_Data.localSiderealLongitude.DoGUIHorizontal("F3"); VOID_Data.localSiderealLongitude.DoGUIHorizontal("F3");
} }
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow();  
  base.ModuleWindow(id);
} }
   
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 Save (KSP.IO.PluginConfiguration config)
{ {
this._precisionValues = this.precisionValues.collection; this._precisionValues = this.precisionValues.collection;
   
base._SaveToConfig (config); base.Save (config);
} }
} }
} }
   
   
// VOID // VOID
// //
// VOID_Rendezvous.cs // VOID_Rendezvous.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.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_Rendezvous : VOID_WindowModule public class VOID_Rendezvous : VOID_WindowModule
{ {
[AVOID_SaveValue("untoggleRegisterInfo")] [AVOID_SaveValue("untoggleRegisterInfo")]
protected VOID_SaveValue<bool> untoggleRegisterInfo = false; protected VOID_SaveValue<bool> untoggleRegisterInfo;
   
[AVOID_SaveValue("toggleExtendedOrbital")] [AVOID_SaveValue("toggleExtendedOrbital")]
protected VOID_SaveValue<bool> toggleExtendedOrbital = false; protected VOID_SaveValue<bool> toggleExtendedOrbital;
   
protected VOID_VesselRegister RegisterModule; protected VOID_VesselRegister RegisterModule;
   
public VOID_Rendezvous() public VOID_Rendezvous()
{ {
this.Name = "Rendezvous Information"; this.Name = "Rendezvous Information";
   
this.WindowPos.x = 845; this.WindowPos.x = 845;
this.WindowPos.y = 85; this.WindowPos.y = 85;
   
  this.untoggleRegisterInfo = (VOID_SaveValue<bool>)false;
  this.toggleExtendedOrbital = (VOID_SaveValue<bool>)false;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
Vessel rendezvessel = new Vessel(); Vessel rendezvessel = new Vessel();
CelestialBody rendezbody = new CelestialBody(); CelestialBody rendezbody = new CelestialBody();
   
if (this.RegisterModule == null) if (this.RegisterModule == null)
{ {
this.RegisterModule = this.core.Modules.Where(m => typeof(VOID_VesselRegister).IsAssignableFrom(m.GetType())).FirstOrDefault() as VOID_VesselRegister; this.RegisterModule = this.core.Modules.Where(m => typeof(VOID_VesselRegister).IsAssignableFrom(m.GetType())).FirstOrDefault() as VOID_VesselRegister;
} }
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
//display both //display both
//Show Target Info //Show Target Info
GUILayout.Label("Target:", VOID_Styles.labelCenterBold); GUILayout.Label("Target:", VOID_Styles.labelCenterBold);
if (FlightGlobals.fetch.VesselTarget != null) if (FlightGlobals.fetch.VesselTarget != null)
{ {
//a KSP Target (body or vessel) is selected //a KSP Target (body or vessel) is selected
if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.Direction) if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.Direction)
{ {
//a Body is selected //a Body is selected
rendezbody = vessel.patchedConicSolver.targetBody; rendezbody = vessel.patchedConicSolver.targetBody;
display_rendezvous_info(null, rendezbody); display_rendezvous_info(null, rendezbody);
} }
else if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.DirectionAndVelocity) else if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.DirectionAndVelocity)
{ {
//a Vessel is selected //a Vessel is selected
rendezvessel = FlightGlobals.fetch.VesselTarget.GetVessel(); rendezvessel = FlightGlobals.fetch.VesselTarget.GetVessel();
display_rendezvous_info(rendezvessel, null); display_rendezvous_info(rendezvessel, null);
} }
//Show Unset button for both options above //Show Unset button for both options above
if (GUILayout.Button("Unset Target", GUILayout.ExpandWidth(false))) if (GUILayout.Button("Unset Target", GUILayout.ExpandWidth(false)))
{ {
FlightGlobals.fetch.SetVesselTarget(null); FlightGlobals.fetch.SetVesselTarget(null);
Tools.PostDebugMessage("VOID_Rendezvous: KSP Target set to null"); Tools.PostDebugMessage("VOID_Rendezvous: KSP Target set to null");
} }
   
} }
else else
{ {
//no KSP Target selected //no KSP Target selected
GUILayout.Label("No Target Selected", VOID_Styles.labelCenterBold); GUILayout.Label("No Target Selected", VOID_Styles.labelCenterBold);
} }
   
//Show Vessel Register vessel info //Show Vessel Register vessel info
if (untoggleRegisterInfo == false && this.RegisterModule != default(IVOID_Module)) if (untoggleRegisterInfo == false && this.RegisterModule != default(IVOID_Module))
{ {
GUILayout.Label("Vessel Register:", VOID_Styles.labelCenterBold); GUILayout.Label("Vessel Register:", VOID_Styles.labelCenterBold);
if (this.RegisterModule.selectedVessel != null) if (this.RegisterModule.selectedVessel != null)
{ {
rendezvessel = this.RegisterModule.selectedVessel; rendezvessel = this.RegisterModule.selectedVessel;
display_rendezvous_info(rendezvessel, null); display_rendezvous_info(rendezvessel, null);
   
//show set/unset buttons //show set/unset buttons
if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() != this.RegisterModule.selectedVessel)) if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() != this.RegisterModule.selectedVessel))
{ {
//no Tgt set or Tgt is not this vessel //no Tgt set or Tgt is not this vessel
//show a Set button //show a Set button
if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false))) if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false)))
{ {
FlightGlobals.fetch.SetVesselTarget(rendezvessel); FlightGlobals.fetch.SetVesselTarget(rendezvessel);
Tools.PostDebugMessage("[VOID] KSP Target set to " + rendezvessel.vesselName); Tools.PostDebugMessage("[VOID] KSP Target set to " + rendezvessel.vesselName);
} }
} }
} }
else else
{ {
//vesreg Vessel is null //vesreg Vessel is null
//targ = null; //targ = null;
GUILayout.Label("No Vessel Selected", VOID_Styles.labelCenterBold); GUILayout.Label("No Vessel Selected", VOID_Styles.labelCenterBold);
} }
} }
   
untoggleRegisterInfo.value = GUITools.Toggle(untoggleRegisterInfo, "Hide Vessel Register Info"); untoggleRegisterInfo.value = GUITools.Toggle(untoggleRegisterInfo, "Hide Vessel Register Info");
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(" ", GUILayout.ExpandWidth(true)); GUILayout.Label(" ", GUILayout.ExpandWidth(true));
if (GUILayout.Button("Close", GUILayout.ExpandWidth(false))) this.toggleActive = false; if (GUILayout.Button("Close", GUILayout.ExpandWidth(false))) this.toggleActive = false;
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow();  
  base.ModuleWindow(id);
} }
   
private void display_rendezvous_info(Vessel v, CelestialBody cb) private void display_rendezvous_info(Vessel v, CelestialBody cb)
{ {
if (cb == null && v != null) if (cb == null && v != null)
{ {
//Display vessel rendezvous info //Display vessel rendezvous info
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label(v.vesselName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true)); GUILayout.Label(v.vesselName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (v.situation == Vessel.Situations.ESCAPING || v.situation == Vessel.Situations.FLYING || v.situation == Vessel.Situations.ORBITING || v.situation == Vessel.Situations.SUB_ORBITAL) if (v.situation == Vessel.Situations.ESCAPING || v.situation == Vessel.Situations.FLYING || v.situation == Vessel.Situations.ORBITING || v.situation == Vessel.Situations.SUB_ORBITAL)
{ {
// Toadicus edit: added local sidereal longitude. // Toadicus edit: added local sidereal longitude.
// Toadicus edit: added local sidereal longitude. // Toadicus edit: added local sidereal longitude.
double LSL = v.longitude + v.orbit.referenceBody.rotationAngle; double LSL = v.longitude + v.orbit.referenceBody.rotationAngle;
LSL = VOID_Tools.FixDegreeDomain (LSL); LSL = VOID_Tools.FixDegreeDomain (LSL);
   
//display orbital info for orbiting/flying/suborbital/escaping vessels only //display orbital info for orbiting/flying/suborbital/escaping vessels only
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Ap/Pe:"); GUILayout.Label("Ap/Pe:");
GUILayout.Label(Tools.MuMech_ToSI(v.orbit.ApA) + "m / " + Tools.MuMech_ToSI(v.orbit.PeA) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI(v.orbit.ApA) + "m / " + Tools.MuMech_ToSI(v.orbit.PeA) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Altitude:"); GUILayout.Label("Altitude:");
GUILayout.Label(Tools.MuMech_ToSI(v.orbit.altitude) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI(v.orbit.altitude) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Inclination:"); GUILayout.Label("Inclination:");
GUILayout.Label(v.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(v.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (vessel.mainBody == v.mainBody) if (vessel.mainBody == v.mainBody)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Relative inclination:"); GUILayout.Label("Relative inclination:");
GUILayout.Label(Vector3d.Angle(vessel.orbit.GetOrbitNormal(), v.orbit.GetOrbitNormal()).ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(Vector3d.Angle(vessel.orbit.GetOrbitNormal(), v.orbit.GetOrbitNormal()).ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
//if (debugging) Debug.Log("[CHATR] v -> v relative incl OK"); //if (debugging) Debug.Log("[CHATR] v -> v relative incl OK");
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Velocity:"); GUILayout.Label("Velocity:");
GUILayout.Label(Tools.MuMech_ToSI(v.orbit.vel.magnitude) + "m/s", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI(v.orbit.vel.magnitude) + "m/s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Relative velocity:"); GUILayout.Label("Relative velocity:");
GUILayout.Label(Tools.MuMech_ToSI(v.orbit.vel.magnitude - vessel.orbit.vel.magnitude) + "m/s", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI(v.orbit.vel.magnitude - vessel.orbit.vel.magnitude) + "m/s", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Distance:"); GUILayout.Label("Distance:");
GUILayout.Label(Tools.MuMech_ToSI((vessel.findWorldCenterOfMass() - v.findWorldCenterOfMass()).magnitude) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI((vessel.findWorldCenterOfMass() - v.findWorldCenterOfMass()).magnitude) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
// Toadicus edit: added local sidereal longitude. // Toadicus edit: added local sidereal longitude.
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Local Sidereal Longitude:"); GUILayout.Label("Local Sidereal Longitude:");
GUILayout.Label(LSL.ToString("F3") + "°", VOID_Styles.labelRight); GUILayout.Label(LSL.ToString("F3") + "°", VOID_Styles.labelRight);
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
toggleExtendedOrbital.value = GUITools.Toggle(toggleExtendedOrbital, "Extended info"); toggleExtendedOrbital.value = GUITools.Toggle(toggleExtendedOrbital, "Extended info");
   
if (toggleExtendedOrbital) if (toggleExtendedOrbital)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Period:"); GUILayout.Label("Period:");
GUILayout.Label(VOID_Tools.FormatInterval(v.orbit.period), GUILayout.ExpandWidth(false)); GUILayout.Label(VOID_Tools.FormatInterval(v.orbit.period), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Semi-major axis:"); GUILayout.Label("Semi-major axis:");
GUILayout.Label((v.orbit.semiMajorAxis / 1000).ToString("##,#") + "km", GUILayout.ExpandWidth(false)); GUILayout.Label((v.orbit.semiMajorAxis / 1000).ToString("##,#") + "km", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Eccentricity:"); GUILayout.Label("Eccentricity:");
GUILayout.Label(v.orbit.eccentricity.ToString("F4"), GUILayout.ExpandWidth(false)); GUILayout.Label(v.orbit.eccentricity.ToString("F4"), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
// Toadicus edit: convert mean anomaly into degrees. // Toadicus edit: convert mean anomaly into degrees.
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Mean anomaly:"); GUILayout.Label("Mean anomaly:");
GUILayout.Label((v.orbit.meanAnomaly * 180d / Math.PI).ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label((v.orbit.meanAnomaly * 180d / Math.PI).ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("True anomaly:"); GUILayout.Label("True anomaly:");
GUILayout.Label(v.orbit.trueAnomaly.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(v.orbit.trueAnomaly.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
// Toadicus edit: convert eccentric anomaly into degrees. // Toadicus edit: convert eccentric anomaly into degrees.
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Eccentric anomaly:"); GUILayout.Label("Eccentric anomaly:");
GUILayout.Label((v.orbit.eccentricAnomaly * 180d / Math.PI).ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label((v.orbit.eccentricAnomaly * 180d / Math.PI).ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Long. ascending node:"); GUILayout.Label("Long. ascending node:");
GUILayout.Label(v.orbit.LAN.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(v.orbit.LAN.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Arg. of periapsis:"); GUILayout.Label("Arg. of periapsis:");
GUILayout.Label(v.orbit.argumentOfPeriapsis.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(v.orbit.argumentOfPeriapsis.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
else else
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Latitude:"); GUILayout.Label("Latitude:");
GUILayout.Label(VOID_Tools.GetLatitudeString(vessel), GUILayout.ExpandWidth(false)); GUILayout.Label(VOID_Tools.GetLatitudeString(vessel), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Longitude:"); GUILayout.Label("Longitude:");
GUILayout.Label(VOID_Tools.GetLongitudeString(vessel), GUILayout.ExpandWidth(false)); GUILayout.Label(VOID_Tools.GetLongitudeString(vessel), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Distance:"); GUILayout.Label("Distance:");
GUILayout.Label(Tools.MuMech_ToSI((vessel.findWorldCenterOfMass() - v.findWorldCenterOfMass()).magnitude) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI((vessel.findWorldCenterOfMass() - v.findWorldCenterOfMass()).magnitude) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
else if (cb != null && v == null) else if (cb != null && v == null)
{ {
//Display CelstialBody rendezvous info //Display CelstialBody rendezvous info
GUILayout.Label(cb.bodyName, VOID_Styles.labelCenterBold); GUILayout.Label(cb.bodyName, VOID_Styles.labelCenterBold);
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Ap/Pe:"); GUILayout.Label("Ap/Pe:");
GUILayout.Label(Tools.MuMech_ToSI(cb.orbit.ApA) + "m / " + Tools.MuMech_ToSI(cb.orbit.PeA) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI(cb.orbit.ApA) + "m / " + Tools.MuMech_ToSI(cb.orbit.PeA) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
//if (debugging) Debug.Log("[VOID] Ap/Pe OK"); //if (debugging) Debug.Log("[VOID] Ap/Pe OK");
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Inclination:"); GUILayout.Label("Inclination:");
GUILayout.Label(cb.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(cb.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
//if (debugging) Debug.Log("[VOID] Inclination OK"); //if (debugging) Debug.Log("[VOID] Inclination OK");
   
if (cb.referenceBody == vessel.mainBody) if (cb.referenceBody == vessel.mainBody)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Relative inclination:"); GUILayout.Label("Relative inclination:");
GUILayout.Label(Vector3d.Angle(vessel.orbit.GetOrbitNormal(), cb.orbit.GetOrbitNormal()).ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label(Vector3d.Angle(vessel.orbit.GetOrbitNormal(), cb.orbit.GetOrbitNormal()).ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
//if (debugging) Debug.Log("[VOID] cb Relative inclination OK"); //if (debugging) Debug.Log("[VOID] cb Relative inclination OK");
} }
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label("Distance:"); GUILayout.Label("Distance:");
GUILayout.Label(Tools.MuMech_ToSI((vessel.mainBody.position - cb.position).magnitude) + "m", GUILayout.ExpandWidth(false)); GUILayout.Label(Tools.MuMech_ToSI((vessel.mainBody.position - cb.position).magnitude) + "m", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
//if (debugging) Debug.Log("[VOID] Distance OK"); //if (debugging) Debug.Log("[VOID] Distance OK");
   
//SUN2PLANET: //SUN2PLANET:
if (vessel.mainBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody) if (vessel.mainBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody)
{ {
VOID_Tools.display_transfer_angles_SUN2PLANET(cb, vessel); VOID_Tools.display_transfer_angles_SUN2PLANET(cb, vessel);
//if (debugging) Debug.Log("[VOID] SUN2PLANET OK"); //if (debugging) Debug.Log("[VOID] SUN2PLANET OK");
} }
   
//PLANET2PLANET //PLANET2PLANET
else if (vessel.mainBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody.referenceBody) else if (vessel.mainBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody.referenceBody)
{ {
VOID_Tools.display_transfer_angles_PLANET2PLANET(cb, vessel); VOID_Tools.display_transfer_angles_PLANET2PLANET(cb, vessel);
//if (debugging) Debug.Log("[VOID] PLANET2PLANET OK"); //if (debugging) Debug.Log("[VOID] PLANET2PLANET OK");
} }
   
//PLANET2MOON //PLANET2MOON
else if (vessel.mainBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody) else if (vessel.mainBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody)
{ {
VOID_Tools.display_transfer_angles_PLANET2MOON(cb, vessel); VOID_Tools.display_transfer_angles_PLANET2MOON(cb, vessel);
//if (debugging) Debug.Log("[VOID] PLANET2MOON OK"); //if (debugging) Debug.Log("[VOID] PLANET2MOON OK");
} }
   
//MOON2MOON //MOON2MOON
else if (vessel.mainBody.referenceBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody.referenceBody) else if (vessel.mainBody.referenceBody.referenceBody.bodyName == "Sun" && cb.referenceBody == vessel.mainBody.referenceBody)
{ {
VOID_Tools.display_transfer_angles_MOON2MOON(cb, vessel); VOID_Tools.display_transfer_angles_MOON2MOON(cb, vessel);
//if (debugging) Debug.Log("[VOID] MOON2MOON OK"); //if (debugging) Debug.Log("[VOID] MOON2MOON OK");
} }
   
//else GUILayout.Label("Transfer angle information\nunavailable for this target"); //else GUILayout.Label("Transfer angle information\nunavailable for this target");
   
} }
} }
} }
} }
// VOID © 2014 toadicus // VOID © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
   
using KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.EDITOR, GameScenes.FLIGHT)] [VOID_Scenes(GameScenes.EDITOR, GameScenes.FLIGHT)]
public class VOID_StageInfo : VOID_WindowModule public class VOID_StageInfo : VOID_WindowModule
{ {
private Table stageTable; private Table stageTable;
   
private Table.Column<int> stageNumberCol; private Table.Column<int> stageNumberCol;
private Table.Column<double> stageDeltaVCol; private Table.Column<double> stageDeltaVCol;
private Table.Column<double> stageTotalDVCol; private Table.Column<double> stageTotalDVCol;
private Table.Column<double> stageInvertDVCol; private Table.Column<double> stageInvertDVCol;
private Table.Column<double> stageMassCol; private Table.Column<double> stageMassCol;
private Table.Column<double> stageTotalMassCol; private Table.Column<double> stageTotalMassCol;
private Table.Column<double> stageThrustCol; private Table.Column<double> stageThrustCol;
private Table.Column<double> stageTWRCol; private Table.Column<double> stageTWRCol;
private Table.Column<string> stageTimeCol; private Table.Column<string> stageTimeCol;
   
private bool stylesApplied; private bool stylesApplied;
   
private bool showBodyList; private bool showBodyList;
private Rect bodyListPos; private Rect bodyListPos;
   
private bool showColumnSelection; private bool showColumnSelection;
   
private CelestialBody selectedBody; private CelestialBody selectedBody;
[AVOID_SaveValue("bodyIdx")] [AVOID_SaveValue("bodyIdx")]
private VOID_SaveValue<int> bodyIdx; private VOID_SaveValue<int> bodyIdx;
private int lastIdx; private int lastIdx;
   
  private bool showAdvanced;
   
  [AVOID_SaveValue("UseSealLevel")]
  private VOID_SaveValue<bool> useSeaLevel;
  private GUIContent seaLevelToggle;
   
public VOID_StageInfo() : base() public VOID_StageInfo() : base()
{ {
this.Name = "Stage Information"; this.Name = "Stage Information";
this.defWidth = 20f; this.defWidth = 20f;
this.bodyIdx = 4; this.bodyIdx = (VOID_SaveValue<int>)4;
   
this.stylesApplied = false; this.stylesApplied = false;
this.showBodyList = false; this.showBodyList = false;
this.showColumnSelection = false; this.showColumnSelection = false;
   
this.bodyListPos = new Rect(); this.bodyListPos = new Rect();
   
this.stageTable = new Table(); this.stageTable = new Table();
   
this.stageNumberCol = new Table.Column<int>("Stage", 20f); this.stageNumberCol = new Table.Column<int>("Stage", 20f);
this.stageTable.Add(this.stageNumberCol); this.stageTable.Add(this.stageNumberCol);
   
this.stageDeltaVCol = new Table.Column<double>("DeltaV [m/s]", 20f); this.stageDeltaVCol = new Table.Column<double>("DeltaV [m/s]", 20f);
this.stageDeltaVCol.Format = "S2"; this.stageDeltaVCol.Format = "S2";
this.stageTable.Add(this.stageDeltaVCol); this.stageTable.Add(this.stageDeltaVCol);
   
this.stageTotalDVCol = new Table.Column<double>("Total ΔV [m/s]", 20f); this.stageTotalDVCol = new Table.Column<double>("Total ΔV [m/s]", 20f);
this.stageTotalDVCol.Format = "S2"; this.stageTotalDVCol.Format = "S2";
this.stageTable.Add(this.stageTotalDVCol); this.stageTable.Add(this.stageTotalDVCol);
   
this.stageInvertDVCol = new Table.Column<double>("Invert ΔV [m/s]", 20f); this.stageInvertDVCol = new Table.Column<double>("Invert ΔV [m/s]", 20f);
this.stageInvertDVCol.Format = "S2"; this.stageInvertDVCol.Format = "S2";
this.stageTable.Add(this.stageInvertDVCol); this.stageTable.Add(this.stageInvertDVCol);
   
this.stageMassCol = new Table.Column<double>("Mass [Mg]", 20f); this.stageMassCol = new Table.Column<double>("Mass [Mg]", 20f);
this.stageMassCol.Format = "#.#"; this.stageMassCol.Format = "#.#";
this.stageTable.Add(this.stageMassCol); this.stageTable.Add(this.stageMassCol);
   
this.stageTotalMassCol = new Table.Column<double>("Total [Mg]", 20f); this.stageTotalMassCol = new Table.Column<double>("Total [Mg]", 20f);
this.stageTotalMassCol.Format = "#.#"; this.stageTotalMassCol.Format = "#.#";
this.stageTable.Add(this.stageTotalMassCol); this.stageTable.Add(this.stageTotalMassCol);
   
this.stageThrustCol = new Table.Column<double>("Thrust [N]", 20f); this.stageThrustCol = new Table.Column<double>("Thrust [N]", 20f);
this.stageThrustCol.Format = "S2"; this.stageThrustCol.Format = "S2";
this.stageTable.Add(this.stageThrustCol); this.stageTable.Add(this.stageThrustCol);
   
this.stageTWRCol = new Table.Column<double>("T/W Ratio", 20f); this.stageTWRCol = new Table.Column<double>("T/W Ratio", 20f);
this.stageTWRCol.Format = "#.#"; this.stageTWRCol.Format = "#.#";
this.stageTable.Add(this.stageTWRCol); this.stageTable.Add(this.stageTWRCol);
   
this.stageTimeCol = new Table.Column<string>("Burn Time", 20f); this.stageTimeCol = new Table.Column<string>("Burn Time", 20f);
this.stageTable.Add(this.stageTimeCol); this.stageTable.Add(this.stageTimeCol);
   
  this.showAdvanced = false;
   
  this.useSeaLevel = (VOID_SaveValue<bool>)false;
   
  seaLevelToggle = new GUIContent(
  "Use Sea Level",
  "Use 'sea' level atmospheric conditions on bodies with atmospheres."
  );
} }
   
public override void DrawGUI() public override void DrawGUI()
{ {
base.DrawGUI(); base.DrawGUI();
   
if (this.showBodyList) if (this.showBodyList)
{ {
GUILayout.Window(core.windowID, this.bodyListPos, this.BodyPickerWindow, string.Empty); GUILayout.Window(core.WindowID, this.bodyListPos, this.BodyPickerWindow, string.Empty);
} }
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
  if (this.selectedBody == null)
  {
  this.selectedBody = core.HomeBody;
  }
   
if ( if (
!HighLogic.LoadedSceneIsFlight || !HighLogic.LoadedSceneIsFlight ||
(TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.WarpMode == TimeWarp.Modes.LOW) ||
(TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate) (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate)
) )
{ {
KerbalEngineer.VesselSimulator.SimManager.RequestSimulation(); KerbalEngineer.VesselSimulator.SimManager.RequestSimulation();
} }
   
if (!this.stylesApplied) if (!this.stylesApplied)
{ {
this.stageTable.ApplyCellStyle(VOID_Styles.labelCenter); this.stageTable.ApplyCellStyle(VOID_Styles.labelCenter);
this.stageTable.ApplyHeaderStyle(VOID_Styles.labelCenterBold); this.stageTable.ApplyHeaderStyle(VOID_Styles.labelCenterBold);
} }
   
this.stageTable.ClearColumns(); this.stageTable.ClearColumns();
   
if (core.Stages == null || core.Stages.Length == 0) if (core.Stages == null || core.Stages.Length == 0)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.Label("No stage data!"); GUILayout.Label("No stage data!");
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
return; return;
} }
   
  if (HighLogic.LoadedSceneIsEditor && this.selectedBody.atmosphere && this.useSeaLevel)
  {
  SimManager.Atmosphere = this.selectedBody.atmosphereMultiplier * 101.325d;
  }
  else
  {
  SimManager.Atmosphere = 0d;
  }
   
foreach (Stage stage in core.Stages) foreach (Stage stage in core.Stages)
{ {
if (stage.deltaV == 0 && stage.mass == 0) if (stage.deltaV == 0 && stage.mass == 0)
{ {
continue; continue;
} }
   
this.stageNumberCol.Add(stage.number); this.stageNumberCol.Add(stage.number);
   
this.stageDeltaVCol.Add(stage.deltaV); this.stageDeltaVCol.Add(stage.deltaV);
this.stageTotalDVCol.Add(stage.totalDeltaV); this.stageTotalDVCol.Add(stage.totalDeltaV);
this.stageInvertDVCol.Add(stage.inverseTotalDeltaV); this.stageInvertDVCol.Add(stage.inverseTotalDeltaV);
   
this.stageMassCol.Add(stage.mass); this.stageMassCol.Add(stage.mass);
this.stageTotalMassCol.Add(stage.totalMass); this.stageTotalMassCol.Add(stage.totalMass);
   
this.stageThrustCol.Add(stage.thrust * 1000f); this.stageThrustCol.Add(stage.thrust * 1000f);
this.stageTWRCol.Add(stage.thrustToWeight / (this.selectedBody ?? core.HomeBody).GeeASL); this.stageTWRCol.Add(stage.thrustToWeight / (this.selectedBody ?? core.HomeBody).GeeASL);
   
this.stageTimeCol.Add(VOID_Tools.FormatInterval(stage.time)); this.stageTimeCol.Add(VOID_Tools.FormatInterval(stage.time));
} }
   
this.stageTable.Render(); this.stageTable.Render();
   
if (core.sortedBodyList != null) if (core.SortedBodyList != null)
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
   
if (GUILayout.Button("◄")) if (GUILayout.Button("◄"))
{ {
this.bodyIdx--; this.bodyIdx.value--;
} }
   
this.showBodyList = GUILayout.Toggle( this.showBodyList = GUILayout.Toggle(
this.showBodyList, this.showBodyList,
(this.selectedBody ?? core.HomeBody).bodyName, (this.selectedBody ?? core.HomeBody).bodyName,
GUI.skin.button GUI.skin.button
); );
   
Rect bodyButtonPos = GUILayoutUtility.GetLastRect(); Rect bodyButtonPos = GUILayoutUtility.GetLastRect();
   
if (Event.current.type == EventType.Repaint) if (Event.current.type == EventType.Repaint)
{ {
this.bodyListPos.width = bodyButtonPos.width; this.bodyListPos.width = bodyButtonPos.width;
this.bodyListPos.x = bodyButtonPos.xMin + this.WindowPos.xMin; this.bodyListPos.x = bodyButtonPos.xMin + this.WindowPos.xMin;
this.bodyListPos.y = bodyButtonPos.yMax + this.WindowPos.yMin; this.bodyListPos.y = bodyButtonPos.yMax + this.WindowPos.yMin;
} }
   
if (GUILayout.Button("►")) if (GUILayout.Button("►"))
{ {
this.bodyIdx++; this.bodyIdx.value++;
} }
   
this.bodyIdx %= core.sortedBodyList.Count; this.bodyIdx.value %= core.SortedBodyList.Count;
   
if (this.bodyIdx < 0) if (this.bodyIdx < 0)
{ {
this.bodyIdx += core.sortedBodyList.Count; this.bodyIdx.value += core.SortedBodyList.Count;
} }
   
if (this.lastIdx != this.bodyIdx) if (this.lastIdx != this.bodyIdx)
{ {
this.lastIdx = this.bodyIdx; this.lastIdx = this.bodyIdx;
this.selectedBody = core.sortedBodyList[this.bodyIdx]; this.selectedBody = core.SortedBodyList[this.bodyIdx];
} }
   
  if (HighLogic.LoadedSceneIsEditor)
  {
  if (
  GUILayout.Button(
  this.showAdvanced ? "▲" : "▼",
  GUILayout.ExpandWidth(false)
  )
  )
  {
  this.showAdvanced = !this.showAdvanced;
  }
  }
   
  GUILayout.EndHorizontal();
  }
   
  if (this.showAdvanced && HighLogic.LoadedSceneIsEditor)
  {
  GUILayout.BeginHorizontal();
   
  this.useSeaLevel.value = GUITools.Toggle(this.useSeaLevel, this.seaLevelToggle, false);
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
   
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
   
if ( if (
GUILayout.Button("Engineering data powered by <i>VesselSimulator from KER</i>.", GUILayout.Button("Engineering data powered by <i>VesselSimulator from KER</i>.",
VOID_Styles.labelLink) VOID_Styles.labelLink)
) )
{ {
Application.OpenURL("http://forum.kerbalspaceprogram.com/threads/18230"); Application.OpenURL("http://forum.kerbalspaceprogram.com/threads/18230");
} }
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
   
public override void DrawConfigurables() public override void DrawConfigurables()
{ {
this.showColumnSelection = GUILayout.Toggle( this.showColumnSelection = GUILayout.Toggle(
this.showColumnSelection, this.showColumnSelection,
"Select StageInfo Columns", "Select StageInfo Columns",
GUI.skin.button GUI.skin.button
); );
} }
   
private void BodyPickerWindow(int _) private void BodyPickerWindow(int _)
{ {
foreach (CelestialBody body in core.sortedBodyList) foreach (CelestialBody body in core.SortedBodyList)
{ {
if (GUILayout.Button(body.bodyName, VOID_Styles.labelDefault)) if (GUILayout.Button(body.bodyName, VOID_Styles.labelDefault))
{ {
Debug.Log("Picked new body focus: " + body.bodyName); Debug.Log("Picked new body focus: " + body.bodyName);
this.bodyIdx = core.sortedBodyList.IndexOf(body); this.bodyIdx.value = core.SortedBodyList.IndexOf(body);
this.showBodyList = false; this.showBodyList = false;
} }
} }
} }
} }
} }
   
   
// 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 VOID_SaveValue<long> _precisionValues;
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;
   
  this._precisionValues = (VOID_SaveValue<long>)230584300921369395;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
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]); this.precisionValues[idx] = (ushort)VOID_Data.downrangeDistance.DoGUIHorizontal(this.precisionValues[idx]);
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");
   
this.precisionValues [idx]= (ushort)VOID_Data.atmDensity.DoGUIHorizontal (this.precisionValues [idx]); this.precisionValues [idx]= (ushort)VOID_Data.atmDensity.DoGUIHorizontal (this.precisionValues [idx]);
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();  
  base.ModuleWindow(id);
} }
   
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 Save (KSP.IO.PluginConfiguration config)
{ {
this._precisionValues = this.precisionValues.collection; this._precisionValues.value = this.precisionValues.collection;
   
base._SaveToConfig (config); base.Save (config);
} }
} }
} }
// VOID © 2014 toadicus // VOID © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
   
using KSP; using KSP;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
[VOID_Scenes(GameScenes.EDITOR, GameScenes.FLIGHT)] [VOID_Scenes(GameScenes.EDITOR, GameScenes.FLIGHT)]
public class VOID_TWR : VOID_WindowModule public class VOID_TWR : VOID_WindowModule
{ {
public VOID_TWR() : base() public VOID_TWR() : base()
{ {
this.Name = "IP Thrust-to-Weight Ratios"; this.Name = "IP Thrust-to-Weight Ratios";
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
if ( if (
!HighLogic.LoadedSceneIsFlight || !HighLogic.LoadedSceneIsFlight ||
(TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.WarpMode == TimeWarp.Modes.LOW) ||
(TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate) (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate)
) )
{ {
KerbalEngineer.VesselSimulator.SimManager.RequestSimulation(); KerbalEngineer.VesselSimulator.SimManager.RequestSimulation();
} }
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
if (core.sortedBodyList == null) if (core.SortedBodyList == null)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
GUILayout.Label("Unavailable"); GUILayout.Label("Unavailable");
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
else else
{ {
foreach (CelestialBody body in core.sortedBodyList) foreach (CelestialBody body in core.SortedBodyList)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
   
GUILayout.Label(body.bodyName); GUILayout.Label(body.bodyName);
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.Label( GUILayout.Label(
(VOID_Data.nominalThrustWeight.Value / body.GeeASL).ToString("0.0##"), (VOID_Data.nominalThrustWeight.Value / body.GeeASL).ToString("0.0##"),
GUILayout.ExpandWidth(true) GUILayout.ExpandWidth(true)
); );
   
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
} }
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
} }
} }
   
   
// VOID // VOID
// //
// VOID_Transfer.cs // VOID_Transfer.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.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_Transfer : VOID_WindowModule public class VOID_Transfer : VOID_WindowModule
{ {
protected List<CelestialBody> selectedBodies = new List<CelestialBody>(); protected List<CelestialBody> selectedBodies = new List<CelestialBody>();
   
public VOID_Transfer() : base() public VOID_Transfer() : base()
{ {
this.Name = "Transfer Angle Information"; this.Name = "Transfer Angle Information";
   
this.WindowPos.x = 475; this.WindowPos.x = 475;
this.WindowPos.y = 85; this.WindowPos.y = 85;
this.defWidth = 315; this.defWidth = 315;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
if (vessel.mainBody.name == "Sun") //Vessel is orbiting the Sun if (vessel.mainBody.name == "Sun") //Vessel is orbiting the Sun
{ {
foreach (CelestialBody body in vessel.mainBody.orbitingBodies) foreach (CelestialBody body in vessel.mainBody.orbitingBodies)
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button(body.bodyName)) if (GUILayout.Button(body.bodyName))
{ {
//add or remove this body to this list of bodies to display more info on //add or remove this body to this list of bodies to display more info on
if (selectedBodies.Contains(body)) selectedBodies.Remove(body); if (selectedBodies.Contains(body)) selectedBodies.Remove(body);
else selectedBodies.Add(body); else selectedBodies.Add(body);
} }
GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (selectedBodies.Contains(body)) if (selectedBodies.Contains(body))
{ {
VOID_Tools.display_transfer_angles_SUN2PLANET(body, vessel); //show phase angles for each selected body VOID_Tools.display_transfer_angles_SUN2PLANET(body, vessel); //show phase angles for each selected body
tad_targeting(body); //display Set/Unset Target button for each selected body tad_targeting(body); //display Set/Unset Target button for each selected body
} }
} }
} }
else if (vessel.mainBody.referenceBody.name == "Sun") //Vessel is orbiting a planet else if (vessel.mainBody.referenceBody.name == "Sun") //Vessel is orbiting a planet
{ {
foreach (CelestialBody body in vessel.mainBody.referenceBody.orbitingBodies) foreach (CelestialBody body in vessel.mainBody.referenceBody.orbitingBodies)
{ {
if (body.name != vessel.mainBody.name) // show other planets if (body.name != vessel.mainBody.name) // show other planets
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button(body.bodyName)) if (GUILayout.Button(body.bodyName))
{ {
//add or remove this body to this list of bodies to display more info on //add or remove this body to this list of bodies to display more info on
if (selectedBodies.Contains(body)) selectedBodies.Remove(body); if (selectedBodies.Contains(body)) selectedBodies.Remove(body);
else selectedBodies.Add(body); else selectedBodies.Add(body);
} }
GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (selectedBodies.Contains(body)) if (selectedBodies.Contains(body))
{ {
VOID_Tools.display_transfer_angles_PLANET2PLANET(body, vessel); VOID_Tools.display_transfer_angles_PLANET2PLANET(body, vessel);
tad_targeting(body); //display Set/Unset Target button tad_targeting(body); //display Set/Unset Target button
} }
} }
} }
foreach (CelestialBody body in vessel.mainBody.orbitingBodies) // show moons foreach (CelestialBody body in vessel.mainBody.orbitingBodies) // show moons
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button(body.bodyName)) if (GUILayout.Button(body.bodyName))
{ {
//add or remove this body to this list of bodies to display more info on //add or remove this body to this list of bodies to display more info on
if (selectedBodies.Contains(body)) selectedBodies.Remove(body); if (selectedBodies.Contains(body)) selectedBodies.Remove(body);
else selectedBodies.Add(body); else selectedBodies.Add(body);
} }
GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (selectedBodies.Contains(body)) if (selectedBodies.Contains(body))
{ {
VOID_Tools.display_transfer_angles_PLANET2MOON(body, vessel); VOID_Tools.display_transfer_angles_PLANET2MOON(body, vessel);
tad_targeting(body); //display Set/Unset Target button tad_targeting(body); //display Set/Unset Target button
} }
} }
} }
else if (vessel.mainBody.referenceBody.referenceBody.name == "Sun") // Vessel is orbiting a moon else if (vessel.mainBody.referenceBody.referenceBody.name == "Sun") // Vessel is orbiting a moon
{ {
foreach (CelestialBody body in vessel.mainBody.referenceBody.orbitingBodies) foreach (CelestialBody body in vessel.mainBody.referenceBody.orbitingBodies)
{ {
if (body.name != vessel.mainBody.name) // show other moons if (body.name != vessel.mainBody.name) // show other moons
{ {
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button(body.bodyName)) if (GUILayout.Button(body.bodyName))
{ {
//add or remove this body to this list of bodies to display more info on //add or remove this body to this list of bodies to display more info on
if (selectedBodies.Contains(body)) selectedBodies.Remove(body); if (selectedBodies.Contains(body)) selectedBodies.Remove(body);
else selectedBodies.Add(body); else selectedBodies.Add(body);
} }
GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false)); GUILayout.Label("Inclined " + body.orbit.inclination.ToString("F3") + "°", GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
if (selectedBodies.Contains(body)) if (selectedBodies.Contains(body))
{ {
VOID_Tools.display_transfer_angles_MOON2MOON(body, vessel); VOID_Tools.display_transfer_angles_MOON2MOON(body, vessel);
tad_targeting(body); //display Set/Unset Target button tad_targeting(body); //display Set/Unset Target button
} }
} }
} }
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
GUI.DragWindow();  
  base.ModuleWindow(id);
} }
   
private void tad_targeting(CelestialBody body) private void tad_targeting(CelestialBody body)
{ {
//Target Set/Unset buttons //Target Set/Unset buttons
if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() == null)) if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() == null))
{ {
//No TGT set or TGT is a Body //No TGT set or TGT is a Body
if ((CelestialBody)FlightGlobals.fetch.VesselTarget != body) if ((CelestialBody)FlightGlobals.fetch.VesselTarget != body)
{ {
if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false))) if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false)))
{ {
FlightGlobals.fetch.SetVesselTarget(body); FlightGlobals.fetch.SetVesselTarget(body);
Tools.PostDebugMessage("[VOID] KSP Target set to CelestialBody " + body.bodyName); Tools.PostDebugMessage("[VOID] KSP Target set to CelestialBody " + body.bodyName);
} }
} }
else if ((CelestialBody)FlightGlobals.fetch.VesselTarget == body) else if ((CelestialBody)FlightGlobals.fetch.VesselTarget == body)
{ {
if (GUILayout.Button("Unset Target", GUILayout.ExpandWidth(false))) if (GUILayout.Button("Unset Target", GUILayout.ExpandWidth(false)))
{ {
FlightGlobals.fetch.SetVesselTarget(null); FlightGlobals.fetch.SetVesselTarget(null);
Tools.PostDebugMessage("[VOID] KSP Target set to null"); Tools.PostDebugMessage("[VOID] KSP Target set to null");
} }
} }
} }
else if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() != null)) else if (FlightGlobals.fetch.VesselTarget == null || (FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget.GetVessel() != null))
{ {
//No TGT or TGT is a vessel //No TGT or TGT is a vessel
if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false))) if (GUILayout.Button("Set Target", GUILayout.ExpandWidth(false)))
{ {
FlightGlobals.fetch.SetVesselTarget(body); FlightGlobals.fetch.SetVesselTarget(body);
Tools.PostDebugMessage("[VOID] KSP Target set to CelestialBody " + body.bodyName); Tools.PostDebugMessage("[VOID] KSP Target set to CelestialBody " + body.bodyName);
} }
} }
} }
} }
} }
   
   
// VOID // VOID
// //
// VOID_VesselInfo.cs // VOID_VesselInfo.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 KerbalEngineer.VesselSimulator; using KerbalEngineer.VesselSimulator;
using KerbalEngineer.Extensions; using KerbalEngineer.Extensions;
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 class VOID_VesselInfo : VOID_WindowModule public class VOID_VesselInfo : VOID_WindowModule
{ {
public VOID_VesselInfo() : base() public VOID_VesselInfo() : base()
{ {
this.Name = "Vessel Information"; this.Name = "Vessel Information";
   
this.WindowPos.x = Screen.width - 260; this.WindowPos.x = Screen.width - 260;
this.WindowPos.y = 450; this.WindowPos.y = 450;
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
if ((TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate)) if ((TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate))
{ {
SimManager.RequestSimulation(); SimManager.RequestSimulation();
} }
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.Label( GUILayout.Label(
vessel.vesselName, vessel.vesselName,
VOID_Styles.labelCenterBold, VOID_Styles.labelCenterBold,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
   
VOID_Data.geeForce.DoGUIHorizontal ("F2"); VOID_Data.geeForce.DoGUIHorizontal ("F2");
   
VOID_Data.partCount.DoGUIHorizontal (); VOID_Data.partCount.DoGUIHorizontal ();
   
VOID_Data.totalMass.DoGUIHorizontal ("F3"); VOID_Data.totalMass.DoGUIHorizontal ("F3");
   
VOID_Data.stageResourceMass.DoGUIHorizontal("F2"); VOID_Data.stageResourceMass.DoGUIHorizontal("F2");
   
VOID_Data.resourceMass.DoGUIHorizontal("F2"); VOID_Data.resourceMass.DoGUIHorizontal("F2");
   
VOID_Data.stageDeltaV.DoGUIHorizontal (3, false); VOID_Data.stageDeltaV.DoGUIHorizontal (3, false);
   
VOID_Data.totalDeltaV.DoGUIHorizontal (3, false); VOID_Data.totalDeltaV.DoGUIHorizontal (3, false);
   
VOID_Data.mainThrottle.DoGUIHorizontal ("F0"); VOID_Data.mainThrottle.DoGUIHorizontal ("F0");
   
VOID_Data.currmaxThrust.DoGUIHorizontal (); VOID_Data.currmaxThrust.DoGUIHorizontal ();
   
VOID_Data.currmaxThrustWeight.DoGUIHorizontal (); VOID_Data.currmaxThrustWeight.DoGUIHorizontal ();
   
VOID_Data.surfaceThrustWeight.DoGUIHorizontal ("F2"); VOID_Data.surfaceThrustWeight.DoGUIHorizontal ("F2");
   
VOID_Data.intakeAirStatus.DoGUIHorizontal(); VOID_Data.intakeAirStatus.DoGUIHorizontal();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
} }
} }
   
// VOID // VOID
// //
// VOID_VesselRegister.cs // VOID_VesselRegister.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.Linq; using System.Linq;
using ToadicusTools; using ToadicusTools;
using UnityEngine; using UnityEngine;
   
namespace VOID namespace VOID
{ {
public class VOID_VesselRegister : VOID_WindowModule public class VOID_VesselRegister : VOID_WindowModule
{ {
[AVOID_SaveValue("selectedBodyIdx")] [AVOID_SaveValue("selectedBodyIdx")]
protected VOID_SaveValue<int> selectedBodyIdx = 0; protected VOID_SaveValue<int> selectedBodyIdx;
protected CelestialBody seletedBody; protected CelestialBody seletedBody;
   
[AVOID_SaveValue("selectedVesselTypeIdx")] [AVOID_SaveValue("selectedVesselTypeIdx")]
protected VOID_SaveValue<int> selectedVesselTypeIdx = 0; protected VOID_SaveValue<int> selectedVesselTypeIdx;
protected VesselType selectedVesselType; protected VesselType selectedVesselType;
   
protected string vesselSituation = "Orbiting"; protected string vesselSituation;
   
protected Vector2 selectorScrollPos = new Vector2(); protected Vector2 selectorScrollPos;
   
protected Vessel _selectedVessel; protected Vessel _selectedVessel;
   
public Vessel selectedVessel public Vessel selectedVessel
{ {
get get
{ {
return this._selectedVessel; return this._selectedVessel;
} }
} }
   
public VOID_VesselRegister() : base() public VOID_VesselRegister() : base()
{ {
this.Name = "Vessel Register"; this.Name = "Vessel Register";
   
this.WindowPos.x = 845; this.WindowPos.x = 845;
this.WindowPos.y = 275; this.WindowPos.y = 275;
this.defHeight = 375; this.defHeight = 375;
   
  this.selectedBodyIdx = (VOID_SaveValue<int>)0;
  this.selectedVesselTypeIdx = (VOID_SaveValue<int>)0;
   
  this.vesselSituation = "Orbiting";
   
  this.selectorScrollPos = new Vector2();
} }
   
public override void ModuleWindow(int _) public override void ModuleWindow(int id)
{ {
if (!this.core.allVesselTypes.Any()) if (!this.core.AllVesselTypes.Any())
{ {
return; return;
} }
   
GUILayout.BeginVertical(); GUILayout.BeginVertical();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("<")) if (GUILayout.Button("<"))
{ {
selectedBodyIdx--; selectedBodyIdx.value--;
if (selectedBodyIdx < 0) selectedBodyIdx = this.core.allBodies.Count - 1; if (selectedBodyIdx < 0)
  {
  selectedBodyIdx.value = this.core.AllBodies.Count - 1;
  }
} }
GUILayout.Label(this.core.allBodies[selectedBodyIdx].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true)); GUILayout.Label(this.core.AllBodies[selectedBodyIdx].bodyName, VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true));
if (GUILayout.Button(">")) if (GUILayout.Button(">"))
{ {
selectedBodyIdx++; selectedBodyIdx.value++;
if (selectedBodyIdx > this.core.allBodies.Count - 1) selectedBodyIdx = 0; if (selectedBodyIdx > this.core.AllBodies.Count - 1)
  {
  selectedBodyIdx.value = 0;
  }
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
seletedBody = this.core.allBodies[selectedBodyIdx]; seletedBody = this.core.AllBodies[selectedBodyIdx];
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("<")) if (GUILayout.Button("<"))
{ {
selectedVesselTypeIdx--; selectedVesselTypeIdx.value--;
if (selectedVesselTypeIdx < 0) selectedVesselTypeIdx = this.core.allVesselTypes.Count - 1; if (selectedVesselTypeIdx < 0)
  {
  selectedVesselTypeIdx.value = this.core.AllVesselTypes.Length - 1;
  }
} }
GUILayout.Label(this.core.allVesselTypes[selectedVesselTypeIdx].ToString(), VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true)); GUILayout.Label(this.core.AllVesselTypes[selectedVesselTypeIdx].ToString(), VOID_Styles.labelCenterBold, GUILayout.ExpandWidth(true));
if (GUILayout.Button(">")) if (GUILayout.Button(">"))
{ {
selectedVesselTypeIdx++; selectedVesselTypeIdx.value++;
if (selectedVesselTypeIdx > this.core.allVesselTypes.Count - 1) selectedVesselTypeIdx = 0; if (selectedVesselTypeIdx > this.core.AllVesselTypes.Length - 1)
  {
  selectedVesselTypeIdx.value = 0;
  }
} }
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
selectedVesselType = this.core.allVesselTypes[selectedVesselTypeIdx]; selectedVesselType = this.core.AllVesselTypes[selectedVesselTypeIdx];
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
if (GUILayout.Button("Landed", GUILayout.ExpandWidth(true))) vesselSituation = "Landed"; if (GUILayout.Button("Landed", GUILayout.ExpandWidth(true))) vesselSituation = "Landed";
if (GUILayout.Button("Orbiting", GUILayout.ExpandWidth(true))) vesselSituation = "Orbiting"; if (GUILayout.Button("Orbiting", GUILayout.ExpandWidth(true))) vesselSituation = "Orbiting";
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.Label( GUILayout.Label(
VOID_Tools.UppercaseFirst(vesselSituation) + " " + selectedVesselType.ToString() + "s @ " + seletedBody.bodyName, VOID_Tools.UppercaseFirst(vesselSituation) + " " + selectedVesselType.ToString() + "s @ " + seletedBody.bodyName,
VOID_Styles.labelCenter, VOID_Styles.labelCenter,
GUILayout.ExpandWidth(true)); GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
   
selectorScrollPos = GUILayout.BeginScrollView(selectorScrollPos, false, false); selectorScrollPos = GUILayout.BeginScrollView(selectorScrollPos, false, false);
   
foreach (Vessel v in FlightGlobals.Vessels) foreach (Vessel v in FlightGlobals.Vessels)
{ {
if (v != vessel && v.vesselType == selectedVesselType && v.mainBody == seletedBody) if (v != vessel && v.vesselType == selectedVesselType && v.mainBody == seletedBody)
{ {
if ((vesselSituation == "Landed" && if ((vesselSituation == "Landed" &&
(v.situation == Vessel.Situations.LANDED || (v.situation == Vessel.Situations.LANDED ||
v.situation == Vessel.Situations.PRELAUNCH || v.situation == Vessel.Situations.PRELAUNCH ||
v.situation == Vessel.Situations.SPLASHED)) || v.situation == Vessel.Situations.SPLASHED)) ||
(vesselSituation == "Orbiting" && (vesselSituation == "Orbiting" &&
(v.situation == Vessel.Situations.ESCAPING || (v.situation == Vessel.Situations.ESCAPING ||
v.situation == Vessel.Situations.FLYING || v.situation == Vessel.Situations.FLYING ||
v.situation == Vessel.Situations.ORBITING || v.situation == Vessel.Situations.ORBITING ||
v.situation == Vessel.Situations.SUB_ORBITAL)) v.situation == Vessel.Situations.SUB_ORBITAL))
) )
{ {
if (GUILayout.Button(v.vesselName, GUILayout.ExpandWidth(true))) if (GUILayout.Button(v.vesselName, GUILayout.ExpandWidth(true)))
{ {
if (_selectedVessel != v) if (_selectedVessel != v)
{ {
_selectedVessel = v; //set clicked vessel as selected_vessel _selectedVessel = v; //set clicked vessel as selected_vessel
this.toggleActive = true; //turn bool on to open the window if closed this.toggleActive = true; //turn bool on to open the window if closed
} }
else else
{ {
_selectedVessel = null; _selectedVessel = null;
} }
} }
} }
} }
} }
   
GUILayout.EndScrollView(); GUILayout.EndScrollView();
   
GUILayout.EndVertical(); GUILayout.EndVertical();
   
GUI.DragWindow(); base.ModuleWindow(id);
} }
} }
} }