├── .gitattributes ├── HyperEdit.version ├── changelog.txt ├── Source ├── Model │ ├── SmaAligner.cs │ ├── SiSuffix.cs │ ├── MiscEditor.cs │ ├── OrbitEditor.cs │ ├── PlanetEditor.cs │ └── Lander.cs ├── View │ ├── AboutWindow.cs │ ├── SmaAlignerView.cs │ ├── CoreView.cs │ ├── MiscEditorView.cs │ ├── LanderView.cs │ ├── Window.cs │ ├── PlanetEditorView.cs │ ├── View.cs │ └── OrbitEditorView.cs └── Core.cs ├── README.md ├── GameData └── Kerbaltek │ └── HyperEdit │ └── README.md ├── HyperEdit.sln ├── .gitignore ├── HyperEdit.csproj └── LICENSE.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /HyperEdit.version: -------------------------------------------------------------------------------- 1 | { 2 | "NAME": "HyperEdit", 3 | "URL": "https://raw.githubusercontent.com/Ezriilc/HyperEdit/master/HyperEdit.version", 4 | "DOWNLOAD": "http://www.kerbaltek.com/hyperedit", 5 | "VERSION": { 6 | "MAJOR": 1, 7 | "MINOR": 5, 8 | "PATCH": 8, 9 | "BUILD": 0 10 | }, 11 | "KSP_VERSION": { 12 | "MAJOR": 1, 13 | "MINOR": 9, 14 | "PATCH": 0 15 | }, 16 | "KSP_VERSION_MIN": { 17 | "MAJOR": 1, 18 | "MINOR": 3, 19 | "PATCH": 1 20 | }, 21 | "KSP_VERSION_MAX": { 22 | "MAJOR": 1, 23 | "MINOR": 12, 24 | "PATCH": 99 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /changelog.txt: -------------------------------------------------------------------------------- 1 | 2 | 2017-12-31: Fix for #41 - Landing vessels near each other doesn't space them miles/kilometres apart. 3 | 4 | 2017-12-27: Change default boost key to Right-Ctrl + B as it was conflicting with the default throttle. 5 | Put config files in PluginData directory inside HyperEdit directory. 6 | Changed Lander view to show altitude above terrain as current altitude instead of ASL. 7 | 8 | 2017-12-26: Reinstated original folder structure for saved settings files. 9 | 10 | 2017-12-23: Make resources area scrollable for now. Added this file (changelog). 11 | 12 | 2017-12-22: Kill time warp during landing logic (to account for some erroneous bugs). 13 | 14 | 2017-12-21: Updated landing logic for KSP 1.3.1. See #29 - https://github.com/Ezriilc/HyperEdit/issues/29 15 | -------------------------------------------------------------------------------- /Source/Model/SmaAligner.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace HyperEdit.Model 5 | { 6 | public static class SmaAligner 7 | { 8 | public static List AvailableVessels => FlightGlobals.fetch?.vessels ?? new List(); 9 | 10 | public static void Align(List vesselsToAlign) 11 | { 12 | vesselsToAlign.RemoveAll(v => AvailableVessels.All(a => a.id != v.id)); 13 | 14 | var averageSma = vesselsToAlign.Average(v => v.orbit.semiMajorAxis); 15 | foreach (var vessel in vesselsToAlign) 16 | { 17 | var orbit = vessel.orbit.Clone(); 18 | orbit.semiMajorAxis = averageSma; 19 | vessel.SetOrbit(orbit); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Source/View/AboutWindow.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using UnityEngine; 3 | 4 | namespace HyperEdit.View 5 | { 6 | public static class AboutWindow 7 | { 8 | public static Action Create() 9 | { 10 | return () => Window.Create("About", true, true, 500, 200, w => GUILayout.Label(AboutContents)); 11 | } 12 | 13 | private const string AboutContents = @"For support and contact information, please visit: http://www.kerbaltek.com/ 14 | 15 | This is a highly eccentric plugin, so there may be lots of bugs and explosions - please tell us if you find any. 16 | 17 | Created by: 18 | khyperia (original creator, code) 19 | Ezriilc (web, code) 20 | sirkut (code) 21 | payo (code [Planet Editor]) 22 | forecaster (graphics, logo) 23 | 24 | GPL license. Opensource at https://github.com/Ezriilc/HyperEdit"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | HyperEdit 2 | ========= 3 | 4 | A plugin for Kerbal Space Program, proudly maintained by Kerbaltek. 5 | 6 | To use this mod, DO NOT DOWNLOAD FROM THIS REPO, as it only contains the source code and not the actual binary .dll file. All releases will be on our own site: http://www.Kerbaltek.com/hyperedit 7 | 8 | Please talk to us on our site: http://www.Kerbaltek.com/contact 9 | Or, on the KSP forum at the link on our site. 10 | 11 | Pull requests are always welcome, as is any other input. In fact, we rely on contributions to keep our projects going. 12 | 13 | Please leave our .version file as it is. That's only here for CKAN, and it will be changed manually by the owner when we package the mod for release. 14 | 15 | To build: 16 | Change the .csproj file where notated to suit your own setup, but please keep it out of your commits when pushing or making a pull request. 17 | 18 | VS2015+ is required, or other C#6 compliant C# compiler (khyperia uses mono 4.2.2, Ezriilc uses VS2019 Community) 19 | -------------------------------------------------------------------------------- /GameData/Kerbaltek/HyperEdit/README.md: -------------------------------------------------------------------------------- 1 | HyperEdit 2 | ========= 3 | 4 | A plugin for Kerbal Space Program, proudly maintained by Kerbaltek. 5 | 6 | To use this mod, DO NOT DOWNLOAD FROM THIS REPO, as it only contains the source code and not the actual binary .dll file. All releases will be on our own site: http://www.Kerbaltek.com/hyperedit 7 | 8 | Please talk to us on our site: http://www.Kerbaltek.com/contact 9 | Or, on the KSP forum at the link on our site. 10 | 11 | Pull requests are always welcome, as is any other input. In fact, we rely on contributions to keep our projects going. 12 | 13 | Please leave our .version file as it is. That's only here for CKAN, and it will be changed manually by the owner when we package the mod for release. 14 | 15 | To build: 16 | Change the .csproj file where notated to suit your own setup, but please keep it out of your commits when pushing or making a pull request. 17 | 18 | VS2015+ is required, or other C#6 compliant C# compiler (khyperia uses mono 4.2.2, Ezriilc uses VS2019 Community) 19 | -------------------------------------------------------------------------------- /HyperEdit.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.14.36109.1 d17.14 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HyperEdit", "HyperEdit.csproj", "{2FF6FC29-02C3-489C-9EFE-B913973AF85B}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {2FF6FC29-02C3-489C-9EFE-B913973AF85B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {2FF6FC29-02C3-489C-9EFE-B913973AF85B}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {2FF6FC29-02C3-489C-9EFE-B913973AF85B}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {2FF6FC29-02C3-489C-9EFE-B913973AF85B}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {75D9E3B8-F5D3-4E44-B3A9-66589AA52177} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Source/View/SmaAlignerView.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections.Generic; 3 | 4 | namespace HyperEdit.View 5 | { 6 | public static class SmaAlignerView 7 | { 8 | public static void Create() 9 | { 10 | var view = View(); 11 | Window.Create("SMA Aligner", true, true, 300, -1, w => view.Draw()); 12 | } 13 | 14 | public static IView View() 15 | { 16 | var scrollPos = new Vector2(0, 0); 17 | var vesselsToAlign = new List(); 18 | var vesselList = new CustomView(() => 19 | { 20 | scrollPos = GUILayout.BeginScrollView(scrollPos, GUILayout.MinHeight(300)); 21 | vesselsToAlign.RemoveAll(v => !Model.SmaAligner.AvailableVessels.Contains(v)); 22 | foreach (var vessel in Model.SmaAligner.AvailableVessels) 23 | { 24 | var alreadyIn = vesselsToAlign.Contains(vessel); 25 | var newIn = GUILayout.Toggle(alreadyIn, vessel.vesselName); 26 | if (!alreadyIn && newIn) 27 | vesselsToAlign.Add(vessel); 28 | if (alreadyIn && !newIn) 29 | vesselsToAlign.Remove(vessel); 30 | } 31 | GUILayout.EndScrollView(); 32 | }); 33 | var align = new ConditionalView(() => vesselsToAlign.Count > 1, 34 | new ButtonView("Align", "Sets all semi-major axes of selected vessels to be equal, so they all have the same period", 35 | () => Model.SmaAligner.Align(vesselsToAlign))); 36 | 37 | return new VerticalView(new IView[] 38 | { 39 | vesselList, 40 | align 41 | }); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Source/View/CoreView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HyperEdit.View 4 | { 5 | public static class CoreView 6 | { 7 | public static Action Create(HyperEditBehaviour hyperedit) 8 | { 9 | var view = View(hyperedit); 10 | return () => Window.Create("HyperEdit", true, true, 120, -1, w => view.Draw()); 11 | } 12 | 13 | public static IView View(HyperEditBehaviour hyperedit) 14 | { 15 | var orbitEditorView = OrbitEditorView.Create(); 16 | var planetEditorView = PlanetEditorView.Create(); 17 | var landerView = LanderView.Create(); 18 | var miscEditorView = MiscEditorView.Create(); 19 | var aboutView = AboutWindow.Create(); 20 | 21 | var closeAll = new ButtonView("Close all", "Closes all windows", Window.CloseAll); 22 | var orbitEditor = new ButtonView("Orbit Editor", "Opens the Orbit Editor window", orbitEditorView); 23 | var planetEditor = new ButtonView("Planet Editor", "Opens the Planet Editor window", planetEditorView); 24 | var shipLander = new ButtonView("Ship Lander", "Opens the Ship Lander window", landerView); 25 | var miscTools = new ButtonView("Misc Tools", "Opens the Misc Tools window", miscEditorView); 26 | //var debugMenu = new ButtonView("KSP Debug Menu", "Opens the KSP Debug Toolbar (also available with Mod+F12)", () => DebugToolbar.toolbarShown = true); // !DebugToolbar.toolbarShown); 27 | var about = new ButtonView("About", "Opens the About window", aboutView); 28 | var appLauncher = new DynamicToggleView("H-Button", 29 | "Enables or disables the AppLauncher button (top right H button)", 30 | () => hyperedit.UseAppLauncherButton, () => true, v => hyperedit.UseAppLauncherButton = v); 31 | 32 | return new VerticalView(new IView[] 33 | { 34 | closeAll, 35 | orbitEditor, 36 | planetEditor, 37 | shipLander, 38 | miscTools, 39 | //debugMenu, 40 | about, 41 | appLauncher 42 | }); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | [Bb]in/ 4 | [Oo]bj/ 5 | BuildOutput/ 6 | Properties/ 7 | lib/ 8 | DTAR*/ 9 | 10 | # User-specific files 11 | *.suo 12 | *.sln 13 | *.sln.docstates 14 | *.user 15 | *.userprefs 16 | 17 | HyperEdit.fronbow.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Rr]elease/ 22 | x64/ 23 | *_i.c 24 | *_p.c 25 | *.ilk 26 | *.meta 27 | *.obj 28 | *.pch 29 | *.pdb 30 | *.pgc 31 | *.pgd 32 | *.rsp 33 | *.sbr 34 | *.tlb 35 | *.tli 36 | *.tlh 37 | *.tmp 38 | *.log 39 | *.vspscc 40 | *.vssscc 41 | .builds 42 | *.dotCover 43 | .vs/ 44 | 45 | # Visual C++ cache files 46 | ipch/ 47 | *.aps 48 | *.ncb 49 | *.opensdf 50 | *.sdf 51 | 52 | # Visual Studio profiler 53 | *.psess 54 | *.vsp 55 | *.vspx 56 | 57 | # Guidance Automation Toolkit 58 | *.gpState 59 | 60 | # ReSharper is a .NET coding add-in 61 | _ReSharper* 62 | 63 | # NCrunch 64 | *.ncrunch* 65 | .*crunch*.local.xml 66 | 67 | # Installshield output folder 68 | [Ee]xpress 69 | 70 | # DocProject is a documentation generator add-in 71 | DocProject/buildhelp/ 72 | DocProject/Help/*.HxT 73 | DocProject/Help/*.HxC 74 | DocProject/Help/*.hhc 75 | DocProject/Help/*.hhk 76 | DocProject/Help/*.hhp 77 | DocProject/Help/Html2 78 | DocProject/Help/html 79 | 80 | # Click-Once directory 81 | publish 82 | 83 | # Publish Web Output 84 | *.Publish.xml 85 | 86 | # NuGet Packages Directory 87 | packages 88 | 89 | # Windows Azure Build Output 90 | csx 91 | *.build.csdef 92 | 93 | # Windows Store app package directory 94 | AppPackages/ 95 | 96 | # Others 97 | [Bb]in 98 | [Oo]bj 99 | sql 100 | TestResults 101 | [Tt]est[Rr]esult* 102 | *.Cache 103 | ClientBin 104 | [Ss]tyle[Cc]op.* 105 | ~$* 106 | *.dbmdl 107 | Generated_Code #added for RIA/Silverlight projects 108 | myVSProject.zip 109 | 110 | # Backup & report files from converting an old project file to a newer 111 | # Visual Studio version. Backup files are not needed, because we have git ;-) 112 | _UpgradeReport_Files/ 113 | Backup*/ 114 | UpgradeLog*.XML 115 | 116 | # Monodevelop 117 | *.userprefs 118 | 119 | .vs/ 120 | 121 | # JetBrains Rider 122 | .idea/ 123 | HyperEdit.sln.iml 124 | /HyperEdit.csproj.old 125 | *.wip 126 | -------------------------------------------------------------------------------- /Source/Model/SiSuffix.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | using UnityEngine; 6 | 7 | namespace HyperEdit.Model 8 | { 9 | public static class SiSuffix 10 | { 11 | private static readonly Dictionary Suffixes = new Dictionary 12 | { 13 | { "Y", 1e24 }, 14 | { "Z", 1e21 }, 15 | { "E", 1e18 }, 16 | { "P", 1e15 }, 17 | { "T", 1e12 }, 18 | { "G", 1e9 }, 19 | { "M", 1e6 }, 20 | { "k", 1e3 }, 21 | { "h", 1e2 }, 22 | { "da", 1e1 }, 23 | 24 | { "d", 1e-1 }, 25 | { "c", 1e-2 }, 26 | { "m", 1e-3 }, 27 | { "u", 1e-6 }, 28 | { "n", 1e-9 }, 29 | { "p", 1e-12 }, 30 | { "f", 1e-15 }, 31 | { "a", 1e-18 }, 32 | { "z", 1e-21 }, 33 | { "y", 1e-24 } 34 | }; 35 | 36 | public static bool TryParse(string s, out float value) 37 | { 38 | double dval; 39 | var success = TryParse(s, out dval); 40 | value = (float)dval; 41 | return success; 42 | } 43 | 44 | public static bool TryParse(string s, out double value) 45 | { 46 | s = s.Trim(); 47 | double multiplier; 48 | var suffix = Suffixes.FirstOrDefault(suf => s.EndsWith(suf.Key, StringComparison.Ordinal)); 49 | if (suffix.Key != null) 50 | { 51 | s = s.Substring(0, s.Length - suffix.Key.Length); 52 | multiplier = suffix.Value; 53 | } 54 | else 55 | multiplier = 1.0; 56 | if (double.TryParse(s, out value) == false) 57 | return false; 58 | value *= multiplier; 59 | return true; 60 | } 61 | 62 | public static bool TryParse(string s, out FloatCurve value) 63 | { 64 | value = new FloatCurve(); 65 | try { 66 | JsonUtility.FromJsonOverwrite(s, value); 67 | return true; 68 | } catch (Exception e) { 69 | return false; 70 | } 71 | } 72 | 73 | public static bool TryParse(string s, out String value) { 74 | value = s; 75 | return true; 76 | } 77 | 78 | public static bool TryParseFloatCurve(string s, out string value) { 79 | value = s; 80 | FloatCurve floatCurve; 81 | return TryParse(s, out floatCurve); 82 | } 83 | 84 | /* 85 | // Not currently used. Si suffixes are unnecessary and confusing. Possibly useful with modification for clarity and practicality. 86 | public static string ToString(this double value) 87 | { 88 | var log = Math.Log10(Math.Abs(value)); 89 | var minDiff = double.MaxValue; 90 | var minSuffix = new KeyValuePair("", 1); 91 | foreach (var suffix in Suffixes.Concat(new[] { new KeyValuePair("", 1) })) 92 | { 93 | var diff = Math.Abs(log - Math.Log10(suffix.Value)); 94 | if (diff < minDiff) 95 | { 96 | minDiff = diff; 97 | minSuffix = suffix; 98 | } 99 | } 100 | value /= minSuffix.Value; 101 | return value.ToString("F") + minSuffix.Key; 102 | } 103 | */ 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /HyperEdit.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Release 6 | AnyCPU 7 | {2FF6FC29-02C3-489C-9EFE-B913973AF85B} 8 | Library 9 | HyperEdit 10 | $(AssemblyName) 11 | $(AssemblyName).dll 12 | v4.8 13 | prompt 14 | 4 15 | false 16 | true 17 | true 18 | 21 | C:\Games\KSP_win64 22 | $(KspInstallDir)\GameData\Kerbaltek 23 | $(KspInstallDir)\KSP_x64_Data\Managed 24 | 25 | 26 | 27 | true 28 | full 29 | false 30 | bin\Debug 31 | DEBUG; 32 | false 33 | false 34 | 35 | 36 | true 37 | bin\Release 38 | false 39 | false 40 | 41 | 42 | 43 | $(KspLibPath)\Assembly-CSharp.dll 44 | 45 | 46 | $(KspLibPath)\Assembly-CSharp-firstpass.dll 47 | 48 | 49 | 50 | $(KspLibPath)\UnityEngine.dll 51 | 52 | 53 | $(KspLibPath)\UnityEngine.AnimationModule.dll 54 | 55 | 56 | $(KspLibPath)\UnityEngine.CoreModule.dll 57 | 58 | 59 | $(KspLibPath)\UnityEngine.IMGUIModule.dll 60 | 61 | 62 | $(KspLibPath)\UnityEngine.PhysicsModule.dll 63 | 64 | 65 | $(KspLibPath)\UnityEngine.InputLegacyModule.dll 66 | 67 | 68 | $(KspLibPath)\UnityEngine.JSONSerializeModule.dll 69 | 70 | 71 | $(KspLibPath)\UnityEngine.UI.dll 72 | 73 | 74 | $(KspLibPath)\mscorlib.dll 75 | 76 | 77 | $(KspLibPath)\System.Core.dll 78 | 79 | 80 | $(KspLibPath)\KSPAssets.dll 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /Source/View/MiscEditorView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using UnityEngine; 3 | 4 | namespace HyperEdit.View { 5 | public class MiscEditorView { 6 | private static ConfigNode _toggleRes; 7 | private static int vwidth = 300; //View width (needed for scrollviews) 8 | private static int vheight = -1; //View height 9 | private static Vector2 scrollPosition; 10 | 11 | public static Action Create() { 12 | var view = View(); 13 | //return () => Window.Create("Misc tools", true, true, 300, -1, w => view.Draw()); 14 | return () => Window.Create("Misc tools", true, true, vwidth, vheight, w => view.Draw()); 15 | } 16 | 17 | public static IView View() { 18 | ReloadConfig(); 19 | 20 | Action resources = () => { 21 | //Using the Vertical to set the box height. 22 | GUILayout.BeginVertical(GUILayout.Height(100)); 23 | scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.MinHeight(140)); 24 | 25 | foreach (var resource in Model.MiscEditor.GetResources()) { 26 | GUILayout.BeginHorizontal(); 27 | GUILayout.Label(resource.Key); 28 | var newval = (double)GUILayout.HorizontalSlider((float)resource.Value, 0, 1); 29 | if (Math.Abs(newval - resource.Value) > 0.001) { 30 | Model.MiscEditor.SetResource(resource.Key, newval); 31 | } 32 | //Just trying an idea 33 | //toggleRes = GUILayout.Toggle(toggleRes[resource.Key], "lock"); 34 | //toggleRes = GUILayout.Toggle(toggleRes, "lock"); 35 | /* 36 | * It'd be nice to lock inf resources for specific vessels, or maybe just any vessel? 37 | */ 38 | 39 | //GUILayout.FlexibleSpace(); 40 | GUILayout.Space(5); 41 | GUILayout.EndHorizontal(); 42 | } 43 | GUILayout.FlexibleSpace(); 44 | GUILayout.EndScrollView(); 45 | GUILayout.EndVertical(); 46 | 47 | }; 48 | var setTimeButtonView = new TextBoxView("Time", "Set time (aka UniversalTime)", 49 | Model.MiscEditor.UniversalTime, Model.SiSuffix.TryParse, null, 50 | v => Model.MiscEditor.UniversalTime = v); 51 | var timeIncrementButtonView = new TextBoxView("Increment", "Set time increment (used for + and - buttons)", 52 | 1, Model.SiSuffix.TryParse, null, null); 53 | Action timeButtons = () => 54 | { 55 | GUILayout.BeginHorizontal(); 56 | if (GUILayout.Button("-")) setTimeButtonView.Object = Model.MiscEditor.DecrementYear(timeIncrementButtonView.Object); 57 | GUILayout.Label("Year"); 58 | if (GUILayout.Button("+")) setTimeButtonView.Object = Model.MiscEditor.IncrementYear(timeIncrementButtonView.Object); 59 | 60 | GUILayout.Space(25); 61 | 62 | if (GUILayout.Button("-")) setTimeButtonView.Object = Model.MiscEditor.DecrementDay(timeIncrementButtonView.Object); 63 | GUILayout.Label("Day"); 64 | if (GUILayout.Button("+")) setTimeButtonView.Object = Model.MiscEditor.IncrementDay(timeIncrementButtonView.Object); 65 | 66 | GUILayout.Space(25); 67 | 68 | if (GUILayout.Button("-")) setTimeButtonView.Object = Model.MiscEditor.DecrementHour(timeIncrementButtonView.Object); 69 | GUILayout.Label("Hour"); 70 | if (GUILayout.Button("+")) setTimeButtonView.Object = Model.MiscEditor.IncrementHour(timeIncrementButtonView.Object); 71 | GUILayout.EndHorizontal(); 72 | }; 73 | return new VerticalView(new IView[] 74 | { 75 | new LabelView("Resources", "Set amounts of various resources contained on the active vessel"), 76 | new CustomView(resources), 77 | setTimeButtonView, 78 | new CustomView(timeButtons), 79 | timeIncrementButtonView, 80 | new ButtonView("Align SMAs", "Open the semi-major axis aligner window", 81 | Model.MiscEditor.AlignSemiMajorAxis), 82 | new ButtonView("Destroy a vessel", "Select a vessel to destroy", Model.MiscEditor.DestroyVessel), 83 | new TextBoxView("Boost button key", "Sets the keybinding used for the boost button", 84 | Model.MiscEditor.BoostButtonKey, Extensions.KeyCodeTryParse, Extensions.KeyCodeToString, 85 | v => Model.MiscEditor.BoostButtonKey = v), 86 | new TextBoxView("Boost button speed", 87 | "Sets the dV applied per frame when the boost button is held down", 88 | Model.MiscEditor.BoostButtonSpeed, Model.SiSuffix.TryParse, null, 89 | v => Model.MiscEditor.BoostButtonSpeed = v) 90 | }); 91 | } 92 | 93 | private static void ReloadConfig() { 94 | var hypereditCfg = IoExt.GetPath("miscoptions.cfg"); 95 | if (System.IO.File.Exists(hypereditCfg)) { 96 | _toggleRes = ConfigNode.Load(hypereditCfg); 97 | _toggleRes.name = "miscoptions"; 98 | } else { 99 | _toggleRes = new ConfigNode("miscoptions"); 100 | } 101 | 102 | //var autoOpenLanderValue = true; 103 | //_toggleRes.TryGetValue("AutoOpenLander", ref autoOpenLanderValue, bool.TryParse); 104 | //AutoOpenLander = autoOpenLanderValue; 105 | 106 | 107 | } 108 | } 109 | } -------------------------------------------------------------------------------- /Source/Model/MiscEditor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using UnityEngine; 4 | 5 | namespace HyperEdit.Model 6 | { 7 | public static class MiscEditor 8 | { 9 | public static void DestroyVessel() 10 | { 11 | if (FlightGlobals.fetch == null || FlightGlobals.Vessels == null) 12 | View.WindowHelper.Error("Could not get list of vessels"); 13 | else 14 | View.WindowHelper.Selector("Destroy...", FlightGlobals.Vessels, v => v.vesselName, v => v.Die()); 15 | } 16 | 17 | public static double UniversalTime 18 | { 19 | get { return Planetarium.GetUniversalTime(); } 20 | set { Planetarium.SetUniversalTime(value); Extensions.Log("Set Planetarium.UniversalTime to " + value); } 21 | } 22 | 23 | // time intervals in seconds 24 | static readonly int Hour = 3600; 25 | static readonly int Day = 6 * Hour; 26 | static readonly int Year = 426 * Day; 27 | 28 | public static double IncrementYear(double multiplier) { UniversalTime += Year * multiplier; return UniversalTime; } 29 | public static double DecrementYear(double multiplier) { UniversalTime -= Year * multiplier; return UniversalTime; } 30 | public static double IncrementDay(double multiplier) { UniversalTime += Day * multiplier; return UniversalTime; } 31 | public static double DecrementDay(double multiplier) { UniversalTime -= Day * multiplier; return UniversalTime; } 32 | public static double IncrementHour(double multiplier) { UniversalTime += Hour * multiplier; return UniversalTime; } 33 | public static double DecrementHour(double multiplier) { UniversalTime -= Hour * multiplier; return UniversalTime; } 34 | 35 | public static void AlignSemiMajorAxis() 36 | { 37 | View.SmaAlignerView.Create(); 38 | } 39 | 40 | public static void RefillVesselResources() 41 | { 42 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) 43 | return; 44 | RefillVesselResources(FlightGlobals.ActiveVessel); 45 | } 46 | 47 | public static IEnumerable> GetResources() 48 | { 49 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) 50 | return new KeyValuePair[0]; 51 | return GetResources(FlightGlobals.ActiveVessel); 52 | } 53 | 54 | public static IEnumerable> GetResources(Vessel vessel) 55 | { 56 | if (vessel.parts == null) 57 | return new KeyValuePair[0]; 58 | return vessel.parts 59 | .SelectMany(part => part.Resources.Cast()) 60 | .GroupBy(p => p.resourceName) 61 | .Select(g => new KeyValuePair(g.Key, g.Sum(x => x.amount) / g.Sum(x => x.maxAmount))); 62 | } 63 | 64 | public static void SetResource(string key, double value) 65 | { 66 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) 67 | return; 68 | SetResource(FlightGlobals.ActiveVessel, key, value); 69 | } 70 | 71 | private static readonly object SetResourceLogObject = new object(); 72 | private static void SetResource(Vessel vessel, string key, double value) 73 | { 74 | if (vessel.parts == null) 75 | return; 76 | foreach (var part in vessel.parts) 77 | { 78 | //foreach(PartResource resource in part.Resources) 79 | int resourceCount = part.Resources.Count; 80 | for(int i = 0; i < resourceCount; ++i) { 81 | PartResource resource = part.Resources[i]; 82 | if (resource.resourceName == key) 83 | { 84 | part.TransferResource(resource.info.id, resource.maxAmount * value - resource.amount); 85 | RateLimitedLogger.Log(SetResourceLogObject, 86 | $"Set part \"{part.partName}\"'s resource \"{resource.resourceName}\" to {value*100}% by requesting {resource.maxAmount*value - resource.amount} from it"); 87 | } 88 | } 89 | } 90 | } 91 | 92 | public static void RefillVesselResources(Vessel vessel) 93 | { 94 | if (vessel.parts == null) 95 | return; 96 | foreach (var part in vessel.parts) 97 | { 98 | //foreach(PartResource resource in part.Resources) 99 | int resourceCount = part.Resources.Count; 100 | for(int i = 0; i < resourceCount; ++i) { 101 | PartResource resource = part.Resources[i]; 102 | 103 | part.TransferResource(resource.info.id, resource.maxAmount - resource.amount); 104 | Extensions.Log( 105 | $"Refilled part \"{part.partName}\"'s resource \"{resource.resourceName}\" by requesting {resource.maxAmount - resource.amount} from it"); 106 | } 107 | } 108 | } 109 | 110 | public static KeyCode[] BoostButtonKey 111 | { 112 | get { 113 | return BoostListener.Fetch.Keys; 114 | } 115 | set { 116 | BoostListener.Fetch.Keys = value; 117 | //Save value to config file 118 | } 119 | } 120 | 121 | public static double BoostButtonSpeed 122 | { 123 | get { return BoostListener.Fetch.Speed; } 124 | set { BoostListener.Fetch.Speed = value; } 125 | } 126 | } 127 | 128 | public class BoostListener : MonoBehaviour 129 | { 130 | private static BoostListener _fetch; 131 | 132 | public static BoostListener Fetch 133 | { 134 | get 135 | { 136 | if (_fetch == null) 137 | { 138 | var go = new GameObject("HyperEditBoostListener"); 139 | DontDestroyOnLoad(go); 140 | _fetch = go.AddComponent(); 141 | } 142 | return _fetch; 143 | } 144 | } 145 | 146 | private bool _doBoost; 147 | private readonly object _boostLogObject = new object(); 148 | 149 | public KeyCode[] Keys { get; set; } = { KeyCode.RightControl, KeyCode.B }; 150 | 151 | public double Speed { get; set; } 152 | 153 | public void Update() 154 | { 155 | _doBoost = Keys.Length > 0 && Keys.All(Input.GetKey); 156 | } 157 | 158 | public void FixedUpdate() 159 | { 160 | if (_doBoost == false) 161 | return; 162 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) 163 | { 164 | _doBoost = false; 165 | return; 166 | } 167 | var vessel = FlightGlobals.ActiveVessel; 168 | var toAdd = vessel.transform.up; 169 | toAdd *= (float)Speed; 170 | vessel.ChangeWorldVelocity(toAdd); 171 | RateLimitedLogger.Log(_boostLogObject, 172 | $"Booster changed vessel's velocity by {toAdd.x},{toAdd.y},{toAdd.z} (mag {toAdd.magnitude})"); 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /Source/View/LanderView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HyperEdit.View 4 | { 5 | public static class LanderView 6 | { 7 | 8 | private static bool _autoOpenLander; 9 | private static ConfigNode _hyperEditConfig; 10 | 11 | public static Action Create() 12 | { 13 | var view = View(); 14 | return () => Window.Create("Lander", true, true, 200, -1, w => view.Draw()); 15 | } 16 | 17 | // Use myTryParse to validate the string, and, if it is 0, to set it to 0.001f 18 | static bool myTryParse(string str, out double d) 19 | { 20 | double d1; 21 | bool b = double.TryParse(str, out d1); 22 | if (!b) 23 | { 24 | d = 0.001f; 25 | return false; 26 | } 27 | if (d1 == 0) 28 | d1 = 0.001d; 29 | d = d1; 30 | return true; 31 | } 32 | /* 33 | static bool lonTryParse(string str, out double result) { 34 | result = null; 35 | double d1; 36 | //Extensions.DegreeFix(str, 0); 37 | bool b = double.TryParse(str, out d1); 38 | 39 | if (!b) { 40 | result = 0.001f; 41 | return false; 42 | } else { 43 | 44 | d1 = Extensions.DegreeFix(result, 0); 45 | 46 | return true; 47 | } 48 | return true; 49 | 50 | } 51 | */ 52 | 53 | static bool latTryParse(string str, out double d) 54 | { 55 | double d1; 56 | double highLimit = 89.9d; 57 | double lowLimit = -89.9d; 58 | bool b = double.TryParse(str, out d1); 59 | if (!b) 60 | { 61 | d = 0.001f; 62 | return false; 63 | } 64 | if (d1 == 0) 65 | { 66 | d = 0.001d; 67 | return true; 68 | } 69 | if (d1 > highLimit) 70 | { 71 | d = highLimit; 72 | return false; 73 | } 74 | if (d1 < lowLimit) 75 | { 76 | d = lowLimit; 77 | return false; 78 | } 79 | //d = d1; 80 | //Getting absolute latitude value 81 | double absD1 = Math.Abs(d1); 82 | //Passing absolute value to degreefix. Changing the sign of the return value back to the right one 83 | d = Math.Sign(d1) * Extensions.DegreeFix(absD1, 0); //checking for massive values 84 | return true; 85 | } 86 | static bool altTryParse(string str, out double d) 87 | { 88 | double d1; 89 | double lowLimit = 0.0d; 90 | bool b = Model.SiSuffix.TryParse(str, out d1); 91 | if (!b) 92 | { 93 | d = 0.001f; 94 | return false; 95 | } 96 | if (d1 == 0) 97 | { 98 | d = 0.001d; 99 | return true; 100 | } 101 | if (d1 < lowLimit) 102 | { 103 | d = lowLimit; 104 | return false; 105 | } 106 | d = d1; 107 | return true; 108 | } 109 | 110 | private static void ReloadConfig() 111 | { 112 | var hypereditCfg = IoExt.GetPath("hyperedit.cfg"); 113 | if (System.IO.File.Exists(hypereditCfg)) 114 | { 115 | _hyperEditConfig = ConfigNode.Load(hypereditCfg); 116 | _hyperEditConfig.name = "hyperedit"; 117 | } 118 | else 119 | { 120 | _hyperEditConfig = new ConfigNode("hyperedit"); 121 | } 122 | 123 | var autoOpenLanderValue = true; 124 | _hyperEditConfig.TryGetValue("AutoOpenLander", ref autoOpenLanderValue, bool.TryParse); 125 | AutoOpenLander = autoOpenLanderValue; 126 | } 127 | 128 | public static bool AutoOpenLander 129 | { 130 | get { return _autoOpenLander; } 131 | set 132 | { 133 | if (_autoOpenLander == value) 134 | return; 135 | _autoOpenLander = value; 136 | _hyperEditConfig.SetValue("AutoOpenLander", value.ToString(), true); 137 | _hyperEditConfig.Save(); 138 | } 139 | } 140 | 141 | public static IView View() 142 | { 143 | // Load Auto Open status. 144 | ReloadConfig(); 145 | 146 | var setAutoOpen = new DynamicToggleView("Auto Open", "Open this view when entering the Flight or Tracking Center scenes.", 147 | () => AutoOpenLander, () => true, v => AutoOpenLander = v); 148 | var bodySelector = new ListSelectView("Body", () => FlightGlobals.fetch == null ? null : FlightGlobals.fetch.bodies, null, Extensions.CbToString); 149 | bodySelector.CurrentlySelected = FlightGlobals.fetch == null ? null : FlightGlobals.ActiveVessel == null ? Planetarium.fetch.Home : FlightGlobals.ActiveVessel.mainBody; 150 | var lat = new TextBoxView("Lat", "Latitude (North/South). Between +90 (North) and -90 (South).", 0.001d, latTryParse); 151 | var lon = new TextBoxView("Lon", "Longitude (East/West). Converts to less than 360 degrees.", 0.001d, myTryParse); 152 | var alt = new TextBoxView("Alt", "Altitude (Up/Down). Distance above the surface.", 20, altTryParse); 153 | var setRot = new ToggleView("Force Rotation", 154 | "Rotates vessel such that up on the vessel is up when landing. Otherwise, the current orientation is kept relative to the body.", 155 | true); 156 | Func isValid = () => lat.Valid && lon.Valid && alt.Valid; 157 | Action load = (latVal, lonVal, altVal, body) => 158 | { 159 | lat.Object = latVal; 160 | lon.Object = lonVal; 161 | alt.Object = altVal; 162 | bodySelector.CurrentlySelected = body; 163 | }; 164 | 165 | // Load last entered values. 166 | Model.DoLander.LoadLast(load); 167 | 168 | return new VerticalView(new IView[] 169 | { 170 | setAutoOpen, 171 | bodySelector, 172 | new ConditionalView(() => FlightGlobals.fetch != null && FlightGlobals.ActiveVessel != null && FlightGlobals.ActiveVessel.mainBody != bodySelector.CurrentlySelected, new LabelView("Landing on a different body is not recommended.", "This may destroy the vessel. Use the Orbit Editor to orbit the body first, then land on it.")), 173 | lat, 174 | new ConditionalView(() => !lat.Valid, new LabelView("Latitude must be a number from 0 to (+/-)89.9.", "Values too close to the poles ((+/-)90) can crash KSP, values beyond that are invalid for a latitude.")), 175 | lon, 176 | alt, 177 | new ConditionalView(() => alt.Object < 0, new LabelView("Altitude must be a positive number.", "This may destroy the vessel. Values less than 0 are sub-surface.")), 178 | setRot, 179 | new ConditionalView(() => !isValid(), new ButtonView("Cannot Land", "Entered location is invalid. Correct items in red.", null)), 180 | new ConditionalView(() => !Model.DoLander.IsLanding() && isValid(), new ButtonView("Land", "Teleport to entered location, then slowly lower to surface.", () => Model.DoLander.ToggleLanding(lat.Object, lon.Object, alt.Object, bodySelector.CurrentlySelected, setRot.Value, load))), 181 | new ConditionalView(() => Model.DoLander.IsLanding(), new ButtonView("Drop (CAUTION!)", "Release vessel to gravity.", () => Model.DoLander.ToggleLanding(lat.Object, lon.Object, alt.Object, bodySelector.CurrentlySelected, setRot.Value, load))), 182 | new ConditionalView(() => Model.DoLander.IsLanding(), new LabelView("LANDING IN PROGRESS.", "Vessel is being lowered to the surface.")), 183 | //Launch button here 184 | new ConditionalView(() => Model.DoLander.IsLanding(), new LabelView(changeHelpString(), "Change location slightly.")), 185 | new ConditionalView(() => !Model.DoLander.IsLanding(), new ButtonView("Land Here", "Stop at current location, then slowly lower to surface.", () => Model.DoLander.LandHere(load))), 186 | new ListSelectView("Set to vessel", Model.DoLander.LandedVessels, select => Model.DoLander.SetToLanded(load, select), Extensions.VesselToString), 187 | new ButtonView("Current", "Set to current location.", () => Model.DoLander.SetToCurrent(load)), 188 | new ConditionalView(isValid, new ButtonView("Save", "Save the entered location.", () => Model.DoLander.AddSavedCoords(lat.Object, lon.Object, alt.Object, bodySelector.CurrentlySelected))), 189 | new ButtonView("Load", "Load a saved location.", () => Model.DoLander.Load(load)), 190 | new ButtonView("Delete", "Delete a saved location.", Model.DoLander.Delete), 191 | }); 192 | } 193 | 194 | private static string changeHelpString() 195 | { 196 | return 197 | $"Use {GameSettings.TRANSLATE_UP.primary},{GameSettings.TRANSLATE_DOWN.primary},{GameSettings.TRANSLATE_LEFT.primary},{GameSettings.TRANSLATE_RIGHT.primary} to fine-tune location."; 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /Source/View/Window.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using UnityEngine; 5 | 6 | namespace HyperEdit.View 7 | { 8 | public static class WindowHelper 9 | { 10 | public static void Prompt(string prompt, Action complete) 11 | { 12 | var str = ""; 13 | Window.Create(prompt, false, false, 200, 100, w => 14 | { 15 | str = GUILayout.TextField(str); 16 | if (GUILayout.Button("OK")) 17 | { 18 | complete(str); 19 | w.Close(); 20 | } 21 | }); 22 | } 23 | 24 | public static void Error(string message) 25 | { 26 | Window.Create("Error", false, false, 400, -1, w => 27 | { 28 | GUILayout.Label(message); 29 | if (GUILayout.Button("OK")) 30 | { 31 | w.Close(); 32 | } 33 | }); 34 | } 35 | 36 | public static void Selector(string title, IEnumerable elements, Func nameSelector, 37 | Action onSelect) 38 | { 39 | var collection = elements.Select(t => new {value = t, name = nameSelector(t)}).ToList(); 40 | var scrollPos = new Vector2(); 41 | Window.Create(title, false, false, 300, 500, w => 42 | { 43 | scrollPos = GUILayout.BeginScrollView(scrollPos); 44 | foreach (var item in collection) 45 | { 46 | if (GUILayout.Button(item.name)) 47 | { 48 | onSelect(item.value); 49 | w.Close(); 50 | return; 51 | } 52 | } 53 | GUILayout.EndScrollView(); 54 | }); 55 | } 56 | } 57 | 58 | public class Window : MonoBehaviour 59 | { 60 | private static GameObject _gameObject; 61 | 62 | internal static GameObject GameObject 63 | { 64 | get 65 | { 66 | if (_gameObject == null) 67 | { 68 | _gameObject = new GameObject("HyperEditWindowManager"); 69 | DontDestroyOnLoad(_gameObject); 70 | } 71 | return _gameObject; 72 | } 73 | } 74 | 75 | private static ConfigNode _windowPos; 76 | 77 | private static ConfigNode WindowPos 78 | { 79 | get 80 | { 81 | if (_windowPos != null) 82 | return _windowPos; 83 | var fp = IoExt.GetPath("windowpos.cfg"); 84 | if (System.IO.File.Exists(fp)) 85 | { 86 | _windowPos = ConfigNode.Load(fp); 87 | _windowPos.name = "windowpos"; 88 | } 89 | else 90 | _windowPos = new ConfigNode("windowpos"); 91 | return _windowPos; 92 | } 93 | } 94 | 95 | private static void SaveWindowPos() 96 | { 97 | WindowPos.Save(); 98 | } 99 | 100 | public static event Action AreWindowsOpenChange; 101 | 102 | private string _tempTooltip; 103 | private string _oldTooltip; 104 | internal string Title; 105 | private bool _shrinkHeight; 106 | private Rect _windowRect; 107 | private Action _drawFunc; 108 | private bool _isOpen; 109 | 110 | public static void Create(string title, bool savepos, bool ensureUniqueTitle, int width, int height, 111 | Action drawFunc) 112 | { 113 | var allOpenWindows = GameObject.GetComponents(); 114 | if (ensureUniqueTitle && allOpenWindows.Any(w => w.Title == title)) 115 | { 116 | Extensions.Log("Not opening window \"" + title + "\", already open"); 117 | return; 118 | } 119 | 120 | var winx = 100; 121 | var winy = 100; 122 | if (savepos) 123 | { 124 | var winposNode = WindowPos.GetNode(title.Replace(' ', '_')); 125 | if (winposNode != null) 126 | { 127 | winposNode.TryGetValue("x", ref winx, int.TryParse); 128 | winposNode.TryGetValue("y", ref winy, int.TryParse); 129 | } 130 | else 131 | { 132 | Extensions.Log("No winpos found for \"" + title + "\", defaulting to " + winx + "," + winy); 133 | } 134 | if (winx >= Screen.width - width) 135 | winx = Screen.width - width; 136 | if (height == -1) 137 | { 138 | if (winy >= Screen.height - 100) 139 | winy = (Screen.height - 100) / 2; 140 | } 141 | else 142 | { 143 | if (winy > Screen.height - height) 144 | winy = Screen.height - height; 145 | } 146 | Extensions.Log("Screen.width: " + Screen.width.ToString() + " width: " + width.ToString() + " winx: " + winx.ToString()); 147 | Extensions.Log("Screen.height: " + Screen.height.ToString() + " height: " + height.ToString() + " winy: " + winy.ToString()); 148 | } 149 | else 150 | { 151 | winx = (Screen.width - width)/2; 152 | winy = (Screen.height - height)/2; 153 | } 154 | 155 | var window = GameObject.AddComponent(); 156 | window._isOpen = true; 157 | window._shrinkHeight = height == -1; 158 | if (window._shrinkHeight) 159 | height = 5; 160 | window.Title = title; 161 | window._windowRect = new Rect(winx, winy, width, height); 162 | window._drawFunc = drawFunc; 163 | if (allOpenWindows.Length == 0) 164 | AreWindowsOpenChange?.Invoke(true); 165 | } 166 | 167 | private Window() 168 | { 169 | GameEvents.onScreenResolutionModified.Add(OnScreenResolutionModified); 170 | } 171 | 172 | void OnScreenResolutionModified(int x, int y) 173 | { 174 | if (this._windowRect.y >= Screen.height) 175 | _windowRect.y = Screen.height - _windowRect.height; 176 | if (this._windowRect.x >= Screen.width) 177 | _windowRect.x = Screen.width - _windowRect.width; 178 | 179 | } 180 | 181 | public void Update() 182 | { 183 | if (_shrinkHeight) 184 | _windowRect.height = 5; 185 | _oldTooltip = _tempTooltip; 186 | } 187 | 188 | public void OnGUI() 189 | { 190 | GUI.skin = HighLogic.Skin; 191 | _windowRect = GUILayout.Window(GetInstanceID(), _windowRect, DrawWindow, Title, GUILayout.ExpandHeight(true)); 192 | 193 | if (string.IsNullOrEmpty(_oldTooltip)) 194 | return; 195 | var rect = new Rect(_windowRect.xMin, _windowRect.yMax, _windowRect.width, 50); 196 | GUI.Label(rect, _oldTooltip); 197 | } 198 | 199 | private void DrawWindow(int windowId) 200 | { 201 | GUILayout.BeginVertical(); 202 | if (GUI.Button(new Rect(_windowRect.width - 18, 2, 16, 16), "X")) // X button from mechjeb 203 | Close(); 204 | _drawFunc(this); 205 | 206 | _tempTooltip = GUI.tooltip; 207 | 208 | GUILayout.EndVertical(); 209 | GUI.DragWindow(); 210 | } 211 | 212 | public void Close() 213 | { 214 | var node = new ConfigNode(Title.Replace(' ', '_')); 215 | node.AddValue("x", (int) _windowRect.x); 216 | node.AddValue("y", (int) _windowRect.y); 217 | if (WindowPos.SetNode(node.name, node) == false) 218 | WindowPos.AddNode(node); 219 | SaveWindowPos(); 220 | _isOpen = false; 221 | GameEvents.onScreenResolutionModified.Remove(OnScreenResolutionModified); 222 | Destroy(this); 223 | if (GameObject.GetComponents().Any(w => w._isOpen) == false) 224 | AreWindowsOpenChange?.Invoke(false); 225 | } 226 | 227 | internal static void CloseAll() 228 | { 229 | foreach (var window in GameObject.GetComponents()) 230 | window.Close(); 231 | } 232 | } 233 | } -------------------------------------------------------------------------------- /Source/View/PlanetEditorView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | using UnityEngine; 4 | 5 | namespace HyperEdit.View 6 | { 7 | public static class PlanetEditorView 8 | { 9 | public static Action Create() 10 | { 11 | var view = View(); 12 | return () => Window.Create("Planet editor", true, true, 400, -1, w => view.Draw()); 13 | } 14 | 15 | public static IView View() 16 | { 17 | CelestialBody body = null; 18 | 19 | var geeAsl = new TextBoxView("Gravity multiplier", "1.0 is kerbin, 0.5 is half of kerbin's gravity, etc.", 1, Model.SiSuffix.TryParse); 20 | var ocean = new ToggleView("Has ocean", "Does weird things to the ocean if off", false); 21 | var atmosphere = new ToggleView("Has atmosphere", "Toggles if the planet has atmosphere or not", false); 22 | var atmosphereContainsOxygen = new ToggleView("Atmosphere contains oxygen", "Whether jet engines work or not", false); 23 | var atmosphereDepth = new TextBoxView("Atmosphere depth", "Theoretically atmosphere height. In reality, doesn't work too well.", 1, Model.SiSuffix.TryParse); 24 | var atmosphereTemperatureSeaLevel = new TextBoxView("atmosphereTemperatureSeaLevel", "New 1.0 field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 25 | var atmosphereTemperatureLapseRate = new TextBoxView("atmosphereTemperatureLapseRate", "Unknown", 1, Model.SiSuffix.TryParse); 26 | var atmospherePressureSeaLevel = new TextBoxView("atmospherePressureSeaLevel", "New 1.0 field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 27 | var atmDensityASL = new TextBoxView("atmDensityASL", "New 1.4-ish field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 28 | var atmosphereGasMassLapseRate = new TextBoxView("atmosphereGasMassLapseRate", "New 1.4-ish field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 29 | var atmosphereMolarMass = new TextBoxView("atmosphereMolarMass", "New 1.0 field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 30 | var atmosphereAdiabaticIndex = new TextBoxView("atmosphereAdiabaticIndex", "New 1.0 field. Unknown what this does.", 1, Model.SiSuffix.TryParse); 31 | var radiusAtmoFactor = new TextBoxView("radiusAtmoFactor", "Unknown", 1, Model.SiSuffix.TryParse); 32 | var atmosphereUsePressureCurve = new ToggleView("Use atmospheric pressure curve", "Unknown", false); 33 | var atmospherePressureCurveIsNormalized = new ToggleView("Atmospheric pressure curve is normalized", "Unknown", false); 34 | var atmospherePressureCurve = new TextAreaView("atmospherePressureCurve", "Atmosphere pressure curve", "", Model.SiSuffix.TryParseFloatCurve); 35 | var atmosphereUseTemperatureCurve = new ToggleView("Use atmospheric temperature curve", "Unknown", false); 36 | var atmosphereTemperatureCurveIsNormalized = new ToggleView("Atmospheric temperature curve is normalized", "Unknown", false); 37 | var atmosphereTemperatureCurve = new TextAreaView("atmosphereTemperatureCurve", "Atmosphere temperature curve", "", Model.SiSuffix.TryParseFloatCurve); 38 | var atmosphereTemperatureSunMultCurve = new TextAreaView("atmosphereTemperatureSunMultCurve", "Atmosphere temperature sun mult curve", "", Model.SiSuffix.TryParseFloatCurve); 39 | var rotates = new ToggleView("Rotates", "If the planet rotates.", false); 40 | var rotationPeriod = new TextBoxView("Rotation period", "Rotation period of the planet, in seconds.", 1, Model.SiSuffix.TryParse); 41 | var initialRotation = new TextBoxView("Initial rotation", "Absolute rotation in degrees of the planet at time=0", 1, Model.SiSuffix.TryParse); 42 | var tidallyLocked = new ToggleView("Tidally locked", "If the planet is tidally locked. Overrides Rotation Period.", false); 43 | 44 | Action onSelect = cb => 45 | { 46 | body = cb; 47 | geeAsl.Object = body.GeeASL; 48 | ocean.Value = body.ocean; 49 | atmosphere.Value = body.atmosphere; 50 | atmosphereContainsOxygen.Value = body.atmosphereContainsOxygen; 51 | atmosphereDepth.Object = body.atmosphereDepth; 52 | atmosphereTemperatureSeaLevel.Object = body.atmosphereTemperatureSeaLevel; 53 | atmosphereTemperatureLapseRate.Object = body.atmosphereTemperatureLapseRate; 54 | atmospherePressureSeaLevel.Object = body.atmospherePressureSeaLevel; 55 | atmDensityASL.Object = body.atmDensityASL; 56 | atmosphereGasMassLapseRate.Object = body.atmosphereGasMassLapseRate; 57 | atmosphereMolarMass.Object = body.atmosphereMolarMass; 58 | atmosphereAdiabaticIndex.Object = body.atmosphereAdiabaticIndex; 59 | radiusAtmoFactor.Object = body.radiusAtmoFactor; 60 | atmosphereUsePressureCurve.Value = body.atmosphereUsePressureCurve; 61 | atmospherePressureCurveIsNormalized.Value = body.atmospherePressureCurveIsNormalized; 62 | atmospherePressureCurve.Object = JsonUtility.ToJson(body.atmospherePressureCurve, true); 63 | atmosphereUseTemperatureCurve.Value = body.atmosphereUseTemperatureCurve; 64 | atmosphereTemperatureCurveIsNormalized.Value = body.atmosphereTemperatureCurveIsNormalized; 65 | atmosphereTemperatureCurve.Object = JsonUtility.ToJson(body.atmospherePressureCurve, true); 66 | atmosphereTemperatureSunMultCurve.Object = JsonUtility.ToJson(body.atmosphereTemperatureSunMultCurve, true); 67 | rotates.Value = body.rotates; 68 | rotationPeriod.Object = body.rotationPeriod; 69 | initialRotation.Object = body.initialRotation; 70 | tidallyLocked.Value = body.tidallyLocked; 71 | }; 72 | 73 | var selectBody = new ConditionalView(() => FlightGlobals.fetch != null && FlightGlobals.Bodies != null, 74 | new ListSelectView("Selected body", () => FlightGlobals.Bodies, onSelect, Extensions.CbToString)); 75 | 76 | var apply = new ConditionalView(() => 77 | geeAsl.Valid && 78 | atmosphereDepth.Valid && 79 | atmosphereTemperatureSeaLevel.Valid && 80 | atmosphereTemperatureLapseRate.Valid && 81 | atmospherePressureSeaLevel.Valid && 82 | atmDensityASL.Valid && 83 | atmosphereGasMassLapseRate.Valid && 84 | atmosphereMolarMass.Valid && 85 | atmosphereAdiabaticIndex.Valid && 86 | radiusAtmoFactor.Valid && 87 | atmospherePressureCurve.Valid && 88 | atmosphereTemperatureCurve.Valid && 89 | atmosphereTemperatureSunMultCurve.Valid && 90 | rotationPeriod.Valid && 91 | initialRotation.Valid, 92 | new ButtonView("Apply", "Applies the changes to the body", () => 93 | { 94 | new Model.PlanetEditor.PlanetSettings( 95 | geeAsl.Object, 96 | ocean.Value, 97 | atmosphere.Value, 98 | atmosphereContainsOxygen.Value, 99 | atmosphereDepth.Object, 100 | atmosphereTemperatureSeaLevel.Object, 101 | atmosphereTemperatureLapseRate.Object, 102 | atmospherePressureSeaLevel.Object, 103 | atmDensityASL.Object, 104 | atmosphereGasMassLapseRate.Object, 105 | atmosphereMolarMass.Object, 106 | atmosphereAdiabaticIndex.Object, 107 | radiusAtmoFactor.Object, 108 | atmosphereUsePressureCurve.Value, 109 | atmospherePressureCurveIsNormalized.Value, 110 | JsonUtility.FromJson(atmospherePressureCurve.Object), 111 | atmosphereUseTemperatureCurve.Value, 112 | atmosphereTemperatureCurveIsNormalized.Value, 113 | JsonUtility.FromJson(atmosphereTemperatureCurve.Object), 114 | JsonUtility.FromJson(atmosphereTemperatureSunMultCurve.Object), 115 | rotates.Value, 116 | rotationPeriod.Object, 117 | initialRotation.Object, 118 | tidallyLocked.Value, 119 | body.orbit).CopyTo(body, false); 120 | })); 121 | 122 | var editFields = new ConditionalView(() => body != null, new VerticalView(new IView[] 123 | { 124 | new ScrollView(new VerticalView(new IView[] 125 | { 126 | geeAsl, 127 | ocean, 128 | atmosphere, 129 | atmosphereContainsOxygen, 130 | atmosphereDepth, 131 | atmosphereTemperatureSeaLevel, 132 | atmosphereTemperatureLapseRate, 133 | atmospherePressureSeaLevel, 134 | atmDensityASL, 135 | atmosphereGasMassLapseRate, 136 | atmosphereMolarMass, 137 | atmosphereAdiabaticIndex, 138 | radiusAtmoFactor, 139 | atmosphereUsePressureCurve, 140 | atmospherePressureCurveIsNormalized, 141 | atmospherePressureCurve, 142 | atmosphereUseTemperatureCurve, 143 | atmosphereTemperatureCurveIsNormalized, 144 | atmosphereTemperatureCurve, 145 | atmosphereTemperatureSunMultCurve, 146 | rotates, 147 | rotationPeriod, 148 | initialRotation, 149 | tidallyLocked 150 | }), GUILayout.MinHeight(600), GUILayout.MaxHeight(Screen.height - 200)), 151 | apply 152 | } 153 | )); 154 | 155 | var resetToDefault = new ConditionalView(() => body != null, 156 | new ButtonView("Reset to defaults", "Reset the selected planet to defaults", 157 | () => { Model.PlanetEditor.ResetToDefault(body); onSelect(body); })); 158 | 159 | var copyToKerbin = new ConditionalView(() => body != null && body != Model.PlanetEditor.Kerbin, 160 | new ButtonView("Copy to kerbin", "Copies the selected planet's settings to kerbin", 161 | () => new Model.PlanetEditor.PlanetSettings(body).CopyTo(Model.PlanetEditor.Kerbin, false))); 162 | 163 | var savePlanet = new ConditionalView(() => body != null, 164 | new ButtonView("Save planet to config file", "Saves the current configuration of the planet to a file, so it stays edited even after a restart. Delete the file named the planet's name in " + IoExt.GetPath(null) + " to undo.", 165 | () => Model.PlanetEditor.SavePlanet(body))); 166 | 167 | var reloadDefaults = new ConditionalView(() => FlightGlobals.fetch != null && FlightGlobals.Bodies != null, 168 | new ButtonView("Reload config files", "Reloads the planet .cfg files in " + IoExt.GetPath(null), 169 | Model.PlanetEditor.ApplyFileDefaults)); 170 | 171 | return new VerticalView(new IView[] 172 | { 173 | selectBody, 174 | editFields, 175 | resetToDefault, 176 | copyToKerbin, 177 | savePlanet, 178 | reloadDefaults 179 | }); 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /Source/View/View.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace HyperEdit.View 6 | { 7 | public interface IView 8 | { 9 | void Draw(); 10 | } 11 | 12 | public class CustomView : IView 13 | { 14 | private readonly Action _draw; 15 | 16 | public CustomView(Action draw) 17 | { 18 | _draw = draw; 19 | } 20 | 21 | public void Draw() 22 | { 23 | _draw(); 24 | } 25 | } 26 | 27 | public class ConditionalView : IView 28 | { 29 | private readonly Func _doDisplay; 30 | private readonly IView _toDisplay; 31 | 32 | public ConditionalView(Func doDisplay, IView toDisplay) 33 | { 34 | _doDisplay = doDisplay; 35 | _toDisplay = toDisplay; 36 | } 37 | 38 | public void Draw() 39 | { 40 | if (_doDisplay()) 41 | _toDisplay.Draw(); 42 | } 43 | } 44 | 45 | public class LabelView : IView 46 | { 47 | private readonly GUIContent _label; 48 | 49 | public LabelView(string label, string help) 50 | { 51 | _label = new GUIContent(label, help); 52 | } 53 | 54 | public void Draw() 55 | { 56 | GUILayout.Label(_label); 57 | } 58 | } 59 | 60 | public class VerticalView : IView 61 | { 62 | private readonly ICollection _views; 63 | 64 | public VerticalView(ICollection views) 65 | { 66 | _views = views; 67 | } 68 | 69 | public void Draw() 70 | { 71 | GUILayout.BeginVertical(); 72 | foreach (var view in _views) 73 | { 74 | view.Draw(); 75 | } 76 | GUILayout.EndVertical(); 77 | } 78 | } 79 | 80 | public class ButtonView : IView 81 | { 82 | private readonly GUIContent _label; 83 | private readonly Action _onChange; 84 | 85 | public ButtonView(string label, string help, Action onChange) 86 | { 87 | _label = new GUIContent(label, help); 88 | _onChange = onChange; 89 | } 90 | 91 | public void Draw() 92 | { 93 | if (GUILayout.Button(_label)) 94 | { 95 | _onChange(); 96 | Extensions.ClearGuiFocus(); 97 | } 98 | } 99 | } 100 | 101 | public class ToggleView : IView 102 | { 103 | private readonly GUIContent _label; 104 | private readonly Action _onChange; 105 | 106 | public bool Value { get; set; } 107 | 108 | public ToggleView(string label, string help, bool initialValue, Action onChange = null) 109 | { 110 | _label = new GUIContent(label, help); 111 | Value = initialValue; 112 | _onChange = onChange; 113 | } 114 | 115 | public void Draw() 116 | { 117 | var oldValue = Value; 118 | Value = GUILayout.Toggle(oldValue, _label); 119 | if (oldValue != Value && _onChange != null) 120 | { 121 | _onChange(Value); 122 | Extensions.ClearGuiFocus(); 123 | } 124 | } 125 | } 126 | 127 | public class DynamicToggleView : IView 128 | { 129 | private readonly GUIContent _label; 130 | private readonly Func _getValue; 131 | private readonly Func _isValid; 132 | private readonly Action _onChange; 133 | 134 | public DynamicToggleView(string label, string help, Func getValue, Func isValid, 135 | Action onChange) 136 | { 137 | _label = new GUIContent(label, help); 138 | _getValue = getValue; 139 | _isValid = isValid; 140 | _onChange = onChange; 141 | } 142 | 143 | public void Draw() 144 | { 145 | var oldValue = _getValue(); 146 | var newValue = GUILayout.Toggle(oldValue, _label); 147 | if (oldValue != newValue && _isValid()) 148 | { 149 | _onChange(newValue); 150 | Extensions.ClearGuiFocus(); 151 | } 152 | } 153 | } 154 | 155 | public class DynamicSliderView : IView 156 | { 157 | private readonly Action _onChange; 158 | private readonly GUIContent _label; 159 | private readonly Func _get; 160 | 161 | public DynamicSliderView(string label, string help, Func get, Action onChange) 162 | { 163 | _onChange = onChange; 164 | _label = new GUIContent(label, help); 165 | _get = get; 166 | } 167 | 168 | public void Draw() 169 | { 170 | GUILayout.BeginHorizontal(); 171 | GUILayout.Label(_label); 172 | var oldValue = _get(); 173 | var newValue = (double) GUILayout.HorizontalSlider((float) oldValue, 0, 1); 174 | if (Math.Abs(newValue - oldValue) > 0.001) 175 | { 176 | _onChange?.Invoke(newValue); 177 | Extensions.ClearGuiFocus(); 178 | } 179 | GUILayout.EndHorizontal(); 180 | } 181 | } 182 | 183 | public class SliderView : IView 184 | { 185 | private readonly Action _onChange; 186 | private readonly GUIContent _label; 187 | 188 | public double Value { get; set; } 189 | 190 | public SliderView(string label, string help, Action onChange = null) 191 | { 192 | _onChange = onChange; 193 | _label = new GUIContent(label, help); 194 | Value = 0; 195 | } 196 | 197 | public void Draw() 198 | { 199 | GUILayout.BeginHorizontal(); 200 | GUILayout.Label(_label); 201 | var newValue = (double) GUILayout.HorizontalSlider((float) Value, 0, 1); 202 | if (Math.Abs(newValue - Value) > 0.001) 203 | { 204 | Value = newValue; 205 | _onChange?.Invoke(Value); 206 | Extensions.ClearGuiFocus(); 207 | } 208 | GUILayout.EndHorizontal(); 209 | } 210 | } 211 | 212 | public class ListSelectView : IView 213 | { 214 | private readonly string _prefix; 215 | private readonly Func> _list; 216 | private readonly Func _toString; 217 | private readonly Action _onSelect; 218 | private T _currentlySelected; 219 | 220 | public T CurrentlySelected 221 | { 222 | get { return _currentlySelected; } 223 | set 224 | { 225 | _currentlySelected = value; 226 | _onSelect?.Invoke(value); 227 | } 228 | } 229 | 230 | public void ReInvokeOnSelect() 231 | { 232 | _onSelect?.Invoke(_currentlySelected); 233 | } 234 | 235 | public ListSelectView(string prefix, Func> list, Action onSelect = null, 236 | Func toString = null) 237 | { 238 | _prefix = prefix + ": "; 239 | _list = list; 240 | _toString = toString ?? (x => x.ToString()); 241 | _onSelect = onSelect; 242 | _currentlySelected = default(T); 243 | } 244 | 245 | public void Draw() 246 | { 247 | GUILayout.BeginHorizontal(); 248 | GUILayout.Label(_prefix + (_currentlySelected == null ? "" : _toString(_currentlySelected))); 249 | if (GUILayout.Button("Select")) 250 | { 251 | Extensions.ClearGuiFocus(); 252 | var realList = _list(); 253 | if (realList != null) 254 | WindowHelper.Selector("Select", realList, _toString, t => CurrentlySelected = t); 255 | } 256 | GUILayout.EndHorizontal(); 257 | } 258 | } 259 | 260 | public class TextBoxView : IView 261 | { 262 | private readonly GUIContent _label; 263 | private readonly TryParse _parser; 264 | private readonly Func _toString; 265 | private readonly Action _onSet; 266 | private string _value; 267 | private T _obj; 268 | 269 | public bool Valid { get; private set; } 270 | 271 | public T Object 272 | { 273 | get { return _obj; } 274 | set 275 | { 276 | _value = _toString(value); 277 | _obj = value; 278 | } 279 | } 280 | 281 | public TextBoxView(string label, string help, T start, TryParse parser, Func toString = null, 282 | Action onSet = null) 283 | { 284 | _label = label == null ? null : new GUIContent(label, help); 285 | _toString = toString ?? (x => x.ToString()); 286 | _value = _toString(start); 287 | _parser = parser; 288 | _onSet = onSet; 289 | } 290 | 291 | public void Draw() 292 | { 293 | if (_label != null || _onSet != null) 294 | { 295 | GUILayout.BeginHorizontal(); 296 | if (_label != null) 297 | GUILayout.Label(_label); 298 | } 299 | 300 | T tempValue; 301 | Valid = _parser(_value, out tempValue); 302 | 303 | if (Valid) 304 | { 305 | _value = GUILayout.TextField(_value); 306 | _obj = tempValue; 307 | } 308 | else 309 | { 310 | var color = GUI.color; 311 | GUI.color = Color.red; 312 | _value = GUILayout.TextField(_value); 313 | GUI.color = color; 314 | } 315 | if (_label != null || _onSet != null) 316 | { 317 | if (_onSet != null && Valid && GUILayout.Button("Set")) 318 | { 319 | _onSet(Object); 320 | Extensions.ClearGuiFocus(); 321 | } 322 | GUILayout.EndHorizontal(); 323 | } 324 | } 325 | } 326 | 327 | public class TextAreaView : IView 328 | { 329 | private readonly GUIContent _label; 330 | private readonly TryParse _parser; 331 | private readonly Func _toString; 332 | private readonly Action _onSet; 333 | private string _value; 334 | private T _obj; 335 | private Vector2 scrollPosition; 336 | 337 | public bool Valid { get; private set; } 338 | 339 | public T Object 340 | { 341 | get { return _obj; } 342 | set 343 | { 344 | _value = _toString(value); 345 | _obj = value; 346 | } 347 | } 348 | 349 | public TextAreaView(string label, string help, T start, TryParse parser, Func toString = null, 350 | Action onSet = null) 351 | { 352 | _label = label == null ? null : new GUIContent(label, help); 353 | _toString = toString ?? (x => x.ToString()); 354 | _value = _toString(start); 355 | _parser = parser; 356 | _onSet = onSet; 357 | } 358 | 359 | public void Draw() 360 | { 361 | if (_label != null || _onSet != null) 362 | { 363 | GUILayout.BeginVertical(); 364 | if (_label != null) 365 | GUILayout.Label(_label); 366 | } 367 | 368 | T tempValue; 369 | Valid = _parser(_value, out tempValue); 370 | 371 | 372 | scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.MinWidth(100), GUILayout.MinHeight(100), GUILayout.MaxHeight(400)); 373 | if (Valid) 374 | { 375 | _value = GUILayout.TextArea(_value); 376 | _obj = tempValue; 377 | } 378 | else 379 | { 380 | var color = GUI.color; 381 | GUI.color = Color.red; 382 | _value = GUILayout.TextArea(_value); 383 | GUI.color = color; 384 | } 385 | GUILayout.EndScrollView(); 386 | if (_label != null || _onSet != null) 387 | { 388 | if (_onSet != null && Valid && GUILayout.Button("Set")) 389 | { 390 | _onSet(Object); 391 | Extensions.ClearGuiFocus(); 392 | } 393 | GUILayout.EndVertical(); 394 | } 395 | } 396 | } 397 | 398 | public class TabView : IView 399 | { 400 | private readonly List> _views; 401 | private KeyValuePair _current; 402 | 403 | public TabView(List> views) 404 | { 405 | _views = views; 406 | _current = views[0]; 407 | } 408 | 409 | public void Draw() 410 | { 411 | GUILayout.BeginHorizontal(); 412 | foreach (var view in _views) 413 | { 414 | if (view.Key == _current.Key) 415 | { 416 | GUILayout.Button(view.Key, Extensions.PressedButton); 417 | } 418 | else 419 | { 420 | if (GUILayout.Button(view.Key)) 421 | { 422 | _current = view; 423 | Extensions.ClearGuiFocus(); 424 | } 425 | } 426 | } 427 | GUILayout.EndHorizontal(); 428 | _current.Value.Draw(); 429 | } 430 | } 431 | 432 | public class ScrollView : IView { 433 | private readonly IView _view; 434 | private readonly GUILayoutOption[] _options; 435 | private Vector2 scrollPosition; 436 | 437 | public ScrollView(IView view, params GUILayoutOption[] options) { 438 | _view = view; 439 | _options = options; 440 | } 441 | 442 | public void Draw() { 443 | scrollPosition = GUILayout.BeginScrollView(scrollPosition, _options); 444 | _view.Draw(); 445 | GUILayout.EndScrollView(); 446 | } 447 | } 448 | } -------------------------------------------------------------------------------- /Source/Model/OrbitEditor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace HyperEdit.Model 6 | { 7 | public static class OrbitEditor 8 | { 9 | public static IEnumerable OrderedOrbits() 10 | { 11 | var query = (IEnumerable) 12 | (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null || FlightGlobals.ActiveVessel.orbitDriver == null 13 | ? new OrbitDriver[0] 14 | : new[] { FlightGlobals.ActiveVessel.orbitDriver }); 15 | if (FlightGlobals.fetch != null) 16 | query = query 17 | .Concat(FlightGlobals.Vessels.Select(v => v.orbitDriver)) 18 | .Concat(FlightGlobals.Bodies.Select(v => v.orbitDriver)); 19 | query = query.Where(o => o != null).Distinct(); 20 | return query; 21 | } 22 | 23 | public static void Simple(OrbitDriver currentlyEditing, double altitude, CelestialBody body) 24 | { 25 | SetOrbit(currentlyEditing, CreateOrbit(0 , 0, altitude + body.Radius, 0, 0, 0, 0, body)); 26 | } 27 | 28 | public static void GetSimple(OrbitDriver currentlyEditing, out double altitude, out CelestialBody body) 29 | { 30 | const int min = 1000; 31 | const int defaultAlt = 100000; 32 | body = currentlyEditing.orbit.referenceBody; 33 | altitude = currentlyEditing.orbit.semiMajorAxis - body.Radius; 34 | if (altitude > min) 35 | return; 36 | altitude = currentlyEditing.orbit.ApA; 37 | if (altitude > min) 38 | return; 39 | altitude = defaultAlt; 40 | } 41 | 42 | public static void Complex(OrbitDriver currentlyEditing, double inclination, double eccentricity, 43 | double semiMajorAxis, double longitudeAscendingNode, double argumentOfPeriapsis, 44 | double meanAnomalyAtEpoch, double epoch, CelestialBody body) 45 | { 46 | SetOrbit(currentlyEditing, CreateOrbit(inclination, eccentricity, semiMajorAxis, 47 | longitudeAscendingNode, argumentOfPeriapsis, meanAnomalyAtEpoch, epoch, body)); 48 | } 49 | 50 | public static void GetComplex(OrbitDriver currentlyEditing, out double inclination, out double eccentricity, 51 | out double semiMajorAxis, out double longitudeAscendingNode, out double argumentOfPeriapsis, 52 | out double meanAnomalyAtEpoch, out double epoch, out CelestialBody body) 53 | { 54 | inclination = currentlyEditing.orbit.inclination; 55 | eccentricity = currentlyEditing.orbit.eccentricity; 56 | semiMajorAxis = currentlyEditing.orbit.semiMajorAxis; 57 | longitudeAscendingNode = currentlyEditing.orbit.LAN; 58 | argumentOfPeriapsis = currentlyEditing.orbit.argumentOfPeriapsis; 59 | meanAnomalyAtEpoch = currentlyEditing.orbit.meanAnomalyAtEpoch; 60 | epoch = currentlyEditing.orbit.epoch; 61 | body = currentlyEditing.orbit.referenceBody; 62 | } 63 | 64 | public static void Graphical(OrbitDriver currentlyEditing, double inclination, double eccentricity, 65 | double periapsis, double longitudeAscendingNode, double argumentOfPeriapsis, 66 | double meanAnomaly, double epoch) 67 | { 68 | var body = currentlyEditing.orbit.referenceBody; 69 | var soi = body.Soi(); 70 | var ratio = soi / (body.Radius + body.atmosphereDepth + 1000); 71 | periapsis = Math.Pow(ratio, periapsis) / ratio; 72 | periapsis *= soi; 73 | 74 | eccentricity *= Math.PI / 2 - 0.001; 75 | 76 | eccentricity = Math.Tan(eccentricity); 77 | var semimajor = periapsis / (1 - eccentricity); 78 | 79 | if (semimajor < 0) 80 | { 81 | meanAnomaly -= 0.5; 82 | meanAnomaly *= eccentricity * 4; // 4 is arbitrary constant 83 | } 84 | 85 | inclination *= 360; 86 | longitudeAscendingNode *= 360; 87 | argumentOfPeriapsis *= 360; 88 | meanAnomaly *= 2 * Math.PI; 89 | 90 | SetOrbit(currentlyEditing, CreateOrbit(inclination, eccentricity, semimajor, longitudeAscendingNode, argumentOfPeriapsis, meanAnomaly, epoch, body)); 91 | } 92 | 93 | public static void GetGraphical(OrbitDriver currentlyEditing, out double inclination, out double eccentricity, 94 | out double periapsis, out double longitudeAscendingNode, out double argumentOfPeriapsis, 95 | out double meanAnomaly, out double epoch) 96 | { 97 | inclination = currentlyEditing.orbit.inclination / 360; 98 | inclination = inclination.Mod(1); 99 | longitudeAscendingNode = currentlyEditing.orbit.LAN / 360; 100 | longitudeAscendingNode = longitudeAscendingNode.Mod(1); 101 | argumentOfPeriapsis = currentlyEditing.orbit.argumentOfPeriapsis / 360; 102 | argumentOfPeriapsis = argumentOfPeriapsis.Mod(1); 103 | var eTemp = Math.Atan(currentlyEditing.orbit.eccentricity); 104 | eccentricity = eTemp / (Math.PI / 2 - 0.001); 105 | var soi = currentlyEditing.orbit.referenceBody.Soi(); 106 | var ratio = soi / (currentlyEditing.orbit.referenceBody.Radius + currentlyEditing.orbit.referenceBody.atmosphereDepth + 1000); 107 | var semimajor = currentlyEditing.orbit.semiMajorAxis * (1 - currentlyEditing.orbit.eccentricity); 108 | semimajor /= soi; 109 | semimajor *= ratio; 110 | semimajor = Math.Log(semimajor, ratio); 111 | periapsis = semimajor; 112 | meanAnomaly = currentlyEditing.orbit.meanAnomalyAtEpoch; 113 | meanAnomaly /= (2 * Math.PI); 114 | if (currentlyEditing.orbit.semiMajorAxis < 0) 115 | { 116 | meanAnomaly /= currentlyEditing.orbit.eccentricity * 4; 117 | meanAnomaly += 0.5; 118 | } 119 | epoch = currentlyEditing.orbit.epoch; 120 | } 121 | 122 | public enum VelocityChangeDirection 123 | { 124 | Prograde, 125 | Normal, 126 | Radial, 127 | North, 128 | East, 129 | Up 130 | } 131 | 132 | public static VelocityChangeDirection[] AllVelocityChanges = Enum.GetValues(typeof(VelocityChangeDirection)).Cast().ToArray(); 133 | 134 | public static void Velocity(OrbitDriver currentlyEditing, VelocityChangeDirection direction, double speed) 135 | { 136 | Vector3d velocity; 137 | switch (direction) 138 | { 139 | case VelocityChangeDirection.Prograde: 140 | velocity = currentlyEditing.orbit.getOrbitalVelocityAtUT(Planetarium.GetUniversalTime()).normalized * speed; 141 | break; 142 | case VelocityChangeDirection.Normal: 143 | velocity = currentlyEditing.orbit.GetOrbitNormal().normalized * speed; 144 | break; 145 | case VelocityChangeDirection.Radial: 146 | velocity = Vector3d.Cross(currentlyEditing.orbit.getOrbitalVelocityAtUT(Planetarium.GetUniversalTime()), currentlyEditing.orbit.GetOrbitNormal()).normalized * speed; 147 | break; 148 | case VelocityChangeDirection.North: 149 | var upn = currentlyEditing.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).normalized; 150 | velocity = Vector3d.Cross(Vector3d.Cross(upn, new Vector3d(0, 0, 1)), upn) * speed; 151 | break; 152 | case VelocityChangeDirection.East: 153 | var upe = currentlyEditing.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).normalized; 154 | velocity = Vector3d.Cross(new Vector3d(0, 0, 1), upe) * speed; 155 | break; 156 | case VelocityChangeDirection.Up: 157 | velocity = currentlyEditing.orbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).normalized * speed; 158 | break; 159 | default: 160 | throw new Exception("Unknown VelChangeDir"); 161 | } 162 | var tempOrbit = currentlyEditing.orbit.Clone(); 163 | tempOrbit.UpdateFromStateVectors(currentlyEditing.orbit.pos, currentlyEditing.orbit.vel + velocity, currentlyEditing.orbit.referenceBody, Planetarium.GetUniversalTime()); 164 | SetOrbit(currentlyEditing, tempOrbit); 165 | } 166 | 167 | public static void GetVelocity(OrbitDriver currentlyEditing, out VelocityChangeDirection direction, out double speed) 168 | { 169 | direction = VelocityChangeDirection.Prograde; 170 | speed = 0; 171 | } 172 | 173 | public static void Rendezvous(OrbitDriver currentlyEditing, double leadTime, Vessel target) 174 | { 175 | SetOrbit(currentlyEditing, CreateOrbit( 176 | target.orbit.inclination, 177 | target.orbit.eccentricity, 178 | target.orbit.semiMajorAxis, 179 | target.orbit.LAN, 180 | target.orbit.argumentOfPeriapsis, 181 | target.orbit.meanAnomalyAtEpoch, 182 | target.orbit.epoch - leadTime, 183 | target.orbit.referenceBody)); 184 | } 185 | 186 | private static void SetOrbit(OrbitDriver currentlyEditing, Orbit orbit) 187 | { 188 | currentlyEditing.DynamicSetOrbit(orbit); 189 | } 190 | 191 | private static Orbit CreateOrbit(double inc, double e, double sma, double lan, double w, double mEp, double epoch, CelestialBody body) 192 | { 193 | if (inc == 0) 194 | inc = 0.0001d; 195 | if (double.IsNaN(inc)) 196 | inc = 0.0001d; 197 | if (double.IsNaN(e)) 198 | e = 0; 199 | if (double.IsNaN(sma)) 200 | sma = body.Radius + body.atmosphereDepth + 10000; 201 | if (double.IsNaN(lan)) 202 | lan = 0.0001d; 203 | if (lan == 0) 204 | lan = 0.0001d; 205 | if (double.IsNaN(w)) 206 | w = 0; 207 | if (double.IsNaN(mEp)) 208 | mEp = 0; 209 | if (double.IsNaN(epoch)) 210 | mEp = Planetarium.GetUniversalTime(); 211 | 212 | if (Math.Sign(e - 1) == Math.Sign(sma)) 213 | sma = -sma; 214 | 215 | if (Math.Sign(sma) >= 0) 216 | { 217 | while (mEp < 0) 218 | mEp += Math.PI * 2; 219 | while (mEp > Math.PI * 2) 220 | mEp -= Math.PI * 2; 221 | } 222 | 223 | // "inc" is probably inclination 224 | // "e" is probably eccentricity 225 | // "sma" is probably semi-major axis 226 | // "lan" is probably longitude of the ascending node 227 | // "w" is probably the argument of periapsis (omega) 228 | // mEp is probably a mean anomaly at some time, like epoch 229 | // t is probably current time 230 | 231 | return new Orbit(inc, e, sma, lan, w, mEp, epoch, body); 232 | } 233 | 234 | public static void DynamicSetOrbit(this OrbitDriver orbit, Orbit newOrbit) 235 | { 236 | var vessel = orbit.vessel; 237 | var body = orbit.celestialBody; 238 | if (vessel != null) 239 | vessel.SetOrbit(newOrbit); 240 | else if (body != null) 241 | body.SetOrbit(newOrbit); 242 | else 243 | HardsetOrbit(orbit, newOrbit); 244 | } 245 | 246 | public static void SetOrbit(this Vessel vessel, Orbit newOrbit) 247 | { 248 | var destinationMagnitude = newOrbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).magnitude; 249 | if (destinationMagnitude > newOrbit.referenceBody.sphereOfInfluence) 250 | { 251 | View.WindowHelper.Error("Destination position was above the sphere of influence"); 252 | return; 253 | } 254 | if (destinationMagnitude < newOrbit.referenceBody.Radius) 255 | { 256 | View.WindowHelper.Error("Destination position was below the surface"); 257 | return; 258 | } 259 | 260 | vessel.PrepVesselTeleport(); 261 | 262 | try 263 | { 264 | OrbitPhysicsManager.HoldVesselUnpack(60); 265 | } 266 | catch (NullReferenceException) 267 | { 268 | Extensions.Log("OrbitPhysicsManager.HoldVesselUnpack threw NullReferenceException"); 269 | } 270 | 271 | var allVessels = FlightGlobals.fetch?.vessels ?? (IEnumerable)new[] { vessel }; 272 | foreach (var v in allVessels) 273 | v.GoOnRails(); 274 | 275 | var oldBody = vessel.orbitDriver.orbit.referenceBody; 276 | 277 | HardsetOrbit(vessel.orbitDriver, newOrbit); 278 | 279 | vessel.orbitDriver.pos = vessel.orbit.pos.xzy; 280 | vessel.orbitDriver.vel = vessel.orbit.vel; 281 | 282 | var newBody = vessel.orbitDriver.orbit.referenceBody; 283 | if (newBody != oldBody) 284 | { 285 | var evnt = new GameEvents.HostedFromToAction(vessel, oldBody, newBody); 286 | GameEvents.onVesselSOIChanged.Fire(evnt); 287 | } 288 | } 289 | 290 | public static void SetOrbit(this CelestialBody body, Orbit newOrbit) 291 | { 292 | var oldBody = body.referenceBody; 293 | HardsetOrbit(body.orbitDriver, newOrbit); 294 | if (oldBody != newOrbit.referenceBody) 295 | { 296 | oldBody.orbitingBodies.Remove(body); 297 | newOrbit.referenceBody.orbitingBodies.Add(body); 298 | } 299 | body.RealCbUpdate(); 300 | } 301 | 302 | private static readonly object HardsetOrbitLogObject = new object(); 303 | 304 | private static void HardsetOrbit(OrbitDriver orbitDriver, Orbit newOrbit) 305 | { 306 | var orbit = orbitDriver.orbit; 307 | orbit.inclination = newOrbit.inclination; 308 | orbit.eccentricity = newOrbit.eccentricity; 309 | orbit.semiMajorAxis = newOrbit.semiMajorAxis; 310 | orbit.LAN = newOrbit.LAN; 311 | orbit.argumentOfPeriapsis = newOrbit.argumentOfPeriapsis; 312 | orbit.meanAnomalyAtEpoch = newOrbit.meanAnomalyAtEpoch; 313 | orbit.epoch = newOrbit.epoch; 314 | orbit.referenceBody = newOrbit.referenceBody; 315 | orbit.Init(); 316 | orbit.UpdateFromUT(Planetarium.GetUniversalTime()); 317 | if (orbit.referenceBody != newOrbit.referenceBody) 318 | { 319 | orbitDriver.OnReferenceBodyChange?.Invoke(newOrbit.referenceBody); 320 | } 321 | RateLimitedLogger.Log(HardsetOrbitLogObject, 322 | $"Orbit \"{orbitDriver.OrbitDriverToString()}\" changed to: inc={orbit.inclination} ecc={orbit.eccentricity} sma={orbit.semiMajorAxis} lan={orbit.LAN} argpe={orbit.argumentOfPeriapsis} mep={orbit.meanAnomalyAtEpoch} epoch={orbit.epoch} refbody={orbit.referenceBody.CbToString()}"); 323 | } 324 | 325 | public static Orbit Clone(this Orbit o) 326 | { 327 | return new Orbit(o.inclination, o.eccentricity, o.semiMajorAxis, o.LAN, 328 | o.argumentOfPeriapsis, o.meanAnomalyAtEpoch, o.epoch, o.referenceBody); 329 | } 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /Source/View/OrbitEditorView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace HyperEdit.View 5 | { 6 | public static class OrbitEditorView 7 | { 8 | public static Action Create() 9 | { 10 | var view = View(); 11 | return () => Window.Create("Orbit Editor", true, true, 300, -1, w => view.Draw()); 12 | } 13 | 14 | // Also known as "closure hell" 15 | public static IView View() 16 | { 17 | ListSelectView currentlyEditing = null; 18 | Action onCurrentlyEditingChange = null; 19 | 20 | var setToCurrentOrbit = new ButtonView("Set to current orbit", "Sets all the fields of the editor to reflect the orbit of the currently selected vessel", 21 | () => onCurrentlyEditingChange(currentlyEditing.CurrentlySelected)); 22 | 23 | var referenceSelector = new ListSelectView("Reference body", () => FlightGlobals.fetch == null ? null : FlightGlobals.fetch.bodies, null, Extensions.CbToString); 24 | 25 | #region Simple 26 | var simpleAltitude = new TextBoxView("Altitude", "Altitude of circular orbit", 110000, Model.SiSuffix.TryParse); 27 | var simpleApply = new ConditionalView(() => simpleAltitude.Valid && referenceSelector.CurrentlySelected != null, 28 | new ButtonView("Apply", "Sets the orbit", () => 29 | { 30 | Model.OrbitEditor.Simple(currentlyEditing.CurrentlySelected, simpleAltitude.Object, referenceSelector.CurrentlySelected); 31 | 32 | currentlyEditing.ReInvokeOnSelect(); 33 | })); 34 | var simple = new VerticalView(new IView[] 35 | { 36 | simpleAltitude, 37 | referenceSelector, 38 | simpleApply, 39 | setToCurrentOrbit 40 | }); 41 | #endregion 42 | 43 | #region Complex 44 | var complexInclination = new TextBoxView("Inclination", "How close to the equator the orbit plane is", 0, double.TryParse); 45 | var complexEccentricity = new TextBoxView("Eccentricity", "How circular the orbit is (0=circular, 0.5=elliptical, 1=parabolic)", 0, double.TryParse); 46 | var complexSemiMajorAxis = new TextBoxView("Semi-major axis", "Mean radius of the orbit (ish)", 10000000, Model.SiSuffix.TryParse); 47 | var complexLongitudeAscendingNode = new TextBoxView("Lon. of asc. node", "Longitude of the place where you cross the equator northwards", 0, double.TryParse); 48 | var complexArgumentOfPeriapsis = new TextBoxView("Argument of periapsis", "Rotation of the orbit around the normal", 0, double.TryParse); 49 | var complexMeanAnomalyAtEpoch = new TextBoxView("Mean anomaly at epoch", "Position along the orbit at the epoch", 0, double.TryParse); 50 | var complexEpoch = new TextBoxView("Epoch", "Epoch at which mEp is measured", 0, Model.SiSuffix.TryParse); 51 | var complexEpochNow = new ButtonView("Set epoch to now", "Sets the Epoch field to the current time", () => complexEpoch.Object = Planetarium.GetUniversalTime()); 52 | var complexApply = new ConditionalView(() => complexInclination.Valid && 53 | complexEccentricity.Valid && 54 | complexSemiMajorAxis.Valid && 55 | complexLongitudeAscendingNode.Valid && 56 | complexArgumentOfPeriapsis.Valid && 57 | complexMeanAnomalyAtEpoch.Valid && 58 | complexEpoch.Valid && 59 | referenceSelector.CurrentlySelected != null, 60 | new ButtonView("Apply", "Sets the orbit", () => 61 | { 62 | Model.OrbitEditor.Complex(currentlyEditing.CurrentlySelected, 63 | complexInclination.Object, 64 | complexEccentricity.Object, 65 | complexSemiMajorAxis.Object, 66 | complexLongitudeAscendingNode.Object, 67 | complexArgumentOfPeriapsis.Object, 68 | complexMeanAnomalyAtEpoch.Object, 69 | complexEpoch.Object, 70 | referenceSelector.CurrentlySelected); 71 | 72 | currentlyEditing.ReInvokeOnSelect(); 73 | })); 74 | var complex = new VerticalView(new IView[] 75 | { 76 | complexInclination, 77 | complexEccentricity, 78 | complexSemiMajorAxis, 79 | complexLongitudeAscendingNode, 80 | complexArgumentOfPeriapsis, 81 | complexMeanAnomalyAtEpoch, 82 | complexEpoch, 83 | complexEpochNow, 84 | referenceSelector, 85 | complexApply, 86 | setToCurrentOrbit 87 | }); 88 | #endregion 89 | 90 | #region Graphical 91 | SliderView graphicalInclination = null; 92 | SliderView graphicalEccentricity = null; 93 | SliderView graphicalPeriapsis = null; 94 | SliderView graphicalLongitudeAscendingNode = null; 95 | SliderView graphicalArgumentOfPeriapsis = null; 96 | SliderView graphicalMeanAnomaly = null; 97 | double graphicalEpoch = 0; 98 | 99 | Action graphicalOnChange = ignored => 100 | { 101 | Model.OrbitEditor.Graphical(currentlyEditing.CurrentlySelected, 102 | graphicalInclination.Value, 103 | graphicalEccentricity.Value, 104 | graphicalPeriapsis.Value, 105 | graphicalLongitudeAscendingNode.Value, 106 | graphicalArgumentOfPeriapsis.Value, 107 | graphicalMeanAnomaly.Value, 108 | graphicalEpoch); 109 | 110 | currentlyEditing.ReInvokeOnSelect(); 111 | }; 112 | 113 | graphicalInclination = new SliderView("Inclination", "How close to the equator the orbit plane is", graphicalOnChange); 114 | graphicalEccentricity = new SliderView("Eccentricity", "How circular the orbit is", graphicalOnChange); 115 | graphicalPeriapsis = new SliderView("Periapsis", "Lowest point in the orbit", graphicalOnChange); 116 | graphicalLongitudeAscendingNode = new SliderView("Lon. of asc. node", "Longitude of the place where you cross the equator northwards", graphicalOnChange); 117 | graphicalArgumentOfPeriapsis = new SliderView("Argument of periapsis", "Rotation of the orbit around the normal", graphicalOnChange); 118 | graphicalMeanAnomaly = new SliderView("Mean anomaly", "Position along the orbit", graphicalOnChange); 119 | 120 | var graphical = new VerticalView(new IView[] 121 | { 122 | graphicalInclination, 123 | graphicalEccentricity, 124 | graphicalPeriapsis, 125 | graphicalLongitudeAscendingNode, 126 | graphicalArgumentOfPeriapsis, 127 | graphicalMeanAnomaly, 128 | setToCurrentOrbit 129 | }); 130 | #endregion 131 | 132 | #region Velocity 133 | var velocitySpeed = new TextBoxView("Speed", "dV to apply", 0, Model.SiSuffix.TryParse); 134 | var velocityDirection = new ListSelectView("Direction", () => Model.OrbitEditor.AllVelocityChanges); 135 | var velocityApply = new ConditionalView(() => velocitySpeed.Valid, 136 | new ButtonView("Apply", "Adds the selected velocity to the orbit", () => 137 | { 138 | Model.OrbitEditor.Velocity(currentlyEditing.CurrentlySelected, velocityDirection.CurrentlySelected, velocitySpeed.Object); 139 | })); 140 | var velocity = new VerticalView(new IView[] 141 | { 142 | velocitySpeed, 143 | velocityDirection, 144 | velocityApply 145 | }); 146 | #endregion 147 | 148 | #region Rendezvous 149 | var rendezvousLeadTime = new TextBoxView("Lead time", "How many seconds off to rendezvous at (zero = on top of each other, bad)", 1, Model.SiSuffix.TryParse); 150 | var rendezvousVessel = new ListSelectView("Target vessel", () => FlightGlobals.fetch == null ? null : FlightGlobals.fetch.vessels, null, Extensions.VesselToString); 151 | var rendezvousApply = new ConditionalView(() => rendezvousLeadTime.Valid && rendezvousVessel.CurrentlySelected != null, 152 | new ButtonView("Apply", "Rendezvous", () => 153 | { 154 | Model.OrbitEditor.Rendezvous(currentlyEditing.CurrentlySelected, rendezvousLeadTime.Object, rendezvousVessel.CurrentlySelected); 155 | })); 156 | // rendezvous gets special ConditionalView to force only editing of planets 157 | var rendezvous = new ConditionalView(() => currentlyEditing.CurrentlySelected != null && currentlyEditing.CurrentlySelected.vessel != null, 158 | new VerticalView(new IView[] 159 | { 160 | rendezvousLeadTime, 161 | rendezvousVessel, 162 | rendezvousApply 163 | })); 164 | #endregion 165 | 166 | #region CurrentlyEditing 167 | onCurrentlyEditingChange = newEditing => 168 | { 169 | if (newEditing == null) 170 | { 171 | return; 172 | } 173 | { 174 | double altitude; 175 | CelestialBody body; 176 | Model.OrbitEditor.GetSimple(newEditing, out altitude, out body); 177 | simpleAltitude.Object = altitude; 178 | referenceSelector.CurrentlySelected = body; 179 | } 180 | { 181 | double inclination; 182 | double eccentricity; 183 | double semiMajorAxis; 184 | double longitudeAscendingNode; 185 | double argumentOfPeriapsis; 186 | double meanAnomalyAtEpoch; 187 | double epoch; 188 | CelestialBody body; 189 | Model.OrbitEditor.GetComplex(newEditing, 190 | out inclination, 191 | out eccentricity, 192 | out semiMajorAxis, 193 | out longitudeAscendingNode, 194 | out argumentOfPeriapsis, 195 | out meanAnomalyAtEpoch, 196 | out epoch, 197 | out body); 198 | complexInclination.Object = inclination; 199 | complexEccentricity.Object = eccentricity; 200 | complexSemiMajorAxis.Object = semiMajorAxis; 201 | complexLongitudeAscendingNode.Object = longitudeAscendingNode; 202 | complexArgumentOfPeriapsis.Object = argumentOfPeriapsis; 203 | complexMeanAnomalyAtEpoch.Object = meanAnomalyAtEpoch; 204 | complexEpoch.Object = epoch; 205 | referenceSelector.CurrentlySelected = body; 206 | } 207 | { 208 | double inclination; 209 | double eccentricity; 210 | double periapsis; 211 | double longitudeAscendingNode; 212 | double argumentOfPeriapsis; 213 | double meanAnomaly; 214 | Model.OrbitEditor.GetGraphical(newEditing, 215 | out inclination, 216 | out eccentricity, 217 | out periapsis, 218 | out longitudeAscendingNode, 219 | out argumentOfPeriapsis, 220 | out meanAnomaly, 221 | out graphicalEpoch); 222 | graphicalInclination.Value = inclination; 223 | graphicalEccentricity.Value = eccentricity; 224 | graphicalPeriapsis.Value = periapsis; 225 | graphicalLongitudeAscendingNode.Value = longitudeAscendingNode; 226 | graphicalArgumentOfPeriapsis.Value = argumentOfPeriapsis; 227 | graphicalMeanAnomaly.Value = meanAnomaly; 228 | } 229 | { 230 | Model.OrbitEditor.VelocityChangeDirection direction; 231 | double speed; 232 | Model.OrbitEditor.GetVelocity(newEditing, out direction, out speed); 233 | velocityDirection.CurrentlySelected = direction; 234 | velocitySpeed.Object = speed; 235 | } 236 | }; 237 | 238 | currentlyEditing = new ListSelectView("Currently editing", Model.OrbitEditor.OrderedOrbits, onCurrentlyEditingChange, Extensions.OrbitDriverToString); 239 | 240 | if (FlightGlobals.fetch != null && FlightGlobals.fetch.activeVessel != null && FlightGlobals.fetch.activeVessel.orbitDriver != null) 241 | { 242 | currentlyEditing.CurrentlySelected = FlightGlobals.fetch.activeVessel.orbitDriver; 243 | } 244 | #endregion 245 | 246 | var savePlanet = new ButtonView("Save planet", "Saves the current orbit of the planet to a file, so it stays edited even after a restart. Delete the file named the planet's name in " + IoExt.GetPath(null) + " to undo.", 247 | () => Model.PlanetEditor.SavePlanet(currentlyEditing.CurrentlySelected.celestialBody)); 248 | var resetPlanet = new ButtonView("Reset to defaults", "Reset the selected planet to defaults", 249 | () => Model.PlanetEditor.ResetToDefault(currentlyEditing.CurrentlySelected.celestialBody)); 250 | 251 | var planetButtons = new ConditionalView(() => currentlyEditing.CurrentlySelected?.celestialBody != null, 252 | new VerticalView(new IView[] 253 | { 254 | savePlanet, 255 | resetPlanet 256 | })); 257 | 258 | var tabs = new TabView(new List>() 259 | { 260 | new KeyValuePair("Simple", simple), 261 | new KeyValuePair("Complex", complex), 262 | new KeyValuePair("Graphical", graphical), 263 | new KeyValuePair("Velocity", velocity), 264 | new KeyValuePair("Rendezvous", rendezvous), 265 | }); 266 | 267 | return new VerticalView(new IView[] 268 | { 269 | currentlyEditing, 270 | planetButtons, 271 | new ConditionalView(() => currentlyEditing.CurrentlySelected != null, tabs) 272 | }); 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /Source/Model/PlanetEditor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace HyperEdit.Model 5 | { 6 | public static class PlanetEditor 7 | { 8 | private static bool _haveAppliedDefaults; 9 | private static readonly Dictionary DefaultSettings = new Dictionary(); 10 | 11 | public struct PlanetSettings 12 | { 13 | // Included fields for copy-paste: 14 | /* 15 | double GeeASL 16 | bool ocean 17 | bool atmosphere 18 | bool atmosphereContainsOxygen 19 | double atmosphereDepth 20 | double atmosphereTemperatureSeaLevel 21 | double atmosphereTemperatureLapseRate 22 | double atmospherePressureSeaLevel 23 | double atmDensityASL 24 | double atmosphereGasMassLapseRate 25 | double atmosphereMolarMass 26 | double atmosphereAdiabaticIndex 27 | double radiusAtmoFactor 28 | bool atmosphereUsePressureCurve 29 | bool atmospherePressureCurveIsNormalized 30 | FloatCurve atmospherePressureCurve 31 | bool atmosphereUseTemperatureCurve 32 | bool atmosphereTemperatureCurveIsNormalized 33 | FloatCurve atmosphereTemperatureCurve 34 | FloatCurve atmosphereTemperatureSunMultCurve 35 | bool rotates 36 | double rotationPeriod 37 | double initialRotation 38 | bool tidallyLocked 39 | */ 40 | 41 | public double GeeASL { get; set; } 42 | public bool ocean { get; set; } 43 | public bool atmosphere { get; set; } 44 | public bool atmosphereContainsOxygen { get; set; } 45 | public double atmosphereDepth { get; set; } 46 | public double atmosphereTemperatureSeaLevel { get; set; } 47 | public double atmosphereTemperatureLapseRate { get; set; } 48 | public double atmospherePressureSeaLevel { get; set; } 49 | public double atmDensityASL { get; set; } 50 | public double atmosphereGasMassLapseRate { get; set; } 51 | public double atmosphereMolarMass { get; set; } 52 | public double atmosphereAdiabaticIndex { get; set; } 53 | public double radiusAtmoFactor { get; set; } 54 | public bool atmosphereUsePressureCurve { get; set; } 55 | public bool atmospherePressureCurveIsNormalized { get; set; } 56 | public FloatCurve atmospherePressureCurve { get; set; } 57 | public bool atmosphereUseTemperatureCurve { get; set; } 58 | public bool atmosphereTemperatureCurveIsNormalized { get; set; } 59 | public FloatCurve atmosphereTemperatureCurve { get; set; } 60 | public FloatCurve atmosphereTemperatureSunMultCurve { get; set; } 61 | public bool rotates { get; set; } 62 | public double rotationPeriod { get; set; } 63 | public double initialRotation { get; set; } 64 | public bool tidallyLocked { get; set; } 65 | public Orbit orbit { get; set; } 66 | 67 | public PlanetSettings( 68 | double GeeASL, 69 | bool ocean, 70 | bool atmosphere, 71 | bool atmosphereContainsOxygen, 72 | double atmosphereDepth, 73 | double atmosphereTemperatureSeaLevel, 74 | double atmosphereTemperatureLapseRate, 75 | double atmospherePressureSeaLevel, 76 | double atmDensityASL, 77 | double atmosphereGasMassLapseRate, 78 | double atmosphereMolarMass, 79 | double atmosphereAdiabaticIndex, 80 | double radiusAtmoFactor, 81 | bool atmosphereUsePressureCurve, 82 | bool atmospherePressureCurveIsNormalized, 83 | FloatCurve atmospherePressureCurve, 84 | bool atmosphereUseTemperatureCurve, 85 | bool atmosphereTemperatureCurveIsNormalized, 86 | FloatCurve atmosphereTemperatureCurve, 87 | FloatCurve atmosphereTemperatureSunMultCurve, 88 | bool rotates, 89 | double rotationPeriod, 90 | double initialRotation, 91 | bool tidallyLocked, 92 | Orbit orbit) : this() 93 | { 94 | this.GeeASL = GeeASL; 95 | this.ocean = ocean; 96 | this.atmosphere = atmosphere; 97 | this.atmosphereContainsOxygen = atmosphereContainsOxygen; 98 | this.atmosphereDepth = atmosphereDepth; 99 | this.atmosphereTemperatureSeaLevel = atmosphereTemperatureSeaLevel; 100 | this.atmosphereTemperatureLapseRate = atmosphereTemperatureLapseRate; 101 | this.atmospherePressureSeaLevel = atmospherePressureSeaLevel; 102 | this.atmDensityASL = atmDensityASL; 103 | this.atmosphereGasMassLapseRate = atmosphereGasMassLapseRate; 104 | this.atmosphereMolarMass = atmosphereMolarMass; 105 | this.atmosphereAdiabaticIndex = atmosphereAdiabaticIndex; 106 | this.radiusAtmoFactor = radiusAtmoFactor; 107 | this.atmosphereUsePressureCurve = atmosphereUsePressureCurve; 108 | this.atmospherePressureCurveIsNormalized = atmospherePressureCurveIsNormalized; 109 | this.atmospherePressureCurve = atmospherePressureCurve; 110 | this.atmosphereUseTemperatureCurve = atmosphereUseTemperatureCurve; 111 | this.atmosphereTemperatureCurveIsNormalized = atmosphereTemperatureCurveIsNormalized; 112 | this.atmosphereTemperatureCurve = atmosphereTemperatureCurve; 113 | this.atmosphereTemperatureSunMultCurve = atmosphereTemperatureSunMultCurve; 114 | this.rotates = rotates; 115 | this.rotationPeriod = rotationPeriod; 116 | this.initialRotation = initialRotation; 117 | this.tidallyLocked = tidallyLocked; 118 | this.orbit = orbit; 119 | } 120 | 121 | public PlanetSettings(CelestialBody body) 122 | : this() 123 | { 124 | GeeASL = body.GeeASL; 125 | ocean = body.ocean; 126 | atmosphere = body.atmosphere; 127 | atmosphereContainsOxygen = body.atmosphereContainsOxygen; 128 | atmosphereDepth = body.atmosphereDepth; 129 | atmosphereTemperatureSeaLevel = body.atmosphereTemperatureSeaLevel; 130 | atmosphereTemperatureLapseRate = body.atmosphereTemperatureLapseRate; 131 | atmospherePressureSeaLevel = body.atmospherePressureSeaLevel; 132 | atmDensityASL = body.atmDensityASL; 133 | atmosphereGasMassLapseRate = body.atmosphereGasMassLapseRate; 134 | atmosphereMolarMass = body.atmosphereMolarMass; 135 | atmosphereAdiabaticIndex = body.atmosphereAdiabaticIndex; 136 | radiusAtmoFactor = body.radiusAtmoFactor; 137 | atmosphereUsePressureCurve = body.atmosphereUsePressureCurve; 138 | atmospherePressureCurveIsNormalized = body.atmospherePressureCurveIsNormalized; 139 | atmospherePressureCurve = body.atmospherePressureCurve; 140 | atmosphereUseTemperatureCurve = body.atmosphereUseTemperatureCurve; 141 | atmosphereTemperatureCurveIsNormalized = body.atmosphereTemperatureCurveIsNormalized; 142 | atmosphereTemperatureCurve = body.atmosphereTemperatureCurve; 143 | atmosphereTemperatureSunMultCurve = body.atmosphereTemperatureSunMultCurve; 144 | rotates = body.rotates; 145 | rotationPeriod = body.rotationPeriod; 146 | initialRotation = body.initialRotation; 147 | tidallyLocked = body.tidallyLocked; 148 | orbit = body.orbitDriver?.orbit.Clone(); 149 | 150 | if (DefaultSettings.ContainsKey(body.bodyName) == false) 151 | { 152 | DefaultSettings.Add(body.bodyName, this); 153 | } 154 | } 155 | 156 | public void CopyTo(CelestialBody body, bool setOrbit) 157 | { 158 | body.GeeASL = GeeASL; 159 | body.ocean = ocean; 160 | body.atmosphere = atmosphere; 161 | body.atmosphereContainsOxygen = atmosphereContainsOxygen; 162 | body.atmosphereDepth = atmosphereDepth; 163 | body.atmosphereTemperatureSeaLevel = atmosphereTemperatureSeaLevel; 164 | body.atmosphereTemperatureLapseRate = atmosphereTemperatureLapseRate; 165 | body.atmospherePressureSeaLevel = atmospherePressureSeaLevel; 166 | body.atmDensityASL = atmDensityASL; 167 | body.atmosphereGasMassLapseRate = atmosphereGasMassLapseRate; 168 | body.atmosphereMolarMass = atmosphereMolarMass; 169 | body.atmosphereAdiabaticIndex = atmosphereAdiabaticIndex; 170 | body.radiusAtmoFactor = radiusAtmoFactor; 171 | body.atmosphereUsePressureCurve = atmosphereUsePressureCurve; 172 | body.atmospherePressureCurveIsNormalized = atmospherePressureCurveIsNormalized; 173 | body.atmospherePressureCurve = atmospherePressureCurve; 174 | body.atmosphereUseTemperatureCurve = atmosphereUseTemperatureCurve; 175 | body.atmosphereTemperatureCurveIsNormalized = atmosphereTemperatureCurveIsNormalized; 176 | body.atmosphereTemperatureCurve = atmosphereTemperatureCurve; 177 | body.atmosphereTemperatureSunMultCurve = atmosphereTemperatureSunMultCurve; 178 | body.rotates = rotates; 179 | body.rotationPeriod = rotationPeriod; 180 | body.initialRotation = initialRotation; 181 | body.tidallyLocked = tidallyLocked; 182 | 183 | if (setOrbit && body.orbitDriver != null && orbit != null) 184 | body.SetOrbit(orbit); 185 | 186 | body.RealCbUpdate(); 187 | 188 | Extensions.Log($"Set body \"{body.bodyName}\"'s parameters to:\n{GetConfig(body)}"); 189 | } 190 | 191 | public static ConfigNode GetConfig(CelestialBody body) 192 | { 193 | var node = new ConfigNode(body.bodyName); 194 | 195 | node.AddValue("GeeASL", body.GeeASL); 196 | node.AddValue("ocean", body.ocean); 197 | node.AddValue("atmosphere", body.atmosphere); 198 | node.AddValue("atmosphereContainsOxygen", body.atmosphereContainsOxygen); 199 | node.AddValue("atmosphereDepth", body.atmosphereDepth); 200 | node.AddValue("atmosphereTemperatureSeaLevel", body.atmosphereTemperatureSeaLevel); 201 | node.AddValue("atmosphereTemperatureLapseRate", body.atmosphereTemperatureLapseRate); 202 | node.AddValue("atmospherePressureSeaLevel", body.atmospherePressureSeaLevel); 203 | node.AddValue("atmDensityASL", body.atmDensityASL); 204 | node.AddValue("atmosphereGasMassLapseRate", body.atmosphereGasMassLapseRate); 205 | node.AddValue("atmosphereMolarMass", body.atmosphereMolarMass); 206 | node.AddValue("atmosphereAdiabaticIndex", body.atmosphereAdiabaticIndex); 207 | node.AddValue("radiusAtmoFactor", body.radiusAtmoFactor); 208 | node.AddValue("atmosphereUsePressureCurve", body.atmosphereUsePressureCurve); 209 | node.AddValue("atmospherePressureCurveIsNormalized", body.atmospherePressureCurveIsNormalized); 210 | if (body.atmospherePressureCurve != null) 211 | { 212 | ConfigNode apc = node.AddNode("atmospherePressureCurve"); 213 | body.atmospherePressureCurve.Save(apc); 214 | } 215 | node.AddValue("atmosphereUseTemperatureCurve", body.atmosphereUseTemperatureCurve); 216 | node.AddValue("atmosphereTemperatureCurveIsNormalized", body.atmosphereTemperatureCurveIsNormalized); 217 | if (body.atmosphereTemperatureCurve != null) 218 | { 219 | ConfigNode tpc = node.AddNode("atmosphereTemperatureCurve"); 220 | body.atmosphereTemperatureCurve.Save(tpc); 221 | } 222 | if (body.atmosphereTemperatureSunMultCurve != null) 223 | { 224 | ConfigNode atsmc = node.AddNode("atmosphereTemperatureSunMultCurve"); 225 | body.atmosphereTemperatureSunMultCurve.Save(atsmc); 226 | } 227 | node.AddValue("rotates", body.rotates); 228 | node.AddValue("rotationPeriod", body.rotationPeriod); 229 | node.AddValue("initialRotation", body.initialRotation); 230 | node.AddValue("tidallyLocked", body.tidallyLocked); 231 | 232 | if (body.orbitDriver == null) 233 | return node; 234 | var orbit = body.orbitDriver.orbit; 235 | node.AddValue("inclination", orbit.inclination); 236 | node.AddValue("eccentricity", orbit.eccentricity); 237 | node.AddValue("semiMajorAxis", orbit.semiMajorAxis); 238 | node.AddValue("LAN", orbit.LAN); 239 | node.AddValue("argumentOfPeriapsis", orbit.argumentOfPeriapsis); 240 | node.AddValue("meanAnomalyAtEpoch", orbit.meanAnomalyAtEpoch); 241 | node.AddValue("orbitEpoch", orbit.epoch); 242 | node.AddValue("orbitBody", orbit.referenceBody.bodyName); 243 | return node; 244 | } 245 | 246 | public static void ApplyConfig(ConfigNode node, CelestialBody body) 247 | { 248 | node.TryGetValue("GeeASL", ref body.GeeASL, double.TryParse); 249 | node.TryGetValue("ocean", ref body.ocean, bool.TryParse); 250 | node.TryGetValue("atmosphere", ref body.atmosphere, bool.TryParse); 251 | node.TryGetValue("atmosphereContainsOxygen", ref body.atmosphereContainsOxygen, bool.TryParse); 252 | node.TryGetValue("atmosphereDepth", ref body.atmosphereDepth, double.TryParse); 253 | node.TryGetValue("atmosphereTemperatureSeaLevel", ref body.atmosphereTemperatureSeaLevel, double.TryParse); 254 | node.TryGetValue("atmosphereTemperatureLapseRate", ref body.atmosphereTemperatureLapseRate, double.TryParse); 255 | node.TryGetValue("atmospherePressureSeaLevel", ref body.atmospherePressureSeaLevel, double.TryParse); 256 | node.TryGetValue("atmDensityASL", ref body.atmDensityASL, double.TryParse); 257 | node.TryGetValue("atmosphereGasMassLapseRate", ref body.atmosphereGasMassLapseRate, double.TryParse); 258 | node.TryGetValue("atmosphereMolarMass", ref body.atmosphereMolarMass, double.TryParse); 259 | node.TryGetValue("atmosphereAdiabaticIndex", ref body.atmosphereAdiabaticIndex, double.TryParse); 260 | node.TryGetValue("radiusAtmoFactor", ref body.radiusAtmoFactor, double.TryParse); 261 | node.TryGetValue("atmosphereUsePressureCurve", ref body.atmosphereUsePressureCurve, bool.TryParse); 262 | node.TryGetValue("atmospherePressureCurveIsNormalized", ref body.atmospherePressureCurveIsNormalized, bool.TryParse); 263 | ConfigNode apc = new ConfigNode(); 264 | if (node.TryGetNode("atmospherePressureCurve", ref apc)) 265 | { 266 | FloatCurve floatCurve = new FloatCurve(); 267 | floatCurve.Load(apc); 268 | body.atmospherePressureCurve = floatCurve; 269 | } 270 | node.TryGetValue("atmosphereUseTemperatureCurve", ref body.atmosphereUseTemperatureCurve, bool.TryParse); 271 | node.TryGetValue("atmosphereTemperatureCurveIsNormalized", ref body.atmosphereTemperatureCurveIsNormalized, bool.TryParse); 272 | ConfigNode tpc = new ConfigNode(); 273 | if (node.TryGetNode("atmosphereTemperatureCurve", ref tpc)) 274 | { 275 | FloatCurve floatCurve = new FloatCurve(); 276 | floatCurve.Load(tpc); 277 | body.atmosphereTemperatureCurve = floatCurve; 278 | } 279 | ConfigNode atsmc = new ConfigNode(); 280 | if (node.TryGetNode("atmosphereTemperatureSunMultCurve", ref atsmc)) 281 | { 282 | FloatCurve floatCurve = new FloatCurve(); 283 | floatCurve.Load(atsmc); 284 | body.atmosphereTemperatureSunMultCurve = floatCurve; 285 | } 286 | node.TryGetValue("rotates", ref body.rotates, bool.TryParse); 287 | node.TryGetValue("rotationPeriod", ref body.rotationPeriod, double.TryParse); 288 | node.TryGetValue("initialRotation", ref body.initialRotation, double.TryParse); 289 | node.TryGetValue("tidallyLocked", ref body.tidallyLocked, bool.TryParse); 290 | 291 | if (body.orbitDriver != null) 292 | { 293 | var orbit = body.orbitDriver.orbit.Clone(); 294 | node.TryGetValue("inclination", ref orbit.inclination, double.TryParse); 295 | node.TryGetValue("eccentricity", ref orbit.eccentricity, double.TryParse); 296 | node.TryGetValue("semiMajorAxis", ref orbit.semiMajorAxis, double.TryParse); 297 | node.TryGetValue("LAN", ref orbit.LAN, double.TryParse); 298 | node.TryGetValue("argumentOfPeriapsis", ref orbit.argumentOfPeriapsis, double.TryParse); 299 | node.TryGetValue("meanAnomalyAtEpoch", ref orbit.meanAnomalyAtEpoch, double.TryParse); 300 | node.TryGetValue("orbitEpoch", ref orbit.epoch, double.TryParse); 301 | node.TryGetValue("orbitBody", ref orbit.referenceBody, Extensions.CbTryParse); 302 | body.SetOrbit(orbit); 303 | } 304 | 305 | body.RealCbUpdate(); 306 | 307 | Extensions.Log($"Set body \"{body.bodyName}\"'s parameters to:\n{GetConfig(body)}"); 308 | } 309 | } 310 | 311 | private static CelestialBody _kerbin; 312 | 313 | public static CelestialBody Kerbin 314 | { 315 | get 316 | { 317 | return _kerbin ?? 318 | (_kerbin = FlightGlobals.fetch == null ? null : 319 | FlightGlobals.fetch.bodies.FirstOrDefault(cb => cb.bodyName == "Kerbin")); 320 | } 321 | } 322 | 323 | public static void ResetToDefault(CelestialBody body) 324 | { 325 | try 326 | { 327 | var defaultCb = DefaultSettings[body.bodyName]; 328 | defaultCb.CopyTo(body, true); 329 | } 330 | catch (KeyNotFoundException) 331 | { 332 | Extensions.Log("Defaults for celestial body " + body.bodyName + " not found"); 333 | } 334 | } 335 | 336 | public static void SavePlanet(CelestialBody body) 337 | { 338 | PlanetSettings.GetConfig(body).Save(); 339 | } 340 | 341 | public static void TryApplyFileDefaults() 342 | { 343 | if (_haveAppliedDefaults) 344 | return; 345 | ApplyFileDefaults(); 346 | } 347 | 348 | public static void ApplyFileDefaults() 349 | { 350 | if (FlightGlobals.fetch == null || FlightGlobals.Bodies == null) 351 | { 352 | Extensions.Log("Could not apply planet defaults: FlightGlobals.Bodies was null"); 353 | return; 354 | } 355 | _haveAppliedDefaults = true; 356 | foreach (var body in FlightGlobals.Bodies) 357 | { 358 | new PlanetSettings(body); // trigger default settings check 359 | var filepath = IoExt.GetPath(body.bodyName + ".cfg"); 360 | if (System.IO.File.Exists(filepath) == false) 361 | continue; 362 | var cfg = ConfigNode.Load(filepath); 363 | Extensions.Log("Applying saved config for " + body.bodyName); 364 | PlanetSettings.ApplyConfig(cfg, body); 365 | } 366 | } 367 | } 368 | } 369 | -------------------------------------------------------------------------------- /Source/Core.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using UnityEngine; 6 | using KSP.UI.Screens; 7 | using System.Reflection; 8 | using System.Diagnostics; 9 | 10 | [assembly: System.Reflection.AssemblyProduct("HyperEdit")] 11 | [assembly: System.Reflection.AssemblyTitle("HyperEdit")] 12 | [assembly: System.Reflection.AssemblyDescription("A plugin mod for Kerbal Space Program")] 13 | [assembly: System.Reflection.AssemblyCompany("Kerbaltek")] 14 | [assembly: System.Reflection.AssemblyCopyright("Erickson Swift")] 15 | [assembly: System.Reflection.AssemblyVersion("1.5.8.0")] 16 | 17 | [KSPAddon(KSPAddon.Startup.SpaceCentre, true)] // Determines when plugin starts. 18 | public class HyperEditModule : MonoBehaviour { 19 | static List appListModHidden; 20 | 21 | public void Awake() // Called after scene (designated w/ KSPAddon) loads, but before Start(). Init data here. 22 | { 23 | HyperEdit.Immortal.AddImmortal(); 24 | } 25 | 26 | private void Start() { 27 | // following needed to fix a stock bug 28 | appListModHidden = (List)typeof(ApplicationLauncher).GetField("appListModHidden", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ApplicationLauncher.Instance); 29 | DontDestroyOnLoad(this); 30 | } 31 | 32 | double lasttimecheck = 0; 33 | GameScenes lastScene = GameScenes.LOADING; 34 | double lastTime = 0; 35 | 36 | private void FixedUpdate() { 37 | if (HighLogic.LoadedScene != lastScene) { 38 | lastScene = HighLogic.LoadedScene; 39 | lastTime = Time.fixedTime; 40 | } 41 | if (Time.fixedTime - lastTime < 2) { 42 | if (Time.fixedTime - lasttimecheck > .1) { 43 | lasttimecheck = Time.fixedTime; 44 | // following fixes a stock bug 45 | if (appListModHidden.Contains(HyperEdit.HyperEditBehaviour.appButton)) { 46 | HyperEdit.HyperEditBehaviour.appButton.gameObject.SetActive(false); 47 | if (HyperEdit.HyperEditBehaviour.appButton.enabled) { 48 | HyperEdit.HyperEditBehaviour.appButton.onDisable(); 49 | } 50 | } 51 | } 52 | 53 | } 54 | } 55 | } 56 | 57 | namespace HyperEdit { 58 | public delegate bool TryParse(string str, out T value); 59 | 60 | public static class Immortal { 61 | private static GameObject _gameObject; 62 | 63 | public static T AddImmortal() where T : Component { 64 | if (_gameObject == null) { 65 | _gameObject = new GameObject("HyperEditImmortal", typeof(T)); 66 | UnityEngine.Object.DontDestroyOnLoad(_gameObject); 67 | } 68 | return _gameObject.GetComponent() ?? _gameObject.AddComponent(); 69 | } 70 | } 71 | 72 | public class HyperEditBehaviour : MonoBehaviour { 73 | private ConfigNode _hyperEditConfig; 74 | private bool _useAppLauncherButton; 75 | private static ApplicationLauncherButton _appLauncherButton; 76 | private Action _createCoreView; 77 | private Action _createLanderView; 78 | private bool _autoOpenLanderValue; 79 | 80 | public static ApplicationLauncherButton appButton { 81 | get { return _appLauncherButton; } 82 | } 83 | 84 | public HyperEditBehaviour() // Constructor. Don't init data here cuz Unity, do so in Awake(); 85 | { 86 | // Extensions.Log("[" + this.GetInstanceID().ToString("X") + "][" + Time.time.ToString("0.0000") + "]: Constructor()"); 87 | } 88 | 89 | public void Awake() // Called after scene (designated w/ KSPAddon) loads, but before Start(). Init data here. 90 | { 91 | // Extensions.Log("[" + this.GetInstanceID().ToString("X") + "][" + Time.time.ToString("0.0000") + "]: Awake()"); 92 | View.Window.AreWindowsOpenChange += AreWindowsOpenChange; 93 | GameEvents.onGUIApplicationLauncherReady.Add(AddAppLauncher); 94 | GameEvents.onGUIApplicationLauncherDestroyed.Add(RemoveAppLauncher); 95 | GameEvents.onLevelWasLoaded.Add(SceneUpdate); 96 | } 97 | 98 | public void Start() // Called after all mods are Awake(). 99 | { 100 | //Extensions.Log("[" + this.GetInstanceID().ToString("X") + "][" + Time.time.ToString("0.0000") + "]: Start()"); 101 | ReloadConfig(); 102 | } 103 | 104 | private void CreateCoreView() { 105 | ReloadConfig(); 106 | if (_createCoreView == null) { 107 | _createCoreView = View.CoreView.Create(this); 108 | } 109 | _createCoreView(); 110 | if (_autoOpenLanderValue == true && !View.Window.GameObject.GetComponents().Any(w => w.Title == "Lander")) { 111 | CreateLanderView(); 112 | } 113 | } 114 | 115 | private void CreateLanderView() { 116 | if (_createLanderView == null) { 117 | _createLanderView = View.LanderView.Create(); 118 | } 119 | _createLanderView(); 120 | } 121 | 122 | // SceneUpdate() fires only when the scene changes. 123 | private void SceneUpdate(GameScenes data) { 124 | ReloadConfig(); 125 | if (HighLogic.LoadedScene == GameScenes.FLIGHT || HighLogic.LoadedScene == GameScenes.TRACKSTATION) { 126 | if (_autoOpenLanderValue == true && !View.Window.GameObject.GetComponents().Any(w => w.Title == "Lander")) { 127 | CreateLanderView(); 128 | } 129 | } else { 130 | View.Window.CloseAll(); 131 | } 132 | } 133 | 134 | // FixedUpdate() fires every physics time step. 135 | public void FixedUpdate() => Model.PlanetEditor.TryApplyFileDefaults(); 136 | 137 | // Update() fires every frame. 138 | public void Update() { 139 | RateLimitedLogger.Update(); 140 | if ((Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)) && Input.GetKeyDown(KeyCode.H)) { 141 | // Linuxgurugamer added this scene check to keep HyperEdit off in the editors. 142 | if (HighLogic.LoadedScene == GameScenes.FLIGHT || HighLogic.LoadedScene == GameScenes.TRACKSTATION) { 143 | if (View.Window.GameObject.GetComponents().Any(w => w.Title == "HyperEdit")) { 144 | if (_appLauncherButton == null) { 145 | View.Window.CloseAll(); 146 | } else { 147 | _appLauncherButton.SetFalse(); 148 | } 149 | } else { 150 | if (_appLauncherButton == null) { 151 | CreateCoreView(); 152 | } else { 153 | _appLauncherButton.SetTrue(); 154 | } 155 | } 156 | } 157 | } 158 | } 159 | 160 | private void ReloadConfig() { 161 | var hypereditCfg = IoExt.GetPath("hyperedit.cfg"); 162 | if (System.IO.File.Exists(hypereditCfg)) { 163 | _hyperEditConfig = ConfigNode.Load(hypereditCfg); 164 | _hyperEditConfig.name = "hyperedit"; 165 | } else { 166 | _hyperEditConfig = new ConfigNode("hyperedit"); 167 | _hyperEditConfig.SetValue("AutoOpenLander", false.ToString(), true); 168 | } 169 | 170 | var launcherButtonValue = true; 171 | _hyperEditConfig.TryGetValue("UseAppLauncherButton", ref launcherButtonValue, bool.TryParse); 172 | UseAppLauncherButton = launcherButtonValue; 173 | 174 | _hyperEditConfig.TryGetValue("AutoOpenLander", ref _autoOpenLanderValue, bool.TryParse); 175 | } 176 | 177 | private void AreWindowsOpenChange(bool isOpen) { 178 | if (_appLauncherButton != null) { 179 | if (isOpen) { 180 | _appLauncherButton.SetTrue(false); 181 | } else { 182 | _appLauncherButton.SetFalse(false); 183 | } 184 | } 185 | } 186 | 187 | public bool UseAppLauncherButton { 188 | get { return _useAppLauncherButton; } 189 | set { 190 | if (_useAppLauncherButton == value) 191 | return; 192 | _useAppLauncherButton = value; 193 | if (value) { 194 | AddAppLauncher(); 195 | } else { 196 | RemoveAppLauncher(); 197 | } 198 | _hyperEditConfig.SetValue("UseAppLauncherButton", value.ToString(), true); 199 | _hyperEditConfig.Save(); 200 | } 201 | } 202 | 203 | private void AddAppLauncher() { 204 | if (_useAppLauncherButton == false) 205 | return; 206 | if (_appLauncherButton != null) { 207 | Extensions.Log( 208 | "Not adding to ApplicationLauncher, button already exists (yet onGUIApplicationLauncherReady was called?)"); 209 | return; 210 | } 211 | var applauncher = ApplicationLauncher.Instance; 212 | if (applauncher == null) { 213 | Extensions.Log("Cannot add to ApplicationLauncher, instance was null"); 214 | return; 215 | } 216 | const ApplicationLauncher.AppScenes scenes = 217 | ApplicationLauncher.AppScenes.FLIGHT | 218 | ApplicationLauncher.AppScenes.MAPVIEW | 219 | ApplicationLauncher.AppScenes.TRACKSTATION; 220 | var tex = new Texture2D(38, 38, TextureFormat.RGBA32, false); 221 | 222 | for (var x = 0; x < tex.width; x++) 223 | for (var y = 0; y < tex.height; y++) 224 | tex.SetPixel(x, y, 225 | new Color(2 * (float)Math.Abs(x - tex.width / 2) / tex.width, 0.25f, 226 | 2 * (float)Math.Abs(y - tex.height / 2) / tex.height, 0)); 227 | for (var x = 10; x < 12; x++) 228 | for (var y = 10; y < tex.height - 10; y++) 229 | tex.SetPixel(x, y, new Color(1, 1, 1)); 230 | for (var x = tex.width - 12; x < tex.width - 10; x++) 231 | for (var y = 10; y < tex.height - 10; y++) 232 | tex.SetPixel(x, y, new Color(1, 1, 1)); 233 | for (var x = 12; x < tex.width - 12; x++) 234 | for (var y = tex.height / 2; y < tex.height / 2 + 2; y++) 235 | tex.SetPixel(x, y, new Color(1, 1, 1)); 236 | 237 | tex.Apply(); 238 | _appLauncherButton = applauncher.AddModApplication( 239 | CreateCoreView, // onTrue 240 | View.Window.CloseAll, // onFalse 241 | () => { }, // onHover 242 | () => { }, // onHoverOut 243 | () => { }, // onEnable 244 | () => { }, // onDisable 245 | scenes, // visibleInScenes 246 | tex // texture 247 | ); 248 | } 249 | 250 | private void RemoveAppLauncher() { 251 | var applauncher = ApplicationLauncher.Instance; 252 | if (applauncher == null) { 253 | Extensions.Log("Cannot remove from ApplicationLauncher, instance was null"); 254 | return; 255 | } 256 | if (_appLauncherButton == null) { 257 | return; 258 | } 259 | applauncher.RemoveModApplication(_appLauncherButton); 260 | _appLauncherButton = null; 261 | } 262 | 263 | // End of class. 264 | } 265 | 266 | public static class IoExt { 267 | private static readonly string PluginDir = System.IO.Path.Combine(System.IO.Path.ChangeExtension(typeof(IoExt).Assembly.Location, null), ".."); 268 | private static readonly string PluginDataDir = System.IO.Path.Combine(PluginDir, "PluginData"); 269 | 270 | //private static readonly string RootDir = System.IO.Path.Combine(System.IO.Path.ChangeExtension(typeof(IoExt).Assembly.Location, null), "PluginData"); 271 | private static readonly string RootDir = PluginDataDir; 272 | 273 | static IoExt() { 274 | if (!System.IO.Directory.Exists(RootDir)) { 275 | System.IO.Directory.CreateDirectory(RootDir); 276 | } 277 | 278 | Extensions.Log("Using '" + RootDir + "' as root config directory"); 279 | } 280 | 281 | public static string GetPath(string path) => path == null ? RootDir : System.IO.Path.Combine(RootDir, path); 282 | 283 | public static void Save(this ConfigNode config) => config.Save(GetPath(config.name + ".cfg")); 284 | } 285 | 286 | public static class RateLimitedLogger { 287 | private const int MaxFrequency = 100; // measured in number of frames 288 | 289 | private class Countdown { 290 | public string LastMessage; 291 | public int FramesLeft; 292 | public bool NeedsPrint; 293 | 294 | public Countdown(string msg, int frames) { 295 | LastMessage = msg; 296 | FramesLeft = frames; 297 | NeedsPrint = false; 298 | } 299 | } 300 | 301 | private static readonly Dictionary Messages = new Dictionary(); 302 | 303 | public static void Update() { 304 | List toRemove = null; 305 | foreach (var kvp in Messages) { 306 | if (kvp.Value.FramesLeft == 0) { 307 | if (kvp.Value.NeedsPrint) { 308 | kvp.Value.NeedsPrint = false; 309 | kvp.Value.FramesLeft = MaxFrequency; 310 | 311 | Extensions.Log(kvp.Value.LastMessage); 312 | } else { 313 | if (toRemove == null) { 314 | toRemove = new List(); 315 | } 316 | toRemove.Add(kvp.Key); 317 | } 318 | } else { 319 | kvp.Value.FramesLeft--; 320 | } 321 | } 322 | if (toRemove != null) { 323 | foreach (var key in toRemove) { 324 | Messages.Remove(key); 325 | } 326 | } 327 | } 328 | 329 | public static void Log(object key, string message) { 330 | Countdown countdown; 331 | if (Messages.TryGetValue(key, out countdown)) { 332 | countdown.NeedsPrint = true; 333 | countdown.LastMessage = message; 334 | } else { 335 | Extensions.Log(message); 336 | Messages[key] = new Countdown(message, MaxFrequency); 337 | } 338 | } 339 | } 340 | 341 | public static class Extensions { 342 | /// 343 | /// Debug logging. Only compiles in DEBUG builds. 344 | /// 345 | /// 346 | [ConditionalAttribute("DEBUG")] 347 | public static void Log(string message) { 348 | UnityEngine.Debug.Log("HyperEdit: " + message); 349 | } 350 | 351 | /// 352 | /// Comma separated debug logging. Only compiles in DEBUG builds. 353 | /// 354 | /// 355 | [ConditionalAttribute("DEBUG")] 356 | public static void ALog(params object[] message) { 357 | StringBuilder sb = new StringBuilder(); 358 | for (int i = 0; i < message.Length; i++) { 359 | sb.Append(message[i].ToString()); 360 | sb.Append("\t"); 361 | } 362 | String s = sb.ToString().Trim(); 363 | UnityEngine.Debug.Log("HyperEdit: " + s); 364 | } 365 | 366 | public static void TryGetValue(this ConfigNode node, string key, ref T value, TryParse tryParse) { 367 | var strvalue = node.GetValue(key); 368 | if (strvalue == null) 369 | return; 370 | if (tryParse == null) { 371 | // `T` better be `string`... 372 | value = (T)(object)strvalue; 373 | return; 374 | } 375 | T temp; 376 | if (tryParse(strvalue, out temp) == false) { 377 | return; 378 | } 379 | value = temp; 380 | } 381 | 382 | private static GUIStyle _pressedButton; 383 | 384 | public static GUIStyle PressedButton => _pressedButton ?? (_pressedButton = new GUIStyle(HighLogic.Skin.button) { 385 | normal = HighLogic.Skin.button.active, 386 | hover = HighLogic.Skin.button.active, 387 | active = HighLogic.Skin.button.normal 388 | }); 389 | 390 | public static void RealCbUpdate(this CelestialBody body) { 391 | body.CBUpdate(); 392 | try { 393 | body.resetTimeWarpLimits(); 394 | } 395 | catch (NullReferenceException) { 396 | Log("resetTimeWarpLimits threw NRE " + (TimeWarp.fetch == null ? "as expected" : "unexpectedly")); 397 | } 398 | 399 | // CBUpdate doesn't update hillSphere 400 | // http://en.wikipedia.org/wiki/Hill_sphere 401 | var orbit = body.orbit; 402 | var cubedRoot = Math.Pow(body.Mass / orbit.referenceBody.Mass, 1.0 / 3.0); 403 | body.hillSphere = orbit.semiMajorAxis * (1.0 - orbit.eccentricity) * cubedRoot; 404 | 405 | // Nor sphereOfInfluence 406 | // http://en.wikipedia.org/wiki/Sphere_of_influence_(astrodynamics) 407 | body.sphereOfInfluence = orbit.semiMajorAxis * Math.Pow(body.Mass / orbit.referenceBody.Mass, 2.0 / 5.0); 408 | } 409 | 410 | public static void PrepVesselTeleport(this Vessel vessel) { 411 | if (vessel.Landed) { 412 | vessel.Landed = false; 413 | Log("Set ActiveVessel.Landed = false"); 414 | } 415 | if (vessel.Splashed) { 416 | vessel.Splashed = false; 417 | Log("Set ActiveVessel.Splashed = false"); 418 | } 419 | if (vessel.landedAt != string.Empty) { 420 | vessel.landedAt = string.Empty; 421 | Log("Set ActiveVessel.landedAt = \"\""); 422 | } 423 | var parts = vessel.parts; 424 | if (parts != null) { 425 | var killcount = 0; 426 | foreach (var part in parts.Where(part => part.Modules.OfType().Any()).ToList()) { 427 | killcount++; 428 | part.Die(); 429 | } 430 | if (killcount != 0) { 431 | Log($"Removed {killcount} launch clamps from {vessel.vesselName}"); 432 | } 433 | } 434 | } 435 | 436 | /// 437 | /// Sphere of Influence. 438 | /// 439 | /// 440 | /// 441 | public static double Soi(this CelestialBody body) { 442 | var radius = body.sphereOfInfluence * 0.95; 443 | if (double.IsNaN(radius) || double.IsInfinity(radius) || radius < 0 || radius > 200000000000) { 444 | radius = 200000000000; // jool apo = 72,212,238,387 445 | } 446 | return radius; 447 | } 448 | 449 | public static double Mod(this double x, double y) { 450 | var result = x % y; 451 | if (result < 0) { 452 | result += y; 453 | } 454 | return result; 455 | } 456 | 457 | public static string VesselToString(this Vessel vessel) { 458 | if (FlightGlobals.fetch != null && FlightGlobals.ActiveVessel == vessel) { 459 | return "Active vessel"; 460 | } 461 | return vessel.vesselName; 462 | } 463 | 464 | public static string OrbitDriverToString(this OrbitDriver driver) { 465 | if (driver == null) { 466 | return null; 467 | } 468 | if (driver.celestialBody != null) { 469 | return driver.celestialBody.bodyName; 470 | } 471 | if (driver.vessel != null) { 472 | return driver.vessel.VesselToString(); 473 | } 474 | if (!string.IsNullOrEmpty(driver.name)) { 475 | return driver.name; 476 | } 477 | return "Unknown"; 478 | } 479 | 480 | private static Dictionary _keyCodeNames; 481 | 482 | public static Dictionary KeyCodeNames { 483 | get { 484 | return _keyCodeNames ?? (_keyCodeNames = 485 | Enum.GetNames(typeof(KeyCode)) 486 | .Distinct() 487 | .ToDictionary(k => k, k => (KeyCode)Enum.Parse(typeof(KeyCode), k))); 488 | } 489 | } 490 | 491 | public static bool KeyCodeTryParse(string str, out KeyCode[] value) { 492 | var split = str.Split('-', '+'); 493 | if (split.Length == 0) { 494 | value = null; 495 | return false; 496 | } 497 | value = new KeyCode[split.Length]; 498 | for (int i = 0; i < split.Length; i++) { 499 | if (KeyCodeNames.TryGetValue(split[i], out value[i]) == false) { 500 | return false; 501 | } 502 | } 503 | return true; 504 | } 505 | 506 | public static string KeyCodeToString(this KeyCode[] values) { 507 | return string.Join("-", values.Select(v => v.ToString()).ToArray()); 508 | } 509 | 510 | /// 511 | /// Convert Celestial Body to human readable form. 512 | /// 513 | /// Celestial Body 514 | /// The name of the Celestial Body. 515 | public static string CbToString(this CelestialBody body) { 516 | return body.bodyName; 517 | } 518 | 519 | public static bool CbTryParse(string bodyName, out CelestialBody body) { 520 | body = FlightGlobals.Bodies == null ? null : FlightGlobals.Bodies.FirstOrDefault(cb => cb.name == bodyName); 521 | return body != null; 522 | } 523 | 524 | public static void ClearGuiFocus() { 525 | GUIUtility.keyboardControl = 0; 526 | } 527 | 528 | private static string TrimUnityColor(string value) { 529 | value = value.Trim(); 530 | if (value.StartsWith("RGBA", StringComparison.OrdinalIgnoreCase)) { 531 | value = value.Substring(4).Trim(); 532 | } 533 | value = value.Trim('(', ')'); 534 | return value; 535 | } 536 | 537 | public static bool ColorTryParse(string value, out Color color) { 538 | color = new Color(); 539 | string parseValue = TrimUnityColor(value); 540 | if (parseValue == null) { 541 | return false; 542 | } 543 | string[] values = parseValue.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); 544 | if (values.Length == 3 || values.Length == 4) { 545 | if (!float.TryParse(values[0], out color.r) || 546 | !float.TryParse(values[1], out color.g) || 547 | !float.TryParse(values[2], out color.b)) { 548 | return false; 549 | } 550 | if (values.Length == 3 && !float.TryParse(values[3], out color.a)) { 551 | return false; 552 | } 553 | return true; 554 | } 555 | return false; 556 | } 557 | 558 | /// Borrowed from https://github.com/KSP-KOS/KOS. 559 | /// 560 | /// Fix the strange too-large or too-small angle degrees that are sometimes 561 | /// returned by KSP, normalizing them into a constrained 360 degree range. 562 | /// 563 | /// input angle in degrees 564 | /// 565 | /// Bottom of 360 degree range to normalize to. 566 | /// ( 0 means the range [0..360]), while -180 means [-180,180] ) 567 | /// 568 | /// the same angle, normalized to the range given. 569 | public static double DegreeFix(double inAngle, double rangeStart) { 570 | double rangeEnd = rangeStart + 360.0; 571 | double outAngle = inAngle; 572 | while (outAngle > rangeEnd) 573 | outAngle -= 360.0; 574 | while (outAngle < rangeStart) 575 | outAngle += 360.0; 576 | return outAngle; 577 | } 578 | 579 | 580 | } 581 | 582 | public static class Utils { 583 | /// Borrowed from https://github.com/KSP-KOS/KOS. 584 | /// 585 | /// Fix the strange too-large or too-small angle degrees that are sometimes 586 | /// returned by KSP, normalizing them into a constrained 360 degree range. 587 | /// 588 | /// input angle in degrees 589 | /// 590 | /// Bottom of 360 degree range to normalize to. 591 | /// ( 0 means the range [0..360]), while -180 means [-180,180] ) 592 | /// 593 | /// the same angle, normalized to the range given. 594 | public static double DegreeFix(double inAngle, double rangeStart) { 595 | double rangeEnd = rangeStart + 360.0; 596 | double outAngle = inAngle; 597 | while (outAngle > rangeEnd) 598 | outAngle -= 360.0; 599 | while (outAngle < rangeStart) 600 | outAngle += 360.0; 601 | return outAngle; 602 | } 603 | 604 | 605 | 606 | } 607 | } 608 | -------------------------------------------------------------------------------- /Source/Model/Lander.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using UnityEngine; 5 | 6 | namespace HyperEdit.Model { 7 | public static class DoLander { 8 | private const string OldFilename = "landcoords.txt"; 9 | private const string FilenameNoExt = "landcoords"; 10 | private const string RecentEntryName = "Most Recent"; 11 | 12 | public static bool IsLanding() { 13 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) { 14 | return false; 15 | } 16 | 17 | return FlightGlobals.ActiveVessel.GetComponent() != null; 18 | } 19 | 20 | public static void ToggleLanding(double latitude, double longitude, double altitude, CelestialBody body, 21 | bool setRotation, Action onManualEdit) { 22 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null || body == null) { 23 | return; 24 | } 25 | 26 | Extensions.Log("HyperEdit.Model.ToggleLanding"); 27 | Extensions.Log("-----------------------------"); 28 | 29 | var lander = FlightGlobals.ActiveVessel.GetComponent(); 30 | if (lander == null) { 31 | Model.DoLander.AddLastCoords(latitude, longitude, altitude, body); 32 | lander = FlightGlobals.ActiveVessel.gameObject.AddComponent(); 33 | 34 | if (latitude == 0.0f) { 35 | latitude = 0.001; 36 | } 37 | 38 | if (longitude == 0.0f) { 39 | longitude = 0.001; 40 | } 41 | 42 | lander.Latitude = latitude; 43 | lander.Longitude = longitude; 44 | 45 | lander.InterimAltitude = body.Radius + body.atmosphereDepth + 10000d; //Altitude threshold 46 | 47 | lander.Altitude = altitude; 48 | lander.SetRotation = setRotation; 49 | lander.Body = body; 50 | lander.OnManualEdit = onManualEdit; 51 | 52 | Extensions.Log("Latitude : " + latitude.ToString()); 53 | Extensions.Log("Longitude: " + longitude.ToString()); 54 | Extensions.Log("Altitude : " + altitude.ToString()); 55 | Extensions.Log("Body : " + body.ToString()); 56 | Extensions.Log("B-Radius : " + body.Radius.ToString()); 57 | //Extensions.Log("B-Depth : " + body.atmosphereDepth.ToString()); 58 | Extensions.Log("NEW:"); 59 | Extensions.Log("lander = " + lander.ToString()); 60 | Extensions.Log("interimAltitude = " + lander.InterimAltitude); 61 | Extensions.Log("-----------------------------"); 62 | 63 | } else { 64 | //lander != null 65 | Extensions.Log("Unity destroy lander"); 66 | UnityEngine.Object.Destroy(lander); 67 | } 68 | } 69 | 70 | public static void LandHere(Action onManualEdit) { 71 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) { 72 | return; 73 | } 74 | 75 | var vessel = FlightGlobals.ActiveVessel; 76 | var lander = vessel.GetComponent(); 77 | if (lander == null) { 78 | Extensions.Log("LandHere"); 79 | Extensions.Log("-----------------------------"); 80 | 81 | Extensions.Log("Vessel Latitude : " + vessel.latitude.ToString()); 82 | Extensions.Log("Vessel Longitude: " + vessel.longitude.ToString()); 83 | Extensions.Log("Vessel Altitude : " + vessel.altitude.ToString()); 84 | 85 | lander = vessel.gameObject.AddComponent(); 86 | lander.Latitude = vessel.latitude; 87 | lander.Longitude = vessel.longitude; 88 | lander.SetRotation = false; 89 | lander.Body = vessel.mainBody; 90 | lander.OnManualEdit = onManualEdit; 91 | lander.AlreadyTeleported = false; 92 | lander.SetAltitudeToCurrent(); 93 | 94 | Extensions.Log("UPDATE: lander:"); 95 | Extensions.Log("lander = " + lander); 96 | Extensions.Log("-----------------------------"); 97 | 98 | } 99 | } 100 | 101 | private static IEnumerable DefaultSavedCoords { 102 | get { 103 | var kerbin = Planetarium.fetch?.Home; 104 | var minmus = FlightGlobals.fetch?.bodies?.FirstOrDefault(b => b.bodyName == "Minmus"); 105 | if (kerbin == null) { 106 | return new List(); 107 | } 108 | var list = new List 109 | { 110 | new LandingCoordinates("KSC Launch Pad", -0.0972, 285.4423, 20, kerbin), 111 | new LandingCoordinates("KSC Runway", -0.0486, 285.2823, 20, kerbin), 112 | new LandingCoordinates("KSC Beach - Wet", -0.04862627, 285.666, 20, kerbin), 113 | new LandingCoordinates("Airstrip Island Runway", -1.518, 288.1, 35, kerbin), 114 | new LandingCoordinates("Airstrip Island Beach - Wet", -1.518, 287.9503, 20, kerbin) 115 | }; 116 | if (minmus != null) { 117 | list.Add(new LandingCoordinates("Minmus Flats", 0.562859, 175.968846, 20, minmus)); 118 | } 119 | return list; 120 | } 121 | } 122 | 123 | private static List SavedCoords { 124 | get { 125 | var path = IoExt.GetPath(FilenameNoExt + ".cfg"); 126 | var oldPath = IoExt.GetPath(OldFilename); 127 | IEnumerable query; 128 | if (System.IO.File.Exists(path)) { 129 | query = ConfigNode.Load(path).nodes.OfType().Select(c => new LandingCoordinates(c)); 130 | } else if (System.IO.File.Exists(oldPath)) { 131 | query = 132 | System.IO.File.ReadAllLines(oldPath) 133 | .Select(x => new LandingCoordinates(x)) 134 | .Where(l => string.IsNullOrEmpty(l.Name) == false); 135 | } else { 136 | query = new LandingCoordinates[0]; 137 | } 138 | query = query.Union(DefaultSavedCoords); 139 | return query.ToList(); 140 | } 141 | set { 142 | var cfg = new ConfigNode(FilenameNoExt); 143 | foreach (var coord in value) { 144 | cfg.AddNode(coord.ToConfigNode()); 145 | } 146 | cfg.Save(); 147 | } 148 | } 149 | 150 | public static void AddLastCoords(double latitude, double longitude, double altitude, CelestialBody body) { 151 | if (body == null) { 152 | return; 153 | } 154 | 155 | AddSavedCoords(RecentEntryName, latitude, longitude, altitude, body); 156 | } 157 | 158 | public static void AddSavedCoords(double latitude, double longitude, double altitude, CelestialBody body) { 159 | if (body == null) { 160 | return; 161 | } 162 | 163 | View.WindowHelper.Prompt("Save as...", s => AddSavedCoords(s, latitude, longitude, altitude, body)); 164 | } 165 | 166 | private static void AddSavedCoords(string name, double latitude, double longitude, double altitude, CelestialBody body) { 167 | var saved = SavedCoords; 168 | saved.RemoveAll(match => match.Name == name); 169 | saved.Add(new LandingCoordinates(name, latitude, longitude, altitude, body)); 170 | SavedCoords = saved; 171 | } 172 | 173 | public static void LoadLast(Action onLoad) { 174 | var lastC = SavedCoords.Find(c => c.Name == RecentEntryName); 175 | //double-check coords are correct (so that we don't load invalid data!) 176 | onLoad(Extensions.DegreeFix(lastC.Lat,0) , lastC.Lon, lastC.Alt, lastC.Body); 177 | } 178 | 179 | public static void Load(Action onLoad) { 180 | View.WindowHelper.Selector("Load...", SavedCoords, c => c.Name, c => onLoad(c.Lat, c.Lon, c.Alt, c.Body)); 181 | } 182 | 183 | public static void Delete() { 184 | var coords = SavedCoords; 185 | View.WindowHelper.Selector("Delete...", coords, c => c.Name, toDelete => { 186 | coords.Remove(toDelete); 187 | SavedCoords = coords; 188 | }); 189 | } 190 | 191 | public static void SetToCurrent(Action onLoad) { 192 | if (FlightGlobals.fetch == null || FlightGlobals.ActiveVessel == null) { 193 | return; 194 | } 195 | 196 | //FlightGlobals.ActiveVessel.altitude is incorrect. 197 | var Body = FlightGlobals.ActiveVessel.mainBody; 198 | var Latitude = FlightGlobals.ActiveVessel.latitude; 199 | var Longitude = FlightGlobals.ActiveVessel.longitude; 200 | var alt = FlightGlobals.ActiveVessel.radarAltitude; 201 | /* 202 | var pqs = FlightGlobals.ActiveVessel.mainBody.pqsController; 203 | 204 | if (pqs != null) { 205 | var alt = pqs.GetSurfaceHeight(Body.GetRelSurfaceNVector(Latitude, Longitude)) - Body.Radius; 206 | } else { 207 | var alt = FlightGlobals.ActiveVessel.radarAltitude; 208 | } 209 | */ 210 | 211 | onLoad(Latitude, Longitude, alt, Body); 212 | } 213 | 214 | public static IEnumerable LandedVessels() { 215 | return FlightGlobals.fetch == null ? null : FlightGlobals.Vessels.Where(v => v.Landed); 216 | } 217 | 218 | public static void SetToLanded(Action onLoad, Vessel landingBeside) { 219 | if (landingBeside == null) { 220 | return; 221 | } 222 | 223 | //doing this here for brevity and correct altitude display. 224 | var Body = landingBeside.mainBody; 225 | var Latitude = landingBeside.latitude; 226 | var Longitude = landingBeside.longitude; 227 | var alt = landingBeside.radarAltitude; 228 | 229 | onLoad(Latitude, Longitude, alt, Body); 230 | } 231 | 232 | private struct LandingCoordinates : IEquatable { 233 | public string Name { get; } 234 | public double Lat { get; } 235 | public double Lon { get; } 236 | public double Alt { get; } 237 | public CelestialBody Body { get; } 238 | 239 | public LandingCoordinates(string name, double lat, double lon, double alt, CelestialBody body) 240 | : this() { 241 | Name = name; 242 | Lat = lat; 243 | Lon = lon; 244 | Alt = alt; 245 | Body = body; 246 | } 247 | 248 | public LandingCoordinates(string value) 249 | : this() { 250 | var split = value.Split(','); 251 | if (split.Length < 3) { 252 | Name = null; 253 | Lat = 0; 254 | Lon = 0; 255 | Alt = 20; 256 | Body = null; 257 | return; 258 | } 259 | double dlat, dlon, dalt; 260 | if (double.TryParse(split[1], out dlat) && double.TryParse(split[2], out dlon) && double.TryParse(split[2], out dalt)) { 261 | Name = split[0]; 262 | Lat = dlat; 263 | Lon = dlon; 264 | Alt = dalt; 265 | CelestialBody body; 266 | if (split.Length >= 4 && Extensions.CbTryParse(split[3], out body)) { 267 | Body = body; 268 | } else { 269 | Body = Planetarium.fetch.Home; 270 | } 271 | } else { 272 | Name = null; 273 | Lat = 0; 274 | Lon = 0; 275 | Alt = 20; 276 | Body = null; 277 | } 278 | } 279 | 280 | public LandingCoordinates(ConfigNode node) { 281 | CelestialBody body = null; 282 | node.TryGetValue("body", ref body, Extensions.CbTryParse); 283 | Body = body; 284 | var temp = 0.0; 285 | var tempAlt = 20.0; 286 | node.TryGetValue("lat", ref temp, double.TryParse); 287 | Lat = temp; 288 | node.TryGetValue("lon", ref temp, double.TryParse); 289 | Lon = temp; 290 | node.TryGetValue("alt", ref tempAlt, double.TryParse); 291 | Alt = tempAlt; 292 | string name = null; 293 | node.TryGetValue("name", ref name, null); 294 | Name = name; 295 | } 296 | 297 | public override int GetHashCode() { 298 | return Name.GetHashCode(); 299 | } 300 | 301 | public override bool Equals(object obj) { 302 | return obj is LandingCoordinates && Equals((LandingCoordinates)obj); 303 | } 304 | 305 | public bool Equals(LandingCoordinates other) { 306 | return Name.Equals(other.Name); 307 | } 308 | 309 | public override string ToString() { 310 | return Name + "," + Lat + "," + Lon + "," + Alt + "," + Body.CbToString(); 311 | } 312 | 313 | public ConfigNode ToConfigNode() { 314 | var node = new ConfigNode("coordinate"); 315 | node.AddValue("name", Name); 316 | node.AddValue("body", Body.CbToString()); 317 | node.AddValue("lat", Lat); 318 | node.AddValue("lon", Lon); 319 | node.AddValue("alt", Alt); 320 | 321 | //Extensions.Log("Checking ToConfigNode: " + node); 322 | 323 | return node; 324 | } 325 | } 326 | } 327 | 328 | public class LanderAttachment : MonoBehaviour { 329 | public bool AlreadyTeleported { get; set; } 330 | public Action OnManualEdit { get; set; } 331 | public CelestialBody Body { get; set; } 332 | public double Latitude { get; set; } 333 | public double Longitude { get; set; } 334 | public double Altitude { get; set; } 335 | public bool SetRotation { get; set; } 336 | public double InterimAltitude { get; set; } 337 | 338 | private readonly object _accelLogObject = new object(); 339 | private bool teleportedToLandingAlt = false; 340 | private double lastUpdate = 0; 341 | //private double altAGL = 0; // Need to work out these in relation 342 | //private double altASL = 0; // to land or sea. 343 | 344 | /// 345 | /// Sets the vessel altitude to the current calculation. 346 | /// 347 | public void SetAltitudeToCurrent() { 348 | var pqs = Body.pqsController; 349 | if (pqs == null) { 350 | Destroy(this); 351 | return; 352 | } 353 | var alt = pqs.GetSurfaceHeight( 354 | QuaternionD.AngleAxis(Longitude, Vector3d.down) * 355 | QuaternionD.AngleAxis(Latitude, Vector3d.forward) * Vector3d.right) - 356 | pqs.radius; 357 | Extensions.Log("SetAltitudeToCurrent:: alt (pqs.GetSurfaceHeight) = " + alt); 358 | 359 | alt = Math.Max(alt, 0); // Underwater! 360 | /* 361 | * I'm not sure whether this is correct to zero the altitude as there are times on certain bodies 362 | * where the altitude of the surface is below sea level...wish I could remember where it was that 363 | * I found this. 364 | * 365 | * Also HyperEdit used to allow you to land underwater for things like submarines! 366 | */ 367 | 368 | Altitude = GetComponent().altitude - alt; 369 | 370 | Extensions.Log("SetAltitudeToCurrent::"); 371 | Extensions.Log(" alt = Math.Max(alt, 0) := " + alt); 372 | Extensions.Log(" .altitude := " + Altitude); 373 | 374 | } 375 | 376 | public void Update() { 377 | 378 | //Testing whether to kill TimeWarp 379 | if (TimeWarp.CurrentRateIndex != 0) { 380 | TimeWarp.SetRate(0, true); 381 | Extensions.Log("Update: Kill TimeWarp"); 382 | } 383 | 384 | // 0.2 meters per frame 385 | var degrees = 0.2 / Body.Radius * (180 / Math.PI); 386 | 387 | var changed = false; 388 | if (GameSettings.TRANSLATE_UP.GetKey()) { 389 | Latitude -= degrees; 390 | changed = true; 391 | } 392 | if (GameSettings.TRANSLATE_DOWN.GetKey()) { 393 | Latitude += degrees; 394 | changed = true; 395 | } 396 | if (GameSettings.TRANSLATE_LEFT.GetKey()) { 397 | Longitude -= degrees / Math.Cos(Latitude * (Math.PI / 180)); 398 | changed = true; 399 | } 400 | if (GameSettings.TRANSLATE_RIGHT.GetKey()) { 401 | Longitude += degrees / Math.Cos(Latitude * (Math.PI / 180)); 402 | changed = true; 403 | } 404 | 405 | if (Latitude == 0) { 406 | Latitude = 0.0001; 407 | } 408 | if (Longitude == 0) { 409 | Longitude = 0.0001; 410 | } 411 | if (changed) { 412 | AlreadyTeleported = false; 413 | teleportedToLandingAlt = false; 414 | OnManualEdit(Latitude, Longitude, Altitude, Body); 415 | } 416 | } 417 | 418 | public void FixedUpdate() { 419 | var vessel = GetComponent(); 420 | 421 | if (vessel != FlightGlobals.ActiveVessel) { 422 | Destroy(this); 423 | return; 424 | } 425 | 426 | if (TimeWarp.CurrentRateIndex != 0) { 427 | TimeWarp.SetRate(0, true); 428 | Extensions.Log("Kill time warp for safety reasons!"); 429 | } 430 | 431 | if (AlreadyTeleported) { 432 | 433 | if (vessel.LandedOrSplashed) { 434 | Destroy(this); 435 | } else { 436 | var accel = (vessel.srf_velocity + vessel.upAxis) * -0.5; 437 | vessel.ChangeWorldVelocity(accel); 438 | /* 439 | RateLimitedLogger.Log(_accelLogObject, 440 | $"(Happening every frame) Soft-lander changed ship velocity this frame by vector {accel.x},{accel.y},{accel.z} (mag {accel.magnitude})"); 441 | */ 442 | } 443 | } else { 444 | //NOT AlreadyTeleported 445 | //Still calculating 446 | var pqs = Body.pqsController; 447 | if (pqs == null) { 448 | // The sun has no terrain. Everthing else has a PQScontroller. 449 | Destroy(this); 450 | return; 451 | } 452 | 453 | var alt = pqs.GetSurfaceHeight(Body.GetRelSurfaceNVector(Latitude, Longitude)) - Body.Radius; 454 | var tmpAlt = Body.TerrainAltitude(Latitude, Longitude); 455 | 456 | double landHeight = FlightGlobals.ActiveVessel.altitude - FlightGlobals.ActiveVessel.pqsAltitude; 457 | 458 | double finalAltitude = 0.0; //trying to isolate this for debugging! 459 | 460 | var checkAlt = FlightGlobals.ActiveVessel.altitude; 461 | var checkPQSAlt = FlightGlobals.ActiveVessel.pqsAltitude; 462 | double terrainAlt = GetTerrainAltitude(); 463 | 464 | Extensions.ALog("-------------------"); 465 | Extensions.ALog("m1. Body.Radius = ", Body.Radius); 466 | Extensions.ALog("m2. PQS SurfaceHeight = ", pqs.GetSurfaceHeight(Body.GetRelSurfaceNVector(Latitude, Longitude))); 467 | Extensions.ALog("alt ( m2 - m1 ) = ", alt); 468 | Extensions.ALog("Body.TerrainAltitude = ", tmpAlt); 469 | Extensions.ALog("checkAlt = ", checkAlt); 470 | Extensions.ALog("checkPQSAlt = ", checkPQSAlt); 471 | Extensions.ALog("landheight = ", landHeight); 472 | Extensions.ALog("terrainAlt = ", terrainAlt); 473 | Extensions.ALog("-------------------"); 474 | Extensions.ALog("Latitude: ", Latitude, "Longitude: ", Longitude); 475 | Extensions.ALog("-------------------"); 476 | 477 | alt = Math.Max(alt, 0d); // Make sure we're not underwater! 478 | 479 | // HoldVesselUnpack is in display frames, not physics frames 480 | 481 | Vector3d teleportPosition; 482 | 483 | if (!teleportedToLandingAlt) { 484 | Extensions.ALog("teleportedToLandingAlt == false"); 485 | Extensions.ALog("interimAltitude: ", InterimAltitude); 486 | Extensions.ALog("Altitude: ", Altitude); 487 | 488 | if (InterimAltitude > Altitude) { 489 | 490 | if (Planetarium.GetUniversalTime() - lastUpdate >= 0.5) { 491 | InterimAltitude = InterimAltitude / 10; 492 | terrainAlt = GetTerrainAltitude(); 493 | 494 | if (InterimAltitude < terrainAlt) { 495 | InterimAltitude = terrainAlt + Altitude; 496 | } 497 | 498 | //InterimAltitude = terrainAlt + Altitude; 499 | 500 | teleportPosition = Body.GetWorldSurfacePosition(Latitude, Longitude, InterimAltitude) - Body.position; 501 | 502 | Extensions.ALog("1. teleportPosition = ", teleportPosition); 503 | Extensions.ALog("1. interimAltitude: ", InterimAltitude); 504 | 505 | if (lastUpdate != 0) { 506 | InterimAltitude = Altitude; 507 | } 508 | lastUpdate = Planetarium.GetUniversalTime(); 509 | 510 | } else { 511 | Extensions.Log("teleportPositionAltitude (no time change):"); 512 | 513 | teleportPosition = Body.GetWorldSurfacePosition(Latitude, Longitude, alt + InterimAltitude) - Body.position; 514 | 515 | Extensions.ALog("2. teleportPosition = ", teleportPosition); 516 | Extensions.ALog("2. alt: ", alt); 517 | Extensions.ALog("2. interimAltitude: ", InterimAltitude); 518 | } 519 | } else { 520 | //InterimAltitude <= Altitude 521 | Extensions.Log("3. teleportedToLandingAlt sets to true"); 522 | 523 | landHeight = FlightGlobals.ActiveVessel.altitude - FlightGlobals.ActiveVessel.pqsAltitude; 524 | terrainAlt = GetTerrainAltitude(); 525 | 526 | //trying to find the correct altitude here. 527 | 528 | if (checkPQSAlt > terrainAlt) { 529 | alt = checkPQSAlt; 530 | } else { 531 | alt = terrainAlt; 532 | } 533 | 534 | if (alt == 0.0) { 535 | //now what? 536 | } 537 | 538 | /* 539 | * landHeight factors into the final altitude somehow. Possibly. 540 | */ 541 | 542 | teleportedToLandingAlt = true; 543 | //finalAltitude = alt + Altitude; 544 | if (alt < 0) { 545 | finalAltitude = Altitude; 546 | } else if (alt > 0) { 547 | 548 | finalAltitude = alt + Altitude; 549 | } else { 550 | finalAltitude = alt + Altitude; 551 | } 552 | 553 | teleportPosition = Body.GetWorldSurfacePosition(Latitude, Longitude, finalAltitude) - Body.position; 554 | 555 | Extensions.ALog("3. teleportPosition = ", teleportPosition); 556 | Extensions.ALog("3. alt = ", alt, "Altitude = ", Altitude, "InterimAltitude = ", InterimAltitude); 557 | Extensions.ALog("3. TerrainAlt = ", terrainAlt, "landHeight = ", landHeight); 558 | } 559 | } else { 560 | /* 561 | * With the current way of calculating, it seems like this part of the conditional 562 | * never gets called. (Well not so far in my (@fronbow) testing. 563 | */ 564 | 565 | Extensions.Log("teleportedToLandingAlt == true"); 566 | 567 | landHeight = FlightGlobals.ActiveVessel.altitude - FlightGlobals.ActiveVessel.pqsAltitude; 568 | terrainAlt = GetTerrainAltitude(); 569 | 570 | Extensions.ALog("4. finalAltitude = ", finalAltitude); 571 | /* 572 | * Depending on finalAltitude, we might not need to calculate it again here. 573 | */ 574 | 575 | //finalAltitude = alt + Altitude; 576 | if (alt < 0) { 577 | finalAltitude = Altitude; 578 | } else if (alt > 0) { 579 | finalAltitude = alt + Altitude; 580 | } else { 581 | finalAltitude = alt + Altitude; 582 | } 583 | 584 | //teleportPosition = Body.GetRelSurfacePosition(Latitude, Longitude, finalAltitude); 585 | teleportPosition = Body.GetWorldSurfacePosition(Latitude, Longitude, finalAltitude) - Body.position; 586 | 587 | Extensions.ALog("4. teleportPosition = ", teleportPosition); 588 | Extensions.ALog("4. alt = ", alt, "Altitude = ", Altitude, "InterimAltitude = ", InterimAltitude); 589 | Extensions.ALog("4. TerrainAlt = ", terrainAlt, "landHeight = ", landHeight); 590 | Extensions.ALog("4. finalAltitude = ", finalAltitude); 591 | } 592 | 593 | var teleportVelocity = Vector3d.Cross(Body.angularVelocity, teleportPosition); 594 | 595 | // convert from world space to orbit space 596 | 597 | teleportPosition = teleportPosition.xzy; 598 | teleportVelocity = teleportVelocity.xzy; 599 | 600 | Extensions.ALog("0. teleportPosition(xzy): ", teleportPosition); 601 | Extensions.ALog("0. teleportVelocity(xzy): ", teleportVelocity); 602 | Extensions.ALog("0. Body : ", Body); 603 | 604 | // counter for the momentary fall when on rails (about one second) 605 | teleportVelocity += teleportPosition.normalized * (Body.gravParameter / teleportPosition.sqrMagnitude); 606 | 607 | Quaternion rotation; 608 | 609 | 610 | if (SetRotation) { 611 | // Need to check vessel and find up for the root command pod 612 | vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); //hopefully this disables SAS as it causes unknown results! 613 | 614 | var from = Vector3d.up; //Sensible default for all vessels 615 | 616 | if (vessel.displaylandedAt == "Runway" || vessel.vesselType.ToString() == "Plane") { 617 | from = vessel.vesselTransform.up; 618 | } 619 | 620 | 621 | var to = teleportPosition.xzy.normalized; 622 | rotation = Quaternion.FromToRotation(from, to); 623 | } else { 624 | var oldUp = vessel.orbit.pos.xzy.normalized; 625 | var newUp = teleportPosition.xzy.normalized; 626 | rotation = Quaternion.FromToRotation(oldUp, newUp) * vessel.vesselTransform.rotation; 627 | } 628 | 629 | var orbit = vessel.orbitDriver.orbit.Clone(); 630 | orbit.UpdateFromStateVectors(teleportPosition, teleportVelocity, Body, Planetarium.GetUniversalTime()); 631 | 632 | vessel.SetOrbit(orbit); 633 | vessel.SetRotation(rotation); 634 | 635 | if (teleportedToLandingAlt) { 636 | AlreadyTeleported = true; 637 | Extensions.Log(" :FINISHED TELEPORTING:"); 638 | } 639 | } 640 | } 641 | 642 | /// 643 | /// Returns the ground's altitude above sea level at this geo position. 644 | /// 645 | /// 646 | /// Borrowed this from the kOS mod with slight modification 647 | /// 648 | public Double GetTerrainAltitude() { 649 | double alt = 0.0; 650 | PQS bodyPQS = Body.pqsController; 651 | if (bodyPQS != null) // The sun has no terrain. Everything else has a PQScontroller. 652 | { 653 | // The PQS controller gives the theoretical ideal smooth surface curve terrain. 654 | // The actual ground that exists in-game that you land on, however, is the terrain 655 | // polygon mesh which is built dynamically from the PQS controller's altitude values, 656 | // and it only approximates the PQS controller. The discrepancy between the two 657 | // can be as high as 20 meters on relatively mild rolling terrain and is probably worse 658 | // in mountainous terrain with steeper slopes. It also varies with the user terrain detail 659 | // graphics setting. 660 | 661 | // Therefore the algorithm here is this: Get the PQS ideal terrain altitude first. 662 | // Then try using RayCast to get the actual terrain altitude, which will only work 663 | // if the LAT/LONG is near the active vessel so the relevant terrain polygons are 664 | // loaded. If the RayCast hit works, it overrides the PQS altitude. 665 | 666 | // PQS controller ideal altitude value: 667 | // ------------------------------------- 668 | 669 | // The vector the pqs GetSurfaceHeight method expects is a vector in the following 670 | // reference frame: 671 | // Origin = body center. 672 | // X axis = LATLNG(0,0), Y axis = LATLNG(90,0)(north pole), Z axis = LATLNG(0,-90). 673 | // Using that reference frame, you tell GetSurfaceHeight what the "up" vector is pointing through 674 | // the spot on the surface you're querying for. 675 | var bodyUpVector = new Vector3d(1, 0, 0); 676 | bodyUpVector = QuaternionD.AngleAxis(Latitude, Vector3d.forward/*around Z axis*/) * bodyUpVector; 677 | bodyUpVector = QuaternionD.AngleAxis(Longitude, Vector3d.down/*around -Y axis*/) * bodyUpVector; 678 | 679 | alt = bodyPQS.GetSurfaceHeight(bodyUpVector) - bodyPQS.radius; 680 | 681 | // Terrain polygon raycasting: 682 | // --------------------------- 683 | const double HIGH_AGL = 1000.0; 684 | const double POINT_AGL = 800.0; 685 | const int TERRAIN_MASK_BIT = 15; 686 | 687 | // a point hopefully above the terrain: 688 | Vector3d worldRayCastStart = Body.GetWorldSurfacePosition(Latitude, Longitude, alt + HIGH_AGL); 689 | // a point a bit below it, to aim down to the terrain: 690 | Vector3d worldRayCastStop = Body.GetWorldSurfacePosition(Latitude, Longitude, alt + POINT_AGL); 691 | RaycastHit hit; 692 | if (Physics.Raycast(worldRayCastStart, (worldRayCastStop - worldRayCastStart), out hit, float.MaxValue, 1 << TERRAIN_MASK_BIT)) { 693 | // Ensure hit is on the topside of planet, near the worldRayCastStart, not on the far side. 694 | if (Mathf.Abs(hit.distance) < 3000) { 695 | // Okay a hit was found, use it instead of PQS alt: 696 | alt = ((alt + HIGH_AGL) - hit.distance); 697 | } 698 | } 699 | } 700 | return alt; 701 | } 702 | 703 | } 704 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------