public IEnumerator TransferData(ScienceHardDrive drive) { if(drive.StartXfering()) { float secTotal = 0f; float secRemaining = 0f; ScreenMessage msg = null; ScienceData data = null; IScienceDataContainer container = null; KeyValuePair<ScienceData, IScienceDataContainer> kvp = new KeyValuePair<ScienceData, IScienceDataContainer>(); while((kvp = QueueManager.instance.GetNextInXferQueue(drive)).Key != null) { data = kvp.Key; container = kvp.Value; if(data.dataAmount <= drive.capacity - drive.usedSpace) { secTotal = secRemaining = data.dataAmount / drive.xferRate; msg = new ScreenMessage("<color=#99ff00ff>Transfering " + data.title + " to " + drive.part.partInfo.title + ": 0%</color>", (float)secTotal + 5f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(msg); while(secRemaining > 0 && Mathf.Round((float)drive.part.RequestResource("ElectricCharge", .1 * drive.powerUsage) * 10000) == .1 * drive.powerUsage * 10000) { yield return new WaitForSeconds(.1f); secRemaining -= .1f; msg.message = "<color=#99ff00ff>Transfering " + data.title + " to " + drive.part.partInfo.title + ": " + Mathf.Round(1000 * (secTotal - secRemaining) / secTotal) / 10 + "%</color>"; } if(secRemaining > 0) { ScreenMessages.RemoveMessage(msg); ScreenMessages.PostScreenMessage("<color=#ff9900ff>Ran out of Electric Charge while transfering " + data.title + " to " + drive.part.partInfo.title + ".</color>", 5f, ScreenMessageStyle.UPPER_LEFT); QueueManager.instance.ClearXferQueue(drive); } else { ScreenMessages.RemoveMessage(msg); ScreenMessages.PostScreenMessage("<color=#99ff00ff>" + data.title + " transfered to " + drive.part.partInfo.title + ".</color>", 5f, ScreenMessageStyle.UPPER_LEFT); drive.AddData(data); container.DumpData(data); } } else { Print(drive.part.partInfo.title + " doesn't have the room for " + data.title); } QueueManager.instance.RemvoeFromXferQueue(drive, data); } yield return new WaitForSeconds(1f); drive.StopXfering(); } else { Print(drive.part.partInfo.title + " is already transfering data."); } }
public override void Start() { base.Start(); if (ullageSet == null) { ullageSet = new Ullage.UllageSet(this); } showPropStatus = (pressureFed || (ullage && RFSettings.Instance.simulateUllage)); Fields["ignitions"].guiActive = Fields["ignitions"].guiActiveEditor = (ignitions >= 0 && RFSettings.Instance.limitedIgnitions); Fields["propellantStatus"].guiActive = Fields["propellantStatus"].guiActiveEditor = showPropStatus; igniteFailIgnitions = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: no ignitions remaining!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); igniteFailResources = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: insufficient resources to ignite!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); ullageFail = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: vapor in feedlines, shut down!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); }
/// <summary> /// Action to add the input frequency to the temporary list to be committed /// </summary> private void addClick() { try { try // input checks { short newFreq = short.Parse(frequencyInput.uiItem.GetComponent <TMP_InputField>().text); if (newFreq < 0) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_negative"));//"Frequency cannot be negative" } else if (this.freqListShown.Contains(newFreq)) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_Contained"));//"Ground station has this frequency already" } else if (!GameUtils.NonLinqAny(CNCCommNetScenario.Instance.constellations, newFreq)) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_Exist"));//"Please choose an existing constellation" } else if (!Constellation.isFrequencyValid(newFreq)) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_Valid", short.MaxValue));//"Frequency must be between 0 and " + } //ALL OK this.freqListShown.Add(newFreq); this.freqListShown.Sort(); CNCLog.Debug("Added g-station freq: {0}", newFreq); refreshList(this.freqListShown); } catch (FormatException e) { throw new FormatException(Localizer.Format("#CNC_CheckFrequency_Format"));//"Frequency must be numeric only" } catch (OverflowException e) { throw new OverflowException(Localizer.Format("#CNC_CheckFrequency_Overflow", short.MaxValue));//string.Format("Frequency must be equal to or less than {0}", ) } } catch (Exception e) { ScreenMessage msg = new ScreenMessage("<color=red>" + e.Message + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); } }
private void updateAntennaFreq(CNCAntennaPartInfo antennaInfo, string freqString) { try { try { short inputFreq = short.Parse(freqString); //Check frequency if (inputFreq < 0) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_negative"));//"Frequency cannot be negative" } else if (!GameUtils.NonLinqAny(CNCCommNetScenario.Instance.constellations, inputFreq)) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_Exist"));//"Please choose an existing constellation" } else if (!Constellation.isFrequencyValid(inputFreq)) { throw new Exception(Localizer.Format("#CNC_CheckFrequency_Valid", short.MaxValue));//"Frequency must be between 0 and " + } if (base.cncVessel != null && antennaInfo != null && inputFreq >= 0) { base.cncVessel.updateFrequency(antennaInfo, inputFreq); base.cncVessel.OnAntennaChange(); this.selfRefresh(); actionCallbacks[0](); } } catch (FormatException e) { throw new FormatException(Localizer.Format("#CNC_CheckFrequency_Format"));//"Frequency must be numeric only" } catch (OverflowException e) { throw new OverflowException(Localizer.Format("#CNC_CheckFrequency_Overflow", short.MaxValue));//string.Format("Frequency must be equal to or less than {0}", ) } } catch (Exception e) { ScreenMessage msg = new ScreenMessage("<color=red>" + e.Message + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); } }
public static KCT_BuildListVessel AddVesselToBuildList(KCT_BuildListVessel blv, Dictionary <String, int> inventory) { if (CurrentGameIsCareer()) { float totalCost = blv.cost; double prevFunds = Funding.Instance.Funds; double newFunds = SpendFunds(totalCost); if (prevFunds == newFunds) { KCTDebug.Log("Tried to add " + blv.shipName + " to build list but not enough funds."); KCTDebug.Log("Vessel cost: " + blv.cost + ", Current funds: " + newFunds); var msg = new ScreenMessage("Not Enough Funds To Build!", 4.0f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg, true); return(blv); } } string type = ""; if (blv.type == KCT_BuildListVessel.ListType.VAB) { KCT_GameStates.VABList.Add(blv); type = "VAB"; } else if (blv.type == KCT_BuildListVessel.ListType.SPH) { KCT_GameStates.SPHList.Add(blv); type = "SPH"; } if (inventory.Count > 0) { foreach (ConfigNode p in blv.ExtractedPartNodes) { if (KCT_Utilities.RemovePartFromInventory(p, inventory)) { blv.InventoryParts.Add(PartNameFromNode(p) + GetTweakScaleSize(p)); } } } KCTDebug.Log("Added " + blv.shipName + " to " + type + " build list. Cost: " + blv.cost); //KCTDebug.Log("Cost Breakdown (total, parts, fuel): " + blv.totalCost + ", " + blv.dryCost + ", " + blv.fuelCost); var message = new ScreenMessage("[KCT] Added " + blv.shipName + " to " + type + " build list.", 4.0f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(message, true); return(blv); }
public void Update() { if (playback) { if (Planetarium.GetUniversalTime() > lastTime) { playback = false; ScreenMessages.RemoveMessage(screenMessage); screenMessage = null; } else { int timeLeft = (int)(lastTime - Planetarium.GetUniversalTime()); ScreenMessages.RemoveMessage(screenMessage); screenMessage = ScreenMessages.PostScreenMessage("Playback time left: " + timeLeft + " / " + (int)(lastTime - firstTime) + " seconds", float.MaxValue, ScreenMessageStyle.UPPER_CENTER); } } }
private void closeGui() { this.enabled = false; resetHighlight(); if (smInfo != null) { ScreenMessages.RemoveMessage(smInfo); smInfo = null; } if (smError != null) { ScreenMessages.RemoveMessage(smError); smError = null; } destinationParts.Clear(); // Delay unlocking UI to end of frame to prevent KSP from handling ESC key NE_Helper.RunOnEndOfFrame(this, NE_Helper.UnlockUI); }
private void PopCommand() { // Maneuvers while (mManeuverQueue.Count > 0 && mManeuverQueue.First.Value.TimeStamp <= RTUtil.GameTime) { DelayedManeuver = mManeuverQueue.First.Value.Node; mManeuverQueue.RemoveFirst(); } // Commands if (SignalProcessor.Powered && mCommandQueue.Count > 0) { if (RTSettings.Instance.ThrottleTimeWarp && TimeWarp.CurrentRate > 1.0f) { var time = TimeWarp.deltaTime; foreach (var dc in mCommandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime + (2 * time + 1.0))) { var message = new ScreenMessage("[Flight Computer]: Throttling back time warp...", 4.0f, ScreenMessageStyle.UPPER_LEFT); while ((2 * TimeWarp.deltaTime + 1.0) > (Math.Max(dc.TimeStamp - RTUtil.GameTime, 0) + dc.ExtraDelay) && TimeWarp.CurrentRate > 1.0f) { TimeWarp.SetRate(TimeWarp.CurrentRateIndex - 1, true); ScreenMessages.PostScreenMessage(message, true); } } } foreach (var dc in mCommandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime).ToList()) { Debug.Log(dc.Description); if (dc.ExtraDelay > 0) { dc.ExtraDelay -= SignalProcessor.Powered ? TimeWarp.deltaTime : 0.0; } else { if (dc.Pop(this)) { mActiveCommands[dc.Priority] = dc; } mCommandQueue.Remove(dc); } } } }
public void Update() { if (playback) { if (sm != null) { ScreenMessages.RemoveMessage(sm); } sm = ScreenMessages.PostScreenMessage("Playback: " + playPos + " / " + pathData.Count, float.MaxValue, ScreenMessageStyle.UPPER_CENTER); } else { if (sm != null) { ScreenMessages.RemoveMessage(sm); sm = null; } } }
private void SetWidthBasedOnUsername(ScreenMessage message, string newText, params RectTransform[] toTheRightOf) { if (!(message.UsernameTextField || message.UsernameTextFieldPro)) { return; } // Based on being top, centre pivot RectTransform textField; float perferredWidth; if (message.UsernameTextField) { textField = message.UsernameTextField.rectTransform; perferredWidth = message.UsernameTextField.cachedTextGeneratorForLayout.GetPreferredWidth(newText, message.UsernameTextField.GetGenerationSettings(textField.sizeDelta)); } else { textField = message.UsernameTextFieldPro.rectTransform; perferredWidth = message.UsernameTextFieldPro.GetPreferredValues(newText, textField.rect.width, 0).x; } var difference = new Vector2(perferredWidth - textField.sizeDelta.x, 0); if (textField.anchorMin.x > 0) { textField.sizeDelta += difference; } textField.anchoredPosition += difference / 2; foreach (var control in toTheRightOf) { if (!control) { return; } control.anchoredPosition += difference; } }
/// <inheritdoc/> public override void OnAwake() { base.OnAwake(); linkStateMachine.onAfterTransition += (start, end) => UpdateContextMenu(); _dropConnectorKeyEvent = Event.KeyboardEvent(KASAPI.CommonConfig.keyDropConnector); _pickupConnectorKeyEvent = Event.KeyboardEvent(KASAPI.CommonConfig.keyPickupConnector); useGUILayout = false; _dropConnectorMessage = new ScreenMessage( "", ScreenMessaging.DefaultMessageTimeout, ScreenMessageStyle.UPPER_CENTER); _pickupConnectorMessage = new ScreenMessage( "", ScreenMessaging.DefaultMessageTimeout, ScreenMessageStyle.LOWER_CENTER); if (HighLogic.LoadedSceneIsFlight) { RegisterGameEventListener(GameEvents.onPartActionUICreate, OnPartGUIStart); RegisterGameEventListener(GameEvents.onPartActionUIDismiss, OnPartGUIStop); } UpdateContextMenu(); }
/// <summary> /// Show a message on the screen if we are spectating /// </summary> private void UpdateOnScreenSpectateMessage() { if (VesselCommon.IsSpectating) { if (_spectateMessage != null) { _spectateMessage.duration = 0f; } _spectateMessage = LunaScreenMsg.PostScreenMessage(SpectatingMessage, 1000 * 2, ScreenMessageStyle.UPPER_CENTER); } else { if (_spectateMessage != null) { _spectateMessage.duration = 0f; _spectateMessage = null; } } }
private ValidationResult ProcessFundsChecks(BuildListVessel blv) { if (CheckAvailableFunds) { double totalCost = blv.GetTotalCost(); double prevFunds = Funding.Instance.Funds; if (totalCost > prevFunds) { KCTDebug.Log($"Tried to add {blv.ShipName} to build list but not enough funds."); KCTDebug.Log($"Vessel cost: {Utilities.GetTotalVesselCost(blv.ShipNode)}, Current funds: {prevFunds}"); var msg = new ScreenMessage("Not Enough Funds To Build!", 4f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); return(ValidationResult.Fail); } } return(ValidationResult.Success); }
/// <summary> /// Action to update the ground station /// </summary> private void updateAction() { bool changesCommitted = false; string newName = nameInput.uiItem.GetComponent<TMP_InputField>().text.Trim(); if (!this.hostStation.stationName.Equals(newName)) // different name { if(newName.Equals(this.hostStation.displaynodeName)) this.hostStation.stationName = ""; else this.hostStation.stationName = newName; ScreenMessage msg = new ScreenMessage(string.Format("Ground station is renamed to '{0}'", this.hostStation.stationName), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); changesCommitted = true; } if(this.hostStation.Color != this.constellColor) { this.hostStation.Color = this.constellColor; ScreenMessage msg = new ScreenMessage(string.Format("Ground station is '{0}' now", UIUtils.colorToHex(this.hostStation.Color)), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); changesCommitted = true; } int commonFreq = GameUtils.NonLinqIntersect(this.freqListShown.ToArray(), this.hostStation.getFrequencyArray()).Length; if (!(commonFreq == this.hostStation.getFrequencyList().Count && commonFreq == this.freqListShown.Count)) { this.hostStation.replaceFrequencies(this.freqListShown); ScreenMessage msg = new ScreenMessage("Ground station's frequency list is updated", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); changesCommitted = true; } string strFreqs = ""; for (int i = 0; i < this.freqListShown.Count; i++) strFreqs += this.freqListShown[i]+" "; CNCLog.Debug("Updated g-station: {0}, {1}", newName, strFreqs); if (changesCommitted) { this.dismiss(); } }
private void UpdateCountdownMessage(ref ScreenMessage msg, float remaining) { Debug.Log("UpdatecountdownMessage, countdownActive: " + countDownActive.ToString()); // If the countdown message is currently being displayed //if (countDownActive) { // If it is still supposed to be displayed if (showCountdown) { // Update the countdown message msg.message = "Self destruct sequence initiated: " + remaining.ToString("#0"); } else { // The UI must have been hidden or the user changed showCountdown? msg.duration = 1.0f; msg = null; } } }
public override void OnUpdate() { base.OnUpdate(); // Stock code adds it's G-limit messages after the FixedUpdate() of this partmodule is run. // Thus OnUpdate() is used for removing those standard messages. if (_anyCrewAboveWarnThreshold) { _anyCrewAboveWarnThreshold = false; for (int i = ScreenMessages.Instance.ActiveMessages.Count - 1; i >= 0; i--) { // Note: Should probably find the "X: lost consciousness!" and "X: reaching G limit!" messages by text but that's a bit more complicated due to localization. ScreenMessage m = ScreenMessages.Instance.ActiveMessages[i]; if (m.style == ScreenMessageStyle.UPPER_CENTER && (m.duration == 5f || m.duration == 3f)) { ScreenMessages.RemoveMessage(m); } } } }
public void Update() { if (Lib.IsFlight()) { // update ui Events["ToggleRelay"].active = type == KAntennaType.low_gain && (extended || !Settings.ExtendedAntenna) && !vessel.isEVA; Events["ToggleRelay"].guiName = Lib.StatusToggle("Relay", relay ? "yes" : "no"); // show transmission messages if (stream.Transmitting()) { string text = Lib.BuildString("Transmitting ", stream.Current_file(), ": ", Lib.HumanReadablePerc(stream.Current_progress())); if (progress_msg != null) { ScreenMessages.RemoveMessage(progress_msg); } progress_msg = ScreenMessages.PostScreenMessage(text, 1.0f, ScreenMessageStyle.UPPER_LEFT); } } }
new public void DeployExperiment() { //print("Clicked event! check data: " + resourceName + " " + resourceAmount.ToString() + " " + experimentID + " "); if (vesselHasEnoughResource(resourceName, resourceAmount)) { //print("Has the possibleAmount!!"); double res = part.RequestResource(resourceName, resourceAmount, ResourceFlowMode.ALL_VESSEL); //print("got " + res.ToString() + "resources"); base.DeployExperiment(); // ReviewDataItem(data); } else { ScreenMessage smg = new ScreenMessage("Not Enough Data Stored", 4.0f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(smg); print("not enough data stored"); } //print("Deploying Experiment"); //print("resourcename, resource possibleAmount " + resourceName + " " + resourceAmount.ToString()); }
void Update() { // Alt-F10 shows the contract configurator window if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F10)) { DebugWindow.showGUI = !DebugWindow.showGUI; } // Display reloading message if (reloading) { if (lastMessage != null) { ScreenMessages.RemoveMessage(lastMessage); lastMessage = null; } switch (reloadStep) { case ReloadStep.GAME_DATABASE: lastMessage = ScreenMessages.PostScreenMessage("Reloading game database...", Time.deltaTime, ScreenMessageStyle.UPPER_CENTER); break; case ReloadStep.MODULE_MANAGER: lastMessage = ScreenMessages.PostScreenMessage("Reloading module manager...", Time.deltaTime, ScreenMessageStyle.UPPER_CENTER); break; case ReloadStep.CLEAR_CONFIG: lastMessage = ScreenMessages.PostScreenMessage("Clearing previously loaded contract configuration...", Time.deltaTime, ScreenMessageStyle.UPPER_CENTER); break; case ReloadStep.LOAD_CONFIG: lastMessage = ScreenMessages.PostScreenMessage("Loading contract configuration (" + attemptedContracts + "/" + totalContracts + ")...", Time.deltaTime, ScreenMessageStyle.UPPER_CENTER); break; } } }
public override void OnStart(StartState state) { base.OnStart(state); if(HighLogic.LoadedSceneIsFlight) { focusIndexes = new List<int>(); commandedPositions = new List<GPSTargetInfo>(); part.force_activate(); StartCoroutine(StartupRoutine()); GameEvents.onGameStateSave.Add(SaveWingmen); GameEvents.onVesselLoaded.Add(OnVesselLoad); GameEvents.onVesselDestroy.Add(OnVesselLoad); GameEvents.onVesselGoOnRails.Add(OnVesselLoad); MissileFire.OnToggleTeam += OnToggleTeam; screenMessage = new ScreenMessage("", 2, ScreenMessageStyle.LOWER_CENTER); } }
public override void OnStart(StartState state) { base.OnStart(state); if (HighLogic.LoadedSceneIsFlight) { focusIndexes = new List <int>(); commandedPositions = new List <GPSTargetInfo>(); part.force_activate(); StartCoroutine(StartupRoutine()); GameEvents.onGameStateSave.Add(SaveWingmen); GameEvents.onVesselLoaded.Add(OnVesselLoad); GameEvents.onVesselDestroy.Add(OnVesselLoad); GameEvents.onVesselGoOnRails.Add(OnVesselLoad); MissileFire.OnToggleTeam += OnToggleTeam; screenMessage = new ScreenMessage("", 2, ScreenMessageStyle.LOWER_CENTER); } }
new public void DeployAction(KSPActionParam actParams) { //print("Clicked event! check data: " + resourceName + " " + resourceAmount.ToString() + " " + experimentID + " "); if (VesselHasEnoughResource(resourceName, resourceAmount)) { //print("Has the possibleAmount!!"); double res = part.RequestResource(resourceName, resourceAmount, ResourceFlowMode.ALL_VESSEL); //print("got " + res.ToString() + "resources"); base.DeployAction(actParams); // ReviewDataItem(data); } else { ScreenMessage smg = new ScreenMessage(Localizer.Format("#LOC_KSPIE_ResourceScience_Postmsg2"), 4.0f, ScreenMessageStyle.UPPER_LEFT);//"Not Enough Data Stored" ScreenMessages.PostScreenMessage(smg); print("not enough data stored"); } //print("Deploying Experiment"); //print("resourcename, resource possibleAmount " + resourceName + " " + resourceAmount.ToString()); }
/// <summary> /// Show a message on the screen if we are spectating /// </summary> private IEnumerator UpdateOnScreenSpectateMessage() { var seconds = new WaitForSeconds(UpdateScreenMessageInterval); while (true) { try { if (!Enabled) { break; } if (VesselLockSystemReady) { if (VesselCommon.IsSpectating) { if (_spectateMessage != null) { _spectateMessage.duration = 0f; } _spectateMessage = ScreenMessages.PostScreenMessage(SpectatingMessage, UpdateScreenMessageInterval * 2, ScreenMessageStyle.UPPER_CENTER); } else { if (_spectateMessage != null) { _spectateMessage.duration = 0f; _spectateMessage = null; } } } } catch (Exception e) { Debug.LogError($"[LMP]: Error in coroutine UpdateOnScreenSpectateMessage {e}"); } yield return(seconds); } }
protected override void Started() { currentSettings.load("SmallUtilities/EditorCamUtilities", "EditorCamUtilitiesSettings", modName); currentSettings.setDefault("rotationSpeed", "5"); currentSettings.setDefault("HeightSpeed", "5"); currentSettings.setDefault("zoomSpeed", "5"); settingsWindowRect.x = currentSettings.getFloat("settingsWindowRectX"); settingsWindowRect.y = currentSettings.getFloat("settingsWindowRectY"); rotationSpeed = currentSettings.getFloat("rotationSpeed"); HeightSpeed = currentSettings.getFloat("HeightSpeed"); zoomSpeed = currentSettings.getFloat("zoomSpeed"); extendHangar = currentSettings.getBool("extendHanger"); setIcon(Utilities.getTexture("EditorCamUtilities", "SmallUtilities/EditorCamUtilities/Textures")); setAppLauncherScenes(ApplicationLauncher.AppScenes.SPH | ApplicationLauncher.AppScenes.VAB); VABControlMessage = new ScreenMessage("Using VAB controls!", 5, ScreenMessageStyle.LOWER_CENTER); SPHControlMessage = new ScreenMessage("Using SPH controls!", 5, ScreenMessageStyle.LOWER_CENTER); initMod(); }
/// <summary> /// Show a message on the screen if we are spectating /// </summary> private void UpdateOnScreenSpectateMessage() { if (Enabled && VesselLockSystemReady) { if (VesselCommon.IsSpectating) { if (_spectateMessage != null) { _spectateMessage.duration = 0f; } _spectateMessage = ScreenMessages.PostScreenMessage(SpectatingMessage, 1000 * 2, ScreenMessageStyle.UPPER_CENTER); } else { if (_spectateMessage != null) { _spectateMessage.duration = 0f; _spectateMessage = null; } } } }
/// <summary> /// Execute actions depending on connection status /// </summary> private void ExecuteConnectionStatusActions() { //stop time wrap if re-connection occurred if (StopTimeWrapOnReconnect && TimeWarp.CurrentRate > 1.0f) { if (!RTCore.Instance.Satellites[SignalProcessor.VesselId].Connections.Any()) // no connection { TimeWrapConnectionLoss = true; } else // working connection { if (TimeWrapConnectionLoss) { TimeWrapConnectionLoss = false; var message = new ScreenMessage(Localizer.Format("#RT_FC_msg1"), 4.0f, ScreenMessageStyle.UPPER_LEFT); //"[Flight Computer]: Throttling back time warp..." TimeWarp.SetRate(0, false); //gentle stopping ScreenMessages.PostScreenMessage(message); } } } }
public void IdentifyResourceBand(string resourceName, ResourceBand band, string bodyName) { if (!IsIdentified(resourceName, band.name, bodyName)) { List <SpaceDustDiscoveryData> toIdentify = distributionData.FindAll(x => (x.ResourceName == resourceName) && (x.BandName == band.name) && (x.BodyName == bodyName)); if (toIdentify == null || toIdentify.Count == 0) { distributionData.Add(new SpaceDustDiscoveryData(resourceName, band.name, bodyName, true, true)); } else { foreach (SpaceDustDiscoveryData data in toIdentify) { data.Discovered = true; data.discoveryPercent = 100; data.Identified = true; data.identifyPercent = 100; } } if (HighLogic.LoadedSceneIsFlight) { ScreenMessage msg = new ScreenMessage(Localizer.Format("#LOC_SpaceDust_Message_Identified", resourceName, bodyName), 5f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); } Utils.Log($"[SpaceDustScenario]: Identified {resourceName} in {band.name} at {bodyName}"); if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER || HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX) { float scienceValue = FlightGlobals.GetBodyByName(bodyName).scienceValues.InSpaceHighDataValue *band.identifyScienceReward; Utils.Log($"[SpaceDustScenario]: Added {scienceValue} science because {band.name} at {bodyName} was identified"); ResearchAndDevelopment.Instance.AddScience(scienceValue, TransactionReasons.ScienceTransmission); } } }
private void onClickUpgrade() { int cost = CNCSettings.Instance.GroundStationUpgradeableCosts[this.hostStation.TechLevel]; if (Funding.Instance != null && Funding.Instance.Funds < cost) { ScreenMessage msg = new ScreenMessage("<color=red>" + Localizer.Format("#CNC_GroundStationBuild_costError") + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER);//Insufficient Funds ScreenMessages.PostScreenMessage(msg); } else { this.hostStation.incrementTechLevel(); updateCallback.Invoke(this.hostStation.ID); if (Funding.Instance != null) { Funding.Instance.AddFunds(-1.0 * cost, TransactionReasons.StructureConstruction); } currentTexture.uiItem.GetComponent <RawImage>().texture = getLevelTexture(this.hostStation.TechLevel); nextTexture.uiItem.GetComponent <RawImage>().texture = getLevelTexture((short)(this.hostStation.TechLevel < 3? (this.hostStation.TechLevel + 1) : this.hostStation.TechLevel)); } }
/// <summary> /// Turn on or off the specific antenna /// </summary> public void toggleAntenna(CNCAntennaPartInfo partInfo, bool inUse) { if (!partInfo.canComm) // antenna is not deployed { ScreenMessage msg = new ScreenMessage(string.Format("Antenna '{0}' is not deployed.", partInfo.name), CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg); CNCLog.Verbose("Cannot set the non-deployed antenna '{0}' of CommNet vessel '{1}' to {2}", partInfo.name, this.Vessel.GetName(), inUse); return; } partInfo.inUse = inUse; if (this.Vessel.loaded) { partInfo.partReference.FindModuleImplementing <CNConstellationAntennaModule>().InUse = inUse; } else { partInfo.partSnapshotReference.FindModule("CNConstellationAntennaModule").moduleValues.SetValue("InUse", inUse); } CNCLog.Verbose("Set the antenna '{0}' of CommNet vessel '{1}' to {2}", partInfo.name, this.Vessel.GetName(), inUse); }
internal void showDialog(List <ExperimentStorage> targets, ExperimentData experimentData) { NE_Helper.log("start"); this.targets = targets; exp = experimentData; NE_Helper.log("init done"); if (exp == null || targets == null || targets.Count == 0) { this.enabled = false; return; } // Highlight source part sourcePart = exp.store.getPart(); sourcePart.SetHighlightColor(dullOrange); sourcePart.SetHighlightType(Part.HighlightType.AlwaysOn); sourcePart.SetHighlight(true, false); // Create a list of destination parts and highlight them for (int i = 0, count = targets.Count; i < count; i++) { Part p = targets[i].part; if (p == sourcePart || destinationParts.Contains(p)) { continue; } destinationParts.Add(p); p.SetHighlightColor(dullCyan); p.SetHighlightType(Part.HighlightType.AlwaysOn); p.SetHighlight(true, false); } smInfo = ScreenMessages.PostScreenMessage(Localizer.Format("#ne_Select_a_part_to_transfer_1_to_ESC_to_cancel", exp.getAbbreviation()), 15, ScreenMessageStyle.UPPER_CENTER); smInfo.color = Color.cyan; this.enabled = true; NE_Helper.LockUI(); }
public void Update() { if (playback) { DisplayUpdateVesselOffset(); if (Planetarium.GetUniversalTime() > (lastTime)) { playback = false; ScreenMessages.RemoveMessage(screenMessage); screenMessage = null; } else { int timeLeft = (int)(lastTime - Planetarium.GetUniversalTime()); ScreenMessages.RemoveMessage(screenMessage); screenMessage = ScreenMessages.PostScreenMessage("Playback time left: " + timeLeft + " / " + (int)(lastTime - firstTime) + " seconds", float.MaxValue, ScreenMessageStyle.UPPER_CENTER); } } if (active) { VesselUpdate vu = Recycler <VesselUpdate> .GetObject(); vu.SetVesselWorker(vesselWorker); vu.CopyFromVessel(FlightGlobals.fetch.activeVessel); ClientMessage updateBytes = networkWorker.GetVesselUpdateMessage(vu); byte[] lengthBytes = BitConverter.GetBytes(updateBytes.data.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthBytes); } recordingVector.Write(lengthBytes, 0, lengthBytes.Length); recordingVector.Write(updateBytes.data.data, 0, updateBytes.data.Length); ByteRecycler.ReleaseObject(updateBytes.data); Recycler <VesselUpdate> .ReleaseObject(vu); } }
private void UploadCKANToServer(string chatCommand) { if (adminSystem.IsAdmin(dmpSettings.playerName)) { Console.WriteLine(); string tempCkanPath = Path.Combine(KSPUtil.ApplicationRootPath, "DarkMultiPlayer-new.ckan"); if (File.Exists(tempCkanPath)) { ScreenMessages.PostScreenMessage("Uploaded KSP/DarkMultiPlayer-new.ckan", 5f, ScreenMessageStyle.UPPER_CENTER); using (MessageWriter mw = new MessageWriter()) { mw.Write <int>((int)ModpackDataMessageType.CKAN); byte[] tempCkanBytes = File.ReadAllBytes(tempCkanPath); mw.Write <byte[]>(tempCkanBytes); networkWorker.SendModpackMessage(mw.GetMessageBytes()); } using (MessageWriter mw = new MessageWriter()) { mw.Write <int>((int)ModpackDataMessageType.MOD_DONE); mw.Write <bool>(true); modWorker.GenerateModControlFile(false, false); byte[] tempModControl = File.ReadAllBytes(Path.Combine(KSPUtil.ApplicationRootPath, "mod-control.txt")); mw.Write <byte[]>(tempModControl); networkWorker.SendModpackMessage(mw.GetMessageBytes()); } } else { ScreenMessages.PostScreenMessage("KSP/DarkMultiPlayer-new.ckan does not exist", 5f, ScreenMessageStyle.UPPER_CENTER); } } else { screenMessage = ScreenMessages.PostScreenMessage("You are not an admin, unable to upload", float.MaxValue, ScreenMessageStyle.UPPER_CENTER); } }
public static void DrawSimulationCompleteFlight(int windowID) { GUILayout.BeginVertical(); if (KCT_GameStates.launchedVessel != null && !KCT_GameStates.EditorShipEditingMode && GUILayout.Button("Build")) //Doesn't work if the vessel is null or we're editing the vessel { KCT_GameStates.buildSimulatedVessel = true; KCTDebug.Log("Ship added from simulation."); var message = new ScreenMessage("[KCT] Ship will be added upon simulation completion!", 4.0f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(message); KCT_GameStates.simulationReason = "USER"; KCTDebug.Log("Simulation complete: USER"); KCT_Utilities.disableSimulationLocks(); KCT_GameStates.flightSimulated = false; KCT_GameStates.simulationEndTime = 0; centralWindowPosition.height = 1; if (FlightDriver.CanRevertToPrelaunch) { if (FlightDriver.LaunchSiteName == "LaunchPad") FlightDriver.RevertToPrelaunch(EditorFacility.VAB); else if (FlightDriver.LaunchSiteName == "Runway") FlightDriver.RevertToPrelaunch(EditorFacility.SPH); } else { HighLogic.LoadScene(GameScenes.SPACECENTER); } } if ((!KCT_Utilities.CurrentGameIsCareer() || !KCT_PresetManager.Instance.ActivePreset.generalSettings.SimulationCosts || Funding.Instance.Funds >= (KCT_GameStates.SimulationCost*1.1)) && GUILayout.Button("Purchase Additional Time\n" + ((!KCT_PresetManager.Instance.ActivePreset.generalSettings.SimulationCosts || !KCT_Utilities.CurrentGameIsCareer()) ? "Free" : Math.Round(KCT_GameStates.SimulationCost * 1.1).ToString() + " funds"))) { showSimulationCompleteFlight = false; if (KCT_Utilities.CurrentGameIsCareer() && KCT_PresetManager.Instance.ActivePreset.generalSettings.SimulationCosts) { KCT_GameStates.FundsToChargeAtSimEnd += KCT_GameStates.SimulationCost * 1.1F; KCT_Utilities.SpendFunds(KCT_GameStates.SimulationCost * 1.1F, TransactionReasons.None); } KCT_GameStates.simulationEndTime += KCT_GameStates.simulationDefaultTimeLimit; KCT_GameStates.simulationTimeLimit += KCT_GameStates.simulationDefaultTimeLimit; KCT_GameStates.SimulationCost *= 1.1F; FlightDriver.SetPause(false); TimeWarp.SetRate(0, true); centralWindowPosition.height = 1; } if (FlightDriver.CanRevertToPostInit && GUILayout.Button("Restart Simulation")) { KerbalConstructionTime.moved = false; KCT_GameStates.flightSimulated = true; KCT_Utilities.enableSimulationLocks(); KCT_GameStates.simulationEndTime = 0; FlightDriver.RevertToLaunch(); centralWindowPosition.height = 1; } if (FlightDriver.CanRevertToPrelaunch && GUILayout.Button("Revert to Editor")) { KCT_GameStates.simulationReason = "USER"; KCTDebug.Log("Simulation complete: " + "USER"); KCT_Utilities.disableSimulationLocks(); KCT_GameStates.flightSimulated = false; KCT_GameStates.simulationEndTime = 0; if (FlightDriver.LaunchSiteName == "LaunchPad") FlightDriver.RevertToPrelaunch(EditorFacility.VAB); else if (FlightDriver.LaunchSiteName == "Runway") FlightDriver.RevertToPrelaunch(EditorFacility.SPH); centralWindowPosition.height = 1; } if (GUILayout.Button("Go to Space Center")) { KCT_GameStates.flightSimulated = false; KCT_Utilities.disableSimulationLocks(); HighLogic.LoadScene(GameScenes.SPACECENTER); centralWindowPosition.height = 1; } GUILayout.EndVertical(); CenterWindow(ref centralWindowPosition); }
private void SendVesselUpdates() { if (HighLogic.LoadedScene != GameScenes.FLIGHT) { //We aren't in flight so we have nothing to send return; } if (FlightGlobals.fetch.activeVessel == null) { //We don't have an active vessel return; } if (!FlightGlobals.fetch.activeVessel.loaded || FlightGlobals.fetch.activeVessel.packed) { //We haven't loaded into the game yet return; } if (ModWorker.fetch.modControl != ModControlMode.DISABLED) { if (!vesselPartsOk.ContainsKey(FlightGlobals.fetch.activeVessel.id.ToString())) { //Check the vessel parts if we haven't already, shows the warning message in the safety bubble. CheckVesselParts(FlightGlobals.fetch.activeVessel); } if (!vesselPartsOk[FlightGlobals.fetch.activeVessel.id.ToString()]) { if ((UnityEngine.Time.realtimeSinceStartup - lastBannedPartsMessageUpdate) > UPDATE_SCREEN_MESSAGE_INTERVAL) { lastBannedPartsMessageUpdate = UnityEngine.Time.realtimeSinceStartup; if (bannedPartsMessage != null) { bannedPartsMessage.duration = 0; } if (ModWorker.fetch.modControl == ModControlMode.ENABLED_STOP_INVALID_PART_SYNC) { bannedPartsMessage = ScreenMessages.PostScreenMessage("Active vessel contains the following banned parts, it will not be saved to the server:\n" + bannedPartsString, 2f, ScreenMessageStyle.UPPER_CENTER); } if (ModWorker.fetch.modControl == ModControlMode.ENABLED_STOP_INVALID_PART_LAUNCH) { bannedPartsMessage = ScreenMessages.PostScreenMessage("Active vessel contains the following banned parts, you will be unable to launch on this server:\n" + bannedPartsString, 2f, ScreenMessageStyle.UPPER_CENTER); } } } } if (isSpectating) { //Don't send updates in spectate mode return; } if (fromDockedVesselID != null || toDockedVesselID != null) { //Don't send updates while docking return; } if (isSpectatorDocking) { //Definitely dont send updates while spectating a docking return; } if (isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody)) { //Don't send updates while in the safety bubble return; } if (LockSystem.fetch.LockIsOurs("control-" + FlightGlobals.fetch.activeVessel.id.ToString())) { SendVesselUpdateIfNeeded(FlightGlobals.fetch.activeVessel); } SortedList<double, Vessel> secondryVessels = new SortedList<double, Vessel>(); foreach (Vessel checkVessel in FlightGlobals.fetch.vessels) { //Only update the vessel if it's loaded and unpacked (not on rails). Skip our vessel. if (checkVessel.loaded && !checkVessel.packed && (checkVessel.id.ToString() != FlightGlobals.fetch.activeVessel.id.ToString()) && (checkVessel.state != Vessel.State.DEAD)) { //Don't update vessels in the safety bubble if (!isInSafetyBubble(checkVessel.GetWorldPos3D(), checkVessel.mainBody)) { //Only attempt to update vessels that we have locks for, and ask for locks. Dont bother with controlled vessels bool updateLockIsFree = !LockSystem.fetch.LockExists("update-" + checkVessel.id.ToString()); bool updateLockIsOurs = LockSystem.fetch.LockIsOurs("update-" + checkVessel.id.ToString()); bool controlledByPlayer = LockSystem.fetch.LockExists("control-" + checkVessel.id.ToString()); if ((updateLockIsFree || updateLockIsOurs) && !controlledByPlayer) { //Dont update vessels manipulated in the future if (!VesselUpdatedInFuture(checkVessel.id.ToString())) { double currentDistance = Vector3d.Distance(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), checkVessel.GetWorldPos3D()); //If there's 2 vessels at the exact same distance. if (!secondryVessels.ContainsKey(currentDistance) && !secondryVessels.ContainsValue(checkVessel)) { secondryVessels.Add(currentDistance, checkVessel); } } } } } } int currentSend = 0; foreach (KeyValuePair<double, Vessel> secondryVessel in secondryVessels) { currentSend++; if (currentSend > DynamicTickWorker.fetch.maxSecondryVesselsPerTick) { break; } SendVesselUpdateIfNeeded(secondryVessel.Value); } }
private void HandleSpectatorDocking() { if (spectatorDockingID == null) { if ((UnityEngine.Time.realtimeSinceStartup - lastDockingMessageUpdate) > 1f) { lastDockingMessageUpdate = UnityEngine.Time.realtimeSinceStartup; if (dockingMessage != null) { dockingMessage.duration = 0f; } dockingMessage = ScreenMessages.PostScreenMessage("Spectating docking in progress...", 3f, ScreenMessageStyle.UPPER_CENTER); } } else { Vessel switchToVessel = null; switchToVessel = FlightGlobals.fetch.vessels.FindLast(v => v.id.ToString() == spectatorDockingID); if (switchToVessel != null) { KillVessel(FlightGlobals.fetch.activeVessel); FlightGlobals.ForceSetActiveVessel(switchToVessel); isSpectatorDocking = false; spectatorDockingID = null; spectatorDockingPlayer = null; } } }
public static KCT_BuildListVessel AddVesselToBuildList(KCT_BuildListVessel blv, Dictionary<String, int> inventory) { if (CurrentGameIsCareer()) { float totalCost = blv.cost; double prevFunds = Funding.Instance.Funds; double newFunds = SpendFunds(totalCost); if (prevFunds == newFunds) { Debug.Log("[KCT] Tried to add " + blv.shipName + " to build list but not enough funds."); Debug.Log("[KCT] Vessel cost: " + blv.cost + ", Current funds: " + newFunds); var msg = new ScreenMessage("Not Enough Funds To Build!", 4.0f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(msg, true); return blv; } } string type = ""; if (blv.type == KCT_BuildListVessel.ListType.VAB) { KCT_GameStates.VABList.Add(blv); type = "VAB"; } else if (blv.type == KCT_BuildListVessel.ListType.SPH) { KCT_GameStates.SPHList.Add(blv); type = "SPH"; } if (inventory.Count > 0) { foreach (string p in blv.GetPartNames()) { if (KCT_Utilities.RemovePartFromInventory(p, inventory)) blv.InventoryParts.Add(p); } } Debug.Log("[KCT] Added " + blv.shipName + " to " + type + " build list. Cost: "+blv.cost); //Debug.Log("[KCT] Cost Breakdown (total, parts, fuel): " + blv.totalCost + ", " + blv.dryCost + ", " + blv.fuelCost); var message = new ScreenMessage("[KCT] Added " + blv.shipName + " to " + type + " build list.", 4.0f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(message, true); return blv; }
private void PopCommand() { // Maneuvers while (mManeuverQueue.Count > 0 && mManeuverQueue.First.Value.TimeStamp <= RTUtil.GameTime) { DelayedManeuver = mManeuverQueue.First.Value.Node; mManeuverQueue.RemoveFirst(); } // Commands if (SignalProcessor.Powered && mCommandQueue.Count > 0) { if (RTSettings.Instance.ThrottleTimeWarp && TimeWarp.CurrentRate > 1.0f) { var time = TimeWarp.deltaTime; foreach (var dc in mCommandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime + (2 * time + 1.0))) { var message = new ScreenMessage("[Flight Computer]: Throttling back time warp...", 4.0f, ScreenMessageStyle.UPPER_LEFT); while ((2 * TimeWarp.deltaTime + 1.0) > (Math.Max(dc.TimeStamp - RTUtil.GameTime, 0) + dc.ExtraDelay) && TimeWarp.CurrentRate > 1.0f) { TimeWarp.SetRate(TimeWarp.CurrentRateIndex - 1, true); ScreenMessages.PostScreenMessage(message, true); } } } foreach (var dc in mCommandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime).ToList()) { if (dc.ExtraDelay > 0) { dc.ExtraDelay -= SignalProcessor.Powered ? TimeWarp.deltaTime : 0.0; } else { if (dc.Pop(this)) mActiveCommands[dc.Priority] = dc; mCommandQueue.Remove(dc); } } } }
public void Update() { if (incorrectlyInstalled) { if (!displayedIncorrectMessage) { displayedIncorrectMessage = true; IncorrectInstallWindow.Enable(); } return; } try { if (HighLogic.LoadedScene == GameScenes.MAINMENU && !ModWorker.fetch.dllListBuilt) { ModWorker.fetch.dllListBuilt = true; ModWorker.fetch.BuildDllFileList(); } //Handle GUI events if (!PlayerStatusWindow.fetch.disconnectEventHandled) { PlayerStatusWindow.fetch.disconnectEventHandled = true; forceQuit = true; NetworkWorker.fetch.SendDisconnect("Quit"); } if (!ConnectionWindow.fetch.renameEventHandled) { PlayerStatusWorker.fetch.myPlayerStatus.playerName = Settings.fetch.playerName; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.renameEventHandled = true; } if (!ConnectionWindow.fetch.addEventHandled) { Settings.fetch.servers.Add(ConnectionWindow.fetch.addEntry); ConnectionWindow.fetch.addEntry = null; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.addingServer = false; ConnectionWindow.fetch.addEventHandled = true; } if (!ConnectionWindow.fetch.editEventHandled) { Settings.fetch.servers[ConnectionWindow.fetch.selected].name = ConnectionWindow.fetch.editEntry.name; Settings.fetch.servers[ConnectionWindow.fetch.selected].address = ConnectionWindow.fetch.editEntry.address; Settings.fetch.servers[ConnectionWindow.fetch.selected].port = ConnectionWindow.fetch.editEntry.port; ConnectionWindow.fetch.editEntry = null; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.addingServer = false; ConnectionWindow.fetch.editEventHandled = true; } if (!ConnectionWindow.fetch.removeEventHandled) { Settings.fetch.servers.RemoveAt(ConnectionWindow.fetch.selected); ConnectionWindow.fetch.selected = -1; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.removeEventHandled = true; } if (!ConnectionWindow.fetch.connectEventHandled) { NetworkWorker.fetch.ConnectToServer(Settings.fetch.servers[ConnectionWindow.fetch.selected].address, Settings.fetch.servers[ConnectionWindow.fetch.selected].port); ConnectionWindow.fetch.connectEventHandled = true; } if (!ConnectionWindow.fetch.disconnectEventHandled) { ConnectionWindow.fetch.disconnectEventHandled = true; gameRunning = false; fireReset = true; NetworkWorker.fetch.SendDisconnect("Quit during initial sync"); } foreach (Action updateAction in updateEvent) { try { updateAction(); } catch (Exception e) { DarkLog.Debug("Threw in UpdateEvent, exception: " + e); if (NetworkWorker.fetch.state != ClientState.RUNNING) { if (NetworkWorker.fetch.state != ClientState.DISCONNECTED) { NetworkWorker.fetch.SendDisconnect("Unhandled error while syncing!"); } else { NetworkWorker.fetch.Disconnect("Unhandled error while syncing!"); } } } } //Force quit if (forceQuit) { forceQuit = false; gameRunning = false; fireReset = true; NetworkWorker.fetch.SendDisconnect("Force quit to main menu"); StopGame(); } if (displayDisconnectMessage) { if (HighLogic.LoadedScene != GameScenes.MAINMENU) { if ((UnityEngine.Time.realtimeSinceStartup - lastDisconnectMessageCheck) > 1f) { lastDisconnectMessageCheck = UnityEngine.Time.realtimeSinceStartup; if (disconnectMessage != null) { disconnectMessage.duration = 0; } disconnectMessage = ScreenMessages.PostScreenMessage("You have been disconnected!", 2f, ScreenMessageStyle.UPPER_CENTER); } } else { displayDisconnectMessage = false; } } //Normal quit if (gameRunning) { if (HighLogic.LoadedScene == GameScenes.MAINMENU) { gameRunning = false; fireReset = true; NetworkWorker.fetch.SendDisconnect("Quit to main menu"); } if (ScreenshotWorker.fetch.uploadScreenshot) { ScreenshotWorker.fetch.uploadScreenshot = false; StartCoroutine(UploadScreenshot()); } if (HighLogic.CurrentGame.flagURL != Settings.fetch.selectedFlag) { DarkLog.Debug("Saving selected flag"); Settings.fetch.selectedFlag = HighLogic.CurrentGame.flagURL; Settings.fetch.SaveSettings(); FlagSyncer.fetch.flagChangeEvent = true; } //handle use of cheats if (!serverAllowCheats) { CheatOptions.InfiniteFuel = false; CheatOptions.InfiniteEVAFuel = false; CheatOptions.InfiniteRCS = false; CheatOptions.NoCrashDamage = false; } } if (fireReset) { fireReset = false; FireResetEvent(); } if (startGame) { startGame = false; StartGame(); } } catch (Exception e) { DarkLog.Debug("Threw in Update, state " + NetworkWorker.fetch.state.ToString() + ", exception" + e); if (NetworkWorker.fetch.state != ClientState.RUNNING) { if (NetworkWorker.fetch.state != ClientState.DISCONNECTED) { NetworkWorker.fetch.SendDisconnect("Unhandled error while syncing!"); } else { NetworkWorker.fetch.Disconnect("Unhandled error while syncing!"); } } } }
public void Update() { try { if (HighLogic.LoadedScene == GameScenes.MAINMENU && !ModWorker.fetch.dllListBuilt) { ModWorker.fetch.dllListBuilt = true; ModWorker.fetch.BuildDllFileList(); } if (displayDisconnectMessage) { if (HighLogic.LoadedScene == GameScenes.MAINMENU) { displayDisconnectMessage = false; } else { if ((UnityEngine.Time.realtimeSinceStartup - lastDisconnectMessageCheck) > 1f) { lastDisconnectMessageCheck = UnityEngine.Time.realtimeSinceStartup; if (disconnectMessage != null) { disconnectMessage.duration = 0; } disconnectMessage = ScreenMessages.PostScreenMessage("You have been disconnected!", 2f, ScreenMessageStyle.UPPER_CENTER); } } } //Handle GUI events if (!PlayerStatusWindow.fetch.disconnectEventHandled) { PlayerStatusWindow.fetch.disconnectEventHandled = true; forceQuit = true; NetworkWorker.fetch.SendDisconnect("Quit"); } if (!ConnectionWindow.fetch.renameEventHandled) { PlayerStatusWorker.fetch.myPlayerStatus.playerName = Settings.fetch.playerName; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.renameEventHandled = true; } if (!ConnectionWindow.fetch.addEventHandled) { Settings.fetch.servers.Add(ConnectionWindow.fetch.addEntry); ConnectionWindow.fetch.addEntry = null; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.addingServer = false; ConnectionWindow.fetch.addEventHandled = true; } if (!ConnectionWindow.fetch.editEventHandled) { Settings.fetch.servers[ConnectionWindow.fetch.selected].name = ConnectionWindow.fetch.editEntry.name; Settings.fetch.servers[ConnectionWindow.fetch.selected].address = ConnectionWindow.fetch.editEntry.address; Settings.fetch.servers[ConnectionWindow.fetch.selected].port = ConnectionWindow.fetch.editEntry.port; ConnectionWindow.fetch.editEntry = null; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.addingServer = false; ConnectionWindow.fetch.editEventHandled = true; } if (!ConnectionWindow.fetch.removeEventHandled) { Settings.fetch.servers.RemoveAt(ConnectionWindow.fetch.selected); ConnectionWindow.fetch.selected = -1; Settings.fetch.SaveSettings(); ConnectionWindow.fetch.removeEventHandled = true; } if (!ConnectionWindow.fetch.connectEventHandled) { NetworkWorker.fetch.ConnectToServer(Settings.fetch.servers[ConnectionWindow.fetch.selected].address, Settings.fetch.servers[ConnectionWindow.fetch.selected].port); ConnectionWindow.fetch.connectEventHandled = true; } if (!ConnectionWindow.fetch.disconnectEventHandled) { ConnectionWindow.fetch.disconnectEventHandled = true; gameRunning = false; FireResetEvent(); NetworkWorker.fetch.SendDisconnect("Quit during initial sync"); } foreach (Action updateAction in updateEvent) { try { updateAction(); } catch (Exception e) { DarkLog.Debug("Threw in UpdateEvent, exception: " + e); } } //Force quit if (forceQuit) { forceQuit = false; gameRunning = false; FireResetEvent(); NetworkWorker.fetch.SendDisconnect("Force quit to main menu"); StopGame(); } //Normal quit if (gameRunning == true && HighLogic.LoadedScene == GameScenes.MAINMENU) { gameRunning = false; FireResetEvent(); NetworkWorker.fetch.SendDisconnect("Quit to main menu"); } } catch (Exception e) { DarkLog.Debug("Threw in Update, exception" + e); } }
//This method is called by the BackgroundProcessing DLL, if the user has installed it. Otherwise it will never be called. //It will consume ElectricCharge for Freezer that contain frozen kerbals for vessels that are unloaded, if the user has turned on the ECreqdForFreezer option in the settings menu. public static void FixedBackgroundUpdate(Vessel v, uint partFlightID, Func<Vessel, float, string, float> resourceRequest, ref Object data) { if (Time.timeSinceLevelLoad < 2.0f) // Check not loading level { return; } bool debug = true; try { debug = DeepFreeze.Instance.DFsettings.debugging; } catch { Utilities.Log("DeepFreeze FixedBackgroundUpdate failed to get debug setting"); } if (debug) Debug.Log("FixedBackgroundUpdate vesselID " + v.id + " partID " + partFlightID); // If the user does not have ECreqdForFreezer option ON, then we do nothing and return if (!DeepFreeze.Instance.DFsettings.ECreqdForFreezer) { //if (debug) Debug.Log("FixedBackgroundUpdate ECreqdForFreezer is OFF, nothing to do"); return; } // If the vessel this module is attached to is NOT stored in the DeepFreeze dictionary of known deepfreeze vessels we can't do anything, But this should NEVER happen. VesselInfo vslinfo; if (!DeepFreeze.Instance.DFgameSettings.knownVessels.TryGetValue(v.id, out vslinfo)) { if (debug) Debug.Log("FixedBackgroundUpdate unknown vessel, cannot process"); return; } //Except if there are no frozen crew on board we don't need to consume any EC if (vslinfo.numFrznCrew == 0) { //if (debug) Debug.Log("FixedBackgroundUpdate No Frozen Crew on-board, nothing to do"); return; } PartInfo partInfo; if (!DeepFreeze.Instance.DFgameSettings.knownFreezerParts.TryGetValue(partFlightID, out partInfo)) { if (debug) Debug.Log("FixedBackgroundUpdate Can't get the Freezer Part Information, so cannot process"); return; } // OK now we have something to do for real. // Calculate the time since last consumption of EC, then calculate the EC required and request it from BackgroundProcessing DLL. // If the vessel runs out of EC the DeepFreezeGUI class will handle notifying the user, not here. double currenttime = Planetarium.GetUniversalTime(); if (Utilities.timewarpIsValid(5)) { double timeperiod = currenttime - partInfo.timeLastElectricity; if (timeperiod >= 1f && partInfo.numFrznCrew > 0) //We have frozen Kerbals, consume EC { double Ecreqd = partInfo.frznChargeRequired / 60.0f * timeperiod * vslinfo.numFrznCrew; if (debug) Debug.Log("FixedBackgroundUpdate timeperiod = " + timeperiod + " frozenkerbals onboard part = " + vslinfo.numFrznCrew + " ECreqd = " + Ecreqd); float Ecrecvd = 0f; Ecrecvd = resourceRequest(v, (float)Ecreqd, MAIN_POWER_NAME); if (debug) Debug.Log("Consumed Freezer EC " + Ecreqd + " units"); if (Ecrecvd >= (float)Ecreqd * 0.99) { if (OnGoingECMsg != null) ScreenMessages.RemoveMessage(OnGoingECMsg); partInfo.timeLastElectricity = (float)currenttime; partInfo.deathCounter = currenttime; partInfo.outofEC = false; partInfo.ECWarning = false; vslinfo.storedEC -= Ecrecvd; } else { if (debug) Debug.Log("FixedBackgroundUpdate DeepFreezer Ran out of EC to run the freezer"); if (!partInfo.ECWarning) { ScreenMessages.PostScreenMessage("Insufficient electric charge to monitor frozen kerbals.", 10.0f, ScreenMessageStyle.UPPER_CENTER); partInfo.ECWarning = true; partInfo.deathCounter = currenttime; } if (OnGoingECMsg != null) ScreenMessages.RemoveMessage(OnGoingECMsg); OnGoingECMsg = ScreenMessages.PostScreenMessage(" Freezer Out of EC : Systems critical in " + (deathRoll - (currenttime - partInfo.deathCounter)).ToString("######0") + " secs"); partInfo.outofEC = true; if (debug) Debug.Log("FixedBackgroundUpdate deathCounter = " + partInfo.deathCounter); if (currenttime - partInfo.deathCounter > deathRoll) { if (DeepFreeze.Instance.DFsettings.fatalOption) { if (debug) Debug.Log("FixedBackgroundUpdate deathRoll reached, Kerbals all die..."); partInfo.deathCounter = currenttime; //all kerbals dies var kerbalsToDelete = new List<string>(); foreach (KeyValuePair<string, KerbalInfo> kerbal in DeepFreeze.Instance.DFgameSettings.KnownFrozenKerbals) { if (kerbal.Value.partID == partFlightID && kerbal.Value.vesselID == v.id && kerbal.Value.type != ProtoCrewMember.KerbalType.Tourist) { kerbalsToDelete.Add(kerbal.Key); } } foreach (string deathKerbal in kerbalsToDelete) { DeepFreeze.Instance.KillFrozenCrew(deathKerbal); ScreenMessages.PostScreenMessage(deathKerbal + " died due to lack of Electrical Charge to run cryogenics", 10.0f, ScreenMessageStyle.UPPER_CENTER); if (debug) Debug.Log("FixedBackgroundUpdate DeepFreezer - kerbal " + deathKerbal + " died due to lack of Electrical charge to run cryogenics"); } kerbalsToDelete.ForEach(id => DeepFreeze.Instance.DFgameSettings.KnownFrozenKerbals.Remove(id)); } else //NON Fatal option - emergency thaw all kerbals. { // Cannot emergency thaw in background processing. It is expected that DeepFreezeGUI will pick up that EC has run out and prompt the user to switch to the vessel. // When the user switches to the vessel the DeepFreezer partmodule will detect no EC is available and perform an emergency thaw procedure. if (debug) Debug.Log("FixedBackgroundUpdate DeepFreezer - EC has run out non-fatal option"); } } } } } else //Timewarp is too high { if (debug) Debug.Log("FixedBackgroundUpdate Timewarp is too high to backgroundprocess"); partInfo.deathCounter = currenttime; partInfo.outofEC = false; partInfo.ECWarning = false; } }
public void Update() { if (Time.timeSinceLevelLoad < 2.0f) // Check not loading level return; // This should only happen once in flight only, we need to load the StoredCrewList of frozen kerbals for this part from the DeepFreeze master list //This should be done in onload, but it doesn't seem to be working, probably should be checking and doing when vessel loads/unloads/switches/etc. if (!setGameSettings && HighLogic.LoadedSceneIsFlight) { onceoffSetup(); } //For some reason when we go on EVA or switch vessels the InternalModel is destroyed. //Which causes a problem when we re-board the part as the re-boarding kerbal ends up in a frozen kerbals seat. //So we check for the internalmodel existing while the vessel this part is attached to is loaded and if it isn't we re-instansiate it. if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && vessel.loaded && partHasInternals && part.internalModel == null) { Utilities.Log("Part " + part.name + "(" + part.flightID + ") is loaded and internalModel has disappeared, so re-instantiate it"); //part.SpawnIVA(); Utilities.spawnInternal(part); resetFrozenKerbals(); resetCryopods(true); } // If we have an external door (CRY-0300) or external pod (CRY-0300R) check RPM transparency setting and change the door settings as appropriate if ((PartHasDoor || isPodExternal) && DFInstalledMods.IsJSITransparentPodsInstalled && !IsFreezeActive && !IsThawActive) { try { checkRPMPodTransparencySetting(); } catch (Exception ex) { Utilities.Log("Exception attempting to check RPM transparency settings. Report this error on the Forum Thread."); Utilities.Log("Err: " + ex); } } //We have to process the occluders for the CRY-0300 and CRY-0300R for KSP 1.1 if (PartHasDoor || isPodExternal) { if (DFInstalledMods.IsJSITransparentPodsInstalled) { RPMPodOccluderProcessing(); } else { noRPMPodOccluderProcessing(); } } if (!HighLogic.LoadedSceneIsFlight) // If scene is not flight we are done with onUpdate return; //This is necessary to override stock crew xfer behaviour. When the user cancels the xfer the Stock highlighting system // it makes the transparent pod opaque. // so when a Transfer dialog is started we set crewTranferInputLock to true. // Here we check if it is true and the crewhatchcontroller is not active the user must have cancelled and we need // to reset the pod to transparent. // If they complete the transfer then the bool will be turned off by those gameevents and we don't have to reset the pod. if (crewTransferInputLock && !CrewHatchController.fetch.Active) { crewTransferInputLock = false; //Reset the bool and then process. if (FlightGlobals.ready && vessel.loaded && isPodExternal && !IsFreezeActive && !IsThawActive && DFInstalledMods.IsJSITransparentPodsInstalled) { if (_prevRPMTransparentpodSetting == "ON") { for (int i = 0; i < cryopodstateclosed.Length; i++) { if (!cryopodstateclosed[i]) //If there isn't a frozen kerbal inside { string windowname = "Cryopod-" + (i + 1) + "-Window"; Renderer extwindowrenderer = part.FindModelComponent<Renderer>(windowname); if (extwindowrenderer != null) { if (extwindowrenderer.material.shader != TransparentSpecularShader) { setCryopodWindowTransparent(i); Utilities.SetInternalDepthMask(part, false, "External_Window_Occluder"); } } } } } } } if (PartHasDoor && Utilities.IsInIVA) //So if we are in IVA mode (inside this loop) and in a CRY-0300 (have External door) Open the Kerbals EYES WIDER! { //Kerbal currentKerbal = CameraManager.Instance.IVACameraActiveKerbal; CameraManager.Instance.IVACameraActiveKerbal.kerbalCam.nearClipPlane = 0.01f; CameraManager.Instance.IVACameraActiveKerbal.kerbalCam.fieldOfView = 95f; //CameraManager.Instance.ivaFOV = 95f; //Turn OFF the Door occluders so we can see outside. if (_externaldoorstate != DoorState.CLOSED) Utilities.SetInternalDepthMask(part, false, "CRY_0300_Doors_Occluder"); } if (Time.time - lastUpdate > updatetnterval && Time.time - lastRemove > updatetnterval) // We only update every updattnterval time interval. { lastUpdate = Time.time; if (FlightGlobals.ready && FlightGlobals.ActiveVessel != null) { CrntVslID = vessel.id; CrntVslName = vessel.vesselName; //Set the Part temperature in the partmenu if (DeepFreeze.Instance.DFsettings.TempinKelvin) { Fields["CabinTemp"].guiUnits = "K"; CabinTemp = (float)part.temperature; } else { Fields["CabinTemp"].guiUnits = "C"; CabinTemp = Utilities.KelvintoCelsius((float)part.temperature); } // If RemoteTech installed set the connection status if (DFInstalledMods.IsRTInstalled) { try { if (DFInstalledMods.RTVesselConnected(part.vessel.id)) { isRTConnected = true; } else { isRTConnected = false; } } catch (Exception ex) { Utilities.Log("Exception attempting to check RemoteTech vessel connections. Report this error on the Forum Thread."); Utilities.Log("Err: " + ex); isRTConnected = false; } } // If we have an external door (CRY-0300) check if the door state has changed and then set the helmet state if (ExternalDoorActive) { // if the current and previous door states are different we need to do checks, otherwise we do nothing. if (_externaldoorstate != _prevexterndoorstate) { // if the previous state was closing and now it's closed we can take our helmets off. if (_prevexterndoorstate == DoorState.CLOSING || _externaldoorstate == DoorState.CLOSED) { part.setHelmets(false); } else // all other door states we keep our helmets on. { part.setHelmets(true); } _prevexterndoorstate = _externaldoorstate; } } // This is now handled by a coroutine callback. //If a kerbal entered the part from EVA into a frozen kerbals seat then we moved them // and now we wait IvaUpdateFrameDelay frames to refresh the portraits /* if (IvaUpdateActive) { Utilities.Log_Debug("IvaUpdateActive delay counter=" + IvaPortraitDelay); if (IvaPortraitDelay >= IvaUpdateFrameDelay) { IvaUpdateActive = false; IvaPortraitDelay = 0; vessel.SpawnCrew(); resetFrozenKerbals(); onvslchgInternal = true; GameEvents.onVesselChange.Fire(vessel); } else { IvaPortraitDelay += 1; } } */ //Refresh IVA mode Messages and Bools if (IVAKerbalName != null) ScreenMessages.RemoveMessage(IVAKerbalName); if (IVAkerbalPart != null) ScreenMessages.RemoveMessage(IVAkerbalPart); if (IVAkerbalPod != null) ScreenMessages.RemoveMessage(IVAkerbalPod); if (Utilities.VesselIsInIVA(part.vessel)) { // Utilities.Log_Debug("Vessel is in IVA mode"); vesselisinIVA = true; vesselisinInternal = false; //Kerbal actkerbal = CameraManager.Instance.IVACameraActiveKerbal; if (CameraManager.Instance.IVACameraActiveKerbal != null) { if (Utilities.ActiveKerbalIsLocal(part)) { ProtoCrewMember crew = part.protoModuleCrew.FirstOrDefault(a => a.name == CameraManager.Instance.IVACameraActiveKerbal.name); int SeatIndx = -1; if (crew != null) { SeatIndx = crew.seatIdx; } // Utilities.Log_Debug("ActiveKerbalFound, seatidx=" + SeatIndx); if (SeatIndx != -1) { SeatIndx++; IVAkerbalPod = new ScreenMessage("Pod:" + SeatIndx, 1, ScreenMessageStyle.UPPER_LEFT); IVAkerbalPod.color = Color.white; ScreenMessages.PostScreenMessage(IVAkerbalPod); } IVAkerbalPart = new ScreenMessage(part.name.Substring(0, 8), 1, ScreenMessageStyle.UPPER_LEFT); IVAkerbalPart.color = Color.white; ScreenMessages.PostScreenMessage(IVAkerbalPart); IVAKerbalName = new ScreenMessage(CameraManager.Instance.IVACameraActiveKerbal.crewMemberName, 1, ScreenMessageStyle.UPPER_LEFT); IVAKerbalName.color = Color.white; ScreenMessages.PostScreenMessage(IVAKerbalName); } } //monitoring beep if (TotalFrozen > 0 && !mon_beep.isPlaying) { mon_beep.Play(); } } else { if (IVAKerbalName != null) ScreenMessages.RemoveMessage(IVAKerbalName); if (IVAkerbalPart != null) ScreenMessages.RemoveMessage(IVAkerbalPart); if (IVAkerbalPod != null) ScreenMessages.RemoveMessage(IVAkerbalPod); vesselisinIVA = false; // Utilities.Log_Debug("Vessel is NOT in IVA mode"); if (Utilities.IsActiveVessel(vessel) && Utilities.IsInInternal) { vesselisinInternal = true; if (TotalFrozen > 0 && !mon_beep.isPlaying) { mon_beep.Play(); } // Utilities.Log_Debug("Vessel is in Internal mode"); } else { vesselisinInternal = false; if (mon_beep.isPlaying) { mon_beep.Stop(); } // Utilities.Log_Debug("Vessel is NOT in Internal mode"); } } /* // If we have Crew Xfers in progress then check and process to completion. if (_crewXferFROMActive || _crewXferTOActive) { completeCrewTransferProcessing(); } */ UpdateEvents(); // Update the Freeze/Thaw Events that are attached to this Part. } } //UpdateCounts(); // Update the Kerbal counters and stored crew lists for the part - MOVED to FixedUpdate }
//This region contains the methods for thawing a kerbal private void ProcessThawKerbal() { Utilities.Log_Debug("DeepFreezer ThawActive Kerbal = " + ToThawKerbal); switch (ThawStepInProgress) { case 0: //Begin // Utilities.Log_Debug("Thaw Step 0"); ThawKerbalStep0(ToThawKerbal); if (vesselisinInternal) { setIVAFrzrCam(ToThawKerbalSeat); } charge_up.Play(); // Play the sound effects. charge_up.loop = true; ThawStepInProgress = 1; break; case 1: //Get EC and Glykerol // Utilities.Log_Debug("Thaw Step 1"); if (skipThawStep1) { Utilities.Log_Debug("Skipping step 1 of Thaw process"); charge_up.Stop(); ThawStepInProgress = 2; break; } if (!requireResource(vessel, EC, ChargeRate, false, out ResAvail)) { ScreenMessages.PostScreenMessage("Insufficient electric charge to thaw kerbal", 5.0f, ScreenMessageStyle.UPPER_CENTER); ThawKerbalAbort(ToThawKerbal); } else { requireResource(vessel, EC, ChargeRate, true, out ResAvail); StoredCharge = StoredCharge + ChargeRate; if (ThawMsg != null) ScreenMessages.RemoveMessage(ThawMsg); ThawMsg = ScreenMessages.PostScreenMessage(" Cryopod - Charging: " + StoredCharge.ToString("######0")); if (DeepFreeze.Instance.DFsettings.RegTempReqd) { part.AddThermalFlux(heatamtThawFreezeKerbal); } if (StoredCharge >= ChargeRequired) { Utilities.Log_Debug("Stored charge requirement met. Have EC"); if (ThawMsg != null) ScreenMessages.RemoveMessage(ThawMsg); charge_up.Stop(); ThawStepInProgress = 2; } } break; case 2: //thaw the cryopod window // Utilities.Log_Debug("Thaw Step 2"); if (partHasInternals) { if (!ThawWindowAnimPlaying) // If animation not already playing start it playing. { Utilities.Log_Debug("Thawing the cryopod window"); ice_freeze.Play(); ThawWindowAnimPlaying = true; if (isPartAnimated || (isPodExternal && DFInstalledMods.IsJSITransparentPodsInstalled && _prevRPMTransparentpodSetting == "ON")) thawCryopodWindow(ToThawKerbalSeat, 1f); if (partHasStripLights && DeepFreeze.Instance.DFsettings.StripLightsActive) { startStripLightFlash(ToThawKerbalSeat); } } else // Animation is already playing, check if it has finished. { if (_windowAnimation != null) { if (_windowAnimation.IsPlaying("CryopodWindowOpen")) { // Utilities.Log_Debug("waiting for the pod animation to complete the thaw"); ThawWindowAnimPlaying = true; } else { Utilities.Log_Debug("Animation has completed. go to step 3."); ThawWindowAnimPlaying = false; ThawStepInProgress = 3; } } else { Utilities.Log_Debug("Animation disappeared. go to step 3."); //There is no animation found? Skip to step 3. ThawWindowAnimPlaying = false; ThawStepInProgress = 3; } } } else { //Part is not animated, skip to step 4. ThawWindowAnimPlaying = false; ThawStepInProgress = 4; } //} break; case 3: //open the Pod door Hal // Utilities.Log_Debug("Thaw Step 3"); if (partHasInternals && isPartAnimated) { if (!OpenPodAnimPlaying) // If animation not already playing start it playing. { Utilities.Log_Debug("Opening the cryopod"); hatch_lock.Play(); // Play the sound effects. machine_hum.Play(); machine_hum.loop = true; OpenPodAnimPlaying = true; openCryopod(ToThawKerbalSeat, 1f); //cryopodstateclosed[ToThawKerbalSeat] = false; //savecryopodstatepersistent(); } else // Animation is already playing, check if it has finished. { if (_animation != null) { if (_animation.IsPlaying("Open")) { // Utilities.Log_Debug("waiting for the pod animation to complete the thaw"); OpenPodAnimPlaying = true; } else { Utilities.Log_Debug("Animation has completed. go to step 4."); OpenPodAnimPlaying = false; ThawStepInProgress = 4; } } else { //There is no animation found? Skip to step 4. Utilities.Log_Debug("Animation disappeared. go to step 4."); OpenPodAnimPlaying = false; ThawStepInProgress = 4; } } } else { //Part is not animated, skip to step 4. OpenPodAnimPlaying = false; cryopodstateclosed[ToThawKerbalSeat] = false; savecryopodstatepersistent(); ThawStepInProgress = 4; } break; case 4: //Finalise // Utilities.Log_Debug("Thaw Step 4"); ThawKerbalStep4(ToThawKerbal); break; } }
private void ChkOngoingEC(PartInfo partInfo) { // The following section of code consumes EC when we have ECreqdForFreezer set to true in the part config. // This consumes electric charge when we have frozen kerbals on board. // But due to bugs in KSP ith EC and SolarPanels at high timewarp if timewarp is > 4x we turn it off. // If we run out of EC and Lethal setting is on, we roll the dice. There is a 1 in 3 chance a Kerbal will DIE!!!! // If lethal setting is off an emergency thaw of all frozen crew occurs. //Utilities.Log_Debug("ChkOngoingEC start"); double currenttime = Planetarium.GetUniversalTime(); double timeperiod = currenttime - timeSinceLastECtaken; // Utilities.Log_Debug("currenttime = " + currenttime + " timeperiod = " + timeperiod + " updateECTempInterval= " + updateECTempInterval); if (timeperiod > updateECTempInterval) //only update every udpateECTempInterval to avoid request resource bug when amounts are too small { if (TotalFrozen > 0) //We have frozen Kerbals, consume EC { double ECreqd = FrznChargeRequired / 60.0f * timeperiod * TotalFrozen; Utilities.Log_Debug("DeepFreezer Running the freezer parms currenttime = {0} timeperiod = {1} ecreqd = {2}" , currenttime.ToString(), timeperiod.ToString(), ECreqd.ToString()); if (requireResource(vessel, EC, ECreqd, false, out ResAvail)) { if (OnGoingECMsg != null) ScreenMessages.RemoveMessage(OnGoingECMsg); //Have resource requireResource(vessel, EC, ECreqd, true, out ResAvail); FrznChargeUsage = (float)ResAvail; Utilities.Log_Debug("DeepFreezer Consumed Freezer EC " + ECreqd + " units"); timeSinceLastECtaken = (float)currenttime; deathCounter = currenttime; _FreezerOutofEC = false; partInfo.ECWarning = false; } else { if (Time.timeSinceLevelLoad < 5.0f) // this is true if vessel just loaded or we just switched to this vessel // we need to check if we aren't going to exhaust all EC in one call.. and??? { ECreqd = ResAvail * 95 / 100; if (requireResource(vessel, EC, ECreqd, false, out ResAvail)) { requireResource(vessel, EC, ECreqd, true, out ResAvail); FrznChargeUsage = (float)ResAvail; } } //Debug.Log("DeepFreezer Ran out of EC to run the freezer"); if (!partInfo.ECWarning) { if (TimeWarp.CurrentRateIndex > 1) Utilities.stopWarp(); ScreenMessages.PostScreenMessage("Insufficient electric charge to monitor frozen kerbals.", 10.0f, ScreenMessageStyle.UPPER_CENTER); partInfo.ECWarning = true; deathCounter = currenttime; } if (OnGoingECMsg != null) ScreenMessages.RemoveMessage(OnGoingECMsg); OnGoingECMsg = ScreenMessages.PostScreenMessage(" Freezer Out of EC : Systems critical in " + (deathRoll - (currenttime - deathCounter)).ToString("######0") + " secs"); _FreezerOutofEC = true; FrznChargeUsage = 0f; Utilities.Log_Debug("DeepFreezer deathCounter = " + deathCounter); if (currenttime - deathCounter > deathRoll) { if (DeepFreeze.Instance.DFsettings.fatalOption) { Utilities.Log_Debug("DeepFreezer deathRoll reached, Kerbals all die..."); deathCounter = currenttime; //all kerbals die var kerbalsToDelete = new List<FrznCrewMbr>(); foreach (FrznCrewMbr deathKerbal in _StoredCrewList) { DeepFreeze.Instance.KillFrozenCrew(deathKerbal.CrewName); ScreenMessages.PostScreenMessage(deathKerbal.CrewName + " died due to lack of Electrical Charge to run cryogenics", 10.0f, ScreenMessageStyle.UPPER_CENTER); Utilities.Log("DeepFreezer - kerbal " + deathKerbal.CrewName + " died due to lack of Electrical charge to run cryogenics"); kerbalsToDelete.Add(deathKerbal); if (!flatline.isPlaying) { flatline.Play(); } } kerbalsToDelete.ForEach(id => _StoredCrewList.Remove(id)); } else //NON-Fatal option set. Thaw them all. { Utilities.Log_Debug("DeepFreezer deathRoll reached, Kerbals all don't die... They just Thaw out..."); deathCounter = currenttime; //all kerbals thaw out emergencyThawInProgress = true; //This will trigger FixedUpdate to thaw all frozen kerbals in the part, one by one. } } } } else // no frozen kerbals, so just update last time EC checked { Utilities.Log_Debug("No frozen kerbals for EC consumption in part " + part.name); timeSinceLastECtaken = (float)currenttime; deathCounter = currenttime; FrznChargeUsage = 0f; } } //Utilities.Log_Debug("ChkOngoingEC end"); }
public static void DrawSimulationWindow(int windowID) { GUILayout.BeginVertical(); GUILayout.Label("This is a simulation. It will end when one of the following conditions are met:"); GUILayout.Label("The time limit is exceeded"); GUILayout.Label("The flight scene is exited"); GUILayout.Label(" "); GUILayout.Label("All progress is lost in a simulation."); bool tmp = GUILayout.Toggle(KCT_GameStates.settings.NoSimGUI, " Do not show at start."); if (tmp != KCT_GameStates.settings.NoSimGUI) { KCT_GameStates.settings.NoSimGUI = tmp; KCT_GameStates.settings.Save(); } if (!PrimarilyDisabled && !KCT_GameStates.EditorShipEditingMode && GUILayout.Button("Build It!")) { KCT_GameStates.buildSimulatedVessel = true; KCTDebug.Log("Ship added from simulation."); var message = new ScreenMessage("[KCT] Ship will be built upon simulation completion!", 4.0f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(message); } if (FlightDriver.CanRevertToPostInit && GUILayout.Button("Restart Simulation")) { showSimulationWindow = false; KerbalConstructionTime.moved = false; KCT_GameStates.flightSimulated = true; KCT_Utilities.enableSimulationLocks(); KCT_GameStates.simulationEndTime = 0; KCT_GameStates.TestFlightPartFailures = true; // if (MCEWrapper.MCEAvailable) //Support for MCE // MCEWrapper.IloadMCEbackup(); FlightDriver.RevertToLaunch(); centralWindowPosition.height = 1; } if (FlightDriver.CanRevertToPrelaunch && GUILayout.Button("Revert to Editor")) { showSimulationWindow = false; KCT_GameStates.simulationReason = "USER"; KCTDebug.Log("Simulation complete: " + "USER"); KCT_Utilities.disableSimulationLocks(); KCT_GameStates.flightSimulated = false; KCT_GameStates.simulationEndTime = 0; KCT_GameStates.TestFlightPartFailures = true; // if (MCEWrapper.MCEAvailable) //Support for MCE // MCEWrapper.IloadMCEbackup(); if (KCT_GameStates.launchedVessel.type == KCT_BuildListVessel.ListType.VAB) FlightDriver.RevertToPrelaunch(EditorFacility.VAB); else FlightDriver.RevertToPrelaunch(EditorFacility.SPH); centralWindowPosition.height = 1; } if (KCT_Utilities.TestFlightInstalled && KCT_GameStates.TestFlightPartFailures && GUILayout.Button("Disable Part Failures")) { KCT_GameStates.TestFlightPartFailures = false; foreach (Part part in FlightGlobals.ActiveVessel.Parts) { bool tfAvailableOnPart = (bool)KCT_Utilities.TestFlightInterface.InvokeMember("TestFlightAvailable", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part }); if (tfAvailableOnPart) { foreach (string failureName in (List<string>)KCT_Utilities.TestFlightInterface.InvokeMember("GetAvailableFailures", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part })) { KCTDebug.Log(part.partInfo.name + ":" + failureName); KCT_Utilities.TestFlightInterface.InvokeMember("DisableFailure", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part, failureName }); } } } } if (KCT_Utilities.TestFlightInstalled && !KCT_GameStates.TestFlightPartFailures && GUILayout.Button("Enable Part Failures")) { KCT_GameStates.TestFlightPartFailures = true; foreach (Part part in FlightGlobals.ActiveVessel.Parts) { bool tfAvailableOnPart = (bool)KCT_Utilities.TestFlightInterface.InvokeMember("TestFlightAvailable", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part }); if (tfAvailableOnPart) { foreach (string failureName in (List<string>)KCT_Utilities.TestFlightInterface.InvokeMember("GetAvailableFailures", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part })) { KCTDebug.Log(part.partInfo.name + ":" + failureName); KCT_Utilities.TestFlightInterface.InvokeMember("EnableFailure", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new System.Object[] { part, failureName }); } } } } if (KCT_Utilities.RemoteTechInstalled && KCT_GameStates.RemoteTechEnabled && GUILayout.Button("Disable RemoteTech")) { KCT_Utilities.DisableRemoteTechLocks(); KCT_GameStates.RemoteTechEnabled = false; } if (KCT_Utilities.RemoteTechInstalled && !KCT_GameStates.RemoteTechEnabled && GUILayout.Button("Enable RemoteTech")) { KCT_Utilities.EnableRemoteTechLocks(); KCT_GameStates.RemoteTechEnabled = true; } if (GUILayout.Button("Close")) { showSimulationWindow = !showSimulationWindow; } GUILayout.EndVertical(); if (simulationWindowPosition.width > 250) simulationWindowPosition.width = 250; CenterWindow(ref simulationWindowPosition); }
public override void Start() { base.Start(); if (ullageSet == null) ullageSet = new Ullage.UllageSet(this); Fields["ignitions"].guiActive = Fields["ignitions"].guiActiveEditor = (ignitions >= 0 && RFSettings.Instance.limitedIgnitions); Fields["propellantStatus"].guiActive = Fields["propellantStatus"].guiActiveEditor = (pressureFed || (ullage && RFSettings.Instance.simulateUllage)); igniteFailIgnitions = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: no ignitions remaining!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); igniteFailResources = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: insufficient resources to ignite!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); ullageFail = new ScreenMessage("<color=orange>[" + part.partInfo.title + "]: vapor in feedlines, shut down!</color>", 5f, ScreenMessageStyle.UPPER_CENTER); }
private void PopCommand() { // Commands if (mCommandQueue.Count > 0) { // Can come out of time warp even if ship unpowered; workaround for KSP 0.24 power consumption bug if (RTSettings.Instance.ThrottleTimeWarp && TimeWarp.CurrentRate > 4.0f) { var time = TimeWarp.deltaTime; foreach (var dc in mCommandQueue.TakeWhile(c => c.TimeStamp <= RTUtil.GameTime + (2 * time + 1.0))) { var message = new ScreenMessage("[Flight Computer]: Throttling back time warp...", 4.0f, ScreenMessageStyle.UPPER_LEFT); while ((2 * TimeWarp.deltaTime + 1.0) > (Math.Max(dc.TimeStamp - RTUtil.GameTime, 0) + dc.ExtraDelay) && TimeWarp.CurrentRate > 1.0f) { TimeWarp.SetRate(TimeWarp.CurrentRateIndex - 1, true); ScreenMessages.PostScreenMessage(message, true); } } } // Proceed the extraDelay for every command where the normal delay is over foreach (var dc in mCommandQueue.Where(s=>s.Delay==0).ToList()) { // Use time decrement instead of comparing scheduled time, in case we later want to // reinstate event clocks stopping under certain conditions if (dc.ExtraDelay > 0) { dc.ExtraDelay -= TimeWarp.deltaTime; } else { if (SignalProcessor.Powered) { // Note: depending on implementation, dc.Pop() may execute the event if (dc.Pop(this)) { mActiveCommands[dc.Priority] = dc; if (onNewCommandPop != null) { onNewCommandPop.Invoke(); } } } else { string message = String.Format ("[Flight Computer]: Out of power, cannot run \"{0}\" on schedule.", dc.ShortName); ScreenMessages.PostScreenMessage(new ScreenMessage( message, 4.0f, ScreenMessageStyle.UPPER_LEFT ), true); } mCommandQueue.Remove(dc); UpdateLastTarget(); } } } }
public static void screenMessage(string msg) { ScreenMessage smg = new ScreenMessage(msg, 4.0f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(smg); }
// starts and stops transfer mode private void StartTransfer() { transferring = true; transferMessage = new ScreenMessage("Left click a part to transfer nuclear fuel", 999f, ScreenMessageStyle.UPPER_CENTER); ScreenMessages.PostScreenMessage(transferMessage); }
internal static void RemoveScreenMsg() { var smessage = new ScreenMessage(string.Empty, 15f, ScreenMessageStyle.LOWER_CENTER); var smessages = FindObjectOfType<ScreenMessages>(); if (smessages != null) { var smessagesToRemove = smessages.activeMessages.Where(x => x.startTime == smessage.startTime && x.style == ScreenMessageStyle.LOWER_CENTER).ToList(); foreach (var m in smessagesToRemove) ScreenMessages.RemoveMessage(m); } }
private void RemoveNoBodyMessage() { if (_noBodyMessage != null) { ScreenMessages.RemoveMessage(_noBodyMessage); _noBodyMessage = null; } }
public static void AddScienceWithMessage(float science) { if (science > 0) { ResearchAndDevelopment.Instance.Science += science; var message = new ScreenMessage("[KCT] " + science + " science added.", 4.0f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(message, true); } }
private void UpdateBoneRig(KerbalActor actor) { if (!_isAvateeringEnabled) { return; //actor.Part.animation.Stop(); } elbowAngle += elbowDelta; if (elbowAngle >= 90 && elbowDelta >= 0) { elbowDelta = -1; elbowAngle = 90; } else if (elbowAngle <= 0) { elbowAngle = 0; elbowDelta = 1; } //actor.ElbowRightTransform.localRotation = Quaternion.Euler(0, elbowAngle, 0); //actor.ShoulderRightTransform.localRotation = Quaternion.Euler(0, elbowAngle, 0); //actor.ElbowLeftTransform.localRotation = Quaternion.Euler(0, 90-elbowAngle, 0); //actor.ShoulderLeftTransform.localRotation = Quaternion.Euler(0, 90 - elbowAngle, 0); actor.ElbowRightTransform.localRotation = Quaternion.identity; actor.ShoulderRightTransform.localRotation = Quaternion.identity; actor.ElbowLeftTransform.localRotation = Quaternion.identity; actor.ShoulderLeftTransform.localRotation = Quaternion.identity; return; if (actor.ElbowRightTransform == null || !_isAvateeringEnabled) { RemoveNoBodyMessage(); return; } var body = _bodySourceManager.PrimaryBody; if (body == null) { if (_noBodyMessage == null) { _noBodyMessage = ScreenMessages.PostScreenMessage("Body not found", 1f, ScreenMessageStyle.UPPER_CENTER); } return; } RemoveNoBodyMessage(); ScreenMessages.PostScreenMessage("Tracking body!", 2f, ScreenMessageStyle.UPPER_CENTER); var rootBone = _mapper.GetBoneOrientations(body); //var elbowBone = rootBone.FindBoneWithChild(Windows.Kinect.JointType.WristRight); //if (elbowBone != null) //{ // actor.ElbowTransform.localRotation = elbowBone.Rotation; //} var shoulderRight = body.Joints[JointType.ShoulderRight].Position; var shoulderCenter = body.Joints[JointType.SpineShoulder].Position; var delta = new Vector3(shoulderRight.X - shoulderCenter.X, shoulderRight.Y - shoulderCenter.Y, shoulderRight.Z - shoulderCenter.Z); //Util.Log("Shoulder quaternion: {0}, {1}, {2}, {3}, Delta vec: {4}, {5}, {6}", q.x, q.y, q.z, q.w, delta.x, delta.y, delta.z); UpdateTransformRotation(actor.ShoulderRightTransform, rootBone.FindBoneWithChild(JointType.ElbowRight).Rotation); //UpdateTransformRotation(actor.ElbowRightTransform, Quaternion.identity); //UpdateTransformRotation(actor.ElbowRightTransform, rootBone.FindBoneWithChild(JointType.WristRight)); //UpdateTransformRotation(actor.ShoulderLeftTransform, rootBone.FindBoneWithChild(JointType.ElbowLeft).Rotation); actor.ShoulderLeftTransform.localRotation = rootBone.FindBoneWithChild(JointType.ElbowLeft).Rotation; //UpdateTransformRotation(actor.ElbowLeftTransform, Quaternion.identity); //UpdateTransformRotation(actor.ElbowLeftTransform, rootBone.FindBoneWithChild(JointType.WristLeft)); }
void ShowModeMessage() { if(moveMessage!=null) { ScreenMessages.RemoveMessage(moveMessage); } moveMessage = ScreenMessages.PostScreenMessage("Mode : "+moveMode.ToString(), 3, ScreenMessageStyle.UPPER_CENTER); }
void AddScreenMessage( string text ) { ScreenMessage message = new ScreenMessage(); message.text = text; message.timeRemaining = 30; screenMessages.Add( message ); while( screenMessages.Count > 20 ) screenMessages.RemoveAt( 0 ); }
private void HandleDocking() { if (sentDockingDestroyUpdate) { //One of them will be null, the other one will be the docked craft. string dockedID = fromDockedVesselID != null ? fromDockedVesselID : toDockedVesselID; //Find the docked craft Vessel dockedVessel = FlightGlobals.fetch.vessels.FindLast(v => v.id.ToString() == dockedID); if (dockedVessel != null ? !dockedVessel.packed : false) { ProtoVessel sendProto = new ProtoVessel(dockedVessel); if (sendProto != null) { DarkLog.Debug("Sending docked protovessel " + dockedID); //Mark the vessel as sent serverVesselsProtoUpdate[dockedID] = UnityEngine.Time.realtimeSinceStartup; serverVesselsPositionUpdate[dockedID] = UnityEngine.Time.realtimeSinceStartup; RegisterServerVessel(dockedID); vesselPartCount[dockedID] = dockedVessel.parts.Count; vesselNames[dockedID] = dockedVessel.vesselName; vesselTypes[dockedID] = dockedVessel.vesselType; vesselSituations[dockedID] = dockedVessel.situation; //Update status if it's us. if (dockedVessel == FlightGlobals.fetch.activeVessel) { //Release old control locks if (lastVesselID != FlightGlobals.fetch.activeVessel.id.ToString()) { LockSystem.fetch.ReleasePlayerLocksWithPrefix(Settings.fetch.playerName, "control-"); lastVesselID = FlightGlobals.fetch.activeVessel.id.ToString(); } //Force the control lock off any other player LockSystem.fetch.AcquireLock("control-" + dockedID, true); PlayerStatusWorker.fetch.myPlayerStatus.vesselText = FlightGlobals.fetch.activeVessel.vesselName; } fromDockedVesselID = null; toDockedVesselID = null; sentDockingDestroyUpdate = false; bool isFlyingUpdate = (sendProto.situation == Vessel.Situations.FLYING); NetworkWorker.fetch.SendVesselProtoMessage(sendProto, true, isFlyingUpdate); if (dockingMessage != null) { dockingMessage.duration = 0f; } dockingMessage = ScreenMessages.PostScreenMessage("Docked!", 3f, ScreenMessageStyle.UPPER_CENTER); DarkLog.Debug("Docking event over!"); } else { DarkLog.Debug("Error sending protovessel!"); PrintDockingInProgress(); } } else { PrintDockingInProgress(); } } else { PrintDockingInProgress(); } }
private void SkewTime() { if ((syncing || warping) && !forceNTP) { return; } forceNTP = false; //Time does not advance in the VAB, SPH or victim selection screen. if (HighLogic.LoadedScene == GameScenes.EDITOR || HighLogic.LoadedScene == GameScenes.SPH) { if (isSkewingTime) { isSkewingTime = false; Time.timeScale = 1f; } return; } //This brings the computers MET timer in to line with the server. if (isTimeSyncronized && skewServerTime != 0 && skewTargetTick != 0) { long timeFromLastSync = (DateTime.UtcNow.Ticks + offsetSyncTick) - skewServerTime; double timeFromLastSyncSeconds = (double)timeFromLastSync / 10000000; double timeFromLastSyncSecondsAdjusted = timeFromLastSyncSeconds * skewSubspaceSpeed; double currentError = Planetarium.GetUniversalTime () - (skewTargetTick + timeFromLastSyncSecondsAdjusted); //Ticks are integers of 100ns, Planetarium camera is a float in seconds. double currentErrorMs = Math.Round (currentError * 1000, 2); if (Math.Abs (currentError) > 5) { if (skewMessage != null) { skewMessage.duration = 0f; } if (isInFlight && FlightGlobals.ActiveVessel != null) { krakensBaneWarp(skewTargetTick + timeFromLastSyncSecondsAdjusted); } else { Planetarium.SetUniversalTime(skewTargetTick + timeFromLastSyncSecondsAdjusted); } return; } //Dynamic warp. float timeWarpRate = (float) Math.Pow(2, -currentError); if ( timeWarpRate > 1.5f ) timeWarpRate = 1.5f; if ( timeWarpRate < 0.5f ) timeWarpRate = 0.5f; if (Math.Abs(currentError) > 0.2) { isSkewingTime = true; Time.timeScale = timeWarpRate; } if (Math.Abs(currentError) < 0.05 && isSkewingTime) { isSkewingTime = false; Time.timeScale = 1; } //Let's give the client a little bit of time to settle before being able to request a different rate. if (UnityEngine.Time.realtimeSinceStartup > lastSubspaceLockChange + 10f) { float requestedRate = (1 / timeWarpRate) * skewSubspaceSpeed; listClientTimeWarp.Add(requestedRate); listClientTimeWarpAverage = listClientTimeWarp.Average(); } else { listClientTimeWarp.Add(skewSubspaceSpeed); listClientTimeWarpAverage = listClientTimeWarp.Average(); } //Keeps the last 10 seconds (300 update steps) of clock speed history to report to the server if (listClientTimeWarp.Count > 300) { listClientTimeWarp.RemoveAt(0); } if (displayNTP) { if (skewMessage != null) { //Hide the old message. skewMessage.duration = 0; } //Current clock error in milliseconds String skewMessageText; skewMessageText = "\n\nClock error: " + currentErrorMs + "ms.\n"; skewMessageText += "Game speed: " + Math.Round(Time.timeScale, 3) + "x.\n"; //Current client latency detected by NTP (latency - server processing time) long latencySyncTickMs = latencySyncTick / 10000; skewMessageText += "Network latency: " + latencySyncTickMs + "ms.\n"; //Current system clock offset skewMessageText += "Clock offset: "; long tempOffsetSyncTick = offsetSyncTick; long offsetSyncTickHours = tempOffsetSyncTick / 36000000000; tempOffsetSyncTick -= offsetSyncTickHours * 36000000000; if (offsetSyncTickHours > 0) { skewMessageText += offsetSyncTickHours + "h, "; } long offsetSyncTickMinutes = tempOffsetSyncTick / 600000000; tempOffsetSyncTick -= offsetSyncTickMinutes * 600000000; if (offsetSyncTickMinutes > 0) { skewMessageText += offsetSyncTickMinutes + "m, "; } long offsetSyncTickSeconds = tempOffsetSyncTick / 10000000; tempOffsetSyncTick -= offsetSyncTickSeconds * 10000000; if (offsetSyncTickSeconds > 0) { skewMessageText += offsetSyncTickSeconds + "s, "; } long offsetSyncTickMilliseconds = tempOffsetSyncTick / 10000; skewMessageText += offsetSyncTickMilliseconds + "ms.\n"; //Current subspace speed skewMessageText += "Subspace Speed: " + Math.Round(skewSubspaceSpeed, 3) + "x.\n"; //Estimated server lag skewMessageText += "Server lag: "; long tempServerLag = estimatedServerLag; long serverLagSeconds = tempServerLag / 10000000; tempServerLag -= serverLagSeconds * 10000000; if (serverLagSeconds > 0) { skewMessageText += serverLagSeconds + "s, "; } long serverLagMilliseconds = tempServerLag / 10000; skewMessageText += serverLagMilliseconds + "ms.\n"; skewMessageText += "Universe Time: " + Planetarium.GetUniversalTime() + "\n"; skewMessage = ScreenMessages.PostScreenMessage(skewMessageText, 1f, ScreenMessageStyle.UPPER_RIGHT); } } }
private void PrintDockingInProgress() { if ((UnityEngine.Time.realtimeSinceStartup - lastDockingMessageUpdate) > 1f) { lastDockingMessageUpdate = UnityEngine.Time.realtimeSinceStartup; if (dockingMessage != null) { dockingMessage.duration = 0f; } dockingMessage = ScreenMessages.PostScreenMessage("Docking in progress...", 3f, ScreenMessageStyle.UPPER_CENTER); } }
//Updates public void updateStep() { try { if (HighLogic.LoadedScene == GameScenes.LOADING || !gameRunning) return; //Don't do anything while the game is loading or not in KMP game //Queue a time sync if needed if (isTimeSyncronized && (UnityEngine.Time.realtimeSinceStartup > lastTimeSyncTime + SYNC_TIME_INTERVAL)) { SyncTime(); } //Do the Phys-warp NTP time sync dance. SkewTime(); if (syncing) { if (vesselLoadedMessage != null) { vesselLoadedMessage.duration = 0f; } if (isTimeSyncronized) { if (!inGameSyncing) { if (numberOfShips != 0) { if (!vesselsLoaded) { vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing vessels: " + vesselUpdatesLoaded.Count + "/" + numberOfShips + " (" + (vesselUpdatesLoaded.Count * 100 / numberOfShips) + "%)", 1f, ScreenMessageStyle.UPPER_RIGHT); } else { vesselLoadedMessage = ScreenMessages.PostScreenMessage("Universe synchronized!",1f,ScreenMessageStyle.UPPER_RIGHT); } } else { vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronized new universe!", 1f, ScreenMessageStyle.UPPER_RIGHT); } } else { vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing vessels: " + FlightGlobals.Vessels.Count, 1f, ScreenMessageStyle.UPPER_RIGHT); } } else { vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing to server clock: " + listClientTimeSyncOffset.Count + "/" + SYNC_TIME_VALID_COUNT + " (" + (listClientTimeSyncOffset.Count * 100 / SYNC_TIME_VALID_COUNT) + "%)", 1f, ScreenMessageStyle.UPPER_RIGHT); } } if (!isInFlight && HighLogic.LoadedScene == GameScenes.TRACKSTATION) { try { SpaceTracking st = (SpaceTracking) GameObject.FindObjectOfType(typeof(SpaceTracking)); if (st.mainCamera.target.vessel != null && (serverVessels_IsMine[st.mainCamera.target.vessel.id] || !serverVessels_IsPrivate[st.mainCamera.target.vessel.id])) { //Public/owned vessel st.FlyButton.Unlock(); st.DeleteButton.Unlock(); if (st.mainCamera.target.vessel.mainBody.bodyName == "Kerbin" && (st.mainCamera.target.vessel.situation == Vessel.Situations.LANDED || st.mainCamera.target.vessel.situation == Vessel.Situations.SPLASHED)) st.RecoverButton.Unlock(); else st.RecoverButton.Lock(); } else { //Private unowned vessel st.FlyButton.Lock(); st.DeleteButton.Lock(); st.RecoverButton.Lock(); } } catch {} } if (lastWarpRate != TimeWarp.CurrentRate) { lastWarpRate = TimeWarp.CurrentRate; OnTimeWarpRateChanged(); } if (warping) { writeUpdates(); return; } foreach (Vessel vessel in FlightGlobals.Vessels.Where(v => v.vesselType == VesselType.SpaceObject && !serverVessels_RemoteID.ContainsKey(v.id))) { Log.Debug("New space object!"); sendVesselMessage(vessel, false); } if (EditorPartList.Instance != null && clearEditorPartList) { clearEditorPartList = false; EditorPartList.Instance.Refresh(); } while (scenarioUpdateQueue.Count > 0 && vesselsLoaded) { applyScenarioUpdate(scenarioUpdateQueue.Dequeue()); } if (syncing) lastScenarioUpdateTime = UnityEngine.Time.realtimeSinceStartup; else if ((UnityEngine.Time.realtimeSinceStartup-lastScenarioUpdateTime) >= SCENARIO_UPDATE_INTERVAL) { sendScenarios(); } //Update Tracking Station names for unavailable vessels if (!isInFlight) { foreach (Vessel vessel in FlightGlobals.Vessels) { string baseName = vessel.vesselName; if (baseName.StartsWith("* ")) baseName = baseName.Substring(2); vessel.vesselName = (((serverVessels_InUse.ContainsKey(vessel.id) ? serverVessels_InUse[vessel.id] : false) || ((serverVessels_IsPrivate.ContainsKey(vessel.id) ? serverVessels_IsPrivate[vessel.id]: false) && (serverVessels_IsMine.ContainsKey(vessel.id) ? !serverVessels_IsMine[vessel.id] : false))) ? "* " : "") + baseName; } } else //Kill Kraken-debris, clean names { foreach (Vessel vessel in FlightGlobals.Vessels.FindAll(v => v.vesselName.Contains("> Debris"))) { try { if (!vessel.isEVA) killVessel(vessel); } catch (Exception e) { Log.Debug("Exception thrown in updateStep(), catch 1, Exception: {0}", e.ToString()); } } } //Ensure player never touches something under another player's control bool controlsLocked = false; if (isInFlight && !docking && serverVessels_InUse.ContainsKey(FlightGlobals.ActiveVessel.id)) { if (serverVessels_InUse[FlightGlobals.ActiveVessel.id]) { ScreenMessages.PostScreenMessage("This vessel is currently controlled by another player...", 2.5f,ScreenMessageStyle.UPPER_CENTER); InputLockManager.SetControlLock(BLOCK_ALL_CONTROLS,"KMP_Occupied"); controlsLocked = true; } else { if (InputLockManager.GetControlLock("KMP_Occupied") == (BLOCK_ALL_CONTROLS)) InputLockManager.RemoveControlLock("KMP_Occupied"); } } //Ensure player never touches a private vessel they don't own if (isInFlight && !docking && serverVessels_IsPrivate.ContainsKey(FlightGlobals.ActiveVessel.id) && serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id)) { if (!serverVessels_IsMine[FlightGlobals.ActiveVessel.id] && serverVessels_IsPrivate[FlightGlobals.ActiveVessel.id]) { ScreenMessages.PostScreenMessage("This vessel is private...", 2.5f,ScreenMessageStyle.UPPER_CENTER); InputLockManager.SetControlLock(BLOCK_ALL_CONTROLS,"KMP_Private"); controlsLocked = true; } else { if (InputLockManager.GetControlLock("KMP_Private") == (BLOCK_ALL_CONTROLS)) InputLockManager.RemoveControlLock("KMP_Private"); } } if (isInFlight && !docking && FlightGlobals.fetch.VesselTarget != null) { //Get targeted vessel Vessel vesselTarget = null; if (FlightGlobals.fetch.VesselTarget is ModuleDockingNode) { ModuleDockingNode moduleTarget = (ModuleDockingNode) FlightGlobals.fetch.VesselTarget; if (moduleTarget.part.vessel != null) vesselTarget = moduleTarget.part.vessel; } if (FlightGlobals.fetch.VesselTarget is Vessel) { vesselTarget = (Vessel) FlightGlobals.fetch.VesselTarget; } if (vesselTarget != null) { double distanceToTarget = Vector3d.Distance(vesselTarget.GetWorldPos3D(), FlightGlobals.ship_position); //Check if target is private and too close if (distanceToTarget < PRIVATE_VESSEL_MIN_TARGET_DISTANCE && serverVessels_IsPrivate.ContainsKey(vesselTarget.id) && serverVessels_IsMine.ContainsKey(vesselTarget.id)) { if (!serverVessels_IsMine[vesselTarget.id] && serverVessels_IsPrivate[vesselTarget.id]) { Log.Debug("Tried to target private vessel"); ScreenMessages.PostScreenMessage("Can't dock - Target vessel is Private", 4f, ScreenMessageStyle.UPPER_CENTER); FlightGlobals.fetch.SetVesselTarget(null); } } } } if (isInFlight && !docking && !gameArrr) { foreach (Vessel possible_target in FlightGlobals.Vessels.ToList()) { checkVesselPrivacy(possible_target); } } //Reset the safety bubble transparency setting so it works when we go back into flight. if (!isInFlight) { safetyTransparency = false; } //Let's let the user know they are actually inside the bubble. if (FlightGlobals.fetch.activeVessel != null) { Vessel activeVessel = FlightGlobals.fetch.activeVessel; if (isInSafetyBubble(activeVessel.GetWorldPos3D(), activeVessel.mainBody, activeVessel.altitude) != safetyTransparency) { safetyTransparency = !safetyTransparency; foreach (Part part in FlightGlobals.fetch.activeVessel.parts) { if (safetyTransparency) { setPartOpacity(part, 0.75f); } else { setPartOpacity(part, 1f); } } } } writeUpdates(); //Once all updates are processed, update the vesselUpdateQueue with new entries vesselUpdateQueue = newVesselUpdateQueue; //If in flight, check remote vessels, set position variable for docking-mode position updates if (isInFlight) { VesselRecoveryButton vrb = null; try { vrb = (VesselRecoveryButton) GameObject.FindObjectOfType(typeof(VesselRecoveryButton)); } catch {} if (controlsLocked) { //Prevent EVA'ing crew or vessel recovery lockCrewGUI(); if (vrb != null) vrb.ssuiButton.Lock(); } else { //Clear locks if (!KMPChatDX.showInput) { InputLockManager.RemoveControlLock("KMP_ChatActive"); } unlockCrewGUI(); if (vrb != null && FlightGlobals.ActiveVessel.mainBody.bodyName == "Kerbin" && (FlightGlobals.ActiveVessel.situation == Vessel.Situations.LANDED || FlightGlobals.ActiveVessel.situation == Vessel.Situations.SPLASHED)) vrb.ssuiButton.Unlock(); else if (vrb != null) vrb.ssuiButton.Lock(); } checkRemoteVesselIntegrity(); activeVesselPosition = FlightGlobals.ship_CoM; dockingRelVel.Clear(); } //Handle all queued vessel updates while (vesselUpdateQueue.Count > 0) { handleVesselUpdate(vesselUpdateQueue.Dequeue()); } if (HighLogic.CurrentGame.flightState.universalTime < Planetarium.GetUniversalTime()) HighLogic.CurrentGame.flightState.universalTime = Planetarium.GetUniversalTime(); processClientInterop(); //Update the displayed player orbit positions List<String> delete_list = new List<String>(); foreach (KeyValuePair<String, VesselEntry> pair in vessels) { VesselEntry entry = pair.Value; if ((UnityEngine.Time.realtimeSinceStartup-entry.lastUpdateTime) <= VESSEL_TIMEOUT_DELAY && entry.vessel != null && entry.vessel.gameObj != null) { entry.vessel.updateRenderProperties(!KMPGlobalSettings.instance.showInactiveShips && entry.vessel.info.state != State.ACTIVE); entry.vessel.updatePosition(); } else { delete_list.Add(pair.Key); //Mark the vessel for deletion if (entry.vessel != null && entry.vessel.gameObj != null) GameObject.Destroy(entry.vessel.gameObj); } } //Delete what needs deletin' foreach (String key in delete_list) vessels.Remove(key); delete_list.Clear(); //Delete outdated player status entries foreach (KeyValuePair<String, VesselStatusInfo> pair in playerStatus) { if ((UnityEngine.Time.realtimeSinceStartup - pair.Value.lastUpdateTime) > VESSEL_TIMEOUT_DELAY) { Log.Debug("deleted player status for timeout: " + pair.Key + " " + pair.Value.vesselName); delete_list.Add(pair.Key); } } foreach (String key in delete_list) playerStatus.Remove(key); } catch (Exception ex) { Log.Debug("Exception thrown in updateStep(), catch 4, Exception: {0}", ex.ToString()); Log.Debug("uS err: " + ex.Message + " " + ex.StackTrace); } }
private void UpdateOnScreenSpectateMessage() { if ((UnityEngine.Time.realtimeSinceStartup - lastSpectateMessageUpdate) > UPDATE_SCREEN_MESSAGE_INTERVAL) { lastSpectateMessageUpdate = UnityEngine.Time.realtimeSinceStartup; if (isSpectating) { if (spectateMessage != null) { spectateMessage.duration = 0f; } switch (spectateType) { case 1: spectateMessage = ScreenMessages.PostScreenMessage("This vessel is controlled by another player.", UPDATE_SCREEN_MESSAGE_INTERVAL * 2, ScreenMessageStyle.UPPER_CENTER); break; case 2: spectateMessage = ScreenMessages.PostScreenMessage("This vessel has been changed in the future.", UPDATE_SCREEN_MESSAGE_INTERVAL * 2, ScreenMessageStyle.UPPER_CENTER); break; } } else { if (spectateMessage != null) { spectateMessage.duration = 0f; spectateMessage = null; } } } }
public virtual void SendMessage(string to, object what) { var message = new ScreenMessage { Id = to, Payload = what, Sender = this }; ParentScene.SendMessage(message); }