public FinePrint.Waypoint ToWaypoint(int index)
        {
            string        cName = celestialName;
            CelestialBody cb    = FlightGlobals.Bodies.Find(x => x.name == cName);

            if (cb == null)
            {
                return(null);
            }
            else
            {
                FinePrint.Waypoint wp = new FinePrint.Waypoint();

                wp.latitude      = latitude;
                wp.longitude     = longitude;
                wp.celestialName = celestialName;
                wp.altitude      = heightAGL;
                wp.name          = waypointName;
                wp.index         = index;
                wp.navigationId  = Guid.NewGuid();
                wp.id            = "vessel"; // seems to be icon name.  May be WPM-specific.

                return(wp);
            }
        }
Exemple #2
0
 /// <summary>
 /// Create a waypoint object.
 /// </summary>
 internal Waypoint(double latitude, double longitude, double altitude, CelestialBody body, string name)
 {
     InternalWaypoint = new FinePrint.Waypoint();
     Name             = name;
     Body             = body;
     Icon             = "report";
     Color            = 1115;
     Latitude         = latitude;
     Longitude        = longitude;
     MeanAltitude     = altitude;
     InternalWaypoint.isNavigatable = true;
     FinePrint.WaypointManager.AddWaypoint(InternalWaypoint);
 }
        internal static void CreateWPForLaunchSite(KKLaunchSite site)
        {
            FinePrint.Waypoint lsWP = new FinePrint.Waypoint();

            //lsWP.altitude = selectedSite.staticInstance.surfaceHeight + 20f;
            lsWP.altitude      = 0;
            lsWP.height        = 20f;
            lsWP.isOnSurface   = true;
            lsWP.latitude      = site.staticInstance.RefLatitude;
            lsWP.longitude     = site.staticInstance.RefLongitude;
            lsWP.name          = site.LaunchSiteName;
            lsWP.celestialName = site.body.name;
            lsWP.isNavigatable = true;

            lsWP.navigationId = Guid.NewGuid();
            lsWP.enableMarker = true;
            lsWP.fadeRange    = site.body.Radius;
            lsWP.seed         = site.LaunchSiteName.GetHashCode();
            lsWP.isCustom     = true;

            switch (site.sitecategory)
            {
            case LaunchSiteCategory.RocketPad:
                lsWP.id = "Squad/PartList/SimpleIcons/R&D_node_icon_heavierrocketry";
                break;

            case LaunchSiteCategory.Runway:
                lsWP.id = "Squad/PartList/SimpleIcons/RDicon_aerospaceTech2";
                break;

            case LaunchSiteCategory.Helipad:
                lsWP.id = "Squad/PartList/SimpleIcons/R&D_node_icon_landing";
                break;

            default:
                lsWP.id = "custom";
                break;
            }

            FinePrint.WaypointManager.AddWaypoint(lsWP);
            site.wayPoint = lsWP;
        }
        internal static void CreateWPForBase(StaticInstance instance)
        {
            FinePrint.Waypoint lsWP = new FinePrint.Waypoint();
            //lsWP.altitude = selectedSite.staticInstance.surfaceHeight + 20f;
            lsWP.altitude      = 0;
            lsWP.height        = 20f;
            lsWP.isOnSurface   = true;
            lsWP.latitude      = instance.RefLatitude;
            lsWP.longitude     = instance.RefLongitude;
            lsWP.name          = instance.GetFacility(KKFacilityType.RecoveryBase).FacilityName;
            lsWP.celestialName = instance.CelestialBody.name;
            lsWP.isNavigatable = true;

            lsWP.navigationId = Guid.NewGuid();
            lsWP.enableMarker = true;
            lsWP.fadeRange    = instance.CelestialBody.Radius;
            lsWP.seed         = lsWP.name.GetHashCode();
            lsWP.isCustom     = true;

            lsWP.id = "Squad/PartList/SimpleIcons/R&D_node_icon_heavierrocketry";

            FinePrint.WaypointManager.AddWaypoint(lsWP);
        }
        /// <summary>
        /// Coroutine for adding scripts to the Lua context.  Paced to load one
        /// string per frame.
        ///
        /// It also looks for existing global RasterPropMonitor COLOR_ definitions.
        /// </summary>
        /// <returns>null when done</returns>
        private IEnumerator LoadAvionicsSystemAssets()
        {
            userScripts.Clear();
            ConfigNode[] userScriptNodes = GameDatabase.Instance.GetConfigNodes("MAS_LUA");
            if (userScriptNodes.Length > 0)
            {
                for (int nodeIdx = 0; nodeIdx < userScriptNodes.Length; ++nodeIdx)
                {
                    if (userScriptNodes[nodeIdx].HasValue("name"))
                    {
                        ConfigNode node    = userScriptNodes[nodeIdx];
                        string[]   scripts = node.GetValues("script");
                        Utility.LogMessage(this, "Parsing MAS_LUA node \"{0}\" ({1} script references)", node.GetValue("name"), scripts.Length);

                        for (int scriptIdx = 0; scriptIdx < scripts.Length; ++scriptIdx)
                        {
                            try
                            {
                                userScripts.Add(string.Join(Environment.NewLine, File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + scripts[scriptIdx], Encoding.UTF8)));
                            }
                            catch (Exception e)
                            {
                                Utility.LogError(this, "Exception caught trying to load script \"{0}\": {1}", scripts[scriptIdx], e.ToString());
                            }
                        }
                        yield return(new WaitForEndOfFrame());
                    }
                }
            }

            namedColors.Clear();
            ConfigNode[] rpmColorNodes = GameDatabase.Instance.GetConfigNodes("RPM_GLOBALCOLORSETUP");
            for (int colorNodeIdx = 0; colorNodeIdx < rpmColorNodes.Length; ++colorNodeIdx)
            {
                ConfigNode[] colorDef = rpmColorNodes[colorNodeIdx].GetNodes("COLORDEFINITION");
                for (int defIdx = 0; defIdx < colorDef.Length; ++defIdx)
                {
                    if (colorDef[defIdx].HasValue("name") && colorDef[defIdx].HasValue("color"))
                    {
                        string  name  = "COLOR_" + (colorDef[defIdx].GetValue("name").Trim());
                        Color32 color = ConfigNode.ParseColor32(colorDef[defIdx].GetValue("color").Trim());
                        if (namedColors.ContainsKey(name))
                        {
                            namedColors[name] = color;
                        }
                        else
                        {
                            namedColors.Add(name, color);
                        }

                        //Utility.LogMessage(this, "{0} = {1}", name, color);
                    }
                }
                yield return(new WaitForEndOfFrame());
            }

            // Add XKCD colors
            Type t = typeof(XKCDColors);

            PropertyInfo[] properties    = t.GetProperties();
            int            numProperties = properties.Length;

            for (int i = 0; i < numProperties; ++i)
            {
                try
                {
                    // This is probably overkill in terms of checks.
                    if (properties[i].PropertyType == typeof(Color) && properties[i].CanRead)
                    {
                        MethodInfo[] accessor = properties[i].GetAccessors();
                        for (int j = 0; j < accessor.Length; ++j)
                        {
                            if (accessor[j].ReturnType == typeof(Color))
                            {
                                object o     = accessor[j].Invoke(null, null);
                                Color  color = (Color)o;

                                StringBuilder sb = StringBuilderCache.Acquire();
                                sb.Append("COLOR_XKCD_").Append(properties[i].Name.ToUpperInvariant());
                                string name = sb.ToStringAndRelease();
                                if (namedColors.ContainsKey(name))
                                {
                                    namedColors[name] = color;
                                }
                                else
                                {
                                    namedColors.Add(name, color);
                                }
                            }
                        }
                    }
                }
                catch { }
            }
            yield return(new WaitForEndOfFrame());

            var dsn = UnityEngine.Object.FindObjectsOfType <CommNet.CommNetHome>();

            if (dsn != null)
            {
                CelestialBody             kerbin = Planetarium.fetch.Home;
                List <FinePrint.Waypoint> relays = new List <FinePrint.Waypoint>();

                for (int i = 0; i < dsn.Length; ++i)
                {
                    // TODO: Support non-Kerbin stations?

                    // Unfortunately, the lat/lon/alt/body fields are all protected, so I have
                    // to do this, instead:
                    Vector3d position = dsn[i].nodeTransform.position;

                    double latitude, longitude, altitude;
                    kerbin.GetLatLonAlt(position, out latitude, out longitude, out altitude);

                    FinePrint.Waypoint dsnWp = new FinePrint.Waypoint();

                    dsnWp.latitude      = latitude;
                    dsnWp.longitude     = longitude;
                    dsnWp.celestialName = kerbin.name;
                    dsnWp.altitude      = altitude;
                    dsnWp.name          = dsn[i].nodeName;
                    dsnWp.index         = 256;      // ?
                    dsnWp.navigationId  = Guid.NewGuid();
                    dsnWp.id            = "vessel"; // seems to be icon name.  May be WPM-specific.

                    relays.Add(dsnWp);
                }

                deepSpaceNetwork = relays.ToArray();
                Array.Sort(deepSpaceNetwork, waypointNameComparer);
            }
            else
            {
                deepSpaceNetwork = new FinePrint.Waypoint[0];
            }
        }
Exemple #6
0
        private void MainWindow(int id)
        {
            Trajectory traj = Trajectory.fetch;

            GUILayout.BeginHorizontal();

            Settings.fetch.DisplayTrajectories = GUILayout.Toggle(Settings.fetch.DisplayTrajectories, "Show trajectory", GUILayout.Width(125));

            Settings.fetch.DisplayTrajectoriesInFlight = GUILayout.Toggle(Settings.fetch.DisplayTrajectoriesInFlight, "In-Flight");

            // check that we have patched conics. If not, apologize to the user and return.
            if (Settings.fetch.DisplayTrajectories && !Util.IsPatchedConicsAvailable)
            {
                ScreenMessages.PostScreenMessage(
                    "Can't show trajectory because patched conics are not available." +
                    " Please update your tracking station facility.");
                Settings.fetch.DisplayTrajectories = false;
                return;
            }

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();

            Settings.fetch.BodyFixedMode = GUILayout.Toggle(Settings.fetch.BodyFixedMode, "Body-fixed mode");

            if (Settings.fetch.DisplayTrajectories)
            {
                Settings.fetch.DisplayCompleteTrajectory = GUILayout.Toggle(Settings.fetch.DisplayCompleteTrajectory, "complete", GUILayout.Width(70));
            }

            GUILayout.EndHorizontal();

            GUILayout.Label("Max G-force: " + guistring_gForce);

            GUILayout.Label(guistring_impactVelocity);
            GUILayout.Space(10);


            if (Settings.fetch.DisplayTargetGUI = ToggleGroup(Settings.fetch.DisplayTargetGUI, "Target"))
            {
                GUI.enabled = Trajectory.Target.WorldPosition.HasValue;

                GUILayout.Label(guistring_targetDistance);

                if (GUILayout.Button("Unset target"))
                {
                    Trajectory.Target.Clear();
                }
                GUI.enabled = true;

                GUILayout.BeginHorizontal();
                var patch = traj.Patches.LastOrDefault();
                GUI.enabled = (patch != null && patch.ImpactPosition.HasValue);
                if (GUILayout.Button("Set current impact", GUILayout.Width(150)))
                {
                    if (patch.ImpactPosition.HasValue)
                    {
                        Trajectory.Target.SetFromWorldPos(patch.StartingState.ReferenceBody, patch.ImpactPosition.Value);
                    }
                }
                GUI.enabled = true;
                if (GUILayout.Button("Set KSC", GUILayout.Width(70)))
                {
                    var homebody = FlightGlobals.GetHomeBody();

                    double latitude  = SpaceCenter.Instance.Latitude;
                    double longitude = SpaceCenter.Instance.Longitude;

                    if (homebody != null)
                    {
                        Trajectory.Target.SetFromLatLonAlt(homebody, latitude, longitude);
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();

                Vessel targetVessel = FlightGlobals.fetch.VesselTarget?.GetVessel();
                GUI.enabled = (patch != null && targetVessel != null && targetVessel.Landed
                               // && targetVessel.lastBody == patch.startingState.referenceBody
                               );
                if (GUILayout.Button("Target vessel"))
                {
                    Trajectory.Target.SetFromWorldPos(targetVessel.lastBody, targetVessel.GetWorldPos3D() - targetVessel.lastBody.position);
                    ScreenMessages.PostScreenMessage("Targeting vessel " + targetVessel.GetName());
                }

                FinePrint.Waypoint navigationWaypoint = FlightGlobals.ActiveVessel?.navigationWaypoint;
                GUI.enabled = (navigationWaypoint != null);
                if (GUILayout.Button("Active waypoint"))
                {
                    Trajectory.Target.SetFromLatLonAlt(navigationWaypoint.celestialBody,
                                                       navigationWaypoint.latitude, navigationWaypoint.longitude, navigationWaypoint.altitude);
                    ScreenMessages.PostScreenMessage("Targeting waypoint " + navigationWaypoint.name);
                }
                GUILayout.EndHorizontal();

                GUI.enabled = true;

                GUILayout.BeginHorizontal();
                coords = GUILayout.TextField(Trajectory.Target.ManualText, GUILayout.Width(170));
                if (coords != Trajectory.Target.ManualText)
                {
                    Trajectory.Target.ManualText = coords;
                    Trajectory.Target.Save();
                }
                if (GUILayout.Button(new GUIContent("Set",
                                                    "Enter target latitude and longitude, separated by a comma, in decimal format (with a dot for decimal separator)"),
                                     GUILayout.Width(50)))
                {
                    string[] latLng = coords.Split(new char[] { ',', ';' });
                    var      body   = FlightGlobals.currentMainBody;
                    if (latLng.Length == 2 && body != null)
                    {
                        double lat;
                        double lng;
                        if (double.TryParse(latLng[0].Trim(), out lat) && double.TryParse(latLng[1].Trim(), out lng))
                        {
                            Trajectory.Target.SetFromLatLonAlt(body, lat, lng);
                        }
                    }
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.Space(10);

            GUILayout.BeginHorizontal();
            bool descentProfileGroup = Settings.fetch.DisplayDescentProfileGUI = ToggleGroup(Settings.fetch.DisplayDescentProfileGUI, "Descent profile", 120);

            DescentProfile.fetch.DoQuickControlsGUI();
            GUILayout.EndHorizontal();
            if (descentProfileGroup)
            {
                DescentProfile.fetch.DoGUI();
            }
            GUILayout.Space(10);

            if (Settings.fetch.DisplaySettingsGUI = ToggleGroup(Settings.fetch.DisplaySettingsGUI, "Settings"))
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Max patches", GUILayout.Width(100));
                Settings.fetch.MaxPatchCount = Mathf.RoundToInt(GUILayout.HorizontalSlider((float)Settings.fetch.MaxPatchCount, 3, 10, GUILayout.Width(100)));
                GUILayout.Label(Settings.fetch.MaxPatchCount.ToString(), GUILayout.Width(15));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Max frames per patch", GUILayout.Width(100));
                Settings.fetch.MaxFramesPerPatch = Mathf.RoundToInt(GUILayout.HorizontalSlider((float)Settings.fetch.MaxFramesPerPatch, 1, 50, GUILayout.Width(100)));
                GUILayout.Label(Settings.fetch.MaxFramesPerPatch.ToString(), GUILayout.Width(15));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                Settings.fetch.UseCache = GUILayout.Toggle(Settings.fetch.UseCache, new GUIContent("Use Cache", "Toggle cache usage. Trajectory will be more precise when cache disabled, but computation time will be higher. It's not recommended to keep it unchecked, unless your CPU can handle the load."), GUILayout.Width(80));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                Settings.fetch.AutoUpdateAerodynamicModel = GUILayout.Toggle(Settings.fetch.AutoUpdateAerodynamicModel, new GUIContent("Auto update", "Auto-update of the aerodynamic model. For example if a part is decoupled, the model needs to be updated. This is independent from trajectory update."));
                if (GUILayout.Button("Update now"))
                {
                    traj.InvalidateAerodynamicModel();
                }
                GUILayout.EndHorizontal();

                if (ToolbarManager.ToolbarAvailable)
                {
                    Settings.fetch.UseBlizzyToolbar = GUILayout.Toggle(Settings.fetch.UseBlizzyToolbar, new GUIContent("Use Blizzy's toolbar", "Will take effect after restart"));
                }

                if (FlightGlobals.ActiveVessel != null)
                {
                    GUILayout.Label("Position:");
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("lat=" + guistring_Latitude, GUILayout.Width(110));
                    GUILayout.Label("lng=" + guistring_Longitude, GUILayout.Width(110));
                    GUILayout.EndHorizontal();
                }

                GUILayout.Label("Aerodynamic model: " + traj.AerodynamicModelName);
                GUILayout.BeginHorizontal();
                GUILayout.Label(String.Format("Perf: {0,5:F1}ms ({1,4:F1})%",
                                              traj.ComputationTime * 1000.0f,
                                              traj.ComputationTime / traj.GameFrameTime * 100.0f
                                              ), GUILayout.Width(130));
                GUILayout.Label(traj.ErrorCount + " error(s)", GUILayout.Width(80));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                if (GUILayout.Toggle(Settings.fetch.NewGui, new GUIContent("New Gui", "Swap to the New Gui")))
                {
                    Settings.fetch.NewGui         = true;
                    Settings.fetch.MainGUIEnabled = true;
                    Settings.fetch.GUIEnabled     = false;
                    InputLockManager.RemoveControlLock("TrajectoriesFlightLock");
                    clickThroughLocked = false;
                }
                else
                {
                    Settings.fetch.NewGui         = false;
                    Settings.fetch.MainGUIEnabled = false;
                    Settings.fetch.GUIEnabled     = true;
                }
                GUILayout.EndHorizontal();
            }

            tooltip = GUI.tooltip;

            GUI.DragWindow();
        }
        /// <summary>
        /// This method is called when a vessel computer awakens since the waypoint manager doesn't
        /// appear to be initialized before the Flight scene.  This method ensures that all of the
        /// MAS NAVAIDS are registered in the waypoint manager.
        /// </summary>
        static internal void InitializeNavAids()
        {
            FinePrint.WaypointManager waypointManager = FinePrint.WaypointManager.Instance();
            List <FinePrint.Waypoint> knownWaypoints  = (waypointManager) ? waypointManager.Waypoints : null;

            int numNavAids = MASLoader.navaids.Count;

            if (MASConfig.navigation.enableNavBeacons)
            {
                bool       anyAdded = false;
                ConfigNode master   = new ConfigNode("CUSTOM_WAYPOINTS");
                for (int i = 0; i < numNavAids; ++i)
                {
                    // Make sure all navigation beacons are updated and added to the waypoint manager.
                    if (MASLoader.navaids[i].maximumRange == -1.0)
                    {
                        MASLoader.navaids[i].UpdateHorizonDistance();
                    }

                    string waypointName = MASLoader.navaids[i].waypointName;

                    FinePrint.Waypoint wp = (knownWaypoints == null) ? null : knownWaypoints.Find(x => x.name == waypointName);
                    if (MASConfig.ResetWaypoints && wp != null)
                    {
                        ScenarioCustomWaypoints.RemoveWaypoint(wp);
                        wp = null;
                    }

                    if (wp == null)
                    {
                        FinePrint.Waypoint newwp = MASLoader.navaids[i].ToWaypoint(i);

                        // Note: this is round-about, but it appears to be the way to register
                        // waypoints to show up in Waypoint Manager.  If I simply add the
                        // waypoint directly using FinePrint.WaypointManager, it's present there, but
                        // not in the Waypoint Manager mod's GUI list.  So this is a simple
                        // way to get compatibility.

                        ConfigNode child = new ConfigNode("WAYPOINT");
                        child.AddValue("latitude", newwp.latitude);
                        child.AddValue("longitude", newwp.longitude);
                        child.AddValue("altitude", newwp.altitude);
                        child.AddValue("celestialName", newwp.celestialName);
                        child.AddValue("name", newwp.name);
                        child.AddValue("id", newwp.id);
                        child.AddValue("index", newwp.index);
                        child.AddValue("navigationId", newwp.navigationId.ToString());

                        master.AddNode(child);
                        anyAdded = true;
                        //FinePrint.WaypointManager.AddWaypoint(newwp);
                    }
                }
                if (anyAdded)
                {
                    ScenarioCustomWaypoints.Instance.OnLoad(master);
                }
            }
            else if (knownWaypoints != null && knownWaypoints.Count > 0)
            {
                for (int i = 0; i < numNavAids; ++i)
                {
                    // If nav beacons are disabled, remove them from the database
                    string             waypointName = MASLoader.navaids[i].waypointName;
                    FinePrint.Waypoint wp           = knownWaypoints.Find(x => x.name == waypointName);

                    if (wp != null)
                    {
                        ScenarioCustomWaypoints.RemoveWaypoint(wp);
                        knownWaypoints.Remove(wp);
                    }
                }
            }

            if (MASConfig.EnableCommNetWaypoints)
            {
                CelestialBody kerbin = Planetarium.fetch.Home;

                int        index    = 0;
                bool       anyAdded = false;
                ConfigNode master   = new ConfigNode("CUSTOM_WAYPOINTS");
                foreach (var keyValue in MASLoader.deepSpaceNetwork)
                {
                    string             waypointName = keyValue.Key;
                    FinePrint.Waypoint wp           = (knownWaypoints == null) ? null : knownWaypoints.Find(x => x.name == waypointName);
                    if (MASConfig.ResetWaypoints && wp != null)
                    {
                        ScenarioCustomWaypoints.RemoveWaypoint(wp);
                        wp = null;
                    }
                    ConfigNode child = new ConfigNode("WAYPOINT");
                    if (wp == null)
                    {
                        Guid g = Guid.NewGuid();

                        // Waypoint altitude keeps reporting a 0 when I query it.
                        // I've tried using altitude above datum (TerrainAltitude) and
                        // AGL (10 meters, here), and I keep seeing a 0 for altitude.
                        // It looks like altitude is not actually stored in ScenarioCustomWaypoints,
                        // so I may have to derive that value myself.
                        //double altitude = kerbin.TerrainAltitude(keyValue.Value.x, keyValue.Value.y, false);

                        child.AddValue("latitude", keyValue.Value.x);
                        child.AddValue("longitude", keyValue.Value.y);
                        child.AddValue("altitude", 10.0);
                        //child.AddValue("altitude", altitude); // This isn't working?
                        child.AddValue("celestialName", kerbin.name);
                        child.AddValue("name", waypointName);
                        child.AddValue("id", "vessel");
                        child.AddValue("index", ++index);
                        child.AddValue("navigationId", g.ToString());
                        anyAdded = true;
                    }

                    master.AddNode(child);
                }
                if (anyAdded)
                {
                    ScenarioCustomWaypoints.Instance.OnLoad(master);
                }
            }
            else if (knownWaypoints != null && knownWaypoints.Count > 0)
            {
                foreach (var keyValue in MASLoader.deepSpaceNetwork)
                {
                    string             waypointName = keyValue.Key;
                    FinePrint.Waypoint wp           = knownWaypoints.Find(x => x.name == waypointName);

                    if (wp != null)
                    {
                        ScenarioCustomWaypoints.RemoveWaypoint(wp);
                        knownWaypoints.Remove(wp);
                    }
                }
            }

            MASConfig.ResetWaypoints = false;
        }
 public WayPoint(FinePrint.Waypoint wp) : this(new Coordinates(wp.latitude, wp.longitude, wp.altitude + wp.height))
 {
     Name = wp.FullName;
 }
Exemple #9
0
 /// <summary>
 /// Create a waypoint object from a KSP waypoint.
 /// </summary>
 public Waypoint(FinePrint.Waypoint wp)
 {
     InternalWaypoint = wp;
 }