private static void HackStrutCData(ShipConstruct ship, Part p,
											int part_base)
        {
            //Debug.Log (String.Format ("[EL] before {0}", p.customPartData));
            string[] Params = p.customPartData.Split (';');
            for (int i = 0; i < Params.Length; i++) {
                string[] keyval = Params[i].Split (':');
                string Key = keyval[0].Trim ();
                string Value = keyval[1].Trim ();
                if (Key == "tgt") {
                    string[] pnameval = Value.Split ('_');
                    string pname = pnameval[0];
                    int val = int.Parse (pnameval[1]);
                    if (val == -1) {
                        Strut strut = new Strut (p, Params);
                        if (strut.target != null) {
                            val = ship.parts.IndexOf (strut.target);
                        }
                    }
                    if (val != -1) {
                        val += part_base;
                    }
                    Params[i] = "tgt: " + pname + "_" + val.ToString ();
                    break;
                }
            }
            p.customPartData = String.Join ("; ", Params);
            //Debug.Log (String.Format ("[EL] after {0}", p.customPartData));
        }
 public static void CaptureThumbnail(ShipConstruct ship, int resolution, 
     float elevation, float azimuth, float pitch, float heading, float fov, string saveFolder, string craftName)
 {
     Log.Info ("CaptureThumbnail  elevation: " + elevation.ToString () + "  azimuth: " + azimuth.ToString () + "pitch: " + pitch.ToString () +
     "   heading: " + heading.ToString () + "  fov: " + fov.ToString ());
         CraftThumbnail.TakeSnaphot(ship, resolution, saveFolder, craftName, elevation, azimuth, pitch, heading, fov);
 }
Example #3
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;
            s.GetShipCosts(out dry, out fuel);
            cost = dry + fuel;
            TotalMass = 0;
            foreach (Part p in s.Parts)
            {
                TotalMass += p.mass;
                TotalMass += p.GetResourceMass();
            }

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (launchSite == "LaunchPad")
                type = ListType.VAB;
            else
                type = ListType.SPH;
            InventoryParts = new Dictionary<string, int>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
Example #4
0
        // Is the Test OK ?
        public override bool TestCondition()
        {
            this.Log_Debug("DFEngReport Test condition");
            this.ship = EditorLogic.fetch.ship;
            cryofreezers.Clear();
            cryofreezers = (from p in ship.parts where p.Modules.Contains("DeepFreezer") select p).ToList();
            if (cryofreezers.Count() <=0)
            {
                //No freezer parts
                this.Log_Debug("DFEngReport No Freezer Parts");
                return true;
            }

            //Search through the ship resources for Glykerol.
            PartResourceDefinition glykerol = PartResourceLibrary.Instance.GetDefinition(Glykerol);
            double glykerolOnBoard = 0;
            foreach ( Part part in ship.parts)
            {
                if (part.Resources.Contains(glykerol.id))
                {
                    PartResource glyk = part.Resources.Get(glykerol.id);
                    glykerolOnBoard += glyk.amount;
                }
            }

            //If we found 5 or more units of glykerol all ok.
            if (glykerolOnBoard >= 5)
            {
                this.Log_Debug("DFEngReport 5 units found");
                return true;
            }
            this.Log_Debug("DFEngReport No Glykerol Found");
            return false;
        }
        public void CheckVessel(ShipConstruct ship)
        {
            if (!MainInstance.checklistSelected)
                return;

            if (EditorLogic.RootPart == null || (MainInstance.partSelection == null && MainInstance.checkSelected))
            {
                ActiveChecklist.items.ForEach(i => i.state = false);
                return;
            }

            if (MainInstance.checkSelected && MainInstance.partSelection != null)
                partsToCheck = MainInstance.partSelection.selectedParts.Intersect(ship.Parts).ToList();
            else
                partsToCheck = ship.Parts;

            for (int j = 0; j < activeChecklist.items.Count; j++)
            //foreach (ChecklistItem item in activeChecklist.items)
            {
                ChecklistItem item = activeChecklist.items[j];
                if (item.isManual)
                    continue;
                item.state = true;
                for (int i = 0; i < item.criteria.Count; i++)
                //foreach(Criterion crton in item.criteria)
                {
                    Criterion crton = item.criteria[i];
                    switch (crton.type)
                    {
                        case CriterionType.Module:
                            crton.met = CheckForModules(crton);
                            break;
                        case CriterionType.Part:
                            crton.met = CheckForParts(crton);
                            break;
                        case CriterionType.MinResourceLevel:
                            crton.met = CheckForResourceLevel(crton);
                            break;
                        case CriterionType.MinResourceCapacity:
                            crton.met = CheckForResourceCapacity(crton);
                            break;
                        case CriterionType.CrewMember:
                            crton.met = CheckForCrewMember(crton);
                            break;
                    }
                    item.criteria[i] = crton;
                }
                if (!item.allRequired)
                {
                    if (item.criteria.TrueForAll(c => !c.met))
                        item.state = false;
                }
                else if (item.criteria.Any(c => !c.met))
                    item.state = false;

                activeChecklist.items[j] = item;
                continue;
            }
        }
 private void OnLoad(ShipConstruct data0, CraftBrowser.LoadType data1)
 {
     if(data1 == CraftBrowser.LoadType.Normal)
     {
         ShipConcerns.Clear();
         SectionConcerns.Clear();
     }
 }
 private void EditorLoad(ShipConstruct data0, CraftBrowser.LoadType data1)
 {
     switch (data1)
     {
         case CraftBrowser.LoadType.Merge:
             RenameSections(data0);
             break;
     }
 }
 /// <summary>
 /// Generates a thumbnail exactly like the one KSP generates automatically.
 /// Behaves exactly like ShipConstruction.CaptureThumbnail() but allows customizing the resolution.
 /// </summary>
 public static void CaptureThumbnail(ShipConstruct ship, int resolution, string saveFolder, string craftName)
 {
     if (ship.shipFacility != EditorFacility.VAB)
     {
         CraftThumbnail.TakeSnaphot(ship, resolution, saveFolder, craftName, 35, 135, 35, 135, 0.9f);
     }
     else
     {
         CraftThumbnail.TakeSnaphot(ship, resolution, saveFolder, craftName, 45, 45, 45, 45, 0.9f);
     }
 }
Example #9
0
 public bool LoadConstruct()
 {
     UnloadConstruct();
     construct = new ShipConstruct();
     if(!construct.LoadShip(vessel_node))
     {
         UnloadConstruct();
         return false;
     }
     return true;
 }
 public static void HackStruts(ShipConstruct ship, int part_base)
 {
     var all_struts = ship.parts.OfType<StrutConnector>();
     var struts = all_struts.Where (p => p.customPartData != "");
     foreach (Part part in struts) {
         HackStrutCData (ship, part, part_base);
     }
     var all_fuelLines = ship.parts.OfType<FuelLine>();
     var fuelLines = all_fuelLines.Where (p => p.customPartData != "");
     foreach (Part part in fuelLines) {
         HackStrutCData (ship, part, part_base);
     }
 }
Example #11
0
 public KCT_BuildListVessel(String name, String ls, double bP, String flagURL, float spentFunds)
 {
     ship = new ShipConstruct();
     launchSite = ls;
     shipName = name;
     buildPoints = bP;
     progress = 0;
     flag = flagURL;
     if (launchSite == "LaunchPad")
         type = ListType.VAB;
     else
         type = ListType.SPH;
     InventoryParts = new List<string>();
     cannotEarnScience = false;
     cost = spentFunds;
 }
        // Thanks to taniwha's Extraplanetary launchpads!
        public Bounds GetAABB(ShipConstruct a_Ship)
        {
            PartHeightQuery partHeight = null;
            Bounds aabb = new Bounds();
            bool initialize = true;
            for (int i = 0; i < a_Ship.parts.Count; i++)
            {
                Part currentPart = a_Ship[i];
                Collider[] colliders = currentPart.transform.FindChild("model").GetComponentsInChildren<Collider>();
                for (int j = 0; j < colliders.Length; j++)
                {
                    Collider currentCollider = colliders[j];

                    if (currentCollider.gameObject.layer != 21 && currentCollider.enabled) // Not sure where the 21 is coming from, have to ask taniwha
                    {
                        if (initialize)
                        {
                            initialize = false;
                            aabb = currentCollider.bounds;
                        }
                        else
                        {
                            aabb.Add(currentCollider.bounds);
                        }

                        float lowest = currentCollider.bounds.min.y;
                        if(partHeight == null)
                        {
                            partHeight = new PartHeightQuery(lowest);
                        }
                        partHeight.lowestPoint = Mathf.Min(partHeight.lowestPoint, lowest);

                        if(partHeight.lowestOnParts.ContainsKey(currentPart))
                        {
                            partHeight.lowestOnParts[currentPart] = Mathf.Min(partHeight.lowestOnParts[currentPart], lowest);
                        }
                    }
                }
            }

            for(int i = 0; i < a_Ship.parts.Count; i++)
            {
                a_Ship[i].SendMessage("OnPutToGround", partHeight, SendMessageOptions.DontRequireReceiver);
            }

            return new Bounds();
        }
        public Transform PlaceShip(ShipConstruct a_Ship, Bounds a_Bounds)
        {
            Transform launchTransform = GetLaunchTransform();

            float angle;
            Vector3 axis;
            launchTransform.rotation.ToAngleAxis(out angle, out axis);

            Part rootPart = a_Ship.parts[0].localRoot;
            Vector3 pos = rootPart.transform.position;

            Vector3 shift = new Vector3(-pos.x, -a_Bounds.min.y, -pos.z);
            shift += launchTransform.position;

            rootPart.transform.Translate(shift, Space.World);
            rootPart.transform.RotateAround(launchTransform.position, axis, angle);

            return launchTransform;
        }
        private void OnEditorShipModified(ShipConstruct shipConstruct)
        {
            if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX || ResearchAndDevelopment.Instance == null)
                return;


            int maxParts = maxPartCount();
            if (shipConstruct.Parts.Count > maxParts)
            {               
                warningMsg = "This vessel has too many parts to be built and launched at the current tech level.\nCurrent maximum is " + maxParts + ", this vessel has " + shipConstruct.Parts.Count + " parts.";
                //ScreenMessages.PostScreenMessage(warningMsg, 15F, ScreenMessageStyle.UPPER_CENTER);
                lockLaunchButton = true;

            } else {
                warningMsg = "";
                if (shipConstruct.Parts.Count > 0)
                    lockLaunchButton = false;
                else
                    lockLaunchButton = true;
            }
        }
Example #15
0
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float dry, fuel;
            s.GetShipCosts(out dry, out fuel);
            cost = dry + fuel;

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (launchSite == "LaunchPad")
                type = ListType.VAB;
            else
                type = ListType.SPH;
            InventoryParts = new List<string>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
        public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL)
        {
            ship = s;
            shipNode = s.SaveShip();
            shipName = s.shipName;
            //Get total ship cost
            float fuel;
            cost = s.GetShipCosts(out emptyCost, out fuel);
            TotalMass = s.GetShipMass(out emptyMass, out fuel);

            launchSite = ls;
            buildPoints = bP;
            progress = 0;
            flag = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
                type = ListType.VAB;
            else if (s.shipFacility == EditorFacility.SPH)
                type = ListType.SPH;
            else
                type = ListType.None;
            InventoryParts = new Dictionary<string, int>();
            id = Guid.NewGuid();
            cannotEarnScience = false;
        }
		private IEnumerator WaitAndRebuildList (ShipConstruct ship)
		{
			yield return null;

			buildCost = null;
			parts_count = 0;

			if (ship == null || ship.parts == null || ship.parts.Count < 1
				|| ship.parts[0] == null) {
				yield break;
			}

			if (ship.parts.Count > 0) {
				Part root = ship.parts[0].localRoot;

				buildCost = new BuildCost ();
				addPart (root);
				foreach (Part p in root.GetComponentsInChildren<Part>()) {
					if (p != root) {
						addPart (p);
					}
				}
			}
		}
Example #18
0
        public void VesselToCraftFile(ConfigNode VesselNode)
        {
            //This code is taken from InflightShipSave by Claw, using the CC-BY-NC-SA license.
            //This code thus is licensed under the same license, despite the GPLv3 license covering original KCT code
            //See https://github.com/ClawKSP/InflightShipSave

            ProtoVessel VesselToSave = HighLogic.CurrentGame.AddVessel(VesselNode);

            if (VesselToSave.vesselRef == null)
            {
                Log("Vessel reference is null!");
                return;
            }

            try
            {
                string ShipName = VesselToSave.vesselName;

                //Vessel FromFlight = FlightGlobals.Vessels.Find(v => v.id == VesselToSave.vesselID);
                try
                {
                    VesselToSave.vesselRef.Load();
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    Log("Attempting to continue.");
                }

                ShipConstruct ConstructToSave  = new ShipConstruct(ShipName, "", VesselToSave.vesselRef.Parts[0]);
                Quaternion    OriginalRotation = VesselToSave.vesselRef.vesselTransform.rotation;
                Vector3       OriginalPosition = VesselToSave.vesselRef.vesselTransform.position;

                VesselToSave.vesselRef.SetRotation(new Quaternion(0, 0, 0, 1));
                Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave);
                VesselToSave.vesselRef.SetPosition(new Vector3(0, ShipSize.y + 2, 0));


                ConfigNode CN = new ConfigNode("ShipConstruct");
                CN = ConstructToSave.SaveShip();
                //SanitizeShipNode(CN);
                CleanEditorNodes(CN);

                //VesselToSave.rotation = OriginalRotation;
                //VesselToSave.position = OriginalPosition;

                if (ConstructToSave.shipFacility == EditorFacility.SPH)
                {
                    CN.Save(UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                            + "/Ships/SPH/" + ShipName + "_Rescued.craft");

                    ScreenMessage message = new ScreenMessage(ShipName + " converted to " + UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                                                              + "/Ships/SPH/" + ShipName + "_Rescued.craft", 6, ScreenMessageStyle.UPPER_CENTER);
                    ScreenMessages.PostScreenMessage(message);
                }
                else
                {
                    CN.Save(UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                            + "/Ships/VAB/" + ShipName + "_Rescued.craft");

                    ScreenMessage message = new ScreenMessage(ShipName + " converted to " + UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                                                              + "/Ships/VAB/" + ShipName + "_Rescued.craft", 6, ScreenMessageStyle.UPPER_CENTER);
                    ScreenMessages.PostScreenMessage(message);
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                HighLogic.CurrentGame.DestroyVessel(VesselToSave.vesselRef);
                VesselToSave.vesselRef.Die();
            }
            //End of Claw's code. Thanks Claw!
        }
Example #19
0
 private void OnVesselRollout(ShipConstruct sc)
 {
     Log.Info("OnVesselRollout");
 }
Example #20
0
 public void ShipModified(ShipConstruct data)
 {
     _updateHitpoints = true;
 }
Example #21
0
 void OnShipLoad(ShipConstruct ship, CraftBrowserDialog.LoadType load_type)
 {
     init_engines = load_type == CraftBrowserDialog.LoadType.Normal;
 }
        private void ResetEditorEvent(ShipConstruct construct)
        {
            if (EditorLogic.RootPart != null)
            {
                List<Part> partsList = EditorLogic.SortedShipList;
                for (int i = 0; i < partsList.Count; i++)
                    UpdateGeometryModule(partsList[i]);

            }

            RequestUpdateVoxel();
        }
Example #23
0
 /// <summary>
 /// Called when ship is modified, checks to see if this part is modified
 /// </summary>
 /// <param name="s"></param>
 void onEditorShipModified(ShipConstruct s)
 {
     Log.Info("onEditorShipModified");
     GetSymList();
 }
Example #24
0
        private void ClobberEngineersReport()
        {
            if (!HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            if (!engineerLocCached)
            {
                engineerLocCached = true;

                cacheAutoLOC_443417  = KSP.Localization.Localizer.Format("#autoLOC_443417");
                cacheAutoLOC_443418  = KSP.Localization.Localizer.Format("#autoLOC_443418");
                cacheAutoLOC_443419  = KSP.Localization.Localizer.Format("#autoLOC_443419");
                cacheAutoLOC_443420  = KSP.Localization.Localizer.Format("#autoLOC_443420");
                cacheAutoLOC_7001411 = KSP.Localization.Localizer.Format("#autoLOC_7001411");
            }

            ShipConstruct ship = EditorLogic.fetch.ship;

            SpaceCenterFacility launchFacility;

            switch (EditorDriver.editorFacility)
            {
            default:
            case EditorFacility.VAB:
                launchFacility = SpaceCenterFacility.LaunchPad;
                break;

            case EditorFacility.SPH:
                launchFacility = SpaceCenterFacility.Runway;
                break;
            }

            //partCount = ship.parts.Count;
            //partLimit = GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(editorFacility), editorFacility == SpaceCenterFacility.VehicleAssemblyBuilding);

            float totalMass = Utilities.GetShipMass(ship, true, out _, out _);
            float massLimit = GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), launchFacility == SpaceCenterFacility.LaunchPad);

            Vector3 craftSize = Utilities.GetShipSize(ship, true);
            Vector3 maxSize   = GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), launchFacility == SpaceCenterFacility.LaunchPad);

            string neutralColorHex = XKCDColors.HexFormat.KSPNeutralUIGrey;

            //string partCountColorHex = partCount <= partLimit ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            //partCountLH.text = partCountLH.text = KSP.Localization.Localizer.Format("#autoLOC_443389", neutralColorHex);

            //if (partLimit < int.MaxValue)
            //{
            //    partCountRH.text = "<color=" + partCountColorHex + ">" + partCount.ToString("0") + " / " + partLimit.ToString("0") + "</color>";
            //}
            //else
            //{
            //    partCountRH.text = "<color=" + partCountColorHex + ">" + partCount.ToString("0") + "</color>";
            //}

            string partMassColorHex = totalMass <= massLimit ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;

            refERpartMassLH.text = KSP.Localization.Localizer.Format("#autoLOC_443401", neutralColorHex);

            if (massLimit < float.MaxValue)
            {
                refERpartMassRH.text = KSP.Localization.Localizer.Format("#autoLOC_443405", partMassColorHex, totalMass.ToString("N3"), massLimit.ToString("N1"));
            }
            else
            {
                refERpartMassRH.text = KSP.Localization.Localizer.Format("#autoLOC_443409", partMassColorHex, totalMass.ToString("N3"));
            }

            string sizeForeAftHex = craftSize.y <= maxSize.y ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            string sizeSpanHex    = craftSize.x <= maxSize.x ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            string sizeTHgtHex    = craftSize.z <= maxSize.z ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;


            refERsizeLH.text = "<line-height=110%><color=" + neutralColorHex + ">" + cacheAutoLOC_443417 + "</color>\n<color=" +
                               neutralColorHex + ">" + cacheAutoLOC_443418 + "</color>\n<color=" +
                               neutralColorHex + ">" + cacheAutoLOC_443419 + "</color>\n<color=" +
                               neutralColorHex + ">" + cacheAutoLOC_443420 + "</color></line-height>";

            if (maxSize.x < float.MaxValue && maxSize.y < float.MaxValue && maxSize.z < float.MaxValue)
            {
                refERsizeRH.text =
                    "<line-height=110%>  \n<color=" + sizeForeAftHex + ">" + KSPUtil.LocalizeNumber(craftSize.y, "0.0") + cacheAutoLOC_7001411 +
                    " / " + KSPUtil.LocalizeNumber(maxSize.y, "0.0") + cacheAutoLOC_7001411 + "</color>\n<color=" +
                    sizeSpanHex + ">" + KSPUtil.LocalizeNumber(craftSize.x, "0.0") + cacheAutoLOC_7001411 + " / " +
                    KSPUtil.LocalizeNumber(maxSize.x, "0.0") +
                    cacheAutoLOC_7001411 + "</color>\n<color=" + sizeTHgtHex + ">" + KSPUtil.LocalizeNumber(craftSize.z, "0.0") + cacheAutoLOC_7001411 + " / " +
                    KSPUtil.LocalizeNumber(maxSize.z, "0.0") + cacheAutoLOC_7001411 + "</color></line-height>";
            }
            else
            {
                refERsizeRH.text = "<line-height=110%> \n<color=" + sizeForeAftHex + ">" + KSPUtil.LocalizeNumber(craftSize.y, "0.0") + cacheAutoLOC_7001411 +
                                   "</color>\n<color=" + sizeSpanHex + ">" + KSPUtil.LocalizeNumber(craftSize.x, "0.0") + cacheAutoLOC_7001411 +
                                   "</color>\n<color=" + sizeTHgtHex + ">" + KSPUtil.LocalizeNumber(craftSize.z, "0.0") + cacheAutoLOC_7001411 + "</color></line-height>";
            }

            bool allGood = //partCount <= partLimit &&
                           totalMass <= massLimit &&
                           craftSize.x <= maxSize.x &&
                           craftSize.y <= maxSize.y &&
                           craftSize.z <= maxSize.z;

            refERappFrame.header.color = allGood ? XKCDColors.ElectricLime : XKCDColors.Orange;

            if (!allGood)
            {
                EngineersReport.Instance.appLauncherButton.sprite.color = XKCDColors.Orange;
            }
            if (allGood)
            {
                EngineersReport.Instance.appLauncherButton.sprite.color = Color.white;
            }
        }
Example #25
0
        public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart)
        {
            UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab);
            if (!obj)
            {
                KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name);
                return null;
            }

            Part newPart = (Part)obj;
            newPart.gameObject.SetActive(true);
            newPart.gameObject.name = avPart.name;
            newPart.partInfo = avPart;
            newPart.highlightRecurse = true;
            newPart.SetMirror(Vector3.one);

            ShipConstruct newShip = new ShipConstruct();
            newShip.Add(newPart);
            newShip.SaveShip();
            newShip.shipName = avPart.title;
            newShip.shipType = 1;

            VesselCrewManifest vessCrewManifest = new VesselCrewManifest();
            Vessel currentVessel = FlightGlobals.ActiveVessel;

            Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>();
            v.id = Guid.NewGuid();
            v.vesselName = newShip.shipName;
            v.Initialize(false);
            v.Landed = true;
            v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
            v.rootPart.missionID = flagFromPart.missionID;
            v.rootPart.flagURL = flagFromPart.flagURL;

            //v.rootPart.collider.isTrigger = true;

            //v.landedAt = "somewhere";
                        
            Staging.beginFlight();
            newShip.parts[0].vessel.ResumeStaging();
            Staging.GenerateStagingSequence(newShip.parts[0].localRoot);
            Staging.RecalculateVesselStaging(newShip.parts[0].vessel);

            FlightGlobals.SetActiveVessel(currentVessel);

            v.SetPosition(position);
            v.SetRotation(rotation);

            // Solar panels from containers don't work otherwise
            for (int i = 0; i < newPart.Modules.Count; i++)
            {
                ConfigNode node = new ConfigNode();
                node.AddValue("name", newPart.Modules[i].moduleName);
                newPart.LoadModule(node, ref i);
            }

            return newPart;
        }
 void UpdateCFG(ShipConstruct ship)
 {
     UpdateCFG(ModuleTCA.AllTCA(ship));
 }
Example #27
0
 private void OnShipModified(ShipConstruct _) => UpdateRate(onRailsCached);
Example #28
0
        /// <remarks>
        ///     This code is based on KAS by KospY and the following license applies:
        ///     http://kerbal.curseforge.com/ksp-mods/223900-kerbal-attachment-system-kas/license (link valid 03.09.2014)
        ///     Usage of this code by me (marce) has been generously granted by KospY on 02.09.2014 per PM.
        /// </remarks>
        public static Part SpawnPartInFlight(string partName, Part referencePart, Vector3 referencePartOriginSpawnOffset, Quaternion spawnRotation, bool spawnLanded = true)
        {
            if (!HighLogic.LoadedSceneIsFlight)
            {
                Debug.Log(LOG_PREFIX + " can only spawn in flight");
                return(null);
            }
            var currentVessel = FlightGlobals.ActiveVessel;
            var avPart        = PartLoader.getPartInfoByName(partName);

            if (avPart == null)
            {
                Debug.Log(LOG_PREFIX + " failed to find part " + partName);
                return(null);
            }
            var obj = UnityEngine.Object.Instantiate(avPart.partPrefab);

            if (obj == null)
            {
                Debug.Log(LOG_PREFIX + " failed to instantiate part " + partName);
                return(null);
            }
            try
            {
                var newPart = (Part)obj;
                newPart.gameObject.SetActive(true);
                newPart.gameObject.name = avPart.name;
                newPart.partInfo        = avPart;
                //newPart.highlightRecurse = true;
                newPart.SetMirror(Vector3.one);
                var newShip = new ShipConstruct {
                    newPart
                };
                newShip.SaveShip();
                newShip.shipName = avPart.title;
                var type = Convert.ChangeType(VesselType.Debris, VesselType.Debris.GetTypeCode());
                //if (type != null)
                //{
                //    newShip.shipType = (int) type;
                //}
                //else
                //{
                //    newShip.shipType = 1;
                //}
                var v = newShip.parts[0].localRoot.gameObject.AddComponent <Vessel>();
                v.id         = Guid.NewGuid();
                v.vesselName = newShip.shipName;
                v.Initialize();
                v.Landed             = spawnLanded;
                v.rootPart.flightID  = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                v.rootPart.missionID = referencePart.missionID;
                v.rootPart.flagURL   = referencePart.flagURL;
                FlightGlobals.SetActiveVessel(currentVessel);
                v.SetPosition(referencePart.transform.position + referencePartOriginSpawnOffset);
                v.SetRotation(spawnRotation);
                for (var i = 0; i < newPart.Modules.Count; i++)
                {
                    var node = new ConfigNode();
                    node.AddValue("name", newPart.Modules[i].moduleName);
                    var j = i;
                    newPart.LoadModule(node, ref j);
                }
                return(newPart);
            }
            catch (NullReferenceException)
            {
                Debug.Log(LOG_PREFIX + " part unknown");
                return(null);
            }
        }
Example #29
0
        private void UpdateGUIInfo(ShipConstruct ship)
        {
            ResetValues();
            if (EditorLogic.fetch != null)
            {
                var parts = EditorLogic.fetch.ship.parts;
                var count = parts.Count;
                for (int i = 0; i < count; ++i)
                {
                    var part = parts[i];
                    maxCrew += part.CrewCapacity;
                }

                var dialog = KSP.UI.CrewAssignmentDialog.Instance;

                if (dialog != null)
                {
                    VesselCrewManifest manifest = dialog.GetManifest();
                    if (manifest != null)
                    {
                        curCrew = manifest.CrewCount;
                    }
                }

                for (int i = 0; i < count; ++i)
                {
                    var part        = parts[i];
                    var swapOptions = part.FindModulesImplementing <AbstractSwapOption>();
                    var bays        = part.FindModulesImplementing <USI_SwappableBay>();
                    if (swapOptions != null && bays != null && swapOptions.Count > 0 && bays.Count > 0)
                    {
                        for (int x = 0; x < bays.Count; x++)
                        {
                            var bay     = bays[x];
                            var loadout = swapOptions[bay.currentLoadout] as USILS_HabitationSwapOption;
                            if (loadout != null)
                            {
                                habs.Add(loadout);
                                //Certain modules, in addition to crew capacity, have living space.
                                extraHabTime += loadout.BaseKerbalMonths;
                                //Some modules act more as 'multipliers', dramatically extending a hab's workable lifespan.
                                habMult += loadout.BaseHabMultiplier * Math.Min(1, loadout.CrewCapacity / Math.Max(curCrew, 1));
                            }
                        }
                    }
                    if (part.Resources.Contains("ColonySupplies"))
                    {
                        colonySupplies += part.Resources["ColonySupplies"].amount;
                    }
                    if (part.Resources.Contains("Fertilizer"))
                    {
                        fertilizer += part.Resources["Fertilizer"].amount;
                    }
                    if (part.Resources.Contains("Supplies"))
                    {
                        supplies += part.Resources["Supplies"].amount;
                    }
                    if (part.Resources.Contains("ElectricCharge"))
                    {
                        batteryAmount += part.Resources["ElectricCharge"].maxAmount;
                    }
                }

                totalHabSpace = (LifeSupportScenario.Instance.settings.GetSettings().BaseHabTime *maxCrew) + extraHabTime;
                //A Kerbal month is 30 six-hour Kerbin days.
                totalHabMult        = habMult * LifeSupportScenario.Instance.settings.GetSettings().HabMultiplier *LifeSupportUtilities.SecondsPerMonth();
                totalBatteryTime    = batteryAmount / LifeSupportScenario.Instance.settings.GetSettings().ECAmount;
                totalSupplyTime     = supplies / LifeSupportScenario.Instance.settings.GetSettings().SupplyAmount;
                totalFertilizerTime = fertilizer * 10 / LifeSupportScenario.Instance.settings.GetSettings().SupplyAmount;

                if (EditorLogic.fetch.ship.parts.Count > 0)
                {
                    for (int i = 0; i < count; ++i)
                    {
                        var part        = parts[i];
                        var swapOptions = part.FindModulesImplementing <AbstractSwapOption>();
                        var bays        = part.FindModulesImplementing <USI_SwappableBay>();
                        if (swapOptions != null && bays != null && swapOptions.Count > 0 && bays.Count > 0)
                        {
                            for (int x = 0; x < bays.Count; x++)
                            {
                                var bay     = bays[x];
                                var loadout = swapOptions[bay.currentLoadout] as USILS_LifeSupportRecyclerSwapOption;
                                if (loadout != null)
                                {
                                    this.recyclers.Add(loadout);
                                }
                            }
                        }
                    }
                    var recyclerMultiplier_curCrew = LifeSupportManager.GetRecyclerMultiplierForParts(EditorLogic.fetch.ship.parts, curCrew);
                    var recyclerMultiplier_maxCrew = LifeSupportManager.GetRecyclerMultiplierForParts(EditorLogic.fetch.ship.parts, maxCrew);

                    supply_curCrew = LifeSupportUtilities.DurationDisplay(
                        totalSupplyTime /
                        Math.Max(1, curCrew) /
                        recyclerMultiplier_curCrew
                        );
                    supply_maxCrew = LifeSupportUtilities.DurationDisplay(
                        totalSupplyTime /
                        Math.Max(1, maxCrew) /
                        recyclerMultiplier_maxCrew
                        );

                    hab_curCrew = LifeSupportUtilities.DurationDisplay(totalHabSpace / Math.Max(1, curCrew) * totalHabMult);
                    hab_maxCrew = LifeSupportUtilities.DurationDisplay(totalHabSpace / Math.Max(1, maxCrew) * totalHabMult);

                    supplyExt_curCrew = LifeSupportUtilities.DurationDisplay(
                        (totalSupplyTime + totalFertilizerTime) /
                        Math.Max(1, curCrew) /
                        recyclerMultiplier_curCrew
                        );
                    supplyExt_maxCrew = LifeSupportUtilities.DurationDisplay(
                        (totalSupplyTime + totalFertilizerTime) /
                        Math.Max(1, maxCrew) /
                        recyclerMultiplier_maxCrew
                        );
                    //Standard is half a colony supply per hour, or 0.000139 per second.
                    var csupPerSecond = 0.000139d;
                    habExt_curCrew = LifeSupportUtilities.DurationDisplay((totalHabSpace / Math.Max(1, curCrew) * totalHabMult) + (colonySupplies / csupPerSecond / curCrew));
                    habExt_maxCrew = LifeSupportUtilities.DurationDisplay((totalHabSpace / Math.Max(1, maxCrew) * totalHabMult) + (colonySupplies / csupPerSecond / maxCrew));
                }
            }
        }
Example #30
0
 private void shipModified(ShipConstruct data)
 {
     needsUpdate = true;
 }
		public CostReport getBuildCost (ConfigNode craft)
		{
			lockedParts = false;
			ShipConstruct ship = new ShipConstruct ();
			if (!ship.LoadShip (craft)) {
				return null;
			}
			if (!ship.shipPartsUnlocked) {
				lockedParts = true;
			}
			GameObject ro = ship.parts[0].localRoot.gameObject;
			Vessel craftVessel = ro.AddComponent<Vessel>();
			craftVessel.Initialize (true);
			if (ExSettings.B9Wings_Present) {
				if (!InitializeB9Wings (craftVessel)
					&& ExSettings.FAR_Present) {
					InitializeFARSurfaces (craftVessel);
				}
			} else if (ExSettings.FAR_Present) {
				InitializeFARSurfaces (craftVessel);
			}

			// needed for displaying optional resources during the planning
			// stage.
			craftResources = new VesselResources (craftVessel);

			BuildCost resources = new BuildCost ();

			foreach (Part p in craftVessel.parts) {
				resources.addPart (p);
			}
			craftVessel.Die ();

			return resources.cost;
		}
 private void onEditorVesselModified(ShipConstruct ship)
 {
     updateGUI();
 }
Example #33
0
        public void onEditorVesselModified(ShipConstruct ship)
        {
            if (!HighLogic.LoadedSceneIsEditor) { return; }
            bool updated = false;
            if (prevMountSizeAdjust != editorMountSizeAdjust)
            {
                prevMountSizeAdjust = editorMountSizeAdjust;
                updateMountSizeFromEditor();

                SSTUEngineCluster module;
                int moduleIndex = part.Modules.IndexOf(this);
                foreach (Part p in part.symmetryCounterparts)
                {
                    module = (SSTUEngineCluster)p.Modules[moduleIndex];
                    module.prevMountSizeAdjust = module.editorMountSizeAdjust = editorMountSizeAdjust;
                    module.editorMountSize = editorMountSize;
                    module.updateMountSizeFromEditor();
                }
                updated = true;
            }
            if (prevEngineSpacingAdjust != editorEngineSpacingAdjust)
            {
                prevEngineSpacingAdjust = editorEngineSpacingAdjust;
                updateEngineSpacingFromEditor();

                SSTUEngineCluster module;
                int moduleIndex = part.Modules.IndexOf(this);
                foreach (Part p in part.symmetryCounterparts)
                {
                    module = (SSTUEngineCluster)p.Modules[moduleIndex];
                    module.prevEngineSpacingAdjust = module.editorEngineSpacingAdjust = editorEngineSpacingAdjust;
                    updateEngineSpacingFromEditor();
                }
                updated = true;
            }
            if (prevEngineHeightAdjust != editorEngineHeightAdjust)
            {
                prevEngineHeightAdjust = editorEngineHeightAdjust;
                currentEngineVerticalOffset = editorEngineHeightAdjust;
                updateMountPositions(true);
                updated = true;

                SSTUEngineCluster module;
                int moduleIndex = part.Modules.IndexOf(this);
                foreach (Part p in part.symmetryCounterparts)
                {
                    module = (SSTUEngineCluster)p.Modules[moduleIndex];
                    module.prevEngineHeightAdjust = module.editorEngineHeightAdjust = editorEngineHeightAdjust;
                    updateMountPositions(true);
                }
            }
            if (!updated)
            {
                updateNodePositions(true);
            }
        }
Example #34
0
        public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation,
                                      Part flagFromPart)
        {
            UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab);
            if (!obj)
            {
                KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name);
                return(null);
            }

            Part newPart = (Part)obj;

            newPart.gameObject.SetActive(true);
            newPart.gameObject.name = avPart.name;
            newPart.partInfo        = avPart;
            //newPart.highlightRecurse = true;
            newPart.SetMirror(Vector3.one);

            ShipConstruct newShip = new ShipConstruct();

            newShip.Add(newPart);
            newShip.SaveShip();
            newShip.shipName = avPart.title;
            //newShip.ty = 1;

            VesselCrewManifest vessCrewManifest = new VesselCrewManifest();
            Vessel             currentVessel    = FlightGlobals.ActiveVessel;

            Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent <Vessel>();

            v.id         = Guid.NewGuid();
            v.vesselName = newShip.shipName;
            v.Initialize(false);
            v.Landed             = true;
            v.rootPart.flightID  = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
            v.rootPart.missionID = flagFromPart.missionID;
            v.rootPart.flagURL   = flagFromPart.flagURL;

            //v.rootPart.collider.isTrigger = true;

            //v.landedAt = "somewhere";

            StageManager.BeginFlight();
            newShip.parts[0].vessel.ResumeStaging();
            StageManager.GenerateStagingSequence(newShip.parts[0].localRoot);
            StageManager.RecalculateVesselStaging(newShip.parts[0].vessel);

            FlightGlobals.SetActiveVessel(currentVessel);

            v.SetPosition(position);
            v.SetRotation(rotation);

            // Solar panels from containers don't work otherwise
            for (int i = 0; i < newPart.Modules.Count; i++)
            {
                ConfigNode node = new ConfigNode();
                node.AddValue("name", newPart.Modules[i].moduleName);
                newPart.LoadModule(node, ref i);
            }

            return(newPart);
        }
Example #35
0
 void onEditorShipModified(ShipConstruct ship)
 {
     StartCoroutine (WaitAndUpdate ());
 }
Example #36
0
File: GUI.cs Project: evonzee/KSTS
        static void ReadAllCraftFiles(string editorFacility, string shipDirectory)
        {
            foreach (var craftFile in Directory.GetFiles(shipDirectory, "*.craft"))
            {
                try
                {
                    string validFileName = Path.GetFileNameWithoutExtension(craftFile);
                    if (validFileName == "Auto-Saved Ship")
                    {
                        continue;                                     // Skip these, they would lead to duplicates, we only use finished crafts.
                    }
                    var cachedTemplate = new CachedShipTemplate();
                    switch (editorFacility)
                    {
                    case "VAB": cachedTemplate.templateOrigin = TemplateOrigin.VAB; break;

                    case "SPH": cachedTemplate.templateOrigin = TemplateOrigin.SPH; break;

                    case "Subassemblies": cachedTemplate.templateOrigin = TemplateOrigin.SubAssembly; break;
                    }

                    cachedTemplate.template = ShipConstruction.LoadTemplate(craftFile);

                    if (cachedTemplate.template == null)
                    {
                        continue;
                    }
                    if (cachedTemplate.template.shipPartsExperimental || !cachedTemplate.template.shipPartsUnlocked)
                    {
                        continue;                                                                                              // We won't bother with ships we can't use anyways.
                    }
                    // Try to load the thumbnail for this craft:
                    var thumbFile = KSPUtil.ApplicationRootPath + "thumbs/" + HighLogic.SaveFolder + "_" + editorFacility + "_" + validFileName + ".png";

                    Texture2D thumbnail;

                    //
                    // Make the thumbnail file if it doesn't exist.
                    // Needed for the subassemblies, will also replace any missing thumbnail files for regular craft
                    //
                    if (!HighLogic.LoadedSceneIsFlight)
                    {
                        if (!File.Exists(thumbFile))
                        {
                            Log.Info("Missing Thumbfile: " + thumbFile);
                            ShipConstruct ship = ShipConstruction.LoadShip(craftFile);
                            ThumbnailHelper.CaptureThumbnail(ship, 256, "thumbs/", HighLogic.SaveFolder + "_" + editorFacility + "_" + validFileName);
                        }
                    }

                    bool placeholder = false;
                    if (File.Exists(thumbFile))
                    {
                        thumbnail = new Texture2D(256, 256, TextureFormat.RGBA32, false);
                        thumbnail.LoadImage(File.ReadAllBytes(thumbFile));
                    }
                    else
                    {
                        thumbnail   = placeholderImage;
                        placeholder = true;
                    }

                    // The thumbnails are rather large, so we have to resize them first:
                    cachedTemplate.thumbnail = GUI.ResizeTexture(thumbnail, 64, 64);
                    if (!placeholder)
                    {
                        Destroy(thumbnail);
                    }
                    GUI.shipTemplates.Add(cachedTemplate);
                }
                catch (Exception e)
                {
                    Debug.LogError("UpdateShipTemplateCache() processing '" + craftFile + "': " + e.ToString());
                }
            }
        }
Example #37
0
 /// <summary>
 /// Event callback for when vessel is modified in the editor.  Used to know when the gui-fields for this module have been updated.
 /// </summary>
 /// <param name="ship"></param>
 public void onEditorVesselModified(ShipConstruct ship)
 {
     if (!HighLogic.LoadedSceneIsEditor) { return; }
     bool updated = false;
     if (prevEditorTankHeightAdjust != editorTankHeightAdjust)
     {
         prevEditorTankHeightAdjust = editorTankHeightAdjust;
         float newHeight = editorTankHeight + (tankHeightIncrement * editorTankHeightAdjust);
         newHeight *= (currentTankDiameter / defaultTankDiameter);
         updateTankHeightFromEditor(newHeight, true);
         updated = true;
     }
     if (prevEditorTankDiameterAdjust != editorTankDiameterAdjust)
     {
         prevEditorTankDiameterAdjust = editorTankDiameterAdjust;
         float newDiameter = editorTankDiameter + (editorTankDiameterAdjust * tankDiameterIncrement);
         setTankDiameterFromEditor(newDiameter, true);
         updated = true;
     }
     if (!updated)
     {
         updateNodePositions(true);
     }
 }
 void onEditorShipModified(ShipConstruct ship)
 {
     RebuildList();
 }
        void SpawnVessel(string craftURL, CelestialBody orbitmainBodyName, double altitude, string stationName)
        {
            foreach (Vessel vessel in FlightGlobals.Vessels)
            {
                if (vessel.vesselName == stationName)
                {
                    vessel.Die();
                    break;
                }
            }
            VesselData vesselData = new VesselData();

            vesselData.craftURL = craftURL;
            vesselData.orbiting = true;
            vesselData.flagURL  = HighLogic.CurrentGame.flagURL;
            vesselData.owned    = true;
            string gameDataDir = KSPUtil.ApplicationRootPath;

            ConfigNode[]  partNodes;
            ShipConstruct shipConstruct = null;
            float         lcHeight      = 0;
            ConfigNode    craftNode;
            ConfigNode    currentShip = ShipConstruction.ShipConfig;

            shipConstruct = ShipConstruction.LoadShip(vesselData.craftURL);
            craftNode     = ConfigNode.Load(vesselData.craftURL);
            lcHeight      = ConfigNode.ParseVector3(craftNode.GetNode("PART").GetValue("pos")).y;
            ShipConstruction.ShipConfig = currentShip;
            ConfigNode  empty       = new ConfigNode();
            ProtoVessel dummyProto  = new ProtoVessel(empty, null);
            Vessel      dummyVessel = new Vessel();

            dummyVessel.parts    = shipConstruct.parts;
            dummyProto.vesselRef = dummyVessel;
            uint missionID = (uint)Guid.NewGuid().GetHashCode();
            uint launchID  = HighLogic.CurrentGame.launchID++;

            foreach (Part p in shipConstruct.parts)
            {
                p.missionID   = missionID;
                p.launchID    = launchID;
                p.flightID    = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                p.temperature = 1.0;
                dummyProto.protoPartSnapshots.Add(new ProtoPartSnapshot(p, dummyProto));
            }
            foreach (ProtoPartSnapshot p in dummyProto.protoPartSnapshots)
            {
                p.storePartRefs();
            }
            List <ConfigNode> partNodesL = new List <ConfigNode>();

            foreach (var snapShot in dummyProto.protoPartSnapshots)
            {
                ConfigNode node = new ConfigNode("PART");
                snapShot.Save(node);
                partNodesL.Add(node);
            }
            partNodes = partNodesL.ToArray();
            ConfigNode[] additionalNodes = new ConfigNode[0];
            ConfigNode   protoVesselNode = ProtoVessel.CreateVesselNode(stationName, VesselType.Station, new Orbit(0, 0, altitude + orbitmainBodyName.Radius, 0, 0, 0, 0, orbitmainBodyName), 0, partNodes, additionalNodes);
            ProtoVessel  protoVessel     = HighLogic.CurrentGame.AddVessel(protoVesselNode);

            vesselData.id = protoVessel.vesselRef.id;
            foreach (var p in FindObjectsOfType <Part>())
            {
                if (!p.vessel)
                {
                    Destroy(p.gameObject);
                }
            }
        }
 private void onEditorLoad(ShipConstruct ship, CraftBrowserDialog.LoadType loadType)
 {
     Debug.LogFormat("ELShipInfo.onEditorLoad: {0} {1}", ship, loadType);
     RebuildList();
 }
Example #41
0
 private void EditorShipModified(ShipConstruct construct)
 {
     SetupGUI();
     UpdateFields();
 }
Example #42
0
        private void SpawnVessel(LootBoxVesselData LootBoxVesselData, List <ProtoCrewMember> crewData = null)
        {
            //      string gameDataDir = KSPUtil.ApplicationRootPath;
            Debug.Log("[Spawn OrX S Mart] Spawning " + LootBoxVesselData.name);

            // Set additional info for landed vessels
            bool landed = false;

            if (!landed)
            {
                landed = true;
                if (LootBoxVesselData.altitude == null || LootBoxVesselData.altitude < 0)
                {
                    LootBoxVesselData.altitude = 5;//LocationUtil.TerrainHeight(LootBoxVesselData.latitude, LootBoxVesselData.longitude, LootBoxVesselData.body);
                }
                Debug.Log("[Spawn OrX S Mart] SpawnVessel Altitude: " + LootBoxVesselData.altitude);

                //Vector3d pos = LootBoxVesselData.body.GetWorldSurfacePosition(LootBoxVesselData.latitude, LootBoxVesselData.longitude, LootBoxVesselData.altitude.Value);
                Vector3d pos = LootBoxVesselData.body.GetRelSurfacePosition(LootBoxVesselData.latitude, LootBoxVesselData.longitude, LootBoxVesselData.altitude.Value);

                LootBoxVesselData.orbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, LootBoxVesselData.body);
                LootBoxVesselData.orbit.UpdateFromStateVectors(pos, LootBoxVesselData.body.getRFrmVel(pos), LootBoxVesselData.body, Planetarium.GetUniversalTime());
            }

            ConfigNode[]  partNodes;
            ShipConstruct shipConstruct = null;
            bool          hasClamp      = false;
            float         lcHeight      = 0;
            ConfigNode    craftNode;
            Quaternion    craftRotation = Quaternion.identity;

            if (!string.IsNullOrEmpty(LootBoxVesselData.craftURL))
            {
                // Save the current ShipConstruction ship, otherwise the player will see the spawned ship next time they enter the VAB!
                ConfigNode currentShip = ShipConstruction.ShipConfig;

                shipConstruct = ShipConstruction.LoadShip(LootBoxVesselData.craftURL);
                if (shipConstruct == null)
                {
                    Debug.Log("[Spawn OrX S Mart] ShipConstruct was null when tried to load '" + LootBoxVesselData.craftURL +
                              "' (usually this means the file could not be found).");
                    return;//continue;
                }

                craftNode     = ConfigNode.Load(LootBoxVesselData.craftURL);
                lcHeight      = ConfigNode.ParseVector3(craftNode.GetNode("PART").GetValue("pos")).y;
                craftRotation = ConfigNode.ParseQuaternion(craftNode.GetNode("PART").GetValue("rot"));

                // Restore ShipConstruction ship
                ShipConstruction.ShipConfig = currentShip;

                // Set the name
                if (string.IsNullOrEmpty(LootBoxVesselData.name))
                {
                    LootBoxVesselData.name = SMIVesselName;
                    ;
                }

                // Set some parameters that need to be at the part level
                uint missionID = (uint)Guid.NewGuid().GetHashCode();
                uint launchID  = HighLogic.CurrentGame.launchID++;
                foreach (Part p in shipConstruct.parts)
                {
                    p.flightID  = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                    p.missionID = missionID;
                    p.launchID  = launchID;
                    p.flagURL   = flagURL;

                    // Had some issues with this being set to -1 for some ships - can't figure out
                    // why.  End result is the vessel exploding, so let's just set it to a positive
                    // value.
                    p.temperature = 1.0;
                }

                // Create a dummy ProtoVessel, we will use this to dump the parts to a config node.
                // We can't use the config nodes from the .craft file, because they are in a
                // slightly different format than those required for a ProtoVessel (seriously
                // Squad?!?).
                ConfigNode  empty       = new ConfigNode();
                ProtoVessel dummyProto  = new ProtoVessel(empty, null);
                Vessel      dummyVessel = new Vessel();
                dummyVessel.parts    = shipConstruct.parts;
                dummyProto.vesselRef = dummyVessel;

                // Create the ProtoPartSnapshot objects and then initialize them
                foreach (Part p in shipConstruct.parts)
                {
                    dummyProto.protoPartSnapshots.Add(new ProtoPartSnapshot(p, dummyProto));
                }
                foreach (ProtoPartSnapshot p in dummyProto.protoPartSnapshots)
                {
                    p.storePartRefs();
                }

                // Create the ship's parts

                List <ConfigNode> partNodesL = new List <ConfigNode>();
                foreach (ProtoPartSnapshot snapShot in dummyProto.protoPartSnapshots)
                {
                    ConfigNode node = new ConfigNode("PART");
                    snapShot.Save(node);
                    partNodesL.Add(node);
                }
                partNodes = partNodesL.ToArray();
            }
            else
            {
                // Create crew member array
                ProtoCrewMember[] crewArray = new ProtoCrewMember[LootBoxVesselData.crew.Count];

                /*
                 *      int i = 0;
                 *      foreach (CrewData cd in LootBoxVesselData.crew)
                 *      {
                 * /*
                 *        // Create the ProtoCrewMember
                 *        ProtoCrewMember crewMember = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Crew);
                 *        if (cd.name != null)
                 *        {
                 *          crewMember.KerbalRef.name = cd.name;
                 *        }
                 *
                 *        crewArray[i++] = crewMember;
                 *
                 *      }
                 */
                // Create part nodes
                uint flightId = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                partNodes    = new ConfigNode[1];
                partNodes[0] = ProtoVessel.CreatePartNode(LootBoxVesselData.craftPart.name, flightId, crewArray);

                // Default the size class
                //sizeClass = UntrackedObjectClass.A;

                // Set the name
                if (string.IsNullOrEmpty(LootBoxVesselData.name))
                {
                    LootBoxVesselData.name = LootBoxVesselData.craftPart.name;
                }
            }

            // Create additional nodes
            ConfigNode[] additionalNodes = new ConfigNode[0];
            //DiscoveryLevels discoveryLevel = LootBoxVesselData.owned ? DiscoveryLevels.Owned : DiscoveryLevels.Unowned;
            //additionalNodes[0] = ProtoVessel.CreateDiscoveryNode(discoveryLevel, sizeClass, contract.TimeDeadline, contract.TimeDeadline);

            // Create the config node representation of the ProtoVessel
            ConfigNode protoVesselNode = ProtoVessel.CreateVesselNode(LootBoxVesselData.name, LootBoxVesselData.vesselType, LootBoxVesselData.orbit, 0, partNodes, additionalNodes);

            // Additional seetings for a landed vessel
            if (!LootBoxVesselData.orbiting)
            {
                Vector3d norm = LootBoxVesselData.body.GetRelSurfaceNVector(LootBoxVesselData.latitude, LootBoxVesselData.longitude);

                double terrainHeight = 0.0;
                if (LootBoxVesselData.body.pqsController != null)
                {
                    terrainHeight = LootBoxVesselData.body.pqsController.GetSurfaceHeight(norm) - LootBoxVesselData.body.pqsController.radius;
                }
                bool splashed = false;// = landed && terrainHeight < 0.001;

                // Create the config node representation of the ProtoVessel
                // Note - flying is experimental, and so far doesn't worx
                protoVesselNode.SetValue("sit", (splashed ? Vessel.Situations.SPLASHED : landed ?
                                                 Vessel.Situations.LANDED : Vessel.Situations.FLYING).ToString());
                protoVesselNode.SetValue("landed", (landed && !splashed).ToString());
                protoVesselNode.SetValue("splashed", splashed.ToString());
                protoVesselNode.SetValue("lat", LootBoxVesselData.latitude.ToString());
                protoVesselNode.SetValue("lon", LootBoxVesselData.longitude.ToString());
                protoVesselNode.SetValue("alt", LootBoxVesselData.altitude.ToString());
                protoVesselNode.SetValue("landedAt", LootBoxVesselData.body.name);

                // Figure out the additional height to subtract
                float lowest = float.MaxValue;
                if (shipConstruct != null)
                {
                    foreach (Part p in shipConstruct.parts)
                    {
                        foreach (Collider collider in p.GetComponentsInChildren <Collider>())
                        {
                            if (collider.gameObject.layer != 21 && collider.enabled)
                            {
                                lowest = Mathf.Min(lowest, collider.bounds.min.y);
                            }
                        }
                    }
                }
                else
                {
                    foreach (Collider collider in LootBoxVesselData.craftPart.partPrefab.GetComponentsInChildren <Collider>())
                    {
                        if (collider.gameObject.layer != 21 && collider.enabled)
                        {
                            lowest = Mathf.Min(lowest, collider.bounds.min.y);
                        }
                    }
                }

                if (lowest == float.MaxValue)
                {
                    lowest = 0;
                }

                // Figure out the surface height and rotation
                Quaternion normal   = Quaternion.LookRotation((Vector3)norm);// new Vector3((float)norm.x, (float)norm.y, (float)norm.z));
                Quaternion rotation = Quaternion.identity;
                float      heading  = LootBoxVesselData.heading;
                if (shipConstruct == null)
                {
                    rotation = rotation * Quaternion.FromToRotation(Vector3.up, Vector3.back);
                }
                else if (shipConstruct.shipFacility == EditorFacility.SPH)
                {
                    rotation = rotation * Quaternion.FromToRotation(Vector3.forward, -Vector3.forward);
                    heading += 180.0f;
                }
                else
                {
                    rotation = rotation * Quaternion.FromToRotation(Vector3.up, Vector3.forward);
                    rotation = Quaternion.FromToRotation(Vector3.up, -Vector3.up) * rotation;

                    //rotation = craftRotation;


                    LootBoxVesselData.heading = 0;
                    LootBoxVesselData.pitch   = 0;
                }

                rotation = rotation * Quaternion.AngleAxis(heading, Vector3.back);
                rotation = rotation * Quaternion.AngleAxis(LootBoxVesselData.roll, Vector3.down);
                rotation = rotation * Quaternion.AngleAxis(LootBoxVesselData.pitch, Vector3.left);

                // Set the height and rotation
                if (landed || splashed)
                {
                    float hgt = (shipConstruct != null ? shipConstruct.parts[0] : LootBoxVesselData.craftPart.partPrefab).localRoot.attPos0.y - lowest;
                    hgt += LootBoxVesselData.height;
                    protoVesselNode.SetValue("hgt", hgt.ToString(), true);
                }
                protoVesselNode.SetValue("rot", KSPUtil.WriteQuaternion(normal * rotation), true);

                // Set the normal vector relative to the surface
                Vector3 nrm = (rotation * Vector3.forward);
                protoVesselNode.SetValue("nrm", nrm.x + "," + nrm.y + "," + nrm.z, true);

                protoVesselNode.SetValue("prst", false.ToString(), true);
            }

            // Add vessel to the game
            ProtoVessel protoVessel = HighLogic.CurrentGame.AddVessel(protoVesselNode);

            //protoVessel.vesselRef.transform.rotation = protoVessel.rotation;


            // Store the id for later use
            LootBoxVesselData.id = protoVessel.vesselRef.id;

            //protoVessel.vesselRef.currentStage = 0;
            hasClamp = false;

            StartCoroutine(PlaceSpawnedVessel(protoVessel.vesselRef, !hasClamp));

            // Associate it so that it can be used in contract parameters
            //ContractVesselTracker.Instance.AssociateVessel(LootBoxVesselData.name, protoVessel.vesselRef);


            //destroy prefabs
            foreach (Part p in FindObjectsOfType <Part>())
            {
                if (!p.vessel)
                {
                    Destroy(p.gameObject);
                }
            }
        }
Example #43
0
 void OnShipModified(ShipConstruct ship)
 {
     update_engines = true;
 }
Example #44
0
 public void UpdateGUI(ShipConstruct ship)
 {
     UpdatePart();
 }
Example #45
0
 private void ShipModifiedEvent(ShipConstruct vessel)
 {
     KCT_Utilities.RecalculateEditorBuildTime(vessel);
 }
Example #46
0
 private void ShipModifiedEvent(ShipConstruct vessel)
 {
     KerbalConstructionTime.instance.editorRecalcuationRequired = true;
 }
		internal void BuildAndLaunchCraft ()
		{
			// build craft
			ShipConstruct nship = new ShipConstruct ();
			nship.LoadShip (craftConfig);

			int numParts = builder.vessel.parts.Count;
			if (craftType != CraftType.SubAss)
				numParts = 0;

			string landedAt = "External Launchpad";
			string flag = flagname;
			Game game = FlightDriver.FlightStateCache;
			VesselCrewManifest crew = new VesselCrewManifest ();

			Box vessel_bounds = GetVesselBox (nship);
			launchTransform = builder.PlaceShip (nship, vessel_bounds);

			EnableExtendingLaunchClamps (nship);
			ShipConstruction.AssembleForLaunch (nship, landedAt, flag, game,
												crew);
			var FlightVessels = FlightGlobals.Vessels;
			craftVessel = FlightVessels[FlightVessels.Count - 1];

			FlightGlobals.ForceSetActiveVessel (craftVessel);
			if (builder.capture) {
				craftVessel.Splashed = craftVessel.Landed = false;
			} else {
				bool loaded = craftVessel.loaded;
				bool packed = craftVessel.packed;
				craftVessel.loaded = true;
				craftVessel.packed = false;
				craftVessel.GetHeightFromTerrain ();
				Debug.Log (String.Format ("[EL] hft {0}", craftVessel.heightFromTerrain));
				craftVessel.loaded = loaded;
				craftVessel.packed = packed;
			}

			Vector3 offset = craftVessel.transform.position - launchTransform.position;
			craftOffset = launchTransform.InverseTransformDirection (offset);
			SetupCraftResources (craftVessel);

			Staging.beginFlight ();

			if (builder.capture) {
				FlightGlobals.overrideOrbit = true;
				(builder as PartModule).StartCoroutine (CaptureCraft ());
			} else {
				state = State.Idle;
			}
		}
Example #48
0
 public void UpdateGUI(ShipConstruct ship)
 {
     massDisplay = Utils.formatMass(part.TotalMass());
 }
        void OnVesselLaunched(ShipConstruct vVessel)
        {
            if (vVessel == null) return;
            if (EditorLogic.fetch.launchSiteName == null) return;

            PersistenceUtils.savePersistenceBackup();

            if (EditorLogic.fetch.launchSiteName == "Runway") return;
            if (EditorLogic.fetch.launchSiteName == "LaunchPad") return;
            if (EditorLogic.fetch.launchSiteName == "KSC") return;

            /* StaticObject soTemp = null;

            foreach (StaticObject soThis in KerbalKonstructs.instance.getStaticDB().getAllStatics())
            {
                if (soThis.getSetting("LaunchSiteName") == null)
                    continue;
                else
                    if ((string)soThis.getSetting("LaunchSiteName") == (string)EditorLogic.fetch.launchSiteName)
                    {
                        soTemp = soThis;
                        break;
                    }
            } */

            // Don't know why newly created launchsites don't appear without a restart of KSP still.
            // This doesn't seem to help.
            /* if (soTemp != null)
            {
                if (DebugMode) Debug.Log("KK: Got launchsite gameobject" + (string)EditorLogic.fetch.launchSiteName);

                soTemp.SetActiveRecursively(soTemp.gameObject, true);
            } */

            if (MiscUtils.CareerStrategyEnabled(HighLogic.CurrentGame))
            {
                VesselLaunched = true;
                string sitename = EditorLogic.fetch.launchSiteName;

                float dryCost = 0f;
                float fuelCost = 0f;
                float total = vVessel.GetShipCosts(out dryCost, out fuelCost);

                var cm = CurrencyModifierQuery.RunQuery(TransactionReasons.VesselRollout, total, 0f, 0f);
                total += cm.GetEffectDelta(Currency.Funds);

                double launchcost = total;
                float fRefund = 0f;
                LaunchSiteManager.getSiteLaunchRefund((string)EditorLogic.fetch.launchSiteName, out fRefund);

                if (fRefund < 1) return;

                RefundAmount = (launchcost / 100) * fRefund;
                VesselCost = launchcost - (RefundAmount);
                if (fRefund > 0)
                {
                    string sMessage = "This launch normally costs " + launchcost.ToString("#0") +
                        " but " + sitename + " provides a " + fRefund + "% refund. \n\nSo " + RefundAmount.ToString("#0") + " funds has been credited to you. \n\nEnjoy and thanks for using " +
                        sitename + ". Have a safe flight.";
                    MiscUtils.PostMessage("Launch Refund", sMessage, MessageSystemButton.MessageButtonColor.GREEN, MessageSystemButton.ButtonIcons.ALERT);
                    Funding.Instance.AddFunds(RefundAmount, TransactionReasons.Cheating);
                }
            }
        }
        private void EditorShipModified(ShipConstruct S)
        {
//				_logger.Trace( "Callback: EditorShipModified" );
            _filterRefreshPending = true;
        }
Example #51
0
 /// <remarks>
 ///     This code is based on KAS by KospY and the following license applies:
 ///     http://kerbal.curseforge.com/ksp-mods/223900-kerbal-attachment-system-kas/license (link valid 03.09.2014)
 ///     Usage of this code by me (marce) has been generously granted by KospY on 02.09.2014 per PM.
 /// </remarks>
 public static Part SpawnPartInFlight(string partName, Part referencePart, Vector3 referencePartOriginSpawnOffset, Quaternion spawnRotation, bool spawnLanded = true)
 {
     if (!HighLogic.LoadedSceneIsFlight)
     {
         Debug.Log(LogPrefix + " can only spawn in flight");
         return null;
     }
     var currentVessel = FlightGlobals.ActiveVessel;
     var avPart = PartLoader.getPartInfoByName(partName);
     var obj = UnityEngine.Object.Instantiate(avPart.partPrefab);
     if (obj == null)
     {
         Debug.Log(LogPrefix + " failed to instantiate part " + partName);
         return null;
     }
     try
     {
         var newPart = (Part) obj;
         newPart.gameObject.SetActive(true);
         newPart.gameObject.name = avPart.name;
         newPart.partInfo = avPart;
         newPart.highlightRecurse = true;
         newPart.SetMirror(Vector3.one);
         var newShip = new ShipConstruct {newPart};
         newShip.SaveShip();
         newShip.shipName = avPart.title;
         var type = Convert.ChangeType(VesselType.Debris, VesselType.Debris.GetTypeCode());
         if (type != null)
         {
             newShip.shipType = (int) type;
         }
         else
         {
             newShip.shipType = 1;
         }
         var v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>();
         v.id = Guid.NewGuid();
         v.vesselName = newShip.shipName;
         v.Initialize();
         v.Landed = spawnLanded;
         v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
         v.rootPart.missionID = referencePart.missionID;
         v.rootPart.flagURL = referencePart.flagURL;
         FlightGlobals.SetActiveVessel(currentVessel);
         v.SetPosition(referencePart.transform.position + referencePartOriginSpawnOffset);
         v.SetRotation(spawnRotation);
         for (var i = 0; i < newPart.Modules.Count; i++)
         {
             var node = new ConfigNode();
             node.AddValue("name", newPart.Modules[i].moduleName);
             var j = i;
             newPart.LoadModule(node, ref j);
         }
         return newPart;
     }
     catch (NullReferenceException)
     {
         Debug.Log(LogPrefix + " part unknown");
         return null;
     }
 }
Example #52
0
        public CostReport getBuildCost(ConfigNode craft, string craftText = null)
        {
            lockedParts = false;
            ShipConstruct ship = new ShipConstruct();

            if (!ship.LoadShip(craft))
            {
                lockedParts = true;
                return(null);
            }
            if (ship.vesselDeltaV != null)
            {
                // The delta-v module is not needed. It has its own gameObject
                // for ShipConstruct.
                UnityEngine.Object.Destroy(ship.vesselDeltaV.gameObject);
                ship.vesselDeltaV = null;
            }
            if (!ship.shipPartsUnlocked)
            {
                lockedParts = true;
            }
            GameObject ro          = ship.parts[0].localRoot.gameObject;
            Vessel     craftVessel = ro.AddComponent <Vessel>();

            craftVessel.vesselName = "EL craftVessel - " + craft.GetValue("ship");
            craftVessel.Initialize(true);
            SetCraftOrbit(craftVessel, OrbitDriver.UpdateMode.IDLE);
            foreach (Part part in craftVessel.parts)
            {
                SanitizePart(part);
                part.ModulesOnStart();
            }

            if (ELSettings.B9Wings_Present)
            {
                if (!InitializeB9Wings(craftVessel) &&
                    ELSettings.FAR_Present)
                {
                    InitializeFARSurfaces(craftVessel);
                }
            }
            else if (ELSettings.FAR_Present)
            {
                InitializeFARSurfaces(craftVessel);
            }

            BuildCost resources = new BuildCost();

            foreach (Part p in craftVessel.parts)
            {
                resources.addPart(p);
            }

            if (craftText != null && ELSettings.ShowCraftHull)
            {
                Quickhull.dump_points = ELSettings.DebugCraftHull;
                Quickhull.points_path = savesPath;
                DestroyCraftHull();
                craftHull = new CraftHull(craftText);
                // GetVesselBox will rotate and minimize any launchclamps,
                // which is probably a good thing.
                var rootPart = ship.parts[0].localRoot;
                var rootPos  = rootPart.transform.position;
                craftHull.SetBox(GetVesselBox(ship), rootPos);
                builder.SetShipTransform(rootPart.transform, rootPart);
                craftHull.SetTransform(rootPart.transform);
                if (ELSettings.DebugCraftHull ||
                    !craftHull.LoadHull(savesPath))
                {
                    craftHull.BuildConvexHull(craftVessel);
                    craftHull.SaveHull(savesPath);
                }
            }

            craftVessel.Die();

            return(resources.cost);
        }
 public void onEditorVesselModified(ShipConstruct ship)
 {
     if(lastTopRadiusExtra != topRadiusExtra || lastBottomRadiusExtra != bottomRadiusExtra || lastHeightExtra != heightExtra)
     {
         float h = currentHeight;
         updateModelParameters();
         updateFairingHeight(h);
     }
     updateShieldStatus();
     setPanelOpacity(0.25f);
 }
Example #54
0
        internal void BuildAndLaunchCraft()
        {
            DestroyCraftHull();
            // build craft
            ShipConstruct nship = new ShipConstruct();

            nship.LoadShip(craftConfig);

            ApplyNodeVariants(nship);

            string             landedAt = "";
            string             flag     = flagname;
            Game               game     = FlightDriver.FlightStateCache;
            VesselCrewManifest crew     = new VesselCrewManifest();

            Box vessel_bounds = GetVesselBox(nship);
            var rootPart      = nship.parts[0].localRoot;
            var shipTransform = rootPart.transform;

            builder.SetShipTransform(shipTransform, rootPart);
            builder.PlaceShip(shipTransform, vessel_bounds);

            EnableExtendingLaunchClamps(nship);
            ShipConstruction.AssembleForLaunch(nship, landedAt, landedAt,
                                               flag, game, crew);
            var craftVessel = nship.parts[0].localRoot.GetComponent <Vessel> ();

            craftVessel.launchedFrom = builder.LaunchedFrom;

            FlightGlobals.ForceSetActiveVessel(craftVessel);
            SetCraftOrbit(craftVessel, OrbitDriver.UpdateMode.IDLE);
            builder.PostBuild(craftVessel);
            if (builder.capture)
            {
                craftVessel.Splashed = craftVessel.Landed = false;
            }
            else
            {
                bool loaded = craftVessel.loaded;
                bool packed = craftVessel.packed;
                craftVessel.loaded = true;
                craftVessel.packed = false;
                // The default situation for new vessels is PRELAUNCH, but
                // that is not so good for bases because contracts check for
                // LANDED. XXX should this be selectable?
                craftVessel.situation = Vessel.Situations.LANDED;
                craftVessel.GetHeightFromTerrain();
                Debug.Log($"[ELBuildControl] height from terrain {craftVessel.heightFromTerrain}");
                craftVessel.loaded = loaded;
                craftVessel.packed = packed;
            }

            SetupCraftResources(craftVessel);

            KSP.UI.Screens.StageManager.BeginFlight();

            builtStuff = null;                  // ensure pad mass gets reset
            SetPadMass();
            if (builder.capture)
            {
                var b = builder as PartModule;
                b.StartCoroutine(CaptureCraft(craftVessel));
            }
            else
            {
                CleanupAfterRelease();
            }
        }
Example #55
0
 /// <summary>
 /// Event callback for when vessel is modified in the editor.  Used to know when the gui-fields for this module have been updated.
 /// </summary>
 /// <param name="ship"></param>
 public void onEditorVesselModified(ShipConstruct ship)
 {
     if (!HighLogic.LoadedSceneIsEditor) { return; }
     if (editorPrevTankDiameterAdjust != editorTankDiameterAdjust)
     {
         editorPrevTankDiameterAdjust = editorTankDiameterAdjust;
         float newDiameter = editorTankWholeDiameter + (editorTankDiameterAdjust * tankDiameterIncrement);
         setTankDiameterFromEditor(newDiameter, true);
     }
     else
     {
         updateAttachNodes(true);
     }
 }
Example #56
0
 public void UnloadConstruct()
 {
     construct?.Unload();
     construct = null;
 }
 private void ResetEditorEvent(ShipConstruct construct, CraftBrowser.LoadType type)
 {
     ResetEditor();
 }
 public void onEditorVesselModified(ShipConstruct ship)
 {
     needsUpdate = true;
 }
 private void EditorShipModified(ShipConstruct construct)
 {
     SetupGUI();
     UpdateFields();
 }
Example #60
0
        public BuildListVessel(ShipConstruct s, string ls, double effCost, double bP, string flagURL)
        {
            _ship    = s;
            ShipNode = s.SaveShip();
            // Override KSP sizing of the ship construct
            ShipNode.SetValue("size", KSPUtil.WriteVector(Utilities.GetShipSize(s, true)));
            ShipName  = s.shipName;
            Cost      = Utilities.GetTotalVesselCost(ShipNode, true);
            EmptyCost = Utilities.GetTotalVesselCost(ShipNode, false);
            TotalMass = Utilities.GetShipMass(s, true, out EmptyMass, out _);

            HashSet <int> stages = new HashSet <int>();

            NumStageParts = 0;
            StagePartCost = 0d;

            foreach (Part p in s.Parts)
            {
                if (p.stagingOn)
                {
                    stages.Add(p.inverseStage);
                    ++NumStageParts;
                    StagePartCost += p.GetModuleCosts(p.partInfo.cost, ModifierStagingSituation.CURRENT) + p.partInfo.cost;
                }
            }
            NumStages = stages.Count;

            LaunchSite    = ls;
            EffectiveCost = effCost;
            BuildPoints   = bP;
            Progress      = 0;
            Flag          = flagURL;
            if (s.shipFacility == EditorFacility.VAB)
            {
                Type = ListType.VAB;
            }
            else if (s.shipFacility == EditorFacility.SPH)
            {
                Type = ListType.SPH;
            }
            else
            {
                Type = ListType.None;
            }
            Id = Guid.NewGuid();
            CannotEarnScience = false;

            //get the crew from the editorlogic
            DesiredManifest = new List <string>();
            if (CrewAssignmentDialog.Instance?.GetManifest()?.CrewCount > 0)
            {
                foreach (ProtoCrewMember crew in CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List <ProtoCrewMember>())
                {
                    DesiredManifest.Add(crew?.name ?? string.Empty);
                }
            }

            if (EffectiveCost == default)
            {
                // Can only happen in older saves that didn't have Effective cost persisted as a separate field
                // This code should be safe to remove after a while.
                EffectiveCost = Utilities.GetEffectiveCost(ShipNode.GetNodes("PART").ToList());
            }

            IntegrationPoints = MathParser.ParseIntegrationTimeFormula(this);
            IntegrationCost   = (float)MathParser.ParseIntegrationCostFormula(this);
        }