コード例 #1
0
ファイル: GameMain.cs プロジェクト: WebDevPT/Barotrauma
 private void CheckContentPackage()
 {
     foreach (ContentPackage contentPackage in Config.SelectedContentPackages)
     {
         var exePaths = contentPackage.GetFilesOfType(ContentType.Executable);
         if (exePaths.Any() && AppDomain.CurrentDomain.FriendlyName != exePaths.First())
         {
             var msgBox = new GUIMessageBox(TextManager.Get("Error"), TextManager.GetWithVariables("IncorrectExe",
                                                                                                   new string[2] {
                 "[selectedpackage]", "[exename]"
             }, new string[2] {
                 contentPackage.Name, exePaths.First()
             }),
                                            new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
             msgBox.Buttons[0].OnClicked += (_, userdata) =>
             {
                 string fullPath = Path.GetFullPath(exePaths.First());
                 Process.Start(fullPath);
                 Exit();
                 return(true);
             };
             msgBox.Buttons[1].OnClicked = msgBox.Close;
             break;
         }
     }
 }
コード例 #2
0
 private void CheckContentPackage()
 {
     foreach (ContentPackage contentPackage in Config.SelectedContentPackages)
     {
         var exePaths = contentPackage.GetFilesOfType(ContentType.ServerExecutable);
         if (exePaths.Count() > 0 && AppDomain.CurrentDomain.FriendlyName != exePaths.First())
         {
             DebugConsole.ShowQuestionPrompt(TextManager.GetWithVariables("IncorrectExe", new string[2] {
                 "[selectedpackage]", "[exename]"
             }, new string[2] {
                 contentPackage.Name, exePaths.First()
             }),
                                             (option) =>
             {
                 if (option.ToLower() == "y" || option.ToLower() == "yes")
                 {
                     string fullPath = Path.GetFullPath(exePaths.First());
                     Process.Start(fullPath);
                     ShouldRun = false;
                 }
             });
             break;
         }
     }
 }
コード例 #3
0
        partial void OnSkillChanged(string skillIdentifier, float prevLevel, float newLevel, Vector2 textPopupPos)
        {
            if (newLevel - prevLevel > 0.1f)
            {
                GUI.AddMessage(
                    "+" + ((int)((newLevel - prevLevel) * 100.0f)).ToString() + " XP",
                    Color.Green,
                    textPopupPos,
                    Vector2.UnitY * 10.0f);
            }
            else if (prevLevel % 0.1f > 0.05f && newLevel % 0.1f < 0.05f)
            {
                GUI.AddMessage(
                    "+10 XP",
                    Color.Green,
                    textPopupPos,
                    Vector2.UnitY * 10.0f);
            }

            if ((int)newLevel > (int)prevLevel)
            {
                GUI.AddMessage(
                    TextManager.GetWithVariables("SkillIncreased", new string[3] {
                    "[name]", "[skillname]", "[newlevel]"
                },
                                                 new string[3] {
                    Name, TextManager.Get("SkillName." + skillIdentifier), ((int)newLevel).ToString()
                },
                                                 new bool[3] {
                    false, true, false
                }), Color.Green);
            }
        }
コード例 #4
0
        public string GetChatMessage(string targetCharacterName, string targetRoomName, bool givingOrderToSelf, string orderOption = "")
        {
            orderOption ??= "";

            string messageTag = (givingOrderToSelf && !TargetAllCharacters ? "OrderDialogSelf." : "OrderDialog.") + Identifier;

            if (!string.IsNullOrEmpty(orderOption))
            {
                messageTag += "." + orderOption;
            }

            if (targetCharacterName == null)
            {
                targetCharacterName = "";
            }
            if (targetRoomName == null)
            {
                targetRoomName = "";
            }
            string msg = TextManager.GetWithVariables(messageTag, new string[2] {
                "[name]", "[roomname]"
            }, new string[2] {
                targetCharacterName, targetRoomName
            }, new bool[2] {
                false, true
            }, true);

            if (msg == null)
            {
                return("");
            }

            return(msg);
        }
コード例 #5
0
ファイル: ContentPackage.cs プロジェクト: lexuv2/Barotrauma
        public bool CheckErrors(out List <string> errorMessages)
        {
            this.errorMessages = errorMessages = new List <string>();
            foreach (ContentFile file in Files)
            {
                switch (file.Type)
                {
                case ContentType.Executable:
                case ContentType.ServerExecutable:
                case ContentType.None:
                case ContentType.Outpost:
                case ContentType.OutpostModule:
                case ContentType.Submarine:
                case ContentType.Wreck:
                    break;

                default:
                    try
                    {
                        XDocument.Load(file.Path);
                    }
                    catch (Exception e)
                    {
                        if (TextManager.Initialized)
                        {
                            errorMessages.Add(TextManager.GetWithVariables("xmlfileinvalid",
                                                                           new string[] { "[filepath]", "[errormessage]" },
                                                                           new string[] { file.Path, e.Message }));
                        }
                        else
                        {
                            errorMessages.Add($"XML File Invalid. PATH: {file.Path}, ERROR: {e.Message}");
#if DEBUG
                            throw;
#endif
                        }
                    }
                    break;
                }
            }

            if (CorePackage && !ContainsRequiredCorePackageFiles(out List <ContentType> missingContentTypes))
            {
                errorMessages.Add(TextManager.GetWithVariables("ContentPackageCantMakeCorePackage",
                                                               new string[2] {
                    "[packagename]", "[missingfiletypes]"
                },
                                                               new string[2] {
                    Name, string.Join(", ", missingContentTypes)
                },
                                                               new bool[2] {
                    false, true
                }));
            }
            VerifyFiles(out List <string> missingFileMessages);

            errorMessages.AddRange(missingFileMessages);
            hasErrors = errorMessages.Count > 0;
            return(!hasErrors.Value);
        }
コード例 #6
0
ファイル: Mission.cs プロジェクト: parhelia512/Barotrauma
        public string GetReputationRewardText(Location currLocation)
        {
            List <string> reputationRewardTexts = new List <string>();

            foreach (var reputationReward in ReputationRewards)
            {
                string name = "";

                if (reputationReward.Key.Equals("location", StringComparison.OrdinalIgnoreCase))
                {
                    name = $"‖color:gui.orange‖{currLocation.Name}‖end‖";
                }
                else
                {
                    var faction = FactionPrefab.Prefabs.Find(f => f.Identifier.Equals(reputationReward.Key, StringComparison.OrdinalIgnoreCase));
                    if (faction != null)
                    {
                        name = $"‖color:{XMLExtensions.ColorToString(faction.IconColor)}‖{faction.Name}‖end‖";
                    }
                    else
                    {
                        name = TextManager.Get(reputationReward.Key);
                    }
                }
                float  normalizedValue = MathUtils.InverseLerp(-100.0f, 100.0f, reputationReward.Value);
                string formattedValue  = ((int)reputationReward.Value).ToString("+#;-#;0"); //force plus sign for positive numbers
                string rewardText      = TextManager.GetWithVariables(
                    "reputationformat",
                    new string[] { "[reputationname]", "[reputationvalue]" },
                    new string[] { name, $"‖color:{XMLExtensions.ColorToString(Reputation.GetReputationColor(normalizedValue))}‖{formattedValue}‖end‖" });
                reputationRewardTexts.Add(rewardText);
            }
            return(TextManager.AddPunctuation(':', TextManager.Get("reputation"), string.Join(", ", reputationRewardTexts)));
        }
コード例 #7
0
        public static string GetSubmarineVoteResultMessage(SubmarineInfo info, VoteType type, string yesVoteString, string noVoteString, bool votePassed)
        {
            string result = string.Empty;

            switch (type)
            {
            case VoteType.PurchaseAndSwitchSub:
                result = TextManager.GetWithVariables(votePassed ? "submarinepurchaseandswitchvotepassed" : "submarinepurchaseandswitchvotefailed", new string[] { "[submarinename]", "[amount]", "[currencyname]", "[yesvotecount]", "[novotecount]" }, new string[] { info.DisplayName, info.Price.ToString(), TextManager.Get("credit").ToLower(), yesVoteString, noVoteString });
                break;

            case VoteType.PurchaseSub:
                result = TextManager.GetWithVariables(votePassed ? "submarinepurchasevotepassed" : "submarinepurchasevotefailed", new string[] { "[submarinename]", "[amount]", "[currencyname]", "[yesvotecount]", "[novotecount]" }, new string[] { info.DisplayName, info.Price.ToString(), TextManager.Get("credit").ToLower(), yesVoteString, noVoteString });
                break;

            case VoteType.SwitchSub:
                int deliveryFee = SubmarineSelection.DeliveryFeePerDistanceTravelled * GameMain.GameSession.Map.DistanceToClosestLocationWithOutpost(GameMain.GameSession.Map.CurrentLocation, out Location endLocation);

                if (deliveryFee > 0)
                {
                    result = TextManager.GetWithVariables(votePassed ? "submarineswitchfeevotepassed" : "submarineswitchfeevotefailed", new string[] { "[submarinename]", "[locationname]", "[amount]", "[currencyname]", "[yesvotecount]", "[novotecount]" }, new string[] { info.DisplayName, endLocation.Name, deliveryFee.ToString(), TextManager.Get("credit").ToLower(), yesVoteString, noVoteString });
                }
                else
                {
                    result = TextManager.GetWithVariables(votePassed ? "submarineswitchnofeevotepassed" : "submarineswitchnofeevotefailed", new string[] { "[submarinename]", "[yesvotecount]", "[novotecount]" }, new string[] { info.DisplayName, yesVoteString, noVoteString });
                }
                break;

            default:
                break;
            }
            return(result);
        }
コード例 #8
0
        private void SetSubmarineVotingText(Client starter, SubmarineInfo info, VoteType type)
        {
            string    name                = starter.Name;
            JobPrefab prefab              = starter?.Character?.Info?.Job?.Prefab;
            Color     nameColor           = prefab != null ? prefab.UIColor : Color.White;
            string    characterRichString = $"‖color:{nameColor.R},{nameColor.G},{nameColor.B}‖{name}‖color:end‖";
            string    submarineRichString = $"‖color:{submarineColor.R},{submarineColor.G},{submarineColor.B}‖{info.DisplayName}‖color:end‖";

            switch (type)
            {
            case VoteType.PurchaseAndSwitchSub:
                votingOnText = TextManager.GetWithVariables("submarinepurchaseandswitchvote", new string[] { "[playername]", "[submarinename]", "[amount]", "[currencyname]" }, new string[] { characterRichString, submarineRichString, info.Price.ToString(), TextManager.Get("credit").ToLower() });
                break;

            case VoteType.PurchaseSub:
                votingOnText = TextManager.GetWithVariables("submarinepurchasevote", new string[] { "[playername]", "[submarinename]", "[amount]", "[currencyname]" }, new string[] { characterRichString, submarineRichString, info.Price.ToString(), TextManager.Get("credit").ToLower() });
                break;

            case VoteType.SwitchSub:
                int deliveryFee = SubmarineSelection.DeliveryFeePerDistanceTravelled * GameMain.GameSession.Map.DistanceToClosestLocationWithOutpost(GameMain.GameSession.Map.CurrentLocation, out Location endLocation);

                if (deliveryFee > 0)
                {
                    votingOnText = TextManager.GetWithVariables("submarineswitchfeevote", new string[] { "[playername]", "[submarinename]", "[locationname]", "[amount]", "[currencyname]" }, new string[] { characterRichString, submarineRichString, endLocation.Name, deliveryFee.ToString(), TextManager.Get("credit").ToLower() });
                }
                else
                {
                    votingOnText = TextManager.GetWithVariables("submarineswitchnofeevote", new string[] { "[playername]", "[submarinename]" }, new string[] { characterRichString, submarineRichString });
                }
                break;
            }

            votingOnTextData = RichTextData.GetRichTextData(votingOnText, out votingOnText);
        }
コード例 #9
0
        private void ShowBuyPrompt(bool purchaseOnly)
        {
            if (GameMain.GameSession.Campaign.Money < selectedSubmarine.Price)
            {
                new GUIMessageBox(TextManager.Get("purchasesubmarineheader"), TextManager.GetWithVariables("notenoughmoneyforpurchasetext", notEnoughCreditsPurchaseTextVariables,
                                                                                                           new string[2] {
                    currencyLongText, selectedSubmarine.DisplayName
                }));
                return;
            }

            GUIMessageBox msgBox;

            if (!purchaseOnly)
            {
                msgBox = new GUIMessageBox(TextManager.Get("purchaseandswitchsubmarineheader"), TextManager.GetWithVariables("purchaseandswitchsubmarinetext", PurchaseAndSwitchTextVariables,
                                                                                                                             new string[4] {
                    selectedSubmarine.DisplayName, selectedSubmarine.Price.ToString(), currencyLongText, CurrentOrPendingSubmarine().DisplayName
                }), messageBoxOptions);

                msgBox.Buttons[0].OnClicked = (applyButton, obj) =>
                {
                    if (GameMain.Client == null)
                    {
                        GameMain.GameSession.PurchaseSubmarine(selectedSubmarine);
                        SubmarineInfo newSub = GameMain.GameSession.SwitchSubmarine(selectedSubmarine, 0);
                        RefreshSubmarineDisplay(true);
                    }
                    else
                    {
                        GameMain.Client.InitiateSubmarineChange(selectedSubmarine, Networking.VoteType.PurchaseAndSwitchSub);
                    }
                    return(true);
                };
            }
            else
            {
                msgBox = new GUIMessageBox(TextManager.Get("purchasesubmarineheader"), TextManager.GetWithVariables("purchasesubmarinetext", PurchaseTextVariables,
                                                                                                                    new string[3] {
                    selectedSubmarine.DisplayName, selectedSubmarine.Price.ToString(), currencyLongText
                }), messageBoxOptions);

                msgBox.Buttons[0].OnClicked = (applyButton, obj) =>
                {
                    if (GameMain.Client == null)
                    {
                        GameMain.GameSession.PurchaseSubmarine(selectedSubmarine);
                        RefreshSubmarineDisplay(true);
                    }
                    else
                    {
                        GameMain.Client.InitiateSubmarineChange(selectedSubmarine, Networking.VoteType.PurchaseSub);
                    }
                    return(true);
                };
            }

            msgBox.Buttons[0].OnClicked += msgBox.Close;
            msgBox.Buttons[1].OnClicked  = msgBox.Close;
        }
コード例 #10
0
        public string GetEndMessage()
        {
            if (GameMain.Server == null || traitorList.Count <= 0)
            {
                return("");
            }

            string endMessage = "";

            foreach (Traitor traitor in traitorList)
            {
                Character traitorCharacter = traitor.Character;
                Character targetCharacter  = traitor.TargetCharacter;
                string    messageTag;

                if (targetCharacter.IsDead) //Partial or complete mission success
                {
                    if (traitorCharacter.IsDead)
                    {
                        messageTag = "TraitorEndMessageSuccessTraitorDead";
                    }
                    else if (traitorCharacter.LockHands)
                    {
                        messageTag = "TraitorEndMessageSuccessTraitorDetained";
                    }
                    else
                    {
                        messageTag = "TraitorEndMessageSuccess";
                    }
                }
                else //Partial or complete failure
                {
                    if (traitorCharacter.IsDead)
                    {
                        messageTag = "TraitorEndMessageFailureTraitorDead";
                    }
                    else if (traitorCharacter.LockHands)
                    {
                        messageTag = "TraitorEndMessageFailureTraitorDetained";
                    }
                    else
                    {
                        messageTag = "TraitorEndMessageFailure";
                    }
                }

                endMessage += (TextManager.ReplaceGenderPronouns(TextManager.GetWithVariables(messageTag, new string[2] {
                    "[traitorname]", "[targetname]"
                },
                                                                                              new string[2] {
                    traitorCharacter.Name, targetCharacter.Name
                }), traitorCharacter.Info.Gender) + "\n");
            }

            return(endMessage);
        }
コード例 #11
0
        public override string GetDescription()
        {
            if (wasDropped)
            {
                return(TextManager.GetWithVariable("Undo.DroppedItem", "[item]", Receivers.FirstOrDefault().Item.Name));
            }

            string container = "[ERROR]";

            if (Inventory.Owner is Item item)
            {
                container = item.Name;
            }

            return(Receivers.Count > 1
                ? TextManager.GetWithVariables("Undo.ContainedItemsMultiple", new[] { "[count]", "[container]" }, new[] { Receivers.Count.ToString(), container })
                : TextManager.GetWithVariables("Undo.ContainedItem", new[] { "[item]", "[container]" }, new[] { Receivers.FirstOrDefault().Item.Name, container }));
        }
コード例 #12
0
        public override string GetMissionRewardText(Submarine sub)
        {
            string rewardText = TextManager.GetWithVariable("currencyformat", "[credits]", string.Format(CultureInfo.InvariantCulture, "{0:N0}", GetReward(sub)));

            if (rewardPerCrate.HasValue)
            {
                string rewardPerCrateText = TextManager.GetWithVariable("currencyformat", "[credits]", string.Format(CultureInfo.InvariantCulture, "{0:N0}", rewardPerCrate.Value));
                return(TextManager.GetWithVariables("missionrewardcargopercrate",
                                                    new string[] { "[rewardpercrate]", "[itemcount]", "[maxitemcount]", "[totalreward]" },
                                                    new string[] { rewardPerCrateText, itemsToSpawn.Count.ToString(), maxItemCount.ToString(), $"‖color:gui.orange‖{rewardText}‖end‖" }));
            }
            else
            {
                return(TextManager.GetWithVariables("missionrewardcargo",
                                                    new string[] { "[totalreward]", "[itemcount]", "[maxitemcount]" },
                                                    new string[] { $"‖color:gui.orange‖{rewardText}‖end‖", itemsToSpawn.Count.ToString(), maxItemCount.ToString() }));
            }
        }
コード例 #13
0
        partial void OnSkillChanged(string skillIdentifier, float prevLevel, float newLevel, Vector2 textPopupPos)
        {
            if (TeamID == Character.TeamType.FriendlyNPC)
            {
                return;
            }
            if (Character.Controlled != null && Character.Controlled.TeamID != TeamID)
            {
                return;
            }

            if (newLevel - prevLevel > 0.1f)
            {
                GUI.AddMessage(
                    "+" + ((int)((newLevel - prevLevel) * 100.0f)).ToString() + " XP",
                    GUI.Style.Green,
                    textPopupPos,
                    Vector2.UnitY * 10.0f,
                    playSound: false);
            }
            else if (prevLevel % 0.1f > 0.05f && newLevel % 0.1f < 0.05f)
            {
                GUI.AddMessage(
                    "+10 XP",
                    GUI.Style.Green,
                    textPopupPos,
                    Vector2.UnitY * 10.0f,
                    playSound: false);
            }

            if ((int)newLevel > (int)prevLevel)
            {
                GUI.AddMessage(
                    TextManager.GetWithVariables("SkillIncreased", new string[3] {
                    "[name]", "[skillname]", "[newlevel]"
                },
                                                 new string[3] {
                    Name, TextManager.Get("SkillName." + skillIdentifier), ((int)newLevel).ToString()
                },
                                                 new bool[3] {
                    false, true, false
                }), GUI.Style.Green);
            }
        }
コード例 #14
0
        private void ShowTransferPrompt()
        {
            if (GameMain.GameSession.Campaign.Money < deliveryFee && deliveryFee > 0)
            {
                new GUIMessageBox(TextManager.Get("deliveryrequestheader"), TextManager.GetWithVariables("notenoughmoneyfordeliverytext", notEnoughCreditsDeliveryTextVariables,
                                                                                                         new string[] { currencyLongText, selectedSubmarine.DisplayName, deliveryLocationName, GameMain.GameSession.Map.CurrentLocation.Name }));
                return;
            }

            GUIMessageBox msgBox;

            if (deliveryFee > 0)
            {
                msgBox = new GUIMessageBox(TextManager.Get("deliveryrequestheader"), TextManager.GetWithVariables("deliveryrequesttext", DeliveryTextVariables,
                                                                                                                  new string[6] {
                    selectedSubmarine.DisplayName, deliveryLocationName, GameMain.GameSession.Map.CurrentLocation.Name, CurrentOrPendingSubmarine().DisplayName, deliveryFee.ToString(), currencyLongText
                }), messageBoxOptions);
            }
            else
            {
                msgBox = new GUIMessageBox(TextManager.Get("switchsubmarineheader"), TextManager.GetWithVariables("switchsubmarinetext", SwitchTextVariables,
                                                                                                                  new string[2] {
                    CurrentOrPendingSubmarine().DisplayName, selectedSubmarine.DisplayName
                }), messageBoxOptions);
            }

            msgBox.Buttons[0].OnClicked = (applyButton, obj) =>
            {
                if (GameMain.Client == null)
                {
                    GameMain.GameSession.SwitchSubmarine(selectedSubmarine, deliveryFee);
                    GameMain.GameSession.Campaign.UpgradeManager.RefundResetAndReload(selectedSubmarine);
                    RefreshSubmarineDisplay(true);
                }
                else
                {
                    GameMain.Client.InitiateSubmarineChange(selectedSubmarine, Networking.VoteType.SwitchSub);
                }
                return(true);
            };
            msgBox.Buttons[0].OnClicked += msgBox.Close;
            msgBox.Buttons[1].OnClicked  = msgBox.Close;
        }
コード例 #15
0
        public void Greet(GameServer server, string codeWords, string codeResponse)
        {
            string greetingMessage   = TextManager.GetWithVariable("TraitorStartMessage", "[targetname]", TargetCharacter.Name);
            string moreAgentsMessage = TextManager.GetWithVariables("TraitorMoreAgentsMessage",
                                                                    new string[2] {
                "[codewords]", "[coderesponse]"
            }, new string[2] {
                codeWords, codeResponse
            });

            var greetingChatMsg   = ChatMessage.Create(null, greetingMessage, ChatMessageType.Server, null);
            var moreAgentsChatMsg = ChatMessage.Create(null, moreAgentsMessage, ChatMessageType.Server, null);

            var greetingMsgBox   = ChatMessage.Create(null, greetingMessage, ChatMessageType.MessageBox, null);
            var moreAgentsMsgBox = ChatMessage.Create(null, moreAgentsMessage, ChatMessageType.MessageBox, null);

            Client traitorClient = server.ConnectedClients.Find(c => c.Character == Character);

            GameMain.Server.SendDirectChatMessage(greetingChatMsg, traitorClient);
            GameMain.Server.SendDirectChatMessage(moreAgentsChatMsg, traitorClient);
            GameMain.Server.SendDirectChatMessage(greetingMsgBox, traitorClient);
            GameMain.Server.SendDirectChatMessage(moreAgentsMsgBox, traitorClient);

            Client ownerClient = server.ConnectedClients.Find(c => c.Connection == server.OwnerConnection);

            if (traitorClient != ownerClient && ownerClient != null && ownerClient.Character == null)
            {
                var ownerMsg = ChatMessage.Create(
                    null,//TextManager.Get("NewTraitor"),
                    TextManager.GetWithVariables("TraitorStartMessageServer", new string[2] {
                    "[targetname]", "[traitorname]"
                }, new string[2] {
                    TargetCharacter.Name, Character.Name
                }),
                    ChatMessageType.MessageBox,
                    null
                    );
                GameMain.Server.SendDirectChatMessage(ownerMsg, ownerClient);
            }
        }
コード例 #16
0
ファイル: Order.cs プロジェクト: bengibollen/Barotrauma
        public string GetChatMessage(string targetCharacterName, string targetRoomName, bool givingOrderToSelf, string orderOption = "", int?priority = null)
        {
            priority ??= CharacterInfo.HighestManualOrderPriority;
            // If the order has a lesser priority, it means we are rearranging character orders
            if (!TargetAllCharacters && priority != CharacterInfo.HighestManualOrderPriority && Identifier != "dismissed")
            {
                return(TextManager.GetWithVariable("rearrangedorders", "[name]", targetCharacterName ?? string.Empty, returnNull: true) ?? string.Empty);
            }
            string messageTag = $"{(givingOrderToSelf && !TargetAllCharacters ? "OrderDialogSelf" : "OrderDialog")}";

            messageTag += $".{Identifier}";
            if (!string.IsNullOrEmpty(orderOption))
            {
                if (Identifier != "dismissed")
                {
                    messageTag += $".{orderOption}";
                }
                else
                {
                    string[] splitOption = orderOption.Split('.');
                    if (splitOption.Length > 0)
                    {
                        messageTag += $".{splitOption[0]}";
                    }
                }
            }
            string msg = TextManager.GetWithVariables(messageTag,
                                                      new string[2] {
                "[name]", "[roomname]"
            },
                                                      new string[2] {
                targetCharacterName ?? string.Empty, targetRoomName ?? string.Empty
            },
                                                      formatCapitals: new bool[2] {
                false, true
            },
                                                      returnNull: true);

            return(msg ?? string.Empty);
        }
コード例 #17
0
        private IEnumerable <object> DoInitialCameraTransition()
        {
            while (GameMain.Instance.LoadingScreenOpen)
            {
                yield return(CoroutineStatus.Running);
            }

            if (GameMain.Client.LateCampaignJoin)
            {
                GameMain.Client.LateCampaignJoin = false;
                yield return(CoroutineStatus.Success);
            }

            Character prevControlled = Character.Controlled;

            if (prevControlled?.AIController != null)
            {
                prevControlled.AIController.Enabled = false;
            }
            GUI.DisableHUD = true;
            if (IsFirstRound)
            {
                Character.Controlled = null;

                if (prevControlled != null)
                {
                    prevControlled.ClearInputs();
                }

                overlayColor     = Color.LightGray;
                overlaySprite    = Map.CurrentLocation.Type.GetPortrait(Map.CurrentLocation.PortraitId);
                overlayTextColor = Color.Transparent;
                overlayText      = TextManager.GetWithVariables("campaignstart",
                                                                new string[] { "xxxx", "yyyy" },
                                                                new string[] { Map.CurrentLocation.Name, TextManager.Get("submarineclass." + Submarine.MainSub.Info.SubmarineClass) });
                float fadeInDuration = 1.0f;
                float textDuration   = 10.0f;
                float timer          = 0.0f;
                while (timer < textDuration)
                {
                    // Try to grab the controlled here to prevent inputs, assigned late on multiplayer
                    if (Character.Controlled != null)
                    {
                        prevControlled       = Character.Controlled;
                        Character.Controlled = null;
                        prevControlled.ClearInputs();
                    }
                    GameMain.GameScreen.Cam.Freeze = true;
                    overlayTextColor = Color.Lerp(Color.Transparent, Color.White, (timer - 1.0f) / fadeInDuration);
                    timer            = Math.Min(timer + CoroutineManager.DeltaTime, textDuration);
                    yield return(CoroutineStatus.Running);
                }
                var transition = new CameraTransition(prevControlled, GameMain.GameScreen.Cam,
                                                      null, null,
                                                      fadeOut: false,
                                                      duration: 5,
                                                      startZoom: 1.5f, endZoom: 1.0f)
                {
                    AllowInterrupt             = true,
                    RemoveControlFromCharacter = false
                };
                fadeInDuration   = 1.0f;
                timer            = 0.0f;
                overlayTextColor = Color.Transparent;
                overlayText      = "";
                while (timer < fadeInDuration)
                {
                    overlayColor = Color.Lerp(Color.LightGray, Color.Transparent, timer / fadeInDuration);
                    timer       += CoroutineManager.DeltaTime;
                    yield return(CoroutineStatus.Running);
                }
                overlayColor = Color.Transparent;
                while (transition.Running)
                {
                    yield return(CoroutineStatus.Running);
                }

                if (prevControlled != null)
                {
                    Character.Controlled = prevControlled;
                }
            }
            else
            {
                var transition = new CameraTransition(Submarine.MainSub, GameMain.GameScreen.Cam,
                                                      null, null,
                                                      fadeOut: false,
                                                      duration: 5,
                                                      startZoom: 0.5f, endZoom: 1.0f)
                {
                    AllowInterrupt             = true,
                    RemoveControlFromCharacter = true
                };
                while (transition.Running)
                {
                    yield return(CoroutineStatus.Running);
                }
            }

            if (prevControlled != null)
            {
                prevControlled.SelectedConstruction = null;
                if (prevControlled.AIController != null)
                {
                    prevControlled.AIController.Enabled = true;
                }
            }
            GUI.DisableHUD = false;
            yield return(CoroutineStatus.Success);
        }
コード例 #18
0
 private static string readyCheckStatus(int ready, int total) => TextManager.GetWithVariables("readycheck.readycount", new[] { "[ready]", "[total]" }, new[] { ready.ToString(), total.ToString() });
コード例 #19
0
        public GUIFrame CreateSummaryFrame(string endMessage)
        {
            bool singleplayer = GameMain.NetworkMember == null;
            bool gameOver     = gameSession.CrewManager.GetCharacters().All(c => c.IsDead || c.IsUnconscious);
            bool progress     = Submarine.MainSub.AtEndPosition;

            if (!singleplayer)
            {
                SoundPlayer.OverrideMusicType     = gameOver ? "crewdead" : "endround";
                SoundPlayer.OverrideMusicDuration = 18.0f;
            }

            GUIFrame frame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker");

            int      width = 760, height = 500;
            GUIFrame innerFrame  = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.5f), frame.RectTransform, Anchor.Center, minSize: new Point(width, height)));
            var      paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), innerFrame.RectTransform, Anchor.Center))
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            GUIListBox infoTextBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.7f), paddedFrame.RectTransform))
            {
                Spacing = (int)(5 * GUI.Scale)
            };

            //spacing
            new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), infoTextBox.Content.RectTransform), style: null);

            string summaryText = TextManager.GetWithVariables(gameOver ? "RoundSummaryGameOver" :
                                                              (progress ? "RoundSummaryProgress" : "RoundSummaryReturn"), new string[2] {
                "[sub]", "[location]"
            },
                                                              new string[2] {
                Submarine.MainSub.Name, progress ? GameMain.GameSession.EndLocation.Name : GameMain.GameSession.StartLocation.Name
            });

            var infoText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform),
                                            summaryText, wrap: true);

            GUIComponent endText = null;

            if (!string.IsNullOrWhiteSpace(endMessage))
            {
                endText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform),
                                           TextManager.GetServerMessage(endMessage), wrap: true);
            }

            //don't show the mission info if the mission was not completed and there's no localized "mission failed" text available
            if (GameMain.GameSession.Mission != null)
            {
                string message = GameMain.GameSession.Mission.Completed ? GameMain.GameSession.Mission.SuccessMessage : GameMain.GameSession.Mission.FailureMessage;
                if (!string.IsNullOrEmpty(message))
                {
                    //spacing
                    var spacingTransform = new RectTransform(new Vector2(1.0f, 0.1f), infoTextBox.Content.RectTransform);

                    new GUIFrame(spacingTransform, style: null);

                    new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform),
                                     TextManager.AddPunctuation(':', TextManager.Get("Mission"), GameMain.GameSession.Mission.Name),
                                     font: GUI.LargeFont);

                    var missionInfo = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform),
                                                       message, wrap: true);

                    if (GameMain.GameSession.Mission.Completed && singleplayer)
                    {
                        var missionReward = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform),
                                                             TextManager.GetWithVariable("MissionReward", "[reward]", GameMain.GameSession.Mission.Reward.ToString()));
                    }
                }
            }

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform),
                             TextManager.Get("RoundSummaryCrewStatus"), font: GUI.LargeFont);

            GUIListBox characterListBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.4f), paddedFrame.RectTransform, minSize: new Point(0, 75)), isHorizontal: true);

            foreach (CharacterInfo characterInfo in gameSession.CrewManager.GetCharacterInfos())
            {
                if (GameMain.GameSession.Mission is CombatMission &&
                    characterInfo.TeamID != GameMain.GameSession.WinningTeam)
                {
                    continue;
                }

                var characterFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.2f, 1.0f), characterListBox.Content.RectTransform, minSize: new Point(170, 0)))
                {
                    CanBeFocused = false,
                    Stretch      = true
                };

                characterInfo.CreateCharacterFrame(characterFrame,
                                                   characterInfo.Job != null ? (characterInfo.Name + '\n' + "(" + characterInfo.Job.Name + ")") : characterInfo.Name, null);

                string statusText  = TextManager.Get("StatusOK");
                Color  statusColor = Color.DarkGreen;

                Character character = characterInfo.Character;
                if (character == null || character.IsDead)
                {
                    if (characterInfo.CauseOfDeath == null)
                    {
                        statusText = TextManager.Get("CauseOfDeathDescription.Unknown");
                    }
                    else if (characterInfo.CauseOfDeath.Type == CauseOfDeathType.Affliction && characterInfo.CauseOfDeath.Affliction == null)
                    {
                        string errorMsg = "Character \"" + character.Name + "\" had an invalid cause of death (the type of the cause of death was Affliction, but affliction was not specified).";
                        DebugConsole.ThrowError(errorMsg);
                        GameAnalyticsManager.AddErrorEventOnce("RoundSummary:InvalidCauseOfDeath", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                        statusText = TextManager.Get("CauseOfDeathDescription.Unknown");
                    }
                    else
                    {
                        statusText = characterInfo.CauseOfDeath.Type == CauseOfDeathType.Affliction ?
                                     characterInfo.CauseOfDeath.Affliction.CauseOfDeathDescription :
                                     TextManager.Get("CauseOfDeathDescription." + characterInfo.CauseOfDeath.Type.ToString());
                    }
                    statusColor = Color.DarkRed;
                }
                else
                {
                    if (character.IsUnconscious)
                    {
                        statusText  = TextManager.Get("Unconscious");
                        statusColor = Color.DarkOrange;
                    }
                    else if (character.Vitality / character.MaxVitality < 0.8f)
                    {
                        statusText  = TextManager.Get("Injured");
                        statusColor = Color.DarkOrange;
                    }
                }

                var textHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.2f), characterFrame.RectTransform, Anchor.BottomCenter), style: "InnerGlow", color: statusColor);
                new GUITextBlock(new RectTransform(Vector2.One, textHolder.RectTransform, Anchor.Center),
                                 statusText, Color.White,
                                 textAlignment: Alignment.Center,
                                 wrap: true, font: GUI.SmallFont, style: null);
            }

            new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), paddedFrame.RectTransform), isHorizontal: true, childAnchor: Anchor.BottomRight)
            {
                RelativeSpacing = 0.05f,
                UserData        = "buttonarea"
            };

            paddedFrame.Recalculate();
            foreach (GUIComponent child in infoTextBox.Content.Children)
            {
                child.CanBeFocused = false;
                if (child is GUITextBlock textBlock)
                {
                    textBlock.CalculateHeightFromText();
                }
            }

            return(frame);
        }
コード例 #20
0
        public void CreateSpecsWindow(GUIListBox parent, ScalableFont font, bool includeTitle = true, bool includeClass = true, bool includeDescription = false)
        {
            float  leftPanelWidth  = 0.6f;
            float  rightPanelWidth = 0.4f;
            string className       = !HasTag(SubmarineTag.Shuttle) ? TextManager.Get($"submarineclass.{SubmarineClass}") : TextManager.Get("shuttle");

            int classHeight       = (int)GUI.SubHeadingFont.MeasureString(className).Y;
            int leftPanelWidthInt = (int)(parent.Rect.Width * leftPanelWidth);

            GUITextBlock submarineNameText  = null;
            GUITextBlock submarineClassText = null;

            if (includeTitle)
            {
                int nameHeight = (int)GUI.LargeFont.MeasureString(DisplayName, true).Y;
                submarineNameText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, nameHeight + HUDLayoutSettings.Padding / 2), parent.Content.RectTransform), DisplayName, textAlignment: Alignment.CenterLeft, font: GUI.LargeFont)
                {
                    CanBeFocused = false
                };
                submarineNameText.RectTransform.MinSize = new Point(0, (int)submarineNameText.TextSize.Y);
            }
            if (includeClass)
            {
                submarineClassText = new GUITextBlock(new RectTransform(new Point(leftPanelWidthInt, classHeight), parent.Content.RectTransform), className, textAlignment: Alignment.CenterLeft, font: GUI.SubHeadingFont)
                {
                    CanBeFocused = false
                };
                submarineClassText.RectTransform.MinSize = new Point(0, (int)submarineClassText.TextSize.Y);
            }
            Vector2 realWorldDimensions = Dimensions * Physics.DisplayToRealWorldRatio;

            if (realWorldDimensions != Vector2.Zero)
            {
                string dimensionsStr = TextManager.GetWithVariables("DimensionsFormat", new string[2] {
                    "[width]", "[height]"
                }, new string[2] {
                    ((int)realWorldDimensions.X).ToString(), ((int)realWorldDimensions.Y).ToString()
                });
                var dimensionsText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                      TextManager.Get("Dimensions"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), dimensionsText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 dimensionsStr, textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                dimensionsText.RectTransform.MinSize = new Point(0, dimensionsText.Children.First().Rect.Height);
            }

            string cargoCapacityStr = CargoCapacity < 0 ? TextManager.Get("unknown") : TextManager.GetWithVariables("cargocapacityformat", new string[1] {
                "[cratecount]"
            }, new string[1] {
                CargoCapacity.ToString()
            });
            var cargoCapacityText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                     TextManager.Get("cargocapacity"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
            {
                CanBeFocused = false
            };

            new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), cargoCapacityText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                             cargoCapacityStr, textAlignment: Alignment.TopLeft, font: font, wrap: true)
            {
                CanBeFocused = false
            };
            cargoCapacityText.RectTransform.MinSize = new Point(0, cargoCapacityText.Children.First().Rect.Height);

            if (RecommendedCrewSizeMax > 0)
            {
                var crewSizeText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                    TextManager.Get("RecommendedCrewSize"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewSizeText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 RecommendedCrewSizeMin + " - " + RecommendedCrewSizeMax, textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                crewSizeText.RectTransform.MinSize = new Point(0, crewSizeText.Children.First().Rect.Height);
            }

            if (!string.IsNullOrEmpty(RecommendedCrewExperience))
            {
                var crewExperienceText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                          TextManager.Get("RecommendedCrewExperience"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewExperienceText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 TextManager.Get(RecommendedCrewExperience), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                crewExperienceText.RectTransform.MinSize = new Point(0, crewExperienceText.Children.First().Rect.Height);
            }

            if (RequiredContentPackages.Any())
            {
                var contentPackagesText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                           TextManager.Get("RequiredContentPackages"), textAlignment: Alignment.TopLeft, font: font)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), contentPackagesText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 string.Join(", ", RequiredContentPackages), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                contentPackagesText.RectTransform.MinSize = new Point(0, contentPackagesText.Children.First().Rect.Height);
            }

            // show what game version the submarine was created on
            if (!IsVanillaSubmarine() && GameVersion != null)
            {
                var versionText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), parent.Content.RectTransform),
                                                   TextManager.Get("serverlistversion"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), versionText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 GameVersion.ToString(), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };

                versionText.RectTransform.MinSize = new Point(0, versionText.Children.First().Rect.Height);
            }

            if (submarineNameText != null)
            {
                submarineNameText.AutoScaleHorizontal = true;
            }

            GUITextBlock descBlock = null;

            if (includeDescription)
            {
                //space
                new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), parent.Content.RectTransform), style: null);

                if (!string.IsNullOrEmpty(Description))
                {
                    var wsItemDesc = new GUITextBlock(new RectTransform(new Vector2(1, 0), parent.Content.RectTransform),
                                                      TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true)
                    {
                        CanBeFocused = false, ForceUpperCase = true
                    };

                    descBlock = new GUITextBlock(new RectTransform(new Vector2(1, 0), parent.Content.RectTransform), Description, font: font, wrap: true)
                    {
                        CanBeFocused = false
                    };
                }
            }
            GUITextBlock.AutoScaleAndNormalize(parent.Content.GetAllChildren <GUITextBlock>().Where(c => c != submarineNameText && c != descBlock));
        }
コード例 #21
0
        private void GiveTreatment(float deltaTime)
        {
            if (targetCharacter == null)
            {
                string errorMsg = $"{character.Name}: Attempted to update a Rescue objective with no target!";
                DebugConsole.ThrowError(errorMsg);
                Abandon = true;
                return;
            }

            SteeringManager?.Reset();

            if (!targetCharacter.IsPlayer)
            {
                // If the target is a bot, don't let it move
                targetCharacter.AIController?.SteeringManager?.Reset();
            }
            if (treatmentTimer > 0.0f)
            {
                treatmentTimer -= deltaTime;
                return;
            }
            treatmentTimer = TreatmentDelay;

            float cprSuitability = targetCharacter.Oxygen < 0.0f ? -targetCharacter.Oxygen * 100.0f : 0.0f;

            //find which treatments are the most suitable to treat the character's current condition
            targetCharacter.CharacterHealth.GetSuitableTreatments(currentTreatmentSuitabilities, normalize: false);

            //check if we already have a suitable treatment for any of the afflictions
            foreach (Affliction affliction in GetSortedAfflictions(targetCharacter))
            {
                if (affliction == null)
                {
                    throw new Exception("Affliction was null");
                }
                if (affliction.Prefab == null)
                {
                    throw new Exception("Affliction prefab was null");
                }
                foreach (KeyValuePair <string, float> treatmentSuitability in affliction.Prefab.TreatmentSuitability)
                {
                    if (currentTreatmentSuitabilities.ContainsKey(treatmentSuitability.Key) && currentTreatmentSuitabilities[treatmentSuitability.Key] > 0.0f)
                    {
                        Item matchingItem = character.Inventory.FindItemByIdentifier(treatmentSuitability.Key, true);
                        if (matchingItem == null)
                        {
                            continue;
                        }
                        if (targetCharacter != character)
                        {
                            character.SelectCharacter(targetCharacter);
                        }
                        ApplyTreatment(affliction, matchingItem);
                        //wait a bit longer after applying a treatment to wait for potential side-effects to manifest
                        treatmentTimer = TreatmentDelay * 4;
                        return;
                    }
                }
            }
            // Find treatments outside of own inventory only if inside the own sub.
            if (character.Submarine != null && character.Submarine.TeamID == character.TeamID)
            {
                //didn't have any suitable treatments available, try to find some medical items
                if (currentTreatmentSuitabilities.Any(s => s.Value > cprSuitability))
                {
                    itemNameList.Clear();
                    suitableItemIdentifiers.Clear();
                    foreach (KeyValuePair <string, float> treatmentSuitability in currentTreatmentSuitabilities)
                    {
                        if (treatmentSuitability.Value <= cprSuitability)
                        {
                            continue;
                        }
                        if (MapEntityPrefab.Find(null, treatmentSuitability.Key, showErrorMessages: false) is ItemPrefab itemPrefab)
                        {
                            if (!Item.ItemList.Any(it => it.prefab.Identifier == treatmentSuitability.Key))
                            {
                                continue;
                            }
                            suitableItemIdentifiers.Add(treatmentSuitability.Key);
                            //only list the first 4 items
                            if (itemNameList.Count < 4)
                            {
                                itemNameList.Add(itemPrefab.Name);
                            }
                        }
                    }
                    if (itemNameList.Any())
                    {
                        string itemListStr = "";
                        if (itemNameList.Count == 1)
                        {
                            itemListStr = itemNameList[0];
                        }
                        else
                        {
                            itemListStr = string.Join(" or ", string.Join(", ", itemNameList.Take(itemNameList.Count - 1)), itemNameList.Last());
                        }
                        if (targetCharacter != character && character.IsOnPlayerTeam)
                        {
                            character.Speak(TextManager.GetWithVariables("DialogListRequiredTreatments", new string[2] {
                                "[targetname]", "[treatmentlist]"
                            },
                                                                         new string[2] {
                                targetCharacter.Name, itemListStr
                            }, new bool[2] {
                                false, true
                            }),
                                            null, 2.0f, "listrequiredtreatments" + targetCharacter.Name, 60.0f);
                        }
                        RemoveSubObjective(ref getItemObjective);
                        TryAddSubObjective(ref getItemObjective,
                                           constructor: () => new AIObjectiveGetItem(character, suitableItemIdentifiers.ToArray(), objectiveManager, equip: true, spawnItemIfNotFound: character.TeamID == CharacterTeamType.FriendlyNPC),
                                           onCompleted: () => RemoveSubObjective(ref getItemObjective),
                                           onAbandon: () =>
                        {
                            Abandon = true;
                            if (character != targetCharacter && character.IsOnPlayerTeam)
                            {
                                character.Speak(TextManager.GetWithVariable("dialogcannottreatpatient", "[name]", targetCharacter.DisplayName, formatCapitals: false), identifier: "cannottreatpatient", minDurationBetweenSimilar: 20.0f);
                            }
                        });
                    }
                    else if (cprSuitability <= 0)
                    {
                        character.Speak(TextManager.GetWithVariable("dialogcannottreatpatient", "[name]", targetCharacter.DisplayName, formatCapitals: false), identifier: "cannottreatpatient", minDurationBetweenSimilar: 20.0f);
                        Abandon = true;
                    }
                }
            }
            else if (!targetCharacter.IsUnconscious)
            {
                //no suitable treatments found, not inside our own sub (= can't search for more treatments), the target isn't unconscious (= can't give CPR)
                character.Speak(TextManager.GetWithVariable("dialogcannottreatpatient", "[name]", targetCharacter.DisplayName, formatCapitals: false), identifier: "cannottreatpatient", minDurationBetweenSimilar: 20.0f);
                Abandon = true;
                return;
            }
            if (character != targetCharacter)
            {
                if (cprSuitability > 0.0f)
                {
                    character.SelectCharacter(targetCharacter);
                    character.AnimController.Anim = AnimController.Animation.CPR;
                }
                else
                {
                    character.DeselectCharacter();
                }
            }
        }
コード例 #22
0
        private void LoadContentPackages(IEnumerable <string> contentPackagePaths)
        {
            var missingPackagePaths  = new List <string>();
            var incompatiblePackages = new List <ContentPackage>();

            SelectedContentPackages.Clear();
            foreach (string path in contentPackagePaths)
            {
                var matchingContentPackage = ContentPackage.List.Find(cp => System.IO.Path.GetFullPath(cp.Path) == path);

                if (matchingContentPackage == null)
                {
                    missingPackagePaths.Add(path);
                }
                else if (!matchingContentPackage.IsCompatible())
                {
                    incompatiblePackages.Add(matchingContentPackage);
                }
                else
                {
                    SelectedContentPackages.Add(matchingContentPackage);
                }
            }

            TextManager.LoadTextPacks(SelectedContentPackages);

            foreach (ContentPackage contentPackage in SelectedContentPackages)
            {
                bool packageOk = contentPackage.VerifyFiles(out List <string> errorMessages);
                if (!packageOk)
                {
                    DebugConsole.ThrowError("Error in content package \"" + contentPackage.Name + "\":\n" + string.Join("\n", errorMessages));
                    continue;
                }
                foreach (ContentFile file in contentPackage.Files)
                {
                    ToolBox.IsProperFilenameCase(file.Path);
                }
            }

            EnsureCoreContentPackageSelected();

            //save to get rid of the invalid selected packages in the config file
            if (missingPackagePaths.Count > 0 || incompatiblePackages.Count > 0)
            {
                SaveNewPlayerConfig();
            }

            //display error messages after all content packages have been loaded
            //to make sure the package that contains text files has been loaded before we attempt to use TextManager
            foreach (string missingPackagePath in missingPackagePaths)
            {
                DebugConsole.ThrowError(TextManager.GetWithVariable("ContentPackageNotFound", "[packagepath]", missingPackagePath));
            }
            foreach (ContentPackage incompatiblePackage in incompatiblePackages)
            {
                DebugConsole.ThrowError(TextManager.GetWithVariables(incompatiblePackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage",
                                                                     new string[3] {
                    "[packagename]", "[packageversion]", "[gameversion]"
                }, new string[3] {
                    incompatiblePackage.Name, incompatiblePackage.GameVersion.ToString(), GameMain.Version.ToString()
                }));
            }
        }
コード例 #23
0
        private IEnumerable <object> DoInitialCameraTransition()
        {
            while (GameMain.Instance.LoadingScreenOpen)
            {
                yield return(CoroutineStatus.Running);
            }
            Character prevControlled = Character.Controlled;

            if (prevControlled?.AIController != null)
            {
                prevControlled.AIController.Enabled = false;
            }
            Character.Controlled = null;
            if (prevControlled != null)
            {
                prevControlled.ClearInputs();
            }

            GUI.DisableHUD = true;
            while (GameMain.Instance.LoadingScreenOpen)
            {
                yield return(CoroutineStatus.Running);
            }

            if (IsFirstRound || showCampaignResetText)
            {
                overlayColor     = Color.LightGray;
                overlaySprite    = Map.CurrentLocation.Type.GetPortrait(Map.CurrentLocation.PortraitId);
                overlayTextColor = Color.Transparent;
                overlayText      = TextManager.GetWithVariables(showCampaignResetText ? "campaignend4" : "campaignstart",
                                                                new string[] { "xxxx", "yyyy" },
                                                                new string[] { Map.CurrentLocation.Name, TextManager.Get("submarineclass." + Submarine.MainSub.Info.SubmarineClass) });
                string pressAnyKeyText = TextManager.Get("pressanykey");
                float  fadeInDuration  = 2.0f;
                float  textDuration    = 10.0f;
                float  timer           = 0.0f;
                while (true)
                {
                    if (timer > fadeInDuration)
                    {
                        overlayTextBottom = pressAnyKeyText;
                        if (PlayerInput.GetKeyboardState.GetPressedKeys().Length > 0 || PlayerInput.PrimaryMouseButtonClicked())
                        {
                            break;
                        }
                    }
                    overlayTextColor = Color.Lerp(Color.Transparent, Color.White, (timer - 1.0f) / fadeInDuration);
                    timer            = Math.Min(timer + CoroutineManager.DeltaTime, textDuration);
                    yield return(CoroutineStatus.Running);
                }
                var transition = new CameraTransition(prevControlled, GameMain.GameScreen.Cam,
                                                      null, null,
                                                      fadeOut: false,
                                                      duration: 5,
                                                      startZoom: 1.5f, endZoom: 1.0f)
                {
                    AllowInterrupt             = true,
                    RemoveControlFromCharacter = false
                };
                fadeInDuration   = 1.0f;
                timer            = 0.0f;
                overlayTextColor = Color.Transparent;
                overlayText      = "";
                while (timer < fadeInDuration)
                {
                    overlayColor = Color.Lerp(Color.LightGray, Color.Transparent, timer / fadeInDuration);
                    timer       += CoroutineManager.DeltaTime;
                    yield return(CoroutineStatus.Running);
                }
                overlayColor = Color.Transparent;
                while (transition.Running)
                {
                    yield return(CoroutineStatus.Running);
                }
                showCampaignResetText = false;
            }
            else
            {
                ISpatialEntity transitionTarget;
                if (prevControlled != null)
                {
                    transitionTarget = prevControlled;
                }
                else
                {
                    transitionTarget = Submarine.MainSub;
                }

                var transition = new CameraTransition(transitionTarget, GameMain.GameScreen.Cam,
                                                      null, null,
                                                      fadeOut: false,
                                                      duration: 5,
                                                      startZoom: 0.5f, endZoom: 1.0f)
                {
                    AllowInterrupt             = true,
                    RemoveControlFromCharacter = false
                };
                while (transition.Running)
                {
                    yield return(CoroutineStatus.Running);
                }
            }

            if (prevControlled != null)
            {
                prevControlled.SelectedConstruction = null;
                if (prevControlled.AIController != null)
                {
                    prevControlled.AIController.Enabled = true;
                }
            }

            if (prevControlled != null)
            {
                Character.Controlled = prevControlled;
            }
            GUI.DisableHUD = false;
            yield return(CoroutineStatus.Success);
        }
コード例 #24
0
        private string GetHeaderText(bool gameOver, CampaignMode.TransitionType transitionType)
        {
            string locationName = Submarine.MainSub.AtEndPosition ? endLocation?.Name : startLocation?.Name;

            string textTag;

            if (gameOver)
            {
                textTag = "RoundSummaryGameOver";
            }
            else
            {
                switch (transitionType)
                {
                case CampaignMode.TransitionType.LeaveLocation:
                    locationName = startLocation?.Name;
                    textTag      = "RoundSummaryLeaving";
                    break;

                case CampaignMode.TransitionType.ProgressToNextLocation:
                case CampaignMode.TransitionType.ProgressToNextEmptyLocation:
                    locationName = endLocation?.Name;
                    textTag      = "RoundSummaryProgress";
                    break;

                case CampaignMode.TransitionType.ReturnToPreviousLocation:
                case CampaignMode.TransitionType.ReturnToPreviousEmptyLocation:
                    locationName = startLocation?.Name;
                    textTag      = "RoundSummaryReturn";
                    break;

                default:
                    textTag = Submarine.MainSub.AtEndPosition ? "RoundSummaryProgress" : "RoundSummaryReturn";
                    break;
                }
            }

            if (textTag == null)
            {
                return("");
            }

            if (locationName == null)
            {
                DebugConsole.ThrowError($"Error while creating round summary: could not determine destination location. Start location: {startLocation?.Name ?? "null"}, end location: {endLocation?.Name ?? "null"}");
                locationName = "[UNKNOWN]";
            }

            string        subName          = string.Empty;
            SubmarineInfo currentOrPending = SubmarineSelection.CurrentOrPendingSubmarine();

            if (currentOrPending != null)
            {
                subName = currentOrPending.DisplayName;
            }

            return(TextManager.GetWithVariables(textTag, new string[2] {
                "[sub]", "[location]"
            }, new string[2] {
                subName, locationName
            }));
        }
コード例 #25
0
        public void CheckForErrors()
        {
            List <string> errorMsgs = new List <string>();

            if (!Hull.hullList.Any())
            {
                errorMsgs.Add(TextManager.Get("NoHullsWarning"));
            }

            if (Info.Type != SubmarineType.OutpostModule ||
                (Info.OutpostModuleInfo?.ModuleFlags.Any(f => !f.Equals("hallwayvertical", StringComparison.OrdinalIgnoreCase) && !f.Equals("hallwayhorizontal", StringComparison.OrdinalIgnoreCase)) ?? true))
            {
                if (!WayPoint.WayPointList.Any(wp => wp.ShouldBeSaved && wp.SpawnType == SpawnType.Path))
                {
                    errorMsgs.Add(TextManager.Get("NoWaypointsWarning"));
                }
            }

            if (Info.Type == SubmarineType.Player)
            {
                foreach (Item item in Item.ItemList)
                {
                    if (item.GetComponent <Items.Components.Vent>() == null)
                    {
                        continue;
                    }
                    if (!item.linkedTo.Any())
                    {
                        errorMsgs.Add(TextManager.Get("DisconnectedVentsWarning"));
                        break;
                    }
                }

                if (!WayPoint.WayPointList.Any(wp => wp.ShouldBeSaved && wp.SpawnType == SpawnType.Human))
                {
                    errorMsgs.Add(TextManager.Get("NoHumanSpawnpointWarning"));
                }
                if (WayPoint.WayPointList.Find(wp => wp.SpawnType == SpawnType.Cargo) == null)
                {
                    errorMsgs.Add(TextManager.Get("NoCargoSpawnpointWarning"));
                }
                if (!Item.ItemList.Any(it => it.GetComponent <Items.Components.Pump>() != null && it.HasTag("ballast")))
                {
                    errorMsgs.Add(TextManager.Get("NoBallastTagsWarning"));
                }
            }
            else if (Info.Type == SubmarineType.OutpostModule)
            {
                foreach (Item item in Item.ItemList)
                {
                    var junctionBox = item.GetComponent <PowerTransfer>();
                    if (junctionBox == null)
                    {
                        continue;
                    }
                    int doorLinks =
                        item.linkedTo.Count(lt => lt is Gap || (lt is Item it2 && it2.GetComponent <Door>() != null)) +
                        Item.ItemList.Count(it2 => it2.linkedTo.Contains(item) && !item.linkedTo.Contains(it2));
                    for (int i = 0; i < item.Connections.Count; i++)
                    {
                        int wireCount = item.Connections[i].Wires.Count(w => w != null);
                        if (doorLinks + wireCount > Connection.MaxLinked)
                        {
                            errorMsgs.Add(TextManager.GetWithVariables("InsufficientFreeConnectionsWarning",
                                                                       new string[] { "[doorcount]", "[freeconnectioncount]" },
                                                                       new string[] { doorLinks.ToString(), (Connection.MaxLinked - wireCount).ToString() }));
                            break;
                        }
                    }
                }
            }

            if (Gap.GapList.Any(g => g.linkedTo.Count == 0))
            {
                errorMsgs.Add(TextManager.Get("NonLinkedGapsWarning"));
            }

            int disabledItemLightCount = 0;

            foreach (Item item in Item.ItemList)
            {
                if (item.ParentInventory == null)
                {
                    continue;
                }
                disabledItemLightCount += item.GetComponents <Items.Components.LightComponent>().Count();
            }
            int count = GameMain.LightManager.Lights.Count(l => l.CastShadows) - disabledItemLightCount;

            if (count > 45)
            {
                errorMsgs.Add(TextManager.Get("subeditor.shadowcastinglightswarning"));
            }

            if (errorMsgs.Any())
            {
                new GUIMessageBox(TextManager.Get("Warning"), string.Join("\n\n", errorMsgs), new Vector2(0.25f, 0.0f), new Point(400, 200));
            }

            foreach (MapEntity e in MapEntity.mapEntityList)
            {
                if (Vector2.Distance(e.Position, HiddenSubPosition) > 20000)
                {
                    //move disabled items (wires, items inside containers) inside the sub
                    if (e is Item item && item.body != null && !item.body.Enabled)
                    {
                        item.SetTransform(ConvertUnits.ToSimUnits(HiddenSubPosition), 0.0f);
                    }
                }
            }

            foreach (MapEntity e in MapEntity.mapEntityList)
            {
                if (Vector2.Distance(e.Position, HiddenSubPosition) > 20000)
                {
                    var msgBox = new GUIMessageBox(
                        TextManager.Get("Warning"),
                        TextManager.Get("FarAwayEntitiesWarning"),
                        new string[] { TextManager.Get("Yes"), TextManager.Get("No") });

                    msgBox.Buttons[0].OnClicked += (btn, obj) =>
                    {
                        GameMain.SubEditorScreen.Cam.Position = e.WorldPosition;
                        return(true);
                    };
                    msgBox.Buttons[0].OnClicked += msgBox.Close;
                    msgBox.Buttons[1].OnClicked += msgBox.Close;

                    break;
                }
            }
        }
コード例 #26
0
        private IEnumerable <object> SendMasterServerRequest()
        {
            RestClient client = null;

            try
            {
                client = new RestClient(NetConfig.MasterServerUrl);
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Error while connecting to master server", e);
            }

            if (client == null)
            {
                yield return(CoroutineStatus.Success);
            }

            var request = new RestRequest("masterserver2.php", Method.GET);

            request.AddParameter("gamename", "barotrauma");
            request.AddParameter("action", "listservers");

            // execute the request
            masterServerResponded = false;
            var restRequestHandle = client.ExecuteAsync(request, response => MasterServerCallBack(response));

            DateTime timeOut = DateTime.Now + new TimeSpan(0, 0, 8);

            while (!masterServerResponded)
            {
                if (DateTime.Now > timeOut)
                {
                    serverList.ClearChildren();
                    restRequestHandle.Abort();
                    new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"), TextManager.Get("MasterServerTimeOutError"));
                    yield return(CoroutineStatus.Success);
                }
                yield return(CoroutineStatus.Running);
            }

            if (masterServerResponse.ErrorException != null)
            {
                serverList.ClearChildren();
                new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"), TextManager.GetWithVariable("MasterServerErrorException", "[error]", masterServerResponse.ErrorException.ToString()));
            }
            else if (masterServerResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                serverList.ClearChildren();

                switch (masterServerResponse.StatusCode)
                {
                case System.Net.HttpStatusCode.NotFound:
                    new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"),
                                      TextManager.GetWithVariable("MasterServerError404", "[masterserverurl]", NetConfig.MasterServerUrl));
                    break;

                case System.Net.HttpStatusCode.ServiceUnavailable:
                    new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"),
                                      TextManager.Get("MasterServerErrorUnavailable"));
                    break;

                default:
                    new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"),
                                      TextManager.GetWithVariables("MasterServerErrorDefault", new string[2] {
                        "[statuscode]", "[statusdescription]"
                    },
                                                                   new string[2] {
                        masterServerResponse.StatusCode.ToString(), masterServerResponse.StatusDescription
                    }));
                    break;
                }
            }
            else
            {
                UpdateServerList(masterServerResponse.Content);
            }

            yield return(CoroutineStatus.Success);
        }
コード例 #27
0
ファイル: Submarine.cs プロジェクト: jamiebidelia/Barotrauma
        public void CreatePreviewWindow(GUIComponent parent)
        {
            var upperPart      = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.BottomCenter));
            var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.TopCenter))
            {
                ScrollBarVisible = true,
                Spacing          = 5
            };

            if (PreviewImage == null)
            {
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1), upperPart.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded"));
            }
            else
            {
                var submarinePreviewBackground = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), upperPart.RectTransform))
                {
                    Color = Color.Black
                };
                new GUIImage(new RectTransform(new Vector2(1.0f, 1.0f), submarinePreviewBackground.RectTransform), PreviewImage, scaleToFit: true);
            }

            //space
            new GUIFrame(new RectTransform(new Vector2(1.0f, 0.03f), descriptionBox.Content.RectTransform), style: null);

            new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Name, font: GUI.LargeFont, wrap: true)
            {
                ForceUpperCase = true, CanBeFocused = false
            };

            float leftPanelWidth  = 0.6f;
            float rightPanelWidth = 0.4f / leftPanelWidth;

            ScalableFont font = descriptionBox.Rect.Width < 350 ? GUI.SmallFont : GUI.Font;

            Vector2 realWorldDimensions = Dimensions * Physics.DisplayToRealWorldRatio;

            if (realWorldDimensions != Vector2.Zero)
            {
                string dimensionsStr = TextManager.GetWithVariables("DimensionsFormat", new string[2] {
                    "[width]", "[height]"
                }, new string[2] {
                    ((int)realWorldDimensions.X).ToString(), ((int)realWorldDimensions.Y).ToString()
                });

                var dimensionsText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform),
                                                      TextManager.Get("Dimensions"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), dimensionsText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 dimensionsStr, textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                dimensionsText.RectTransform.MinSize = new Point(0, dimensionsText.Children.First().Rect.Height);
            }

            if (RecommendedCrewSizeMax > 0)
            {
                var crewSizeText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform),
                                                    TextManager.Get("RecommendedCrewSize"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewSizeText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 RecommendedCrewSizeMin + " - " + RecommendedCrewSizeMax, textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                crewSizeText.RectTransform.MinSize = new Point(0, crewSizeText.Children.First().Rect.Height);
            }

            if (!string.IsNullOrEmpty(RecommendedCrewExperience))
            {
                var crewExperienceText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform),
                                                          TextManager.Get("RecommendedCrewExperience"), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewExperienceText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 TextManager.Get(RecommendedCrewExperience), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                crewExperienceText.RectTransform.MinSize = new Point(0, crewExperienceText.Children.First().Rect.Height);
            }

            if (RequiredContentPackages.Any())
            {
                var contentPackagesText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform),
                                                           TextManager.Get("RequiredContentPackages"), textAlignment: Alignment.TopLeft, font: font)
                {
                    CanBeFocused = false
                };
                new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), contentPackagesText.RectTransform, Anchor.TopRight, Pivot.TopLeft),
                                 string.Join(", ", RequiredContentPackages), textAlignment: Alignment.TopLeft, font: font, wrap: true)
                {
                    CanBeFocused = false
                };
                contentPackagesText.RectTransform.MinSize = new Point(0, contentPackagesText.Children.First().Rect.Height);
            }

            GUITextBlock.AutoScaleAndNormalize(descriptionBox.Content.Children.Where(c => c is GUITextBlock).Cast <GUITextBlock>());

            //space
            new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), descriptionBox.Content.RectTransform), style: null);

            if (!string.IsNullOrEmpty(Description))
            {
                new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
                                 TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true)
                {
                    CanBeFocused = false, ForceUpperCase = true
                };
            }

            new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Description, font: font, wrap: true)
            {
                CanBeFocused = false
            };
        }
コード例 #28
0
        public void UpdateLoadMenu(IEnumerable <string> saveFiles = null)
        {
            prevSaveFiles?.Clear();
            loadGameContainer.ClearChildren();

            if (saveFiles == null)
            {
                saveFiles = SaveUtil.GetSaveFiles(isMultiplayer ? SaveUtil.SaveType.Multiplayer : SaveUtil.SaveType.Singleplayer);
            }

            var leftColumn = new GUILayoutGroup(new RectTransform(isMultiplayer ? new Vector2(1.0f, 0.85f) : new Vector2(0.5f, 1.0f), loadGameContainer.RectTransform), childAnchor: Anchor.TopCenter)
            {
                Stretch         = true,
                RelativeSpacing = 0.03f
            };

            saveList = new GUIListBox(new RectTransform(Vector2.One, leftColumn.RectTransform))
            {
                OnSelected = SelectSaveFile
            };

            if (!isMultiplayer)
            {
                new GUIButton(new RectTransform(new Vector2(0.6f, 0.08f), leftColumn.RectTransform), TextManager.Get("showinfolder"))
                {
                    OnClicked = (btn, userdata) =>
                    {
                        try
                        {
                            ToolBox.OpenFileWithShell(SaveUtil.SaveFolder);
                        }
                        catch (Exception e)
                        {
                            new GUIMessageBox(
                                TextManager.Get("error"),
                                TextManager.GetWithVariables("showinfoldererror", new string[] { "[folder]", "[errormessage]" }, new string[] { SaveUtil.SaveFolder, e.Message }));
                        }
                        return(true);
                    }
                };
            }

            foreach (string saveFile in saveFiles)
            {
                string fileName          = saveFile;
                string subName           = "";
                string saveTime          = "";
                string contentPackageStr = "";
                var    saveFrame         = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), saveList.Content.RectTransform)
                {
                    MinSize = new Point(0, 45)
                }, style: "ListBoxElement")
                {
                    UserData = saveFile
                };

                var nameText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform), "")
                {
                    CanBeFocused = false
                };

                if (!isMultiplayer)
                {
                    nameText.Text = Path.GetFileNameWithoutExtension(saveFile);
                    XDocument doc = SaveUtil.LoadGameSessionDoc(saveFile);

                    if (doc?.Root == null)
                    {
                        DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
                        nameText.TextColor = GUI.Style.Red;
                        continue;
                    }
                    if (doc.Root.GetChildElement("multiplayercampaign") != null)
                    {
                        //multiplayer campaign save in the wrong folder -> don't show the save
                        saveList.Content.RemoveChild(saveFrame);
                        continue;
                    }
                    subName           = doc.Root.GetAttributeString("submarine", "");
                    saveTime          = doc.Root.GetAttributeString("savetime", "");
                    contentPackageStr = doc.Root.GetAttributeString("selectedcontentpackages", "");

                    prevSaveFiles?.Add(saveFile);
                }
                else
                {
                    string[] splitSaveFile = saveFile.Split(';');
                    saveFrame.UserData = splitSaveFile[0];
                    fileName           = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
                    prevSaveFiles?.Add(fileName);
                    if (splitSaveFile.Length > 1)
                    {
                        subName = splitSaveFile[1];
                    }
                    if (splitSaveFile.Length > 2)
                    {
                        saveTime = splitSaveFile[2];
                    }
                    if (splitSaveFile.Length > 3)
                    {
                        contentPackageStr = splitSaveFile[3];
                    }
                }
                if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
                {
                    DateTime time = ToolBox.Epoch.ToDateTime(unixTime);
                    saveTime = time.ToString();
                }
                if (!string.IsNullOrEmpty(contentPackageStr))
                {
                    List <string> contentPackagePaths = contentPackageStr.Split('|').ToList();
                    if (!GameSession.IsCompatibleWithSelectedContentPackages(contentPackagePaths, out string errorMsg))
                    {
                        nameText.TextColor = GUI.Style.Red;
                        saveFrame.ToolTip  = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
                    }
                }

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
                                 text: subName, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };

                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), saveFrame.RectTransform),
                                 text: saveTime, textAlignment: Alignment.Right, font: GUI.SmallFont)
                {
                    CanBeFocused = false,
                    UserData     = fileName
                };
            }

            saveList.Content.RectTransform.SortChildren((c1, c2) =>
            {
                string file1            = c1.GUIComponent.UserData as string;
                string file2            = c2.GUIComponent.UserData as string;
                DateTime file1WriteTime = DateTime.MinValue;
                DateTime file2WriteTime = DateTime.MinValue;
                try
                {
                    file1WriteTime = File.GetLastWriteTime(file1);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                try
                {
                    file2WriteTime = File.GetLastWriteTime(file2);
                }
                catch
                {
                    //do nothing - DateTime.MinValue will be used and the element will get sorted at the bottom of the list
                };
                return(file2WriteTime.CompareTo(file1WriteTime));
            });

            loadGameButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomRight), TextManager.Get("LoadButton"))
            {
                OnClicked = (btn, obj) =>
                {
                    if (string.IsNullOrWhiteSpace(saveList.SelectedData as string))
                    {
                        return(false);
                    }
                    LoadGame?.Invoke(saveList.SelectedData as string);
                    if (isMultiplayer)
                    {
                        CoroutineManager.StartCoroutine(WaitForCampaignSetup(), "WaitForCampaignSetup");
                    }
                    return(true);
                },
                Enabled = false
            };
            deleteMpSaveButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.12f), loadGameContainer.RectTransform, Anchor.BottomLeft),
                                               TextManager.Get("Delete"), style: "GUIButtonSmall")
            {
                OnClicked = DeleteSave,
                Visible   = false
            };
        }
コード例 #29
0
        protected override void Act(float deltaTime)
        {
            if (character.LockHands || targetCharacter == null || targetCharacter.CurrentHull == null || targetCharacter.Removed || targetCharacter.IsDead)
            {
                Abandon = true;
                return;
            }
            var otherRescuer = targetCharacter.SelectedBy;

            if (otherRescuer != null && otherRescuer != character)
            {
                // Someone else is rescuing/holding the target.
                Abandon = otherRescuer.IsPlayer || character.GetSkillLevel("medical") < otherRescuer.GetSkillLevel("medical");
                return;
            }
            if (targetCharacter != character)
            {
                if (targetCharacter.IsIncapacitated)
                {
                    // Check if the character needs more oxygen
                    if (!ignoreOxygen && character.SelectedCharacter == targetCharacter || character.CanInteractWith(targetCharacter))
                    {
                        // Replace empty oxygen and welding fuel.
                        if (HumanAIController.HasItem(targetCharacter, AIObjectiveFindDivingGear.HEAVY_DIVING_GEAR, out IEnumerable <Item> suits, requireEquipped: true))
                        {
                            Item suit = suits.FirstOrDefault();
                            if (suit != null)
                            {
                                AIController.UnequipEmptyItems(character, suit);
                                AIController.UnequipContainedItems(character, suit, it => it.HasTag("weldingfuel"));
                            }
                        }
                        else if (HumanAIController.HasItem(targetCharacter, AIObjectiveFindDivingGear.LIGHT_DIVING_GEAR, out IEnumerable <Item> masks, requireEquipped: true))
                        {
                            Item mask = masks.FirstOrDefault();
                            if (mask != null)
                            {
                                AIController.UnequipEmptyItems(character, mask);
                                AIController.UnequipContainedItems(character, mask, it => it.HasTag("weldingfuel"));
                            }
                        }
                        bool ShouldRemoveDivingSuit() => targetCharacter.OxygenAvailable < CharacterHealth.InsufficientOxygenThreshold && targetCharacter.CurrentHull?.LethalPressure <= 0;

                        if (ShouldRemoveDivingSuit())
                        {
                            suits.ForEach(suit => suit.Drop(character));
                        }
                        else if (suits.Any() && suits.None(s => s.OwnInventory?.AllItems != null && s.OwnInventory.AllItems.Any(it => it.HasTag(AIObjectiveFindDivingGear.OXYGEN_SOURCE) && it.ConditionPercentage > 0)))
                        {
                            // The target has a suit equipped with an empty oxygen tank.
                            // Can't remove the suit, because the target needs it.
                            // If we happen to have an extra oxygen tank in the inventory, let's swap it.
                            Item spareOxygenTank = FindOxygenTank(targetCharacter) ?? FindOxygenTank(character);
                            if (spareOxygenTank != null)
                            {
                                Item suit = suits.FirstOrDefault();
                                if (suit != null)
                                {
                                    // Insert the new oxygen tank
                                    TryAddSubObjective(ref replaceOxygenObjective, () => new AIObjectiveContainItem(character, spareOxygenTank, suit.GetComponent <ItemContainer>(), objectiveManager),
                                                       onCompleted: () => RemoveSubObjective(ref replaceOxygenObjective),
                                                       onAbandon: () =>
                                    {
                                        RemoveSubObjective(ref replaceOxygenObjective);
                                        ignoreOxygen = true;
                                        if (ShouldRemoveDivingSuit())
                                        {
                                            suits.ForEach(suit => suit.Drop(character));
                                        }
                                    });
                                    return;
                                }
                            }

                            Item FindOxygenTank(Character c) =>
                            c.Inventory.FindItem(i =>
                                                 i.HasTag(AIObjectiveFindDivingGear.OXYGEN_SOURCE) &&
                                                 i.ConditionPercentage > 1 &&
                                                 i.FindParentInventory(inv => inv.Owner is Item otherItem && otherItem.HasTag("diving")) == null,
                                                 recursive: true);
                        }
                    }
                    if (HumanAIController.GetHullSafety(targetCharacter.CurrentHull, targetCharacter) < HumanAIController.HULL_SAFETY_THRESHOLD)
                    {
                        // Incapacitated target is not in a safe place -> Move to a safe place first
                        if (character.SelectedCharacter != targetCharacter)
                        {
                            if (targetCharacter.CurrentHull != null && HumanAIController.VisibleHulls.Contains(targetCharacter.CurrentHull) && targetCharacter.CurrentHull.DisplayName != null)
                            {
                                character.Speak(TextManager.GetWithVariables("DialogFoundUnconsciousTarget", new string[2] {
                                    "[targetname]", "[roomname]"
                                },
                                                                             new string[2] {
                                    targetCharacter.Name, targetCharacter.CurrentHull.DisplayName
                                }, new bool[2] {
                                    false, true
                                }),
                                                null, 1.0f, "foundunconscioustarget" + targetCharacter.Name, 60.0f);
                            }
                            // Go to the target and select it
                            if (!character.CanInteractWith(targetCharacter))
                            {
                                RemoveSubObjective(ref replaceOxygenObjective);
                                RemoveSubObjective(ref goToObjective);
                                TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(targetCharacter, character, objectiveManager)
                                {
                                    CloseEnough        = CloseEnoughToTreat,
                                    DialogueIdentifier = "dialogcannotreachpatient",
                                    TargetName         = targetCharacter.DisplayName
                                },
                                                   onCompleted: () => RemoveSubObjective(ref goToObjective),
                                                   onAbandon: () =>
                                {
                                    RemoveSubObjective(ref goToObjective);
                                    Abandon = true;
                                });
                            }
                            else
                            {
                                character.SelectCharacter(targetCharacter);
                            }
                        }
                        else
                        {
                            // Drag the character into safety
                            if (safeHull == null)
                            {
                                if (findHullTimer > 0)
                                {
                                    findHullTimer -= deltaTime;
                                }
                                else
                                {
                                    safeHull      = objectiveManager.GetObjective <AIObjectiveFindSafety>().FindBestHull(HumanAIController.VisibleHulls);
                                    findHullTimer = findHullInterval * Rand.Range(0.9f, 1.1f);
                                }
                            }
                            if (safeHull != null && character.CurrentHull != safeHull)
                            {
                                RemoveSubObjective(ref replaceOxygenObjective);
                                RemoveSubObjective(ref goToObjective);
                                TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(safeHull, character, objectiveManager),
                                                   onCompleted: () => RemoveSubObjective(ref goToObjective),
                                                   onAbandon: () =>
                                {
                                    RemoveSubObjective(ref goToObjective);
                                    safeHull = character.CurrentHull;
                                });
                            }
                        }
                    }
                }
            }

            if (subObjectives.Any())
            {
                return;
            }

            if (targetCharacter != character && !character.CanInteractWith(targetCharacter))
            {
                RemoveSubObjective(ref replaceOxygenObjective);
                RemoveSubObjective(ref goToObjective);
                // Go to the target and select it
                TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(targetCharacter, character, objectiveManager)
                {
                    CloseEnough        = CloseEnoughToTreat,
                    DialogueIdentifier = "dialogcannotreachpatient",
                    TargetName         = targetCharacter.DisplayName
                },
                                   onCompleted: () => RemoveSubObjective(ref goToObjective),
                                   onAbandon: () =>
                {
                    RemoveSubObjective(ref goToObjective);
                    Abandon = true;
                });
            }
            else
            {
                // We can start applying treatment
                if (character != targetCharacter && character.SelectedCharacter != targetCharacter)
                {
                    if (targetCharacter.CurrentHull.DisplayName != null)
                    {
                        character.Speak(TextManager.GetWithVariables("DialogFoundWoundedTarget", new string[2] {
                            "[targetname]", "[roomname]"
                        },
                                                                     new string[2] {
                            targetCharacter.Name, targetCharacter.CurrentHull.DisplayName
                        }, new bool[2] {
                            false, true
                        }),
                                        null, 1.0f, "foundwoundedtarget" + targetCharacter.Name, 60.0f);
                    }
                }
                GiveTreatment(deltaTime);
            }
        }
コード例 #30
0
        private void UpdateServerInfo(ServerInfo serverInfo)
        {
            var serverFrame = serverList.Content.FindChild(serverInfo);

            if (serverFrame == null)
            {
                return;
            }

            var serverContent = serverFrame.Children.First();

            serverContent.ClearChildren();

            var compatibleBox = new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[0], 0.9f), serverContent.RectTransform, Anchor.Center), label: "")
            {
                Enabled  = false,
                Selected =
                    serverInfo.GameVersion == GameMain.Version.ToString() &&
                    serverInfo.ContentPackagesMatch(GameMain.SelectedPackages),
                UserData = "compatible"
            };

            var passwordBox = new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[1], 0.5f), serverContent.RectTransform, Anchor.Center), label: "", style: "GUIServerListPasswordTickBox")
            {
                ToolTip  = TextManager.Get((serverInfo.HasPassword) ? "ServerListHasPassword" : "FilterPassword"),
                Selected = serverInfo.HasPassword,
                Enabled  = false,
                UserData = "password"
            };

            var serverName = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[3], 1.0f), serverContent.RectTransform), serverInfo.ServerName, style: "GUIServerListTextBox");

            var gameStartedBox = new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[4], 0.4f), serverContent.RectTransform, Anchor.Center),
                                                label: "", style: "GUIServerListRoundStartedTickBox")
            {
                ToolTip  = TextManager.Get((serverInfo.GameStarted) ? "ServerListRoundStarted" : "ServerListRoundNotStarted"),
                Selected = serverInfo.GameStarted,
                Enabled  = false
            };

            var serverPlayers = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[5], 1.0f), serverContent.RectTransform),
                                                 serverInfo.PlayerCount + "/" + serverInfo.MaxPlayers, style: "GUIServerListTextBox", textAlignment: Alignment.Right)
            {
                ToolTip = TextManager.Get("ServerListPlayers")
            };

            var serverPingText = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[6], 1.0f), serverContent.RectTransform), "?",
                                                  style: "GUIServerListTextBox", textColor: Color.White * 0.5f, textAlignment: Alignment.Right)
            {
                ToolTip = TextManager.Get("ServerListPing")
            };

            if (serverInfo.PingChecked)
            {
                serverPingText.Text = serverInfo.Ping > -1 ? serverInfo.Ping.ToString() : "?";
            }
            else if (!string.IsNullOrEmpty(serverInfo.IP))
            {
                try
                {
                    GetServerPing(serverInfo, serverPingText);
                }
                catch (NullReferenceException ex)
                {
                    DebugConsole.ThrowError("Ping is null", ex);
                }
            }

            if (GameMain.Config.UseSteamMatchmaking && serverInfo.RespondedToSteamQuery.HasValue && serverInfo.RespondedToSteamQuery.Value == false)
            {
                string toolTip = TextManager.Get("ServerListNoSteamQueryResponse");
                compatibleBox.Selected = false;
                serverContent.Children.ForEach(c => c.ToolTip = toolTip);
                serverName.TextColor    *= 0.8f;
                serverPlayers.TextColor *= 0.8f;
            }
            else if (string.IsNullOrEmpty(serverInfo.GameVersion) || !serverInfo.ContentPackageHashes.Any())
            {
                compatibleBox.Selected = false;
                new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), compatibleBox.Box.RectTransform, Anchor.Center), " ? ", Color.Yellow * 0.85f, textAlignment: Alignment.Center)
                {
                    ToolTip = TextManager.Get(string.IsNullOrEmpty(serverInfo.GameVersion) ?
                                              "ServerListUnknownVersion" :
                                              "ServerListUnknownContentPackage")
                };
            }
            else if (!compatibleBox.Selected)
            {
                string toolTip = "";
                if (serverInfo.GameVersion != GameMain.Version.ToString())
                {
                    toolTip = TextManager.GetWithVariable("ServerListIncompatibleVersion", "[version]", serverInfo.GameVersion);
                }

                for (int i = 0; i < serverInfo.ContentPackageNames.Count; i++)
                {
                    if (!GameMain.SelectedPackages.Any(cp => cp.MD5hash.Hash == serverInfo.ContentPackageHashes[i]))
                    {
                        if (toolTip != "")
                        {
                            toolTip += "\n";
                        }
                        toolTip += TextManager.GetWithVariables("ServerListIncompatibleContentPackage", new string[2] {
                            "[contentpackage]", "[hash]"
                        },
                                                                new string[2] {
                            serverInfo.ContentPackageNames[i], Md5Hash.GetShortHash(serverInfo.ContentPackageHashes[i])
                        });
                    }
                }

                serverContent.Children.ForEach(c => c.ToolTip = toolTip);

                serverName.TextColor    *= 0.5f;
                serverPlayers.TextColor *= 0.5f;
            }

            FilterServers();
        }