internal static bool CanKerbalBeAdded(ProtoCrewMember kerbal) { return ((SMSettings.RealismMode && SMAddon.SmVessel.IsRecoverable) || !SMSettings.RealismMode) && kerbal.rosterStatus == ProtoCrewMember.RosterStatus.Available && SMAddon.SmVessel.SelectedPartsSource.Count > 0 && !SMPart.IsCrewFull(SMAddon.SmVessel.SelectedPartsSource[0]); }
public Kerbal(ProtoCrewMember.Gender gender, string name) { Initialize(gender, name); this.gender = gender; this.name = name; }
private bool IsQualifiedByMissionCount(ProtoCrewMember kerbal) { HallOfFameEntry entry = HallOfFame.Instance().GetEntry(kerbal); if (entry == null) return false; if (entry.MissionsFlown < 50) return false; return true; }
public void PromoteIfEligible(ProtoCrewMember kerbal) { if(IsQualifiedByMissionCount(kerbal)) { Promote(kerbal); } }
public LifeSupportStatus FetchKerbal(ProtoCrewMember crew) { if (!IsKerbalTracked(crew.name)) { var k = new LifeSupportStatus(); k.KerbalName = crew.name; k.HomeBodyId = FlightGlobals.GetHomeBodyIndex(); k.LastPlanet = FlightGlobals.GetHomeBodyIndex(); k.LastMeal = Planetarium.GetUniversalTime(); k.LastEC = Planetarium.GetUniversalTime(); k.LastAtHome = Planetarium.GetUniversalTime(); k.LastSOIChange = Planetarium.GetUniversalTime(); k.MaxOffKerbinTime = 648000; //TODO - make this configurable k.TimeEnteredVessel = Planetarium.GetUniversalTime(); k.CurrentVesselId = "?UNKNOWN?"; k.PreviousVesselId = "??UNKNOWN??"; k.LastUpdate = Planetarium.GetUniversalTime(); k.IsGrouchy = false; k.OldTrait = crew.experienceTrait.Title; TrackKerbal(k); } var kerbal = LifeSupportInfo.FirstOrDefault(k => k.KerbalName == crew.name); return kerbal; }
public static EvaAction GetEvaAction(ProtoCrewMember kerbal, Vessel fromVessel) { if (fromVessel != null) { bool atmosphere = fromVessel.IsInAtmosphere(); bool oxygen = fromVessel.IsInAtmosphereWithOxygen(); if (Log.IsLogable(Log.LEVEL.DETAIL)) Log.Detail("creating EVA action for kerbal " + kerbal.name + " in atmosphere:" + atmosphere + ", oxygen:" + oxygen); if (atmosphere && oxygen) { return ActionPool.ACTION_EVA_OXYGEN; } else if (atmosphere && ! oxygen) { return ActionPool.ACTION_EVA_INATM; } else if (!atmosphere) { return ActionPool.ACTION_EVA_NOATM; } else { Log.Warning("unexpected EVA situation"); return ActionPool.ACTION_EVA_NOATM; } } else { Log.Warning("no vessel for kerbal "+kerbal.name+" on EVA"); return ActionPool.ACTION_EVA_NOATM; } }
public void addCrewObject(ProtoCrewMember c) { Notes_CrewObject o = new Notes_CrewObject(c, this); if (!allCrew.ContainsKey(c.name)) allCrew.Add(c.name, o); }
private void OnKerbalStatusChange(ProtoCrewMember pcm, ProtoCrewMember.RosterStatus oldStatus, ProtoCrewMember.RosterStatus newStatus) { if (oldStatus == ProtoCrewMember.RosterStatus.Assigned && newStatus == ProtoCrewMember.RosterStatus.Available) { FlightLog tmpLog = new FlightLog(); foreach (FlightLog.Entry entry in pcm.careerLog.Entries.Union(pcm.flightLog.Entries)) { tmpLog.AddEntry(entry); } float xp = KerbalRoster.CalculateExperience(pcm.careerLog); float xp2 = KerbalRoster.CalculateExperience(tmpLog); float amount = (xp2 - xp) * multiplier; if (currency == Currency.Funds) { Funding.Instance.AddFunds(amount, TransactionReasons.Strategies); } else if (currency == Currency.Reputation) { Reputation.Instance.AddReputation(amount, TransactionReasons.Strategies); } else if (currency == Currency.Science) { ResearchAndDevelopment.Instance.AddScience(amount, TransactionReasons.Strategies); } CurrencyPopup.Instance.AddPopup(currency, amount, TransactionReasons.Strategies, Parent.Config.Title, false); } }
public Kerbal(Kerbal k) { _pcm = k._pcm; name = k.name; gender = k.gender; experienceTrait = k.experienceTrait; kerbalType = k.kerbalType; }
public Kerbal(ProtoCrewMember.Gender gender, string name, string experienceTrait) { Initialize(gender, name); this.gender = gender; this.name = name; this.experienceTrait = experienceTrait; }
// Irradiates a kerbal public void IrradiateKerbal(ProtoCrewMember crew, Vessel crewVessel, double pointAmount) { foreach (KeyValuePair<string,RadioactivityKerbal> kerbal in KerbalDB.Kerbals) { if (crew == kerbal.Value.Kerbal) kerbal.Value.IrradiatePoint(crewVessel, pointAmount); } }
public static int TimeToStranded(ProtoCrewMember Kerb) { Vessel Vsl = GetVessel (Kerb); if (Vsl != null) { return TimeHelper.Days (TimeHelper.ToYears (2) - Vsl.missionTime); } return 0; }
public SpawnPassengers(List<string> passengerNames, int minPassengers, ProtoCrewMember.Gender? gender, ProtoCrewMember.KerbalType kerbalType, string experienceTrait) { this.passengerNames = passengerNames; this.count = passengerNames.Count != 0 ? passengerNames.Count : minPassengers; this.gender = gender; this.kerbalType = kerbalType; this.experienceTrait = experienceTrait; }
public void BeginTask(ProtoCrewMember kerbal, double UT, string task, string body, string situation) { if (!kerbal_experience.ContainsKey (kerbal.name)) { AddKerbal (kerbal); } var exp = kerbal_experience[kerbal.name]; exp.BeginTask (UT, task, body, situation); }
string GetSeat(ProtoCrewMember kerbal) { // Try to find the seat name string seat = ""; if (kerbal.seat != null) { seat = kerbal.seat.seatTransformName; } return seat; }
/* public void OnContractOffered(Contracts.Contract contract) { System.Type type = contract.GetType(); if (contract is FinePrint.Contracts.TourismContract); { } foreach (var p in contract.AllParameters) { Debug.Log(p); } } */ public void ArchiveKerbal(ProtoCrewMember pcm) { Debug.Log("Archiving " + pcm.name); pcm.type = ProtoCrewMember.KerbalType.Crew; KerbalRoster.SetExperienceTrait(pcm); CustomerRecord customer = new CustomerRecord(pcm); customer.status = "ARCHIVED"; CustomerSave.ArchivedCustomers()[pcm.name] = customer; }
public KerbalModel(ProtoCrewMember kerbal, bool isNew) { this.Kerbal = kerbal; Name = kerbal.name; Stupidity = kerbal.stupidity; Courage = kerbal.courage; Badass = kerbal.isBadass; IsNew = isNew; }
public CrewMember(ProtoCrewMember _crew, Part _part, int _index) { crew = _crew; part = _part; index = _index; Stupidity = _crew.stupidity; Courage = _crew.courage; isBadass = _crew.isBadass; Name = _crew.name; }
public ModKerbal(ProtoCrewMember kerbal, bool isNew) { this.Kerbal = kerbal; Name = kerbal.name; Stupidity = kerbal.stupidity; Courage = kerbal.courage; Badass = kerbal.isBadass; Title = kerbal.experienceTrait.Title; Gender = kerbal.gender; IsNew = isNew; }
public void IrradiateKerbal(ProtoCrewMember crew, Vessel crewVessel, double pointAmount, double bodyFraction, double skyFraction, double partFraction) { foreach (KeyValuePair<string,RadioactivityKerbal> kerbal in KerbalDB.Kerbals) { if (crew == kerbal.Value.Kerbal) { kerbal.Value.IrradiatePoint(crewVessel, amount); kerbal.Value.SetAmbientExposure(bodyFraction, skyFraction, partFraction); } } }
public static bool IsStranded(ProtoCrewMember Kerb) { Vessel Vsl = GetVessel (Kerb); if (Vsl != null && KerbalHelper.QualifiedStranded(Kerb) && Vsl.missionTime > TimeHelper.ToYears(2)) { return true; } return false; }
public ModKerbal(ProtoCrewMember kerbal, bool isNew) { Kerbal = kerbal; Name = kerbal.name; Stupidity = kerbal.stupidity; Courage = kerbal.courage; Badass = kerbal.isBadass; Trait = kerbal.trait; Gender = kerbal.gender; IsNew = isNew; }
// callback for new crew member hired private void OnCrewmemberHired(ProtoCrewMember kerbal, int value) { // its better to be safe than sorry if (kerbal == null) return; // Debug.Log("applicant " + kerbal.name+ " will receive the KSP ribbon"); // // now we want to award the KSP ribbon this.adapter.AwardRibbonToKerbal(RIBBON_CODE, kerbal); // an alternative to award the ribbon: //this.adapter.AwardRibbonToKerbal(KspRibbon, kerbal); }
private void OnKerbalTypeChange(ProtoCrewMember pcm, ProtoCrewMember.KerbalType oldType, ProtoCrewMember.KerbalType newType) { if (oldType == ProtoCrewMember.KerbalType.Applicant && newType == ProtoCrewMember.KerbalType.Crew) { // Check for correct trait if (!string.IsNullOrEmpty(trait) && pcm.experienceTrait.Config.Name != trait) { return; } // Check for correct gender if (gender != null && pcm.gender != gender.Value) { return; } CelestialBody homeworld = FlightGlobals.Bodies.Where(cb => cb.isHomeWorld).FirstOrDefault(); Debug.Log("Strategia: Awarding experience to " + pcm.name); // Find existing entries int currentValue = 2; foreach (FlightLog.Entry entry in pcm.careerLog.Entries.Concat(pcm.flightLog.Entries).Where(e => e.type.Contains(SPECIAL_XP))) { // Get the entry with the largest value int entryValue = Convert.ToInt32(entry.type.Substring(SPECIAL_XP.Length, entry.type.Length - SPECIAL_XP.Length)); currentValue = Math.Max(currentValue, entryValue); } // Get the experience level int value = Parent.Level(); string type = SPECIAL_XP + value.ToString(); // Do the awarding pcm.flightLog.AddEntry(type, homeworld.name); pcm.ArchiveFlightLog(); // Force the astronaut complex GUI to refresh so we actually see the experience AstronautComplex ac = UnityEngine.Object.FindObjectOfType<AstronautComplex>(); if (ac != null) { Debug.Log("NewKerbalExperience: CreateAvailableList"); MethodInfo updateListMethod = typeof(AstronautComplex).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance). Where(mi => mi.Name == "CreateAvailableList").First(); updateListMethod.Invoke(ac, new object[] { }); Debug.Log("NewKerbalExperience: AddItem_Available"); MethodInfo addToListMethod = typeof(AstronautComplex).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance). Where(mi => mi.Name == "AddItem_Available").First(); addToListMethod.Invoke(ac, new object[] { pcm }); } } }
/** * Award a ribbon to a kerbal. If a ribbon is awarded twice only the first award counts. * Parameter: * ribbon: ribbon * kerbal: kerbal that will be awarded with a ribbon */ public void AwardRibbonToKerbal(object ribbon, ProtoCrewMember kerbal) { if (IsInstalled() && methodAwardRibbonToKerbalByRibbon != null) { try { methodAwardRibbonToKerbalByRibbon.Invoke(instanceExternalInterface, new object[] { ribbon, kerbal }); } catch (Exception e) { LogFailedMethodAccess("AwardRibbonToKerbal", e); } } }
public static bool IsStranded(ProtoCrewMember Kerb) { Vessel Vsl = GetVessel (Kerb); if (Vsl != null) { if (!VesselHelper.HasLiquidFuel (Vsl)) { if(!VesselHelper.VesselHasModule(Vsl, "ModuleScienceLab")) { if (!VesselHelper.VesselHasModule (Vsl, "ModuleResourceHarvester")) { return true; } } } } return false; }
public LifeSupportStatus FetchKerbal(ProtoCrewMember crew) { if (!IsKerbalTracked(crew.name)) { var k = new LifeSupportStatus(); k.KerbalName = crew.name; k.LastMeal = Planetarium.GetUniversalTime(); k.LastUpdate = Planetarium.GetUniversalTime(); k.IsGrouchy = false; TrackKerbal(k); } var kerbal = LifeSupportInfo.FirstOrDefault(k => k.KerbalName == crew.name); return kerbal; }
public static Vessel GetVessel(ProtoCrewMember Kerb) { Vessel[] Vessels = (Vessel[])FlightGlobals.Vessels.ToArray(); for(int i = 0; i < Vessels.Length; i++) { Vessel Vsl = Vessels [i]; ProtoCrewMember[] Crew = Vsl.GetVesselCrew ().ToArray(); for(int k = 0; k < Crew.Length; k++) { ProtoCrewMember CrewMember = Crew [k]; if (CrewMember.name == Kerb.name) { return Vsl; } } } return null; }
public static string Get(ProtoCrewMember kerbal, string parms) { string system = parms; if (parms.Contains (":")) { int index = parms.IndexOf (":"); system = parms.Substring (0, index); parms = parms.Substring (index + 1); } else { parms = ""; } if (!modules.ContainsKey (system)) { Debug.LogError ("[KS] KerbalExt.Get: no such module: " + system); return null; } return modules[system].Get (kerbal, parms); }
public string SubmitChanges() { if (NameExists()) { return "That name is in use!"; } if (IsNew) { Kerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(); Kerbal.rosterStatus = ProtoCrewMember.RosterStatus.Available; } SyncKerbal(); return string.Empty; }
/// <summary> /// Returns actual chance per day of this outcome considering all modifiers /// </summary> /// <param name="pcm"></param> /// <returns></returns> public double GetChancePerDay(ProtoCrewMember pcm) => ChanceModifier.Calculate(ChanceModifiers, ChancePerDay, pcm);
private void OnContractAccepted(Contract contract) { DarkLog.Debug("Contract accepted, state: " + contract.ContractState); ConfigNode contractNode = new ConfigNode(); contract.Save(contractNode); if (contractNode.GetValue("type") == "RecoverAsset") { string kerbalName = contractNode.GetValue("kerbalName").Trim(); uint partID = uint.Parse(contractNode.GetValue("partID")); if (!string.IsNullOrEmpty(kerbalName)) { ProtoCrewMember rescueKerbal = null; if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName)) { DarkLog.Debug("Generating missing kerbal " + kerbalName + " for rescue contract"); int kerbalGender = int.Parse(contractNode.GetValue("gender")); rescueKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned); rescueKerbal.ChangeName(kerbalName); rescueKerbal.gender = (ProtoCrewMember.Gender)kerbalGender; rescueKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned; } else { rescueKerbal = HighLogic.CurrentGame.CrewRoster[kerbalName]; DarkLog.Debug("Kerbal " + kerbalName + " already exists, skipping respawn"); } if (rescueKerbal != null) { vesselWorker.SendKerbalIfDifferent(rescueKerbal); } } if (partID != 0) { Vessel contractVessel = FinePrint.Utilities.VesselUtilities.FindVesselWithPartIDs(new List <uint> { partID }); if (contractVessel != null) { vesselWorker.SendVesselUpdateIfNeeded(contractVessel); } } } else if (contractNode.GetValue("type") == "TourismContract") { string tourists = contractNode.GetValue("tourists"); if (tourists != null) { string[] touristsNames = tourists.Split(new char[] { '|' }); foreach (string touristName in touristsNames) { ProtoCrewMember pcm = null; if (!HighLogic.CurrentGame.CrewRoster.Exists(touristName)) { DarkLog.Debug("Spawning missing tourist " + touristName + " for tourism contract"); pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist); pcm.rosterStatus = ProtoCrewMember.RosterStatus.Available; pcm.ChangeName(touristName); } else { DarkLog.Debug("Skipped respawn of existing tourist " + touristName); pcm = HighLogic.CurrentGame.CrewRoster[touristName]; } if (pcm != null) { vesselWorker.SendKerbalIfDifferent(pcm); } } } } }
private void ApplyEVAEffect(LifeSupportStatus kStat, ProtoCrewMember crew, Vessel v, int effectId) { /* * SIDE EFFECTS: * * 0 = No Effect (The feature is effectively turned off * 1 = Grouchy (they become a Tourist until rescued) * 2 = Mutinous (A tourist, but destroys a part of a nearby vessel...) * 3 = Instantly 'wander' back to the KSC - don't ask us how! * 4 = M.I.A. (will eventually respawn) * 5 = K.I.A. * */ var msg = ""; switch (effectId) { case 1: //Grouchy if (crew.type != ProtoCrewMember.KerbalType.Tourist) { msg = string.Format("{0} refuses to work", crew.name); kStat.OldTrait = crew.experienceTrait.Title; crew.type = ProtoCrewMember.KerbalType.Tourist; KerbalRoster.SetExperienceTrait(crew, "Tourist"); kStat.IsGrouchy = true; LifeSupportManager.Instance.TrackKerbal(kStat); } break; case 2: //Mutinous { msg = string.Format("{0} has become mutinous", crew.name); kStat.OldTrait = crew.experienceTrait.Title; crew.type = ProtoCrewMember.KerbalType.Tourist; KerbalRoster.SetExperienceTrait(crew, "Tourist"); kStat.IsGrouchy = true; LifeSupportManager.Instance.TrackKerbal(kStat); DestroyRandomPart(v); } break; case 3: //Return to KSC msg = string.Format("{0} gets fed up and wanders back to the KSC", crew.name); LifeSupportManager.Instance.UntrackKerbal(crew.name); crew.rosterStatus = ProtoCrewMember.RosterStatus.Available; DestroyVessel(v); break; case 4: //Despawn msg = string.Format("{0} has gone missing", crew.name); LifeSupportManager.Instance.UntrackKerbal(crew.name); crew.rosterStatus = ProtoCrewMember.RosterStatus.Missing; DestroyVessel(v); break; case 5: //Kill msg = string.Format("{0} has died", crew.name); LifeSupportManager.Instance.UntrackKerbal(crew.name); crew.rosterStatus = ProtoCrewMember.RosterStatus.Dead; DestroyVessel(v); break; } ScreenMessages.PostScreenMessage(msg, 5f, ScreenMessageStyle.UPPER_CENTER); }
protected bool CreateVessels() { if (vesselsCreated) { return(false); } String gameDataDir = KSPUtil.ApplicationRootPath; gameDataDir = gameDataDir.Replace("\\", "/"); if (!gameDataDir.EndsWith("/")) { gameDataDir += "/"; } gameDataDir += "GameData"; // Spawn the vessel in the game world foreach (VesselData vesselData in vessels) { LoggingUtil.LogVerbose(this, "Spawning a vessel named '" + vesselData.name + "'"); // Set additional info for landed vessels bool landed = false; if (!vesselData.orbiting) { landed = true; if (vesselData.altitude == null) { vesselData.altitude = LocationUtil.TerrainHeight(vesselData.latitude, vesselData.longitude, vesselData.body); } Vector3d pos = vesselData.body.GetWorldSurfacePosition(vesselData.latitude, vesselData.longitude, vesselData.altitude.Value); vesselData.orbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, vesselData.body); vesselData.orbit.UpdateFromStateVectors(pos, vesselData.body.getRFrmVel(pos), vesselData.body, Planetarium.GetUniversalTime()); } else { vesselData.orbit.referenceBody = vesselData.body; } ConfigNode[] partNodes; UntrackedObjectClass sizeClass; ShipConstruct shipConstruct = null; if (!string.IsNullOrEmpty(vesselData.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(gameDataDir + "/" + vesselData.craftURL); if (shipConstruct == null) { LoggingUtil.LogError(this, "ShipConstruct was null when tried to load '" + vesselData.craftURL + "' (usually this means the file could not be found)."); continue; } // Restore ShipConstruction ship ShipConstruction.ShipConfig = currentShip; // Set the name if (string.IsNullOrEmpty(vesselData.name)) { vesselData.name = shipConstruct.shipName; } // 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 = vesselData.flagURL ?? HighLogic.CurrentGame.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; } // Estimate an object class, numbers are based on the in game description of the // size classes. float size = shipConstruct.shipSize.magnitude / 2.0f; if (size < 4.0f) { sizeClass = UntrackedObjectClass.A; } else if (size < 7.0f) { sizeClass = UntrackedObjectClass.B; } else if (size < 12.0f) { sizeClass = UntrackedObjectClass.C; } else if (size < 18.0f) { sizeClass = UntrackedObjectClass.D; } else { sizeClass = UntrackedObjectClass.E; } foreach (CrewData cd in vesselData.crew) { bool success = false; // Find a seat for the crew Part part = shipConstruct.parts.Find(p => p.protoModuleCrew.Count < p.CrewCapacity); // Add the crew member if (part != null) { // Create the ProtoCrewMember ProtoCrewMember crewMember = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned); if (cd.gender != null) { crewMember.gender = cd.gender.Value; } if (cd.name != null) { crewMember.ChangeName(cd.name); } // Add them to the part success = part.AddCrewmemberAt(crewMember, part.protoModuleCrew.Count); } if (!success) { LoggingUtil.LogWarning(this, "Unable to add crew to vessel named '" + vesselData.name + "'. Perhaps there's no room?"); break; } } // 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. ConfigNode empty = new ConfigNode(); ProtoVessel dummyProto = new ProtoVessel(empty, null); Vessel dummyVessel = new GameObject().AddComponent <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 partNodes = dummyProto.protoPartSnapshots.Select <ProtoPartSnapshot, ConfigNode>(GetNodeForPart).ToArray(); // Clean up GameObject.Destroy(dummyVessel.gameObject); } else { // Create crew member array ProtoCrewMember[] crewArray = new ProtoCrewMember[vesselData.crew.Count]; int i = 0; foreach (CrewData cd in vesselData.crew) { // Create the ProtoCrewMember ProtoCrewMember crewMember = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned); if (cd.name != null) { crewMember.ChangeName(cd.name); } crewArray[i++] = crewMember; } // Create part nodes uint flightId = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); partNodes = new ConfigNode[1]; partNodes[0] = ProtoVessel.CreatePartNode(vesselData.craftPart.name, flightId, crewArray); // Default the size class sizeClass = UntrackedObjectClass.A; // Set the name if (string.IsNullOrEmpty(vesselData.name)) { vesselData.name = vesselData.craftPart.name; } } // Create additional nodes ConfigNode[] additionalNodes = new ConfigNode[1]; DiscoveryLevels discoveryLevel = vesselData.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(vesselData.name, vesselData.vesselType, vesselData.orbit, 0, partNodes, additionalNodes); // Additional seetings for a landed vessel if (!vesselData.orbiting) { Vector3d norm = vesselData.body.GetRelSurfaceNVector(vesselData.latitude, vesselData.longitude); double terrainHeight = 0.0; if (vesselData.body.pqsController != null) { terrainHeight = vesselData.body.pqsController.GetSurfaceHeight(norm) - vesselData.body.pqsController.radius; } bool splashed = landed && terrainHeight < 0.001; // Create the config node representation of the ProtoVessel // Note - flying is experimental, and so far doesn't work 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", vesselData.latitude.ToString()); protoVesselNode.SetValue("lon", vesselData.longitude.ToString()); protoVesselNode.SetValue("alt", vesselData.altitude.ToString()); protoVesselNode.SetValue("landedAt", vesselData.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 vesselData.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(new Vector3((float)norm.x, (float)norm.y, (float)norm.z)); Quaternion rotation = Quaternion.identity; float heading = vesselData.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 = rotation * Quaternion.AngleAxis(vesselData.pitch, Vector3.right); rotation = rotation * Quaternion.AngleAxis(vesselData.roll, Vector3.down); rotation = rotation * Quaternion.AngleAxis(heading, Vector3.forward); // Set the height and rotation if (landed || splashed) { float hgt = (shipConstruct != null ? shipConstruct.parts[0] : vesselData.craftPart.partPrefab).localRoot.attPos0.y - lowest; hgt += vesselData.height; protoVesselNode.SetValue("hgt", hgt.ToString()); } protoVesselNode.SetValue("rot", KSPUtil.WriteQuaternion(rotation * normal)); // Set the normal vector relative to the surface Vector3 nrm = (rotation * Vector3.forward); protoVesselNode.SetValue("nrm", nrm.x + "," + nrm.y + "," + nrm.z); protoVesselNode.SetValue("prst", false.ToString()); } // Add vessel to the game ProtoVessel protoVessel = new ProtoVessel(protoVesselNode, HighLogic.CurrentGame); protoVessel.Load(HighLogic.CurrentGame.flightState); // Store the id for later use vesselData.id = protoVessel.vesselRef.id; // Associate it so that it can be used in contract parameters ContractVesselTracker.Instance.AssociateVessel(vesselData.name, protoVessel.vesselRef); } vesselsCreated = true; return(true); }
public CrewMemberAssignment(ProtoCrewMember pcm) { PCM = pcm; }
private void SpawnVessel(HoloCacheData HoloCacheData, List <ProtoCrewMember> crewData = null) { // string gameDataDir = KSPUtil.ApplicationRootPath; Debug.Log("[Spawn OrX HoloCache] Spawning " + HoloCacheData.name); // Set additional info for landed vessels bool landed = false; if (!landed) { landed = true; if (HoloCacheData.altitude == null || HoloCacheData.altitude < 0) { HoloCacheData.altitude = 5;//LocationUtil.TerrainHeight(HoloCacheData.latitude, HoloCacheData.longitude, HoloCacheData.body); } Debug.Log("[Spawn OrX HoloCache] SpawnVessel Altitude: " + HoloCacheData.altitude); //Vector3d pos = HoloCacheData.body.GetWorldSurfacePosition(HoloCacheData.latitude, HoloCacheData.longitude, HoloCacheData.altitude.Value); Vector3d pos = HoloCacheData.body.GetRelSurfacePosition(HoloCacheData.latitude, HoloCacheData.longitude, HoloCacheData.altitude.Value); HoloCacheData.orbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, HoloCacheData.body); HoloCacheData.orbit.UpdateFromStateVectors(pos, HoloCacheData.body.getRFrmVel(pos), HoloCacheData.body, Planetarium.GetUniversalTime()); } ConfigNode[] partNodes; ShipConstruct shipConstruct = null; bool hasClamp = false; float lcHeight = 0; ConfigNode craftNode; Quaternion craftRotation = Quaternion.identity; if (!string.IsNullOrEmpty(HoloCacheData.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(HoloCacheData.craftURL); if (shipConstruct == null) { Debug.Log("[Spawn OrX HoloCache] ShipConstruct was null when tried to load '" + HoloCacheData.craftURL + "' (usually this means the file could not be found)."); return;//continue; } craftNode = ConfigNode.Load(HoloCacheData.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(HoloCacheData.name)) { HoloCacheData.name = craftFile; } // 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[HoloCacheData.crew.Count]; /* * int i = 0; * foreach (CrewData cd in HoloCacheData.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(HoloCacheData.craftPart.name, flightId, crewArray); // Default the size class //sizeClass = UntrackedObjectClass.A; // Set the name if (string.IsNullOrEmpty(HoloCacheData.name)) { HoloCacheData.name = HoloCacheData.craftPart.name; } } // Create additional nodes ConfigNode[] additionalNodes = new ConfigNode[0]; //DiscoveryLevels discoveryLevel = HoloCacheData.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(HoloCacheData.name, HoloCacheData.vesselType, HoloCacheData.orbit, 0, partNodes, additionalNodes); // Additional seetings for a landed vessel if (!HoloCacheData.orbiting) { Vector3d norm = HoloCacheData.body.GetRelSurfaceNVector(HoloCacheData.latitude, HoloCacheData.longitude); double terrainHeight = 0.0; if (HoloCacheData.body.pqsController != null) { terrainHeight = HoloCacheData.body.pqsController.GetSurfaceHeight(norm) - HoloCacheData.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", HoloCacheData.latitude.ToString()); protoVesselNode.SetValue("lon", HoloCacheData.longitude.ToString()); protoVesselNode.SetValue("alt", HoloCacheData.altitude.ToString()); protoVesselNode.SetValue("landedAt", HoloCacheData.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 HoloCacheData.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 = HoloCacheData.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; HoloCacheData.heading = 0; HoloCacheData.pitch = 0; } rotation = rotation * Quaternion.AngleAxis(heading, Vector3.back); rotation = rotation * Quaternion.AngleAxis(HoloCacheData.roll, Vector3.down); rotation = rotation * Quaternion.AngleAxis(HoloCacheData.pitch, Vector3.left); // Set the height and rotation if (landed || splashed) { float hgt = (shipConstruct != null ? shipConstruct.parts[0] : HoloCacheData.craftPart.partPrefab).localRoot.attPos0.y - lowest; hgt += HoloCacheData.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 HoloCacheData.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(HoloCacheData.name, protoVessel.vesselRef); //destroy prefabs foreach (Part p in FindObjectsOfType <Part>()) { if (!p.vessel) { Destroy(p.gameObject); } } }
// Adds to given kerbal as a crew-member to the (unloaded) vessel: public static void AddCrewMember(Vessel vessel, string kerbonautName) { // We can only manipulate the crew of an unloaded ship: if (vessel.loaded) { throw new Exception("TargetVessel.AddCrewMember can only be called on unloaded vessels"); } try { // Find the requested Kerbal on the crew-roster: ProtoCrewMember kerbonaut = null; foreach (ProtoCrewMember rosterKerbonaut in HighLogic.CurrentGame.CrewRoster.Kerbals(ProtoCrewMember.KerbalType.Crew, ProtoCrewMember.RosterStatus.Available)) { if (rosterKerbonaut.name == kerbonautName) { kerbonaut = rosterKerbonaut; break; } } if (kerbonaut == null) { // The player must have removed the kerbal from the pool of available kerbonauts: Debug.Log("[KSTS] unable to complete crew-transfer to " + vessel.vesselName + ", kerbonaut " + kerbonautName + " unavailable or missiong"); ScreenMessages.PostScreenMessage("Crew-Transfer aborted: Kerbonaut " + kerbonautName + " unavailable for transfer to " + vessel.vesselName); return; } // Find an available seat on the target-vessel: ProtoPartSnapshot targetPart = null; foreach (ProtoPartSnapshot protoPart in vessel.protoVessel.protoPartSnapshots) { if (!KSTS.partDictionary.ContainsKey(protoPart.partName)) { continue; } int crewCapacity = KSTS.partDictionary[protoPart.partName].partPrefab.CrewCapacity; if (crewCapacity <= 0) { continue; } if (protoPart.protoCrewNames.Count >= crewCapacity) { continue; } targetPart = protoPart; break; } if (targetPart == null) { // Maybe there was a different transport-mission to the same target-vessel: Debug.Log("[KSTS] unable to complete crew-transfer to " + vessel.vesselName + ", no free seats"); ScreenMessages.PostScreenMessage("Crew-Transfer aborted: Vessel " + vessel.vesselName + " had no free seat for Kerbonaut " + kerbonautName); return; } // Add the kerbonaut to the selected part, using the next available seat: int seatIdx = 0; foreach (ProtoCrewMember crewMember in targetPart.protoModuleCrew) { if (seatIdx == crewMember.seatIdx) { seatIdx++; } } targetPart.protoModuleCrew.Add(kerbonaut); targetPart.protoCrewNames.Add(kerbonautName); // Remove kerbonaut from crew-roster: kerbonaut.rosterStatus = ProtoCrewMember.RosterStatus.Assigned; kerbonaut.seatIdx = seatIdx; // Add the phases the kerbonaut would have gone through during his launch to his flight-log: kerbonaut.flightLog.AddEntry(FlightLog.EntryType.Launch, Planetarium.fetch.Home.bodyName); kerbonaut.flightLog.AddEntry(FlightLog.EntryType.Flight, Planetarium.fetch.Home.bodyName); kerbonaut.flightLog.AddEntry(FlightLog.EntryType.Suborbit, Planetarium.fetch.Home.bodyName); kerbonaut.flightLog.AddEntry(FlightLog.EntryType.Orbit, Planetarium.fetch.Home.bodyName); Debug.Log("[KSTS] added kerbonaut " + kerbonautName + " to vessel " + vessel.vesselName); ScreenMessages.PostScreenMessage("Kerbonaut " + kerbonautName + " transfered to " + vessel.vesselName); } catch (Exception e) { Debug.LogError("[KSTS] TargetVessel.AddCrewMember(" + vessel.vesselName + "," + kerbonautName + "): " + e.ToString()); } }
public KerbalPair(ProtoCrewMember pcm, KerbalExt ext) { this.pcm = pcm; this.ext = ext; }
void onKerbalRemoved(ProtoCrewMember pcm) { kerbals.Remove(pcm.name); }
public static void RemoveKerbal(ProtoCrewMember pcm) { LoggingUtil.LogVerbose(typeof(Kerbal), "Removing kerbal " + pcm.name + "..."); Vessel vessel = FlightGlobals.Vessels.Where(v => v.GetVesselCrew().Contains(pcm)).FirstOrDefault(); if (vessel != null) { // If it's an EVA make them disappear... if (vessel.isEVA) { FlightGlobals.Vessels.Remove(vessel); } else { if (vessel.loaded) { foreach (Part p in vessel.parts) { if (p.protoModuleCrew.Contains(pcm)) { // Command seats if (p.partName == "kerbalEVA") { vessel.parts.Remove(p); } // Everything else else { LoggingUtil.LogVerbose(typeof(Kerbal), " Removing " + pcm.name + " from vessel " + vessel.vesselName); p.RemoveCrewmember(pcm); } break; } } } else { foreach (ProtoPartSnapshot pps in vessel.protoVessel.protoPartSnapshots) { if (pps.HasCrew(pcm.name)) { // Command seats if (pps.partName == "kerbalEVA") { vessel.protoVessel.protoPartSnapshots.Remove(pps); } // Everything else else { LoggingUtil.LogVerbose(typeof(Kerbal), " Removing " + pcm.name + " from vessel " + vessel.vesselName); pps.RemoveCrew(pcm); } break; } } } } } // Remove the kerbal from the roster HighLogic.CurrentGame.CrewRoster.Remove(pcm.name); HighLogic.CurrentGame.CrewRoster.RemoveMIA(pcm); }
public override bool IsValid(ProtoCrewMember astronaut) { if (!base.IsValid(astronaut)) { return(false); } if (string.IsNullOrEmpty(keyValueName)) { return(false); } AstronautData astronautData = SnacksScenario.Instance.GetAstronautData(astronaut); if (astronautData == null) { return(false); } if (!astronautData.keyValuePairs.ContainsKey(keyValueName)) { return(false); } int value = 0; bool valueParsed = int.TryParse(astronautData.keyValuePairs[keyValueName], out value); switch (checkType) { case CheckValueConditionals.checkEquals: if (!string.IsNullOrEmpty(stringValue)) { return(astronautData.keyValuePairs[keyValueName] == stringValue); } else if (valueParsed) { return(value == intValue); } else { return(false); } case CheckValueConditionals.checkNotEqual: if (!string.IsNullOrEmpty(stringValue)) { return(astronautData.keyValuePairs[keyValueName] != stringValue); } else if (valueParsed) { return(value != intValue); } else { return(false); } case CheckValueConditionals.checkGreaterOrEqual: if (valueParsed) { return(value >= intValue); } else { return(false); } case CheckValueConditionals.checkGreaterThan: if (valueParsed) { return(value > intValue); } else { return(false); } case CheckValueConditionals.checkLesserOrEqual: if (valueParsed) { return(value <= intValue); } else { return(false); } case CheckValueConditionals.checkLessThan: if (valueParsed) { return(value < intValue); } else { return(false); } } return(false); }
protected override bool Generate() { int contractCount = WBIContractScenario.Instance.GetContractCount(ContractType); Log("Trying to generate a WBIColonistContract, count: " + contractCount + "/" + WBIContractScenario.maxContracts); if (contractCount == WBIContractScenario.maxContracts) { return(false); } //Find destination candidates if (destinationCandidates.Count == 0) { getDestinationCandidates(); } if (destinationCandidates.Count == 0) { return(false); } //Determine which candidate to use int candidateID = UnityEngine.Random.Range(0, destinationCandidates.Count); Vessel targetVessel = destinationCandidates[candidateID]; vesselName = targetVessel.vesselName; targetBody = targetVessel.mainBody; Log("Target vessel: " + vesselName); Log("Target body: " + targetBody); bool isOrbiting = false; if (targetVessel.situation == Vessel.Situations.ORBITING) { isOrbiting = true; } //Generate number of tourists totalTourists = UnityEngine.Random.Range(1, MaxTourists) * ((int)prestige + 1); Log("totalTourists: " + totalTourists); //Generate total days totalDays = UnityEngine.Random.Range(minimumDays, maximumDays) * ((int)prestige + 1); Log("totalDays: " + totalDays); //Calculate completion funds float deliveryFunds; float stayFunds; float totalFunds; if (!isOrbiting) { deliveryFunds = fundsFerryComplete * targetBody.scienceValues.LandedDataValue; stayFunds = fundsStayComplete * (float)totalDays * targetBody.scienceValues.LandedDataValue; totalFunds = fundsCompleteBase * targetBody.scienceValues.LandedDataValue; } else { deliveryFunds = fundsFerryComplete * targetBody.scienceValues.InSpaceLowDataValue; stayFunds = fundsStayComplete * (float)totalDays * targetBody.scienceValues.InSpaceLowDataValue; totalFunds = fundsCompleteBase * targetBody.scienceValues.InSpaceLowDataValue; } stayFunds *= ((float)prestige + 1.0f); totalFunds *= ((float)prestige + 1.0f); //Be in command of <targetVessel> parameter SpecificVesselParameter specificVesselParam = new SpecificVesselParameter(targetVessel); this.AddParameter(specificVesselParam, null); //Generate kerbals WBIFerryKerbalParam ferryParameter; WBIKerbalStayParam stayParameter; KerbalRoster roster = HighLogic.CurrentGame.CrewRoster; kerbalNames.Clear(); for (int index = 0; index < totalTourists; index++) { tourist = createTourist(); //Stay at vessel parameter stayParameter = new WBIKerbalStayParam(vesselName, tourist.name, totalDays); this.AddParameter(stayParameter, null); //Do this before setting other things in the parameter stayParameter.SetFunds(stayFunds, targetBody); //Ferry to vessel parameter ferryParameter = new WBIFerryKerbalParam(vesselName, tourist.name); stayParameter.AddParameter(ferryParameter, null); ferryParameter.SetFunds(deliveryFunds, targetBody); //Record funds totalFunds += stayFunds + deliveryFunds; //Clean up the roster- we only generate tourists when the contract is accepted. kerbalNames.Add(tourist.name); roster.Remove(tourist.name); } //Set rewards base.SetExpiry(); base.SetDeadlineYears(10f, targetBody); base.SetReputation(repComplete, repFailure, targetBody); base.SetFunds(fundsAdvance, totalFunds, totalFunds * 0.25f, targetBody); //Record contract contractCount += 1; if (contractCount > WBIContractScenario.maxContracts) { contractCount = WBIContractScenario.maxContracts; } WBIContractScenario.Instance.SetContractCount(ContractType, contractCount); //Done if (string.IsNullOrEmpty(contractID)) { contractID = Guid.NewGuid().ToString(); } return(true); }
public override bool IsValid(ProtoCrewMember astronaut, Vessel vessel) { return(IsValid(astronaut)); }
/// <summary> /// Applies all modifiers in the list to baseValue chance for pcm and returns resulting chance /// </summary> /// <param name="modifiers"></param> /// <param name="baseValue"></param> /// <param name="pcm"></param> /// <returns></returns> public static double Calculate(List <ChanceModifier> modifiers, double baseValue, ProtoCrewMember pcm) { double v = baseValue; foreach (ChanceModifier m in modifiers) { v = m.Calculate(v, pcm); } Core.Log($"Base chance: {baseValue:P1}; modified chance: {v:P1}."); return(v); }
public Kerbal(ProtoCrewMember pcm) { this.pcm = pcm; }
internal static void RemoveCrewMember(ProtoCrewMember pKerbal, Part part) { part.RemoveCrewmember(pKerbal); pKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Available; FireEventTriggers(part.vessel); }
// Load informations void LoadFor(ProtoCrewMember kerbal) { Debug.Log("CustomDescription.LoadFor", "kerbal = " + kerbal); Info.hash = ""; string collection = ""; displayName = ""; tooltipName = ""; informations = ""; sprite = null; int index = 0; int?indexChance = null; for (int i = 0; i < DescriptionInfo.DataBase?.Count; i++) { DescriptionInfo info = (DescriptionInfo)DescriptionInfo.DataBase[i].GetFor(kerbal); if (info != null) { Debug.Log("CustomDescription.LoadFor", "Matching description index = " + info.index + " to current index = " + index); if (info.index == null || info.index == index) { Debug.Log("CustomDescription.LoadFor", "Matching description collection = " + info.collection + " to current collection = " + collection); if (string.IsNullOrEmpty(collection) || collection == info.collection) { if (info.useChance != 1 && indexChance == null) { indexChance = kerbal.Hash(info.useGameSeed) % 100; } Debug.Log("CustomDescription.LoadFor", "Matching description useChance = " + info.useChance + " to current index chance = " + indexChance + " %"); if (info.useChance == 1 || indexChance < info.useChance * 100) { Debug.Log("CustomDescription.LoadFor", "Matched all requirements."); // Collection collection = info.collection; Debug.Log("CustomDescription.LoadFor", "Current collection = " + collection); // Unique if (info.unique) { displayName = tooltipName = informations = ""; sprite = null; } // displayName if (string.IsNullOrEmpty(displayName)) { displayName = info.displayName; } // tooltipName if (string.IsNullOrEmpty(tooltipName)) { tooltipName = info.tooltipName; } // sprite sprite = sprite ?? info.sprite; // informations if (info.informations?.Length > 0) { Debug.Log("CustomDescription.LoadFor", "Adding text to informations field, index = " + index); if (info.informations.Length == 1) { informations += info.informations[0]; } else { informations += info.informations[kerbal.Hash(info.useGameSeed) % info.informations.Length]; } Debug.Log("CustomDescription.LoadFor", "Updated informations field = " + informations); } if (info.unique || info.last) { break; } index++; indexChance = null; Debug.Log("CustomDescription.LoadFor", "Index bumped to = " + index); } } } } } }
public HallOfFameEntry GetEntry(ProtoCrewMember kerbal) { return(GetEntry(kerbal.name)); }
public bool MeetsStudentReqs(ProtoCrewMember student) { if (!((student.type == (ProtoCrewMember.KerbalType.Crew) && (seatMax <= 0 || Students.Count < seatMax) && !student.inactive && student.rosterStatus == ProtoCrewMember.RosterStatus.Available && student.experienceLevel >= minLevel && student.experienceLevel <= maxLevel && (classes.Length == 0 || classes.Contains(student.trait)) && !Students.Contains(student)))) { return(false); } int pCount = preReqs.GetLength(0); int pACount = preReqsAny.GetLength(0); int cCount = conflicts.GetLength(0); if (pCount > 0 || cCount > 0 || pACount > 0) { for (int i = pCount; i-- > 0;) { pChecker[i] = true; } int needCount = pCount; bool needAnyStill = pACount > 0; for (int entryIdx = student.careerLog.Count; entryIdx-- > 0 && (needCount > 0 || cCount > 0 || needAnyStill);) { FlightLog.Entry e = student.careerLog.Entries[entryIdx]; string tgt = string.IsNullOrEmpty(e.target) ? string.Empty : e.target; for (int preIdx = pCount; preIdx-- > 0 && needCount > 0;) { if (pChecker[preIdx] && (e.type == preReqs[preIdx, 0] && tgt == preReqs[preIdx, 1])) { pChecker[preIdx] = false; --needCount; } } for (int anyIdx = pACount; anyIdx-- > 0 && needAnyStill;) { if (e.type == preReqsAny[anyIdx, 0] && tgt == preReqsAny[anyIdx, 1]) { needAnyStill = false; } } for (int conIdx = cCount; conIdx-- > 0;) { if (e.type == conflicts[conIdx, 0] && tgt == conflicts[conIdx, 1]) { return(false); } } } if (needCount > 0 || needAnyStill) { return(false); } } return(true); }
public override void ApplyOutcome(Vessel vessel, SnacksProcessorResult result) { ProtoCrewMember[] astronauts; AstronautData astronautData; //Get affected astronauts if (result.afftectedAstronauts != null) { astronauts = result.afftectedAstronauts.ToArray(); } else if (vessel.loaded) { astronauts = vessel.GetVesselCrew().ToArray(); } else { astronauts = vessel.protoVessel.GetVesselCrew().ToArray(); } //Get valid astronauts List <ProtoCrewMember> validAstronauts = new List <ProtoCrewMember>(); for (int index = 0; index < astronauts.Length; index++) { if (astronauts[index].type == ProtoCrewMember.KerbalType.Unowned) { continue; } validAstronauts.Add(astronauts[index]); } if (validAstronauts.Count == 0) { return; } else { astronauts = validAstronauts.ToArray(); } //Select random crew if needed if (selectRandomCrew) { int randomIndex = UnityEngine.Random.Range(0, astronauts.Length - 1); astronauts = new ProtoCrewMember[] { astronauts[randomIndex] }; } for (int index = 0; index < astronauts.Length; index++) { if (astronauts[index].type == ProtoCrewMember.KerbalType.Unowned) { continue; } astronautData = SnacksScenario.Instance.GetAstronautData(astronauts[index]); if (astronautData == null) { continue; } astronautData.SetCondition(conditionName); SnacksScenario.Instance.SetAstronautData(astronautData); SnacksScenario.Instance.RemoveSkillsIfNeeded(astronauts[index]); } //Inform player if (!string.IsNullOrEmpty(playerMessage)) { string message = playerMessage; ScreenMessages.PostScreenMessage(message, 5, ScreenMessageStyle.UPPER_LEFT); } //Call the base class base.ApplyOutcome(vessel, result); }
void OnCrewFired(ProtoCrewMember kerbal, int n) { Debug.Log("CustomDescription.OnCrewFired"); UpdateItem(kerbal, Type.Applicant); }
/// <summary> /// Determines whether the specified crew member is assigned to anything in the list. /// </summary> /// <param name="crewMember"></param> /// <returns></returns> public bool IsAssigned(ProtoCrewMember crewMember) { return(Crewable.IsAssigned(allCrewables, crewMember)); }
/// <summary> /// Handles the situation where the kerbal went on EVA. /// </summary> /// <param name="astronaut">The kerbal that went on EVA.</param> /// <param name="part">The part that the kerbal left.</param> public virtual void onKerbalEVA(ProtoCrewMember astronaut, Part part) { }
public void DodgeKerbals(ConfigNode inputNode, Guid protovesselID) { List <string> takenKerbals = new List <string>(); foreach (ConfigNode partNode in inputNode.GetNodes("PART")) { int crewIndex = 0; foreach (string currentKerbalName in partNode.GetValues("crew")) { if (kerbalToVessel.ContainsKey(currentKerbalName) ? kerbalToVessel[currentKerbalName] != protovesselID : false) { ProtoCrewMember newKerbal = null; ProtoCrewMember.Gender newKerbalGender = GetKerbalGender(currentKerbalName); string newExperienceTrait = null; if (HighLogic.CurrentGame.CrewRoster.Exists(currentKerbalName)) { ProtoCrewMember oldKerbal = HighLogic.CurrentGame.CrewRoster[currentKerbalName]; newKerbalGender = oldKerbal.gender; newExperienceTrait = oldKerbal.experienceTrait.TypeName; } foreach (ProtoCrewMember possibleKerbal in HighLogic.CurrentGame.CrewRoster.Crew) { bool kerbalOk = true; if (kerbalOk && kerbalToVessel.ContainsKey(possibleKerbal.name) && (takenKerbals.Contains(possibleKerbal.name) || kerbalToVessel[possibleKerbal.name] != protovesselID)) { kerbalOk = false; } if (kerbalOk && possibleKerbal.gender != newKerbalGender) { kerbalOk = false; } if (kerbalOk && newExperienceTrait != null && possibleKerbal.experienceTrait != null && newExperienceTrait != possibleKerbal.experienceTrait.TypeName) { kerbalOk = false; } if (kerbalOk) { newKerbal = possibleKerbal; break; } } int kerbalTries = 0; while (newKerbal == null) { bool kerbalOk = true; ProtoCrewMember.KerbalType kerbalType = ProtoCrewMember.KerbalType.Crew; if (newExperienceTrait == "Tourist") { kerbalType = ProtoCrewMember.KerbalType.Tourist; } if (newExperienceTrait == "Unowned") { kerbalType = ProtoCrewMember.KerbalType.Unowned; } ProtoCrewMember possibleKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(kerbalType); if (kerbalTries < 200 && possibleKerbal.gender != newKerbalGender) { kerbalOk = false; } if (kerbalTries < 100 && newExperienceTrait != null && newExperienceTrait != possibleKerbal.experienceTrait.TypeName) { kerbalOk = false; } if (kerbalOk) { newKerbal = possibleKerbal; } kerbalTries++; } DarkLog.Debug("Generated dodged kerbal with " + kerbalTries + " tries"); partNode.SetValue("crew", newKerbal.name, crewIndex); newKerbal.seatIdx = crewIndex; newKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned; takenKerbals.Add(newKerbal.name); } else { takenKerbals.Add(currentKerbalName); CreateKerbalIfMissing(currentKerbalName, protovesselID); HighLogic.CurrentGame.CrewRoster[currentKerbalName].rosterStatus = ProtoCrewMember.RosterStatus.Assigned; HighLogic.CurrentGame.CrewRoster[currentKerbalName].seatIdx = crewIndex; } crewIndex++; } } vesselToKerbal[protovesselID] = takenKerbals; foreach (string name in takenKerbals) { kerbalToVessel[name] = protovesselID; } }
private KerbalModel CreateKerbal() { ProtoCrewMember kerbal = CrewGenerator.RandomCrewMemberPrototype(); return(new KerbalModel(kerbal, true)); }
internal static Part FindKerbalPart(ProtoCrewMember pKerbal) { Part kPart = FlightGlobals.ActiveVessel.Parts.Find(x => x.protoModuleCrew.Find(y => y == pKerbal) != null); return(kPart); }
private void ManifestWindow(int windowId) { GUILayout.BeginVertical(); partScrollViewer = GUILayout.BeginScrollView(partScrollViewer, GUILayout.Height(200), GUILayout.Width(300)); GUILayout.BeginVertical(); if (IsPreLaunch) { GUILayout.BeginHorizontal(); if (GUILayout.Button(string.Format("Fill Vessel"), GUILayout.Width(130))) { FillVessel(); } if (GUILayout.Button(string.Format("Empty Vessel"), GUILayout.Width(130))) { EmptyVessel(); } GUILayout.EndHorizontal(); } foreach (Part part in CrewableParts) { var style = part == SelectedPart ? Resources.ButtonToggledStyle : Resources.ButtonStyle; if (GUILayout.Button(string.Format("{0} {1}/{2}", part.partInfo.title, part.protoModuleCrew.Count, part.CrewCapacity), style, GUILayout.Width(265))) { if (SelectedPart == part) { SelectedPart = null; } else { SelectedPart = part; } } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.Label(SelectedPart != null ? string.Format("{0} {1}/{2}", SelectedPart.partInfo.title, SelectedPart.protoModuleCrew.Count, SelectedPart.CrewCapacity) : "No Part Selected", GUILayout.Width(300)); partScrollViewer2 = GUILayout.BeginScrollView(partScrollViewer2, GUILayout.Height(200), GUILayout.Width(300)); GUILayout.BeginVertical(); if (SelectedPart != null) { if (!PartIsFull(SelectedPart) && IsPreLaunch) { if (GUILayout.Button(string.Format("Add a Kerbal"), GUILayout.Width(275))) { AddCrew(1, SelectedPart, true); } } for (int i = 0; i < SelectedPart.protoModuleCrew.Count; i++) { ProtoCrewMember kerbal = SelectedPart.protoModuleCrew[i]; GUILayout.BeginHorizontal(); GUILayout.Label(kerbal.name, GUILayout.Width(200)); if (IsPreLaunch) { if (GUILayout.Button("Remove", GUILayout.Width(60))) { RemoveCrew(kerbal, SelectedPart, true); } } GUILayout.EndHorizontal(); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.BeginHorizontal(); var crewButtonStyle = _showRosterWindow ? Resources.ButtonToggledStyle : Resources.ButtonStyle; var transferStyle = _showTransferWindow ? Resources.ButtonToggledStyle : Resources.ButtonStyle; if (GUILayout.Button("Crew Roster", crewButtonStyle, GUILayout.Width(150))) { _showRosterWindow = !_showRosterWindow; } if (GUILayout.Button("Transfer Crew", transferStyle, GUILayout.Width(150))) { _showTransferWindow = !_showTransferWindow; if (!_showTransferWindow) { ClearHighlight(_selectedPartSource); ClearHighlight(_selectedPartTarget); _selectedPartSource = _selectedPartTarget = null; } } GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUI.DragWindow(new Rect(0, 0, Screen.width, 30)); }
private void TransferWindow(int windowId) { GUILayout.BeginHorizontal(); GUILayout.BeginVertical(); partSourceScrollViewer = GUILayout.BeginScrollView(partSourceScrollViewer, GUILayout.Width(300), GUILayout.Height(200)); GUILayout.BeginVertical(); foreach (Part part in CrewablePartsSource) { var style = part == SelectedPartSource ? Resources.ButtonToggledStyle : Resources.ButtonStyle; if (GUILayout.Button(string.Format("{0} {1}/{2}", part.partInfo.title, part.protoModuleCrew.Count, part.CrewCapacity), style, GUILayout.Width(265))) { SelectedPartSource = part; } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.Label(SelectedPartSource != null ? string.Format("{0} {1}/{2}", SelectedPartSource.partInfo.title, SelectedPartSource.protoModuleCrew.Count, SelectedPartSource.CrewCapacity) : "No Part Selected", GUILayout.Width(300)); partSourceScrollViewer2 = GUILayout.BeginScrollView(partSourceScrollViewer2, GUILayout.Height(200), GUILayout.Width(300)); GUILayout.BeginVertical(); if (SelectedPartSource != null) { for (int i = 0; i < SelectedPartSource.protoModuleCrew.Count; i++) { ProtoCrewMember kerbal = SelectedPartSource.protoModuleCrew[i]; GUILayout.BeginHorizontal(); GUILayout.Label(kerbal.name, GUILayout.Width(200)); if (SelectedPartTarget != null && SelectedPartTarget.protoModuleCrew.Count < SelectedPartTarget.CrewCapacity) { if (GUILayout.Button("Out", GUILayout.Width(60))) { MoveKerbal(SelectedPartSource, SelectedPartTarget, kerbal); } } GUILayout.EndHorizontal(); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.BeginVertical(); partTargetScrollViewer = GUILayout.BeginScrollView(partTargetScrollViewer, GUILayout.Height(200), GUILayout.Width(300)); GUILayout.BeginVertical(); foreach (Part part in CrewablePartsTarget) { var style = part == SelectedPartTarget ? Resources.ButtonToggledRedStyle : Resources.ButtonStyle; if (GUILayout.Button(string.Format("{0} {1}/{2}", part.partInfo.title, part.protoModuleCrew.Count, part.CrewCapacity), style, GUILayout.Width(265))) { SelectedPartTarget = part; } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.Label(SelectedPartTarget != null ? string.Format("{0} {1}/{2}", SelectedPartTarget.partInfo.title, SelectedPartTarget.protoModuleCrew.Count, SelectedPartTarget.CrewCapacity) : "No Part Selected", GUILayout.Width(300)); partTargetScrollViewer2 = GUILayout.BeginScrollView(partTargetScrollViewer2, GUILayout.Height(200), GUILayout.Width(300)); GUILayout.BeginVertical(); if (SelectedPartTarget != null) { for (int i = 0; i < SelectedPartTarget.protoModuleCrew.Count; i++) { ProtoCrewMember kerbal = SelectedPartTarget.protoModuleCrew[i]; GUILayout.BeginHorizontal(); GUILayout.Label(kerbal.name, GUILayout.Width(200)); if (SelectedPartSource != null && SelectedPartSource.protoModuleCrew.Count < SelectedPartSource.CrewCapacity) { if (GUILayout.Button("Out", GUILayout.Width(60))) { MoveKerbal(SelectedPartTarget, SelectedPartSource, kerbal); } } GUILayout.EndHorizontal(); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUI.DragWindow(new Rect(0, 0, Screen.width, 30)); }
public Kerbal(ProtoCrewMember pcm) { SetCrew(pcm); }
// return true if the specified crew member satisfy the specs public bool Check(ProtoCrewMember c) { return(trait.Length == 0 || (c.trait == trait && c.experienceLevel >= level)); }