Unstable 0.17.0.0

This commit is contained in:
Markus Isberg
2022-02-26 02:43:01 +09:00
parent a83f375681
commit 3974067915
913 changed files with 32472 additions and 32364 deletions
@@ -15,7 +15,7 @@ namespace Barotrauma
public Action OnFinished;
private string textOverlay;
private LocalizedString textOverlay;
private float textOverlayTimer;
private Vector2 textOverlaySize;
@@ -43,15 +43,15 @@ namespace Barotrauma
{
base.Select();
textOverlay = ToolBox.WrapText(TextManager.Get("campaignend1"), GameMain.GraphicsWidth / 3, GUI.Font);
textOverlaySize = GUI.Font.MeasureString(textOverlay);
textOverlay = ToolBox.WrapText(TextManager.Get("campaignend1"), GameMain.GraphicsWidth / 3, GUIStyle.Font);
textOverlaySize = GUIStyle.Font.MeasureString(textOverlay);
textOverlayTimer = 0.0f;
video = Video.Load(GameMain.GraphicsDeviceManager.GraphicsDevice, GameMain.SoundManager, "Content/SplashScreens/Ending.webm");
video.Play();
creditsPlayer.Restart();
creditsPlayer.Visible = false;
SteamAchievementManager.UnlockAchievement("campaigncompleted", unlockClients: true);
SteamAchievementManager.UnlockAchievement("campaigncompleted".ToIdentifier(), unlockClients: true);
}
public override void Deselect()
@@ -59,7 +59,7 @@ namespace Barotrauma
video?.Dispose();
video = null;
GUI.HideCursor = false;
SoundPlayer.OverrideMusicType = null;
SoundPlayer.OverrideMusicType = Identifier.Empty;
}
public override void Update(double deltaTime)
@@ -67,7 +67,7 @@ namespace Barotrauma
if (creditsPlayer.Finished)
{
OnFinished?.Invoke();
SoundPlayer.OverrideMusicType = null;
SoundPlayer.OverrideMusicType = Identifier.Empty;
}
}
@@ -82,7 +82,7 @@ namespace Barotrauma
}
else
{
SoundPlayer.OverrideMusicType = "ending";
SoundPlayer.OverrideMusicType = "ending".ToIdentifier();
float duration = 20.0f;
float creditsDelay = 3.0f;
if (textOverlayTimer < duration + creditsDelay)
@@ -102,7 +102,7 @@ namespace Barotrauma
{
textAlpha = 1.0f;
}
GUI.Font.DrawString(spriteBatch, textOverlay, new Vector2(GameMain.GraphicsWidth, GameMain.GraphicsHeight) / 2 - textOverlaySize / 2, Color.White * textAlpha);
GUIStyle.Font.DrawString(spriteBatch, textOverlay, new Vector2(GameMain.GraphicsWidth, GameMain.GraphicsHeight) / 2 - textOverlaySize / 2, Color.White * textAlpha);
}
else
{
@@ -22,13 +22,13 @@ namespace Barotrauma
};
// New game
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SaveName"), font: GUI.SubHeadingFont, textAlignment: Alignment.BottomLeft);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SaveName"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.BottomLeft);
saveNameBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, string.Empty)
{
textFilterFunction = (string str) => { return ToolBox.RemoveInvalidFileNameChars(str); }
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("MapSeed"), font: GUI.SubHeadingFont, textAlignment: Alignment.BottomLeft);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("MapSeed"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.BottomLeft);
seedBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.03f), verticalLayout.RectTransform) { MinSize = new Point(0, 20) }, ToolBox.RandomSeed(8));
GUIFrame radiationBoxContainer
@@ -36,7 +36,7 @@ namespace Barotrauma
GUITickBox radiationEnabledTickBox = null;
if (MapGenerationParams.Instance.RadiationParams != null)
{
radiationEnabledTickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.5f), radiationBoxContainer.RectTransform, Anchor.Center), TextManager.Get("CampaignOption.EnableRadiation"), font: GUI.Style.Font)
radiationEnabledTickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.5f), radiationBoxContainer.RectTransform, Anchor.Center), TextManager.Get("CampaignOption.EnableRadiation"), font: GUIStyle.Font)
{
Selected = true,
OnSelected = box => true
@@ -44,8 +44,8 @@ namespace Barotrauma
}
var maxMissionCountSettingHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), verticalLayout.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft) { Stretch = true };
var maxMissionCountDescription = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.0f), maxMissionCountSettingHolder.RectTransform), TextManager.Get("maxmissioncount", fallBackTag: "missions"), wrap: true)
{
var maxMissionCountDescription = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.0f), maxMissionCountSettingHolder.RectTransform), TextManager.Get("maxmissioncount", "missions"), wrap: true)
{
ToolTip = TextManager.Get("maxmissioncounttooltip")
};
int maxMissionCount = GameMain.NetworkMember.ServerSettings.MaxMissionCount;
@@ -91,7 +91,7 @@ namespace Barotrauma
{
if (string.IsNullOrWhiteSpace(saveNameBox.Text))
{
saveNameBox.Flash(GUI.Style.Red);
saveNameBox.Flash(GUIStyle.Red);
return false;
}
@@ -106,7 +106,7 @@ namespace Barotrauma
return false;
}
if (string.IsNullOrEmpty(selectedSub.MD5Hash.Hash))
if (string.IsNullOrEmpty(selectedSub.MD5Hash.StringRepresentation))
{
new GUIMessageBox(TextManager.Get("error"), TextManager.Get("nohashsubmarineselected"));
return false;
@@ -127,7 +127,7 @@ namespace Barotrauma
{
var msgBox = new GUIMessageBox(TextManager.Get("ContentPackageMismatch"),
TextManager.GetWithVariable("ContentPackageMismatchWarning", "[requiredcontentpackages]", string.Join(", ", selectedSub.RequiredContentPackages)),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = msgBox.Close;
msgBox.Buttons[0].OnClicked += (button, obj) =>
@@ -147,7 +147,7 @@ namespace Barotrauma
{
var msgBox = new GUIMessageBox(TextManager.Get("ShuttleSelected"),
TextManager.Get("ShuttleWarning"),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = (button, obj) =>
{
@@ -173,7 +173,7 @@ namespace Barotrauma
StartButton.RectTransform.MaxSize = RectTransform.MaxPoint;
StartButton.Children.ForEach(c => c.RectTransform.MaxSize = RectTransform.MaxPoint);
InitialMoneyText = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1f), buttonContainer.RectTransform), "", font: GUI.Style.SmallFont, textColor: GUI.Style.Green)
InitialMoneyText = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1f), buttonContainer.RectTransform), "", font: GUIStyle.SmallFont, textColor: GUIStyle.Green)
{
TextGetter = () =>
{
@@ -195,8 +195,8 @@ namespace Barotrauma
private IEnumerable<CoroutineStatus> WaitForCampaignSetup()
{
GUI.SetCursorWaiting();
string headerText = TextManager.Get("CampaignStartingPleaseWait");
var msgBox = new GUIMessageBox(headerText, TextManager.Get("CampaignStarting"), new string[] { TextManager.Get("Cancel") });
var headerText = TextManager.Get("CampaignStartingPleaseWait");
var msgBox = new GUIMessageBox(headerText, TextManager.Get("CampaignStarting"), new LocalizedString[] { TextManager.Get("Cancel") });
msgBox.Buttons[0].OnClicked = (btn, userdata) =>
{
@@ -270,7 +270,8 @@ namespace Barotrauma
prevSaveFiles?.Add(saveFile);
string[] splitSaveFile = saveFile.Split(';');
saveFrame.UserData = splitSaveFile[0];
fileName = nameText.Text = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
fileName = Path.GetFileNameWithoutExtension(splitSaveFile[0]);
nameText.Text = fileName;
if (splitSaveFile.Length > 1) { subName = splitSaveFile[1]; }
if (splitSaveFile.Length > 2) { saveTime = splitSaveFile[2]; }
if (splitSaveFile.Length > 3) { contentPackageStr = splitSaveFile[3]; }
@@ -283,27 +284,27 @@ namespace Barotrauma
if (!string.IsNullOrEmpty(contentPackageStr))
{
List<string> contentPackagePaths = contentPackageStr.Split('|').ToList();
if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out string errorMsg))
if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out LocalizedString errorMsg))
{
nameText.TextColor = GUI.Style.Red;
nameText.TextColor = GUIStyle.Red;
saveFrame.ToolTip = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
}
}
if (!isCompatible)
{
nameText.TextColor = GUI.Style.Red;
nameText.TextColor = GUIStyle.Red;
saveFrame.ToolTip = TextManager.Get("campaignmode.incompatiblesave");
}
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
text: subName, font: GUI.SmallFont)
text: subName, font: GUIStyle.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)
text: saveTime, textAlignment: Alignment.Right, font: GUIStyle.SmallFont)
{
CanBeFocused = false,
UserData = fileName
@@ -373,8 +374,8 @@ namespace Barotrauma
string saveFile = obj as string;
if (obj == null) { return false; }
string header = TextManager.Get("deletedialoglabel");
string body = TextManager.GetWithVariable("deletedialogquestion", "[file]", Path.GetFileNameWithoutExtension(saveFile));
var header = TextManager.Get("deletedialoglabel");
var body = TextManager.GetWithVariable("deletedialogquestion", "[file]", Path.GetFileNameWithoutExtension(saveFile));
EventEditorScreen.AskForConfirmation(header, body, () =>
{
@@ -134,16 +134,16 @@ namespace Barotrauma
columnContainer.Recalculate();
// New game left side
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SaveName"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SaveName"), font: GUIStyle.SubHeadingFont);
saveNameBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, string.Empty)
{
textFilterFunction = (string str) => { return ToolBox.RemoveInvalidFileNameChars(str); }
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("MapSeed"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("MapSeed"), font: GUIStyle.SubHeadingFont);
seedBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, ToolBox.RandomSeed(8));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SelectedSub"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SelectedSub"), font: GUIStyle.SubHeadingFont);
var moddedDropdown = new GUIDropDown(new RectTransform(new Vector2(1f, 0.02f), leftColumn.RectTransform), "", 3);
moddedDropdown.AddItem(TextManager.Get("clientpermission.all"), CategoryFilter.All);
@@ -155,11 +155,11 @@ namespace Barotrauma
{
Stretch = true
};
subList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.65f), leftColumn.RectTransform)) { ScrollBarVisible = true };
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("serverlog.filter"), textAlignment: Alignment.CenterLeft, font: GUI.Font);
var searchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform, Anchor.CenterRight), font: GUI.Font, createClearButton: true);
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("serverlog.filter"), textAlignment: Alignment.CenterLeft, font: GUIStyle.Font);
var searchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform, Anchor.CenterRight), font: GUIStyle.Font, createClearButton: true);
filterContainer.RectTransform.MinSize = searchBox.RectTransform.MinSize;
searchBox.OnSelected += (sender, userdata) => { searchTitle.Visible = false; };
searchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
@@ -187,7 +187,7 @@ namespace Barotrauma
RelativeSpacing = 0.025f
};
InitialMoneyText = new GUITextBlock(new RectTransform(new Vector2(0.3f, 1f), firstPageButtonContainer.RectTransform), "", font: GUI.Style.Font, textColor: GUI.Style.Green, textAlignment: Alignment.CenterLeft)
InitialMoneyText = new GUITextBlock(new RectTransform(new Vector2(0.3f, 1f), firstPageButtonContainer.RectTransform), "", font: GUIStyle.Font, textColor: GUIStyle.Green, textAlignment: Alignment.CenterLeft)
{
TextGetter = () =>
{
@@ -200,7 +200,7 @@ namespace Barotrauma
return TextManager.GetWithVariable("campaignstartingmoney", "[money]", string.Format(CultureInfo.InvariantCulture, "{0:N0}", initialMoney));
}
};
CampaignCustomizeButton = new GUIButton(new RectTransform(new Vector2(0.25f, 1f), firstPageButtonContainer.RectTransform, Anchor.CenterLeft), TextManager.Get("SettingsButton"))
{
OnClicked = (tb, userdata) =>
@@ -218,7 +218,7 @@ namespace Barotrauma
return false;
}
};
var disclaimerBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.8f), rightColumn.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(5) }, style: "GUINotificationButton")
{
IgnoreLayoutGroups = true,
@@ -238,8 +238,8 @@ namespace Barotrauma
secondPageLayout.RelativeSpacing = 0.01f;
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.04f), secondPageLayout.RectTransform),
TextManager.Get("Crew"), font: GUI.Style.SubHeadingFont, textAlignment: Alignment.TopLeft);
TextManager.Get("Crew"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.TopLeft);
characterInfoColumns = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.86f), secondPageLayout.RectTransform), isHorizontal: true)
{
Stretch = true,
@@ -266,7 +266,7 @@ namespace Barotrauma
OnClicked = FinishSetup
};
}
public void RandomizeCrew()
{
var characterInfos = new List<(CharacterInfo Info, JobPrefab Job)>();
@@ -275,9 +275,10 @@ namespace Barotrauma
for (int i = 0; i < jobPrefab.InitialCount; i++)
{
var variant = Rand.Range(0, jobPrefab.Variants);
characterInfos.Add((new CharacterInfo(CharacterPrefab.HumanSpeciesName, jobPrefab: jobPrefab, variant: variant), jobPrefab));
characterInfos.Add((new CharacterInfo(CharacterPrefab.HumanSpeciesName, jobOrJobPrefab: jobPrefab, variant: variant), jobPrefab));
}
}
characterInfos.Sort((a, b) => Math.Sign(b.Job.MinKarma - a.Job.MinKarma));
characterInfoColumns.ClearChildren();
CharacterMenus?.ForEach(m => m.Dispose());
@@ -344,7 +345,7 @@ namespace Barotrauma
private void CreateCustomizeWindow()
{
CampaignCustomizeSettings = new GUIMessageBox("", "", new string[] { TextManager.Get("OK") }, new Vector2(0.2f, 0.2f));
CampaignCustomizeSettings = new GUIMessageBox("", "", new LocalizedString[] { TextManager.Get("OK") }, new Vector2(0.2f, 0.2f));
CampaignCustomizeSettings.Buttons[0].OnClicked += CampaignCustomizeSettings.Close;
CampaignSettingsContent = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), CampaignCustomizeSettings.Content.RectTransform, Anchor.TopCenter))
@@ -355,7 +356,7 @@ namespace Barotrauma
if (MapGenerationParams.Instance.RadiationParams != null)
{
bool prevRadiationToggleEnabled = EnableRadiationToggle?.Selected ?? true;
EnableRadiationToggle = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), CampaignSettingsContent.RectTransform), TextManager.Get("CampaignOption.EnableRadiation"), font: GUI.Style.Font)
EnableRadiationToggle = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.3f), CampaignSettingsContent.RectTransform), TextManager.Get("CampaignOption.EnableRadiation"), font: GUIStyle.Font)
{
Selected = prevRadiationToggleEnabled,
ToolTip = TextManager.Get("campaignoption.enableradiation.tooltip")
@@ -366,25 +367,25 @@ namespace Barotrauma
Stretch = true,
ToolTip = TextManager.Get("maxmissioncounttooltip")
};
var maxMissionCountDescription = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.0f), maxMissionCountSettingHolder.RectTransform), TextManager.Get("maxmissioncount", fallBackTag: "missions"), wrap: true);
var maxMissionCountDescription = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.0f), maxMissionCountSettingHolder.RectTransform), TextManager.Get("maxmissioncount", "missions"), wrap: true);
var maxMissionCountContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 1.0f), maxMissionCountSettingHolder.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft) { RelativeSpacing = 0.05f, Stretch = true };
var maxMissionCountButtons = new GUIButton[2];
maxMissionCountButtons[0] = new GUIButton(new RectTransform(new Vector2(0.15f, 0.8f), maxMissionCountContainer.RectTransform), style: "GUIButtonToggleLeft")
{
OnClicked = (button, obj) =>
{
MaxMissionCountText.Text = Math.Clamp(Int32.Parse(MaxMissionCountText.Text) - 1, CampaignSettings.MinMissionCountLimit, CampaignSettings.MaxMissionCountLimit).ToString();
MaxMissionCountText.Text = Math.Clamp(Int32.Parse(MaxMissionCountText.Text.SanitizedValue) - 1, CampaignSettings.MinMissionCountLimit, CampaignSettings.MaxMissionCountLimit).ToString();
return true;
}
};
string prevMaxMissionCountText = MaxMissionCountText?.Text ?? CampaignSettings.DefaultMaxMissionCount.ToString();
RichString prevMaxMissionCountText = MaxMissionCountText?.Text ?? CampaignSettings.DefaultMaxMissionCount.ToString();
MaxMissionCountText = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), maxMissionCountContainer.RectTransform), prevMaxMissionCountText, textAlignment: Alignment.Center, style: "GUITextBox");
maxMissionCountButtons[1] = new GUIButton(new RectTransform(new Vector2(0.15f, 0.8f), maxMissionCountContainer.RectTransform), style: "GUIButtonToggleRight")
{
OnClicked = (button, obj) =>
{
MaxMissionCountText.Text = Math.Clamp(Int32.Parse(MaxMissionCountText.Text) + 1, CampaignSettings.MinMissionCountLimit, CampaignSettings.MaxMissionCountLimit).ToString();
MaxMissionCountText.Text = Math.Clamp(Int32.Parse(MaxMissionCountText.Text.SanitizedValue) + 1, CampaignSettings.MinMissionCountLimit, CampaignSettings.MaxMissionCountLimit).ToString();
return true;
}
};
@@ -405,10 +406,10 @@ namespace Barotrauma
{
if (string.IsNullOrWhiteSpace(saveNameBox.Text))
{
saveNameBox.Flash(GUI.Style.Red);
saveNameBox.Flash(GUIStyle.Red);
return false;
}
SubmarineInfo selectedSub = null;
if (!(subList.SelectedData is SubmarineInfo)) { return false; }
@@ -420,7 +421,7 @@ namespace Barotrauma
return false;
}
if (string.IsNullOrEmpty(selectedSub.MD5Hash.Hash))
if (string.IsNullOrEmpty(selectedSub.MD5Hash.StringRepresentation))
{
((GUITextBlock)subList.SelectedComponent).TextColor = Color.DarkRed * 0.8f;
subList.SelectedComponent.CanBeFocused = false;
@@ -433,7 +434,7 @@ namespace Barotrauma
CampaignSettings settings = new CampaignSettings();
settings.RadiationEnabled = EnableRadiationToggle?.Selected ?? false;
if (MaxMissionCountText != null && Int32.TryParse(MaxMissionCountText.Text, out int missionCount))
if (MaxMissionCountText != null && Int32.TryParse(MaxMissionCountText.Text.SanitizedValue, out int missionCount))
{
settings.MaxMissionCount = missionCount;
}
@@ -448,8 +449,8 @@ namespace Barotrauma
{
var msgBox = new GUIMessageBox(TextManager.Get("ContentPackageMismatch"),
TextManager.GetWithVariable("ContentPackageMismatchWarning", "[requiredcontentpackages]", string.Join(", ", selectedSub.RequiredContentPackages)),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = msgBox.Close;
msgBox.Buttons[0].OnClicked += (button, obj) =>
{
@@ -467,7 +468,7 @@ namespace Barotrauma
{
var msgBox = new GUIMessageBox(TextManager.Get("ShuttleSelected"),
TextManager.Get("ShuttleWarning"),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = (button, obj) =>
{
@@ -499,7 +500,7 @@ namespace Barotrauma
{
var sub = child.UserData as SubmarineInfo;
if (sub == null) { return; }
child.Visible = string.IsNullOrEmpty(filter) || sub.DisplayName.ToLower().Contains(filter.ToLower());
child.Visible = string.IsNullOrEmpty(filter) || sub.DisplayName.Contains(filter.ToLower(), StringComparison.OrdinalIgnoreCase);
}
}
@@ -522,7 +523,7 @@ namespace Barotrauma
sub.CreatePreviewWindow(subPreviewContainer);
return true;
}
public void CreateDefaultSaveName()
{
string savePath = SaveUtil.CreateSavePath(SaveUtil.SaveType.Singleplayer);
@@ -555,7 +556,7 @@ namespace Barotrauma
{
var textBlock = new GUITextBlock(
new RectTransform(new Vector2(1, 0.1f), subList.Content.RectTransform) { MinSize = new Point(0, 30) },
ToolBox.LimitString(sub.DisplayName, GUI.Font, subList.Rect.Width - 65), style: "ListBoxElement")
ToolBox.LimitString(sub.DisplayName.Value, GUIStyle.Font, subList.Rect.Width - 65), style: "ListBoxElement")
{
ToolTip = sub.Description,
UserData = sub
@@ -564,13 +565,13 @@ namespace Barotrauma
if (!sub.RequiredContentPackagesInstalled)
{
textBlock.TextColor = Color.Lerp(textBlock.TextColor, Color.DarkRed, .5f);
textBlock.ToolTip = TextManager.Get("ContentPackageMismatch") + "\n\n" + textBlock.RawToolTip;
textBlock.ToolTip = TextManager.Get("ContentPackageMismatch") + "\n\n" + textBlock.ToolTip.SanitizedString;
}
var priceText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textBlock.RectTransform, Anchor.CenterRight),
TextManager.GetWithVariable("currencyformat", "[credits]", string.Format(CultureInfo.InvariantCulture, "{0:N0}", sub.Price)), textAlignment: Alignment.CenterRight, font: GUI.SmallFont)
TextManager.GetWithVariable("currencyformat", "[credits]", string.Format(CultureInfo.InvariantCulture, "{0:N0}", sub.Price)), textAlignment: Alignment.CenterRight, font: GUIStyle.SmallFont)
{
TextColor = sub.Price > CampaignMode.InitialMoney ? GUI.Style.Red : textBlock.TextColor * 0.8f,
TextColor = sub.Price > CampaignMode.InitialMoney ? GUIStyle.Red : textBlock.TextColor * 0.8f,
ToolTip = textBlock.ToolTip
};
#if !DEBUG
@@ -629,7 +630,7 @@ namespace Barotrauma
{
new GUIMessageBox(
TextManager.Get("error"),
TextManager.GetWithVariables("showinfoldererror", new string[] { "[folder]", "[errormessage]" }, new string[] { SaveUtil.SaveFolder, e.Message }));
TextManager.GetWithVariables("showinfoldererror", ("[folder]", SaveUtil.SaveFolder), ("[errormessage]", e.Message)));
}
return true;
}
@@ -653,14 +654,14 @@ namespace Barotrauma
bool isCompatible = true;
prevSaveFiles ??= new List<string>();
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;
nameText.TextColor = GUIStyle.Red;
continue;
}
if (doc.Root.GetChildElement("multiplayercampaign") != null)
@@ -672,7 +673,7 @@ namespace Barotrauma
subName = doc.Root.GetAttributeString("submarine", "");
saveTime = doc.Root.GetAttributeString("savetime", "");
isCompatible = SaveUtil.IsSaveFileCompatible(doc);
contentPackageStr = doc.Root.GetAttributeString("selectedcontentpackages", "");
contentPackageStr = doc.Root.GetAttributeStringUnrestricted("selectedcontentpackages", "");
prevSaveFiles?.Add(saveFile);
if (!string.IsNullOrEmpty(saveTime) && long.TryParse(saveTime, out long unixTime))
{
@@ -682,27 +683,27 @@ namespace Barotrauma
if (!string.IsNullOrEmpty(contentPackageStr))
{
List<string> contentPackagePaths = contentPackageStr.Split('|').ToList();
if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out string errorMsg))
if (!GameSession.IsCompatibleWithEnabledContentPackages(contentPackagePaths, out LocalizedString errorMsg))
{
nameText.TextColor = GUI.Style.Red;
nameText.TextColor = GUIStyle.Red;
saveFrame.ToolTip = string.Join("\n", errorMsg, TextManager.Get("campaignmode.contentpackagemismatchwarning"));
}
}
if (!isCompatible)
{
nameText.TextColor = GUI.Style.Red;
nameText.TextColor = GUIStyle.Red;
saveFrame.ToolTip = TextManager.Get("campaignmode.incompatiblesave");
}
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), saveFrame.RectTransform, Anchor.BottomLeft),
text: subName, font: GUI.SmallFont)
text: subName, font: GUIStyle.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)
text: saveTime, textAlignment: Alignment.Right, font: GUIStyle.SmallFont)
{
CanBeFocused = false,
UserData = fileName
@@ -782,8 +783,8 @@ namespace Barotrauma
var titleText = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.2f), saveFileFrame.RectTransform, Anchor.TopCenter)
{
RelativeOffset = new Vector2(0, 0.05f)
},
Path.GetFileNameWithoutExtension(fileName), font: GUI.LargeFont, textAlignment: Alignment.Center);
},
Path.GetFileNameWithoutExtension(fileName), font: GUIStyle.LargeFont, textAlignment: Alignment.Center);
titleText.Text = ToolBox.LimitString(titleText.Text, titleText.Font, titleText.Rect.Width);
var layoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.5f), saveFileFrame.RectTransform, Anchor.Center)
@@ -791,9 +792,9 @@ namespace Barotrauma
RelativeOffset = new Vector2(0, 0.1f)
});
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("Submarine")} : {subName}", font: GUI.SmallFont);
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("LastSaved")} : {saveTime}", font: GUI.SmallFont);
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("MapSeed")} : {mapseed}", font: GUI.SmallFont);
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("Submarine")} : {subName}", font: GUIStyle.SmallFont);
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("LastSaved")} : {saveTime}", font: GUIStyle.SmallFont);
new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform), $"{TextManager.Get("MapSeed")} : {mapseed}", font: GUIStyle.SmallFont);
new GUIButton(new RectTransform(new Vector2(0.4f, 0.15f), saveFileFrame.RectTransform, Anchor.BottomCenter)
{
@@ -812,8 +813,8 @@ namespace Barotrauma
string saveFile = obj as string;
if (obj == null) { return false; }
string header = TextManager.Get("deletedialoglabel");
string body = TextManager.GetWithVariable("deletedialogquestion", "[file]", Path.GetFileNameWithoutExtension(saveFile));
LocalizedString header = TextManager.Get("deletedialoglabel");
LocalizedString body = TextManager.GetWithVariable("deletedialogquestion", "[file]", Path.GetFileNameWithoutExtension(saveFile));
EventEditorScreen.AskForConfirmation(header, body, () =>
{
@@ -115,7 +115,7 @@ namespace Barotrauma
RelativeSpacing = 0.05f,
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), repairContent.RectTransform), "", font: GUI.LargeFont)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), repairContent.RectTransform), "", font: GUIStyle.LargeFont)
{
TextGetter = GetMoney
};
@@ -132,11 +132,11 @@ namespace Barotrauma
IgnoreLayoutGroups = true,
CanBeFocused = false
};
var repairHullsLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), repairHullsHolder.RectTransform), TextManager.Get("RepairAllWalls"), textAlignment: Alignment.Right, font: GUI.SubHeadingFont)
var repairHullsLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), repairHullsHolder.RectTransform), TextManager.Get("RepairAllWalls"), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont)
{
ForceUpperCase = true
ForceUpperCase = ForceUpperCase.Yes
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairHullsHolder.RectTransform), CampaignMode.HullRepairCost.ToString(), textAlignment: Alignment.Right, font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairHullsHolder.RectTransform), CampaignMode.HullRepairCost.ToString(), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont);
repairHullsButton = new GUIButton(new RectTransform(new Vector2(0.4f, 0.3f), repairHullsHolder.RectTransform) { MinSize = new Point(140, 0) }, TextManager.Get("Repair"))
{
OnClicked = (btn, userdata) =>
@@ -178,11 +178,11 @@ namespace Barotrauma
IgnoreLayoutGroups = true,
CanBeFocused = false
};
var repairItemsLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), repairItemsHolder.RectTransform), TextManager.Get("RepairAllItems"), textAlignment: Alignment.Right, font: GUI.SubHeadingFont)
var repairItemsLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), repairItemsHolder.RectTransform), TextManager.Get("RepairAllItems"), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont)
{
ForceUpperCase = true
ForceUpperCase = ForceUpperCase.Yes
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairItemsHolder.RectTransform), CampaignMode.ItemRepairCost.ToString(), textAlignment: Alignment.Right, font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairItemsHolder.RectTransform), CampaignMode.ItemRepairCost.ToString(), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont);
repairItemsButton = new GUIButton(new RectTransform(new Vector2(0.4f, 0.3f), repairItemsHolder.RectTransform) { MinSize = new Point(140, 0) }, TextManager.Get("Repair"))
{
OnClicked = (btn, userdata) =>
@@ -224,11 +224,11 @@ namespace Barotrauma
IgnoreLayoutGroups = true,
CanBeFocused = false
};
var replaceShuttlesLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), replaceShuttlesHolder.RectTransform), TextManager.Get("ReplaceLostShuttles"), textAlignment: Alignment.Right, font: GUI.SubHeadingFont)
var replaceShuttlesLabel = new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.3f), replaceShuttlesHolder.RectTransform), TextManager.Get("ReplaceLostShuttles"), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont)
{
ForceUpperCase = true
ForceUpperCase = ForceUpperCase.Yes
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), replaceShuttlesHolder.RectTransform), CampaignMode.ShuttleReplaceCost.ToString(), textAlignment: Alignment.Right, font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), replaceShuttlesHolder.RectTransform), CampaignMode.ShuttleReplaceCost.ToString(), textAlignment: Alignment.Right, font: GUIStyle.SubHeadingFont);
replaceShuttlesButton = new GUIButton(new RectTransform(new Vector2(0.4f, 0.3f), replaceShuttlesHolder.RectTransform) { MinSize = new Point(140, 0) }, TextManager.Get("ReplaceShuttles"))
{
OnClicked = (btn, userdata) =>
@@ -404,11 +404,11 @@ namespace Barotrauma
RelativeSpacing = 0.02f,
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Name, font: GUI.LargeFont)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Name, font: GUIStyle.LargeFont)
{
AutoScaleHorizontal = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Type.Name, font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Type.Name, font: GUIStyle.SubHeadingFont);
Sprite portrait = location.Type.GetPortrait(location.PortraitId);
portrait.EnsureLazyLoaded();
@@ -429,11 +429,11 @@ namespace Barotrauma
if (connection?.LevelData != null)
{
var biomeLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContent.RectTransform),
TextManager.Get("Biome", fallBackTag: "location"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft);
TextManager.Get("Biome", "location"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), biomeLabel.RectTransform), connection.Biome.DisplayName, textAlignment: Alignment.CenterRight);
var difficultyLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContent.RectTransform),
TextManager.Get("LevelDifficulty"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft);
TextManager.Get("LevelDifficulty"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), difficultyLabel.RectTransform), ((int)connection.LevelData.Difficulty) + " %", textAlignment: Alignment.CenterRight);
if (connection.LevelData.HasBeaconStation)
@@ -448,7 +448,7 @@ namespace Barotrauma
ToolTip = TextManager.Get(connection.LevelData.IsBeaconActive ? "BeaconStationActiveTooltip" : "BeaconStationInactiveTooltip")
};
new GUITextBlock(new RectTransform(Vector2.One, beaconStationContent.RectTransform),
TextManager.Get("submarinetype.beaconstation", fallBackTag: "beaconstationsonarlabel"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
TextManager.Get("submarinetype.beaconstation", "beaconstationsonarlabel"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{
Padding = Vector4.Zero,
ToolTip = icon.ToolTip
@@ -465,7 +465,7 @@ namespace Barotrauma
ToolTip = TextManager.Get("HuntingGroundsTooltip")
};
new GUITextBlock(new RectTransform(Vector2.One, huntingGroundsContent.RectTransform),
TextManager.Get("missionname.huntinggrounds"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
TextManager.Get("missionname.huntinggrounds"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{
Padding = Vector4.Zero,
ToolTip = icon.ToolTip
@@ -513,7 +513,7 @@ namespace Barotrauma
AbsoluteSpacing = GUI.IntScale(5)
};
var missionName = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission?.Name ?? TextManager.Get("NoMission"), font: GUI.SubHeadingFont, wrap: true);
var missionName = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission?.Name ?? TextManager.Get("NoMission"), font: GUIStyle.SubHeadingFont, wrap: true);
// missionName.RectTransform.MinSize = new Point(0, (int)(missionName.Rect.Height * 1.5f));
if (mission != null)
{
@@ -541,7 +541,7 @@ namespace Barotrauma
foreach (GUITextBlock rewardText in missionRewardTexts)
{
Mission otherMission = rewardText.UserData as Mission;
rewardText.SetRichText(otherMission.GetMissionRewardText(Submarine.MainSub));
rewardText.Text = otherMission.GetMissionRewardText(Submarine.MainSub);
}
UpdateMaxMissions(connection.OtherLocation(currentDisplayLocation));
@@ -586,17 +586,17 @@ namespace Barotrauma
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform) { MinSize = new Point(0, GUI.IntScale(10)) }, style: null);
var rewardText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission.GetMissionRewardText(Submarine.MainSub), wrap: true, parseRichText: true)
var rewardText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), RichString.Rich(mission.GetMissionRewardText(Submarine.MainSub)), wrap: true)
{
UserData = mission
};
missionRewardTexts.Add(rewardText);
string reputationText = mission.GetReputationRewardText(mission.Locations[0]);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), reputationText, wrap: true, parseRichText: true);
LocalizedString reputationText = mission.GetReputationRewardText(mission.Locations[0]);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), RichString.Rich(reputationText), wrap: true);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission.Description, wrap: true, parseRichText: true);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), RichString.Rich(mission.Description), wrap: true);
}
missionPanel.RectTransform.MinSize = new Point(0, (int)(missionTextContent.Children.Sum(c => c.Rect.Height + missionTextContent.AbsoluteSpacing) / missionTextContent.RectTransform.RelativeSize.Y) + GUI.IntScale(0));
foreach (GUIComponent child in missionTextContent.Children)
@@ -636,7 +636,7 @@ namespace Barotrauma
var buttonArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), content.RectTransform), isHorizontal: true);
new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), buttonArea.RectTransform), "", font: GUI.Style.SubHeadingFont)
new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), buttonArea.RectTransform), "", font: GUIStyle.SubHeadingFont)
{
TextGetter = () =>
{
@@ -652,7 +652,7 @@ namespace Barotrauma
if (missionList.Content.FindChild(c => c is GUITickBox tickBox && tickBox.Selected, recursive: true) == null &&
missionList.Content.Children.Any(c => c.UserData is Mission))
{
var noMissionVerification = new GUIMessageBox(string.Empty, TextManager.Get("nomissionprompt"), new string[] { TextManager.Get("yes"), TextManager.Get("no") });
var noMissionVerification = new GUIMessageBox(string.Empty, TextManager.Get("nomissionprompt"), new LocalizedString[] { TextManager.Get("yes"), TextManager.Get("no") });
noMissionVerification.Buttons[0].OnClicked = (btn, userdata) =>
{
StartRound?.Invoke();
@@ -740,7 +740,7 @@ namespace Barotrauma
}
}
public static string GetMoney()
public static LocalizedString GetMoney()
{
return TextManager.GetWithVariable("PlayerCredits", "[credits]", (GameMain.GameSession?.Campaign == null) ? "0" : string.Format(CultureInfo.InvariantCulture, "{0:N0}", GameMain.GameSession.Campaign.Money));
}
@@ -11,7 +11,7 @@ namespace Barotrauma.CharacterEditor
class Wizard
{
// Ragdoll data
private string name;
private Identifier name;
private bool isHumanoid;
private bool canEnterSubmarine = true;
private bool canWalk;
@@ -39,7 +39,7 @@ namespace Barotrauma.CharacterEditor
canEnterSubmarine = ragdoll.CanEnterSubmarine;
canWalk = ragdoll.CanWalk;
texturePath = ragdoll.Texture;
if (string.IsNullOrEmpty(texturePath) && !name.Equals(CharacterPrefab.HumanSpeciesName, StringComparison.OrdinalIgnoreCase))
if (string.IsNullOrEmpty(texturePath) && name != CharacterPrefab.HumanSpeciesName)
{
texturePath = ragdoll.Limbs.FirstOrDefault()?.GetSprite().Texture;
}
@@ -58,7 +58,7 @@ namespace Barotrauma.CharacterEditor
}
}
public static string GetCharacterEditorTranslation(string text) => CharacterEditorScreen.GetCharacterEditorTranslation(text);
public static LocalizedString GetCharacterEditorTranslation(string text) => CharacterEditorScreen.GetCharacterEditorTranslation(text);
public void Reset()
{
@@ -97,11 +97,11 @@ namespace Barotrauma.CharacterEditor
public void CreateCharacter(XElement ragdollElement, XElement characterElement = null, IEnumerable<AnimationParams> animations = null)
{
if (CharacterPrefab.Find(p => p.Identifier.Equals(name, StringComparison.OrdinalIgnoreCase)) != null)
if (CharacterPrefab.Find(p => p.Identifier == name) != null)
{
bool isSamePackage = contentPackage.GetFilesOfType(ContentType.Character).Any(c => Path.GetFileNameWithoutExtension(c).Equals(name, StringComparison.OrdinalIgnoreCase));
string verificationText = isSamePackage ? GetCharacterEditorTranslation("existingcharacterfoundreplaceverification") : GetCharacterEditorTranslation("existingcharacterfoundoverrideverification");
var msgBox = new GUIMessageBox("", verificationText, new string[] { TextManager.Get("Yes"), TextManager.Get("No") })
bool isSamePackage = contentPackage.GetFiles<CharacterFile>().Any(f => Path.GetFileNameWithoutExtension(f.Path.Value) == name);
LocalizedString verificationText = isSamePackage ? GetCharacterEditorTranslation("existingcharacterfoundreplaceverification") : GetCharacterEditorTranslation("existingcharacterfoundoverrideverification");
var msgBox = new GUIMessageBox("", verificationText, new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") })
{
UserData = "verificationprompt"
};
@@ -110,7 +110,7 @@ namespace Barotrauma.CharacterEditor
msgBox.Close();
if (CharacterEditorScreen.Instance.CreateCharacter(name, Path.GetDirectoryName(xmlPath), isHumanoid, contentPackage, ragdollElement, characterElement, animations))
{
GUI.AddMessage(GetCharacterEditorTranslation("CharacterCreated").Replace("[name]", name), GUI.Style.Green, font: GUI.Font);
GUI.AddMessage(GetCharacterEditorTranslation("CharacterCreated").Replace("[name]", name.Value), GUIStyle.Green, font: GUIStyle.Font);
}
Wizard.Instance.SelectTab(Tab.None);
return true;
@@ -126,7 +126,7 @@ namespace Barotrauma.CharacterEditor
{
if (CharacterEditorScreen.Instance.CreateCharacter(name, Path.GetDirectoryName(xmlPath), isHumanoid, contentPackage, ragdollElement, characterElement, animations))
{
GUI.AddMessage(GetCharacterEditorTranslation("CharacterCreated").Replace("[name]", name), GUI.Style.Green, font: GUI.Font);
GUI.AddMessage(GetCharacterEditorTranslation("CharacterCreated").Replace("[name]", name.Value), GUIStyle.Green, font: GUIStyle.Font);
}
Wizard.Instance.SelectTab(Tab.None);
}
@@ -141,8 +141,8 @@ namespace Barotrauma.CharacterEditor
protected override GUIMessageBox Create()
{
var box = new GUIMessageBox(GetCharacterEditorTranslation("CreateNewCharacter"), string.Empty, new string[] { TextManager.Get("Cancel"), IsCopy ? TextManager.Get("Create") : TextManager.Get("Next") }, new Vector2(0.65f, 0.9f));
box.Header.Font = GUI.LargeFont;
var box = new GUIMessageBox(GetCharacterEditorTranslation("CreateNewCharacter"), string.Empty, new LocalizedString[] { TextManager.Get("Cancel"), IsCopy ? TextManager.Get("Create") : TextManager.Get("Next") }, new Vector2(0.65f, 0.9f));
box.Header.Font = GUIStyle.LargeFont;
box.Content.ChildAnchor = Anchor.TopCenter;
box.Content.AbsoluteSpacing = 20;
int elementSize = 30;
@@ -161,7 +161,7 @@ namespace Barotrauma.CharacterEditor
void UpdatePaths()
{
string pathBase = ContentPackage == GameMain.VanillaContent ? $"Content/Characters/{Name}/{Name}"
: $"Mods/{(ContentPackage != null ? ContentPackage.Name + "/" : string.Empty)}Characters/{Name}/{Name}";
: $"{ContentPath.ModDirStr}/Characters/{Name}/{Name}";
XMLPath = $"{pathBase}.xml";
xmlPathElement.Text = XMLPath;
if (updateTexturePath)
@@ -178,12 +178,12 @@ namespace Barotrauma.CharacterEditor
{
case 0:
new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), mainElement.RectTransform, Anchor.CenterLeft), TextManager.Get("Name"));
var nameField = new GUITextBox(new RectTransform(new Vector2(0.7f, 1), mainElement.RectTransform, Anchor.CenterRight), Name ?? GetCharacterEditorTranslation("DefaultName")) { CaretColor = Color.White };
var nameField = new GUITextBox(new RectTransform(new Vector2(0.7f, 1), mainElement.RectTransform, Anchor.CenterRight), Name.Value ?? GetCharacterEditorTranslation("DefaultName").Value) { CaretColor = Color.White };
string ProcessText(string text) => text.RemoveWhitespace().CapitaliseFirstInvariant();
Name = ProcessText(nameField.Text);
Name = ProcessText(nameField.Text).ToIdentifier();
nameField.OnTextChanged += (tb, text) =>
{
Name = ProcessText(text);
Name = ProcessText(text).ToIdentifier();
UpdatePaths();
return true;
};
@@ -255,7 +255,7 @@ namespace Barotrauma.CharacterEditor
TexturePath = text;
return true;
};
string title = GetCharacterEditorTranslation("SelectTexture");
LocalizedString title = GetCharacterEditorTranslation("SelectTexture");
new GUIButton(new RectTransform(new Vector2(0.3f / texturePathElement.RectTransform.RelativeSize.X, 1.0f), texturePathElement.RectTransform, Anchor.CenterRight, Pivot.CenterLeft), title, style: "GUIButtonSmall")
{
OnClicked = (button, data) =>
@@ -305,12 +305,12 @@ namespace Barotrauma.CharacterEditor
new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), mainElement.RectTransform, Anchor.CenterLeft), TextManager.Get("ContentPackage"));
var rightContainer = new GUIFrame(new RectTransform(new Vector2(0.7f, 1), mainElement.RectTransform, Anchor.CenterRight), style: null);
contentPackageDropDown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.5f), rightContainer.RectTransform, Anchor.TopRight));
foreach (ContentPackage cp in GameMain.Config.AllEnabledPackages)
foreach (ContentPackage contentPackage in ContentPackageManager.EnabledPackages.All)
{
#if !DEBUG
if (cp == GameMain.VanillaContent) { continue; }
if (contentPackage == GameMain.VanillaContent) { continue; }
#endif
contentPackageDropDown.AddItem(cp.Name, userData: cp, toolTip: cp.Path);
contentPackageDropDown.AddItem(contentPackage.Name, userData: contentPackage, toolTip: contentPackage.Path);
}
contentPackageDropDown.OnSelected = (obj, userdata) =>
{
@@ -321,7 +321,7 @@ namespace Barotrauma.CharacterEditor
};
contentPackageDropDown.Select(0);
var contentPackageNameElement = new GUITextBox(new RectTransform(new Vector2(0.7f, 0.5f), rightContainer.RectTransform, Anchor.BottomLeft),
GetCharacterEditorTranslation("NewContentPackage"))
GetCharacterEditorTranslation("NewContentPackage").Value)
{
CaretColor = Color.White,
};
@@ -334,15 +334,16 @@ namespace Barotrauma.CharacterEditor
contentPackageNameElement.Flash();
return false;
}
if (ContentPackage.AllPackages.Any(cp => cp.Name.ToLower() == contentPackageNameElement.Text.ToLower()))
if (ContentPackageManager.AllPackages.Any(cp => cp.Name.ToLower() == contentPackageNameElement.Text.ToLower()))
{
new GUIMessageBox("", TextManager.Get("charactereditor.contentpackagenameinuse", fallBackTag: "leveleditorlevelobjnametaken"));
new GUIMessageBox("", TextManager.Get("charactereditor.contentpackagenameinuse", "leveleditorlevelobjnametaken"));
return false;
}
string modName = ToolBox.RemoveInvalidFileNameChars(contentPackageNameElement.Text);
ContentPackage = ContentPackage.CreatePackage(contentPackageNameElement.Text, Path.Combine("Mods", modName, Steam.SteamManager.MetadataFileName), false);
ContentPackage.AddPackage(ContentPackage);
GameMain.Config.EnableRegularPackage(ContentPackage);
string modName = contentPackageNameElement.Text;
var modProject = new ModProject { Name = modName };
ContentPackage = ContentPackageManager.LocalPackages.SaveAndEnableRegularMod(modProject);
contentPackageDropDown.AddItem(ContentPackage.Name, ContentPackage, ContentPackage.Path);
contentPackageDropDown.SelectItem(ContentPackage);
contentPackageNameElement.Text = "";
@@ -389,15 +390,15 @@ namespace Barotrauma.CharacterEditor
}
if (!File.Exists(TexturePath))
{
GUI.AddMessage(GetCharacterEditorTranslation("TextureDoesNotExist"), GUI.Style.Red);
texturePathElement.Flash(GUI.Style.Red);
GUI.AddMessage(GetCharacterEditorTranslation("TextureDoesNotExist"), GUIStyle.Red);
texturePathElement.Flash(GUIStyle.Red);
return false;
}
var path = Path.GetFileName(TexturePath);
if (!path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
{
GUI.AddMessage(TextManager.Get("WrongFileType"), GUI.Style.Red);
texturePathElement.Flash(GUI.Style.Red);
GUI.AddMessage(TextManager.Get("WrongFileType"), GUIStyle.Red);
texturePathElement.Flash(GUIStyle.Red);
return false;
}
if (IsCopy)
@@ -427,8 +428,8 @@ namespace Barotrauma.CharacterEditor
protected override GUIMessageBox Create()
{
var box = new GUIMessageBox(GetCharacterEditorTranslation("DefineRagdoll"), string.Empty, new string[] { TextManager.Get("Previous"), TextManager.Get("Create") }, new Vector2(0.65f, 1f));
box.Header.Font = GUI.LargeFont;
var box = new GUIMessageBox(GetCharacterEditorTranslation("DefineRagdoll"), string.Empty, new LocalizedString[] { TextManager.Get("Previous"), TextManager.Get("Create") }, new Vector2(0.65f, 1f));
box.Header.Font = GUIStyle.LargeFont;
box.Content.ChildAnchor = Anchor.TopCenter;
box.Content.AbsoluteSpacing = (int)(20 * GUI.Scale);
int elementSize = (int)(40 * GUI.Scale);
@@ -453,7 +454,7 @@ namespace Barotrauma.CharacterEditor
Stretch = true,
RelativeSpacing = 0.02f
};
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1f), limbEditLayout.RectTransform), GetCharacterEditorTranslation("Limbs"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1f), limbEditLayout.RectTransform), GetCharacterEditorTranslation("Limbs"), font: GUIStyle.SubHeadingFont);
var limbsList = new GUIListBox(new RectTransform(new Vector2(1, 0.45f), content.RectTransform));
var removeLimbButton = new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), limbEditLayout.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "GUIMinusButton")
{
@@ -494,10 +495,10 @@ namespace Barotrauma.CharacterEditor
for (int i = 3; i >= 0; i--)
{
var element = new GUIFrame(new RectTransform(new Vector2(0.22f, 1), inputArea.RectTransform) { MinSize = new Point(50, 0), MaxSize = new Point(150, 50) }, style: null);
new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), element.RectTransform, Anchor.CenterLeft), GUI.rectComponentLabels[i], font: GUI.SmallFont, textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), element.RectTransform, Anchor.CenterLeft), GUI.RectComponentLabels[i], font: GUIStyle.SmallFont, textAlignment: Alignment.CenterLeft);
GUINumberInput numberInput = new GUINumberInput(new RectTransform(new Vector2(0.7f, 1), element.RectTransform, Anchor.CenterRight), GUINumberInput.NumberType.Int)
{
Font = GUI.SmallFont
Font = GUIStyle.SmallFont
};
switch (i)
{
@@ -623,7 +624,7 @@ namespace Barotrauma.CharacterEditor
// Joints
new GUIFrame(new RectTransform(new Vector2(1, 0.05f), content.RectTransform), style: null) { CanBeFocused = false };
var jointsElement = new GUIFrame(new RectTransform(new Vector2(1, 0.05f), content.RectTransform), style: null) { CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1f), jointsElement.RectTransform), GetCharacterEditorTranslation("Joints"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1f), jointsElement.RectTransform), GetCharacterEditorTranslation("Joints"), font: GUIStyle.SubHeadingFont);
var jointButtonElement = new GUIFrame(new RectTransform(new Vector2(0.5f, 1f), jointsElement.RectTransform)
{
RelativeOffset = new Vector2(0.15f, 0)
@@ -658,12 +659,12 @@ namespace Barotrauma.CharacterEditor
{
if (htmlBox == null)
{
htmlBox = new GUIMessageBox(GetCharacterEditorTranslation("LoadHTML"), string.Empty, new string[] { TextManager.Get("Close"), TextManager.Get("Load") }, new Vector2(0.65f, 1f));
htmlBox.Header.Font = GUI.LargeFont;
htmlBox = new GUIMessageBox(GetCharacterEditorTranslation("LoadHTML"), string.Empty, new LocalizedString[] { TextManager.Get("Close"), TextManager.Get("Load") }, new Vector2(0.65f, 1f));
htmlBox.Header.Font = GUIStyle.LargeFont;
var element = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.05f), htmlBox.Content.RectTransform), style: null, color: Color.Gray * 0.25f);
//new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), element.RectTransform), GetCharacterEditorTranslation("HTMLPath"));
var htmlPathElement = new GUITextBox(new RectTransform(new Vector2(0.7f, 1), element.RectTransform, Anchor.TopRight), GetCharacterEditorTranslation("HTMLPath"));
string title = GetCharacterEditorTranslation("SelectFile");
var htmlPathElement = new GUITextBox(new RectTransform(new Vector2(0.7f, 1), element.RectTransform, Anchor.TopRight), GetCharacterEditorTranslation("HTMLPath").Value);
LocalizedString title = GetCharacterEditorTranslation("SelectFile");
new GUIButton(new RectTransform(new Vector2(0.3f, 1), element.RectTransform), title)
{
OnClicked = (button, data) =>
@@ -732,14 +733,14 @@ namespace Barotrauma.CharacterEditor
LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.Equals("head", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (main == null)
{
GUI.AddMessage(GetCharacterEditorTranslation("MissingTorsoOrHead"), GUI.Style.Red);
GUI.AddMessage(GetCharacterEditorTranslation("MissingTorsoOrHead"), GUIStyle.Red);
return false;
}
if (IsHumanoid)
{
if (!IsValid(LimbXElements.Values, true, out string missingType))
{
GUI.AddMessage(GetCharacterEditorTranslation("MissingLimbType").Replace("[limbtype]", missingType.FormatCamelCaseWithSpaces()), GUI.Style.Red);
GUI.AddMessage(GetCharacterEditorTranslation("MissingLimbType").Replace("[limbtype]", missingType.FormatCamelCaseWithSpaces()), GUIStyle.Red);
return false;
}
}
@@ -829,11 +830,11 @@ namespace Barotrauma.CharacterEditor
CanBeFocused = false
};
var group = new GUILayoutGroup(new RectTransform(Vector2.One, limbElement.RectTransform)) { AbsoluteSpacing = 16 };
var label = new GUITextBlock(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), name, font: GUI.SubHeadingFont);
var label = new GUITextBlock(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), name, font: GUIStyle.SubHeadingFont);
var idField = new GUIFrame(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), style: null);
var nameField = new GUIFrame(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), style: null);
var limbTypeField = GUI.CreateEnumField(limbType, elementSize, GetCharacterEditorTranslation("LimbType"), group.RectTransform, font: GUI.Font);
var sourceRectField = GUI.CreateRectangleField(sourceRect ?? new Rectangle(0, 100 * LimbGUIElements.Count, 100, 100), elementSize, GetCharacterEditorTranslation("SourceRectangle"), group.RectTransform, font: GUI.Font);
var limbTypeField = GUI.CreateEnumField(limbType, elementSize, GetCharacterEditorTranslation("LimbType"), group.RectTransform, font: GUIStyle.Font);
var sourceRectField = GUI.CreateRectangleField(sourceRect ?? new Rectangle(0, 100 * LimbGUIElements.Count, 100, 100), elementSize, GetCharacterEditorTranslation("SourceRectangle"), group.RectTransform, font: GUIStyle.Font);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1), idField.RectTransform, Anchor.TopLeft), GetCharacterEditorTranslation("ID"));
new GUINumberInput(new RectTransform(new Vector2(0.5f, 1), idField.RectTransform, Anchor.TopRight), GUINumberInput.NumberType.Int)
{
@@ -869,7 +870,7 @@ namespace Barotrauma.CharacterEditor
CanBeFocused = false
};
var group = new GUILayoutGroup(new RectTransform(Vector2.One, jointElement.RectTransform)) { AbsoluteSpacing = 2 };
var label = new GUITextBlock(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), jointName, font: GUI.SubHeadingFont);
var label = new GUITextBlock(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), jointName, font: GUIStyle.SubHeadingFont);
var nameField = new GUIFrame(new RectTransform(new Point(group.Rect.Width, elementSize), group.RectTransform), style: null);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1), nameField.RectTransform, Anchor.TopLeft), TextManager.Get("Name"));
var nameInput = new GUITextBox(new RectTransform(new Vector2(0.5f, 1), nameField.RectTransform, Anchor.TopRight), jointName)
@@ -898,8 +899,8 @@ namespace Barotrauma.CharacterEditor
MaxValueInt = byte.MaxValue,
IntValue = id2
};
GUI.CreateVector2Field(anchor1 ?? Vector2.Zero, elementSize, GetCharacterEditorTranslation("LimbWithIndexAnchor").Replace("[index]", "1"), group.RectTransform, font: GUI.Font, decimalsToDisplay: 2);
GUI.CreateVector2Field(anchor2 ?? Vector2.Zero, elementSize, GetCharacterEditorTranslation("LimbWithIndexAnchor").Replace("[index]", "2"), group.RectTransform, font: GUI.Font, decimalsToDisplay: 2);
GUI.CreateVector2Field(anchor1 ?? Vector2.Zero, elementSize, GetCharacterEditorTranslation("LimbWithIndexAnchor").Replace("[index]", "1"), group.RectTransform, font: GUIStyle.Font, decimalsToDisplay: 2);
GUI.CreateVector2Field(anchor2 ?? Vector2.Zero, elementSize, GetCharacterEditorTranslation("LimbWithIndexAnchor").Replace("[index]", "2"), group.RectTransform, font: GUIStyle.Font, decimalsToDisplay: 2);
label.Text = GetJointName(jointName);
limb1InputField.OnValueChanged += nInput => label.Text = GetJointName(jointName);
limb2InputField.OnValueChanged += nInput => label.Text = GetJointName(jointName);
@@ -917,7 +918,7 @@ namespace Barotrauma.CharacterEditor
public CharacterParams SourceCharacter => Instance.SourceCharacter;
public RagdollParams SourceRagdoll => Instance.SourceRagdoll;
public string Name
public Identifier Name
{
get => Instance.name;
set => Instance.name = value;
@@ -1005,7 +1006,7 @@ namespace Barotrauma.CharacterEditor
{
var limbGUIElement = LimbGUIElements[i];
var allChildren = limbGUIElement.GetAllChildren();
GUITextBlock GetField(string n) => allChildren.First(c => c is GUITextBlock textBlock && textBlock.Text == n) as GUITextBlock;
GUITextBlock GetField(LocalizedString n) => allChildren.First(c => c is GUITextBlock textBlock && textBlock.Text == n) as GUITextBlock;
int id = GetField(GetCharacterEditorTranslation("ID")).Parent.GetChild<GUINumberInput>().IntValue;
string limbName = GetField(TextManager.Get("Name")).Parent.GetChild<GUITextBox>().Text;
LimbType limbType = (LimbType)GetField(GetCharacterEditorTranslation("LimbType")).Parent.GetChild<GUIDropDown>().SelectedData;
@@ -1056,7 +1057,7 @@ namespace Barotrauma.CharacterEditor
{
var jointGUIElement = JointGUIElements[i];
var allChildren = jointGUIElement.GetAllChildren();
GUITextBlock GetField(string n) => allChildren.First(c => c is GUITextBlock textBlock && textBlock.Text == n) as GUITextBlock;
GUITextBlock GetField(LocalizedString n) => allChildren.First(c => c is GUITextBlock textBlock && textBlock.Text == n) as GUITextBlock;
string jointName = GetField(TextManager.Get("Name")).Parent.GetChild<GUITextBox>().Text;
int limb1ID = GetField(GetCharacterEditorTranslation("LimbWithIndex").Replace("[index]", "1")).Parent.GetChild<GUINumberInput>().IntValue;
int limb2ID = GetField(GetCharacterEditorTranslation("LimbWithIndex").Replace("[index]", "2")).Parent.GetChild<GUINumberInput>().IntValue;
@@ -8,7 +8,7 @@ namespace Barotrauma
{
private GUIListBox listBox;
private XElement configElement;
private ContentXElement configElement;
private float scrollSpeed;
@@ -48,7 +48,7 @@ namespace Barotrauma
var doc = XMLExtensions.TryLoadXml(configFile);
if (doc == null) { return; }
configElement = doc.Root;
configElement = doc.Root.FromPackage(ContentPackageManager.VanillaCorePackage);
Load();
}
@@ -63,7 +63,7 @@ namespace Barotrauma
Spacing = spacing
};
foreach (XElement subElement in configElement.Elements())
foreach (var subElement in configElement.Elements())
{
FromXML(subElement, listBox.Content.RectTransform);
}
@@ -93,7 +93,7 @@ namespace Barotrauma
public bool EditorMode;
private string editModeText = "";
private LocalizedString editModeText = "";
private Vector2 textSize = Vector2.Zero;
public void Save(XElement element)
@@ -117,7 +117,7 @@ namespace Barotrauma
{
Clear(alsoPending: true);
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
EditorImageContainer? tempImage = EditorImageContainer.Load(subElement);
if (tempImage != null)
@@ -130,7 +130,7 @@ namespace Barotrauma
public void OnEditorSelected()
{
editModeText = TextManager.Get("SubEditor.ImageEditingMode");
textSize = GUI.LargeFont.MeasureString(editModeText);
textSize = GUIStyle.LargeFont.MeasureString(editModeText);
TryLoadPendingImages();
}
@@ -267,7 +267,7 @@ namespace Barotrauma
pos.Y = -pos.Y;
Images.Add(new EditorImage(file, pos) { DrawTarget = EditorImage.DrawTargetType.World });
UpdateImageCategories();
GameMain.Config.SaveNewPlayerConfig();
GameSettings.SaveCurrentConfig();
};
FileSelection.ClearFileTypeFilters();
@@ -287,7 +287,7 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState);
Vector2 textPos = new Vector2(GameMain.GraphicsWidth / 2f - (textSize.X / 2f), GameMain.GraphicsHeight / 10f - (textSize.Y / 2f));
GUI.DrawString(spriteBatch, textPos, editModeText, GUI.Style.Yellow, Color.Black * 0.4f, 8, GUI.LargeFont);
GUI.DrawString(spriteBatch, textPos, editModeText, GUIStyle.Yellow, Color.Black * 0.4f, 8, GUIStyle.LargeFont);
spriteBatch.End();
}
@@ -352,7 +352,7 @@ namespace Barotrauma
public EditorImage(string path, Vector2 pos)
{
Image = Sprite.LoadTexture(path, out Sprite _, compress: false);
Image = Sprite.LoadTexture(path, compress: false);
ImagePath = path;
Position = pos;
UpdateRectangle();
@@ -440,7 +440,7 @@ namespace Barotrauma
{
widget.MouseDown += () =>
{
widget.color = GUI.Style.Green;
widget.color = GUIStyle.Green;
prevAngle = Rotation;
disableMove = true;
};
@@ -493,7 +493,7 @@ namespace Barotrauma
});
currentWidget.Draw(spriteBatch, (float) Timing.Step);
GUI.DrawLine(spriteBatch, Position, currentWidget.DrawPos, GUI.Style.Green, width: width);
GUI.DrawLine(spriteBatch, Position, currentWidget.DrawPos, GUIStyle.Green, width: width);
}
private float GetRotationAngle(Vector2 drawPosition)
@@ -561,7 +561,7 @@ namespace Barotrauma
width = (int) (width / cam.Zoom);
}
GUI.DrawRectangle(spriteBatch, bounds, Selected ? GUI.Style.Red : GUI.Style.Green, thickness: width);
GUI.DrawRectangle(spriteBatch, bounds, Selected ? GUIStyle.Red : GUIStyle.Green, thickness: width);
if (Selected)
{
DrawWidgets(spriteBatch);
@@ -4,7 +4,8 @@ namespace Barotrauma
{
class EditorScreen : Screen
{
public static Color BackgroundColor = GameSettings.SubEditorBackgroundColor;
public static Color BackgroundColor = GameSettings.CurrentConfig.SubEditorBackground;
public override bool IsEditor => true;
public void CreateBackgroundColorPicker()
{
@@ -17,7 +18,7 @@ namespace Barotrauma
for (int i = 0; i < 3; i++)
{
var colorContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.33f, 1), rgbLayout.RectTransform), isHorizontal: true) { Stretch = true };
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), colorContainer.RectTransform, Anchor.CenterLeft) { MinSize = new Point(15, 0) }, GUI.colorComponentLabels[i], font: GUI.SmallFont, textAlignment: Alignment.Center);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), colorContainer.RectTransform, Anchor.CenterLeft) { MinSize = new Point(15, 0) }, GUI.ColorComponentLabels[i], font: GUIStyle.SmallFont, textAlignment: Alignment.Center);
layoutParents[i] = colorContainer;
}
@@ -33,7 +34,9 @@ namespace Barotrauma
{
var color = new Color(rInput.IntValue, gInput.IntValue, bInput.IntValue);
BackgroundColor = color;
GameSettings.SubEditorBackgroundColor = color;
var config = GameSettings.CurrentConfig;
config.SubEditorBackground = color;
GameSettings.SetCurrentConfig(config);
};
// Reset button
@@ -49,7 +52,7 @@ namespace Barotrauma
msgBox.Buttons[1].OnClicked = (button, o) =>
{
msgBox.Close();
GameMain.Config.SaveNewPlayerConfig();
GameSettings.SaveCurrentConfig();
return true;
};
}
@@ -63,10 +63,10 @@ namespace Barotrauma
connectionElement.Add(new XAttribute("optiontext", connection.OptionText));
}
if (!string.IsNullOrWhiteSpace(connection.OverrideValue?.ToString()))
if (connection.OverrideValue is { } overrideValue && !string.IsNullOrWhiteSpace(connection.OverrideValue?.ToString()))
{
connectionElement.Add(new XAttribute("overridevalue", connection.OverrideValue?.ToString()));
connectionElement.Add(new XAttribute("valuetype", connection.OverrideValue?.GetType().ToString()));
connectionElement.Add(new XAttribute("overridevalue", overrideValue.ToString() ?? string.Empty));
connectionElement.Add(new XAttribute("valuetype", overrideValue.GetType().ToString()));
}
foreach (var nodeConnection in connection.ConnectedTo)
@@ -85,7 +85,7 @@ namespace Barotrauma
public void LoadConnections(XElement element)
{
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
int id = subElement.GetAttributeInt("i", -1);
string? connectionType = subElement.GetAttributeString("type", null);
@@ -170,9 +170,9 @@ namespace Barotrauma
{
if (connection.Type == NodeConnectionType.Value)
{
if (connection.GetValue() != null)
if (connection.GetValue() is { } connValue)
{
newElement.Add(new XAttribute(connection.Attribute?.ToLowerInvariant(), connection.GetValue()));
newElement.Add(new XAttribute(connection.Attribute.ToLowerInvariant(), connValue));
}
}
}
@@ -269,8 +269,8 @@ namespace Barotrauma
}
}
Vector2 headerSize = GUI.SubHeadingFont.MeasureString(Name);
GUI.SubHeadingFont.DrawString(spriteBatch, Name, HeaderRectangle.Location.ToVector2() + (HeaderRectangle.Size.ToVector2() / 2) - (headerSize / 2), fontColor);
Vector2 headerSize = GUIStyle.SubHeadingFont.MeasureString(Name);
GUIStyle.SubHeadingFont.DrawString(spriteBatch, Name, HeaderRectangle.Location.ToVector2() + (HeaderRectangle.Size.ToVector2() / 2) - (headerSize / 2), fontColor);
}
public virtual void AddOption()
@@ -445,13 +445,13 @@ namespace Barotrauma
nodeValue = value;
if (value is string str)
{
WrappedText = TextManager.Get(str, true) is { } translated ? translated : str;
WrappedText = TextManager.Get(str) is { Loaded:true } translated ? translated.Value : str;
}
else
{
WrappedText = value?.ToString() ?? string.Empty;
}
valueTextSize = GUI.SubHeadingFont.MeasureString(WrappedText);
valueTextSize = GUIStyle.SubHeadingFont.MeasureString(WrappedText);
}
}
@@ -545,7 +545,7 @@ namespace Barotrauma
width -= 16;
}
valueText = ToolBox.WrapText(valueText, width, GUI.SubHeadingFont);
valueText = ToolBox.WrapText(valueText, width, GUIStyle.SubHeadingFont.Value);
wrappedText = valueText;
}
}
@@ -553,7 +553,7 @@ namespace Barotrauma
public override Rectangle GetDrawRectangle()
{
Rectangle drawRectangle = Rectangle;
Vector2 size = GUI.SubHeadingFont.MeasureString(WrappedText);
Vector2 size = GUIStyle.SubHeadingFont.MeasureString(WrappedText ?? "");
drawRectangle.Height = (int) Math.Max(size.Y + 16, drawRectangle.Height);
return drawRectangle;
}
@@ -564,7 +564,7 @@ namespace Barotrauma
Vector2 pos = GetDrawRectangle().Location.ToVector2() + (GetDrawRectangle().Size.ToVector2() / 2) - (valueTextSize / 2);
Rectangle drawRect = Rectangle;
drawRect.Inflate(-1, -1);
GUI.DrawString(spriteBatch, pos, WrappedText, NodeConnection.GetPropertyColor(Type), font: GUI.SubHeadingFont);
GUI.DrawString(spriteBatch, pos, WrappedText, NodeConnection.GetPropertyColor(Type), font: GUIStyle.SubHeadingFont);
}
}
@@ -13,7 +13,7 @@ using Directory = System.IO.Directory;
namespace Barotrauma
{
internal class EventEditorScreen : Screen
internal class EventEditorScreen : EditorScreen
{
private GUIFrame GuiFrame = null!;
@@ -68,7 +68,7 @@ namespace Barotrauma
// === LOAD PREFAB === //
GUILayoutGroup loadEventLayout = new GUILayoutGroup(RectTransform(1.0f, 0.125f, layoutGroup));
new GUITextBlock(RectTransform(1.0f, 0.5f, loadEventLayout), TextManager.Get("EventEditor.LoadEvent"), font: GUI.SubHeadingFont);
new GUITextBlock(RectTransform(1.0f, 0.5f, loadEventLayout), TextManager.Get("EventEditor.LoadEvent"), font: GUIStyle.SubHeadingFont);
GUILayoutGroup loadDropdownLayout = new GUILayoutGroup(RectTransform(1.0f, 0.5f, loadEventLayout), isHorizontal: true, childAnchor: Anchor.CenterLeft);
GUIDropDown loadDropdown = new GUIDropDown(RectTransform(0.8f, 1.0f, loadDropdownLayout), elementCount: 10);
@@ -77,7 +77,7 @@ namespace Barotrauma
// === ADD ACTION === //
GUILayoutGroup addActionLayout = new GUILayoutGroup(RectTransform(1.0f, 0.125f, layoutGroup));
new GUITextBlock(RectTransform(1.0f, 0.5f, addActionLayout), TextManager.Get("EventEditor.AddAction"), font: GUI.SubHeadingFont);
new GUITextBlock(RectTransform(1.0f, 0.5f, addActionLayout), TextManager.Get("EventEditor.AddAction"), font: GUIStyle.SubHeadingFont);
GUILayoutGroup addActionDropdownLayout = new GUILayoutGroup(RectTransform(1.0f, 0.5f, addActionLayout), isHorizontal: true, childAnchor: Anchor.CenterLeft);
GUIDropDown addActionDropdown = new GUIDropDown(RectTransform(0.8f, 1.0f, addActionDropdownLayout), elementCount: 10);
@@ -85,7 +85,7 @@ namespace Barotrauma
// === ADD VALUE === //
GUILayoutGroup addValueLayout = new GUILayoutGroup(RectTransform(1.0f, 0.125f, layoutGroup));
new GUITextBlock(RectTransform(1.0f, 0.5f, addValueLayout), TextManager.Get("EventEditor.AddValue"), font: GUI.SubHeadingFont);
new GUITextBlock(RectTransform(1.0f, 0.5f, addValueLayout), TextManager.Get("EventEditor.AddValue"), font: GUIStyle.SubHeadingFont);
GUILayoutGroup addValueDropdownLayout = new GUILayoutGroup(RectTransform(1.0f, 0.5f, addValueLayout), isHorizontal: true, childAnchor: Anchor.CenterLeft);
GUIDropDown addValueDropdown = new GUIDropDown(RectTransform(0.8f, 1.0f, addValueDropdownLayout), elementCount: 7);
@@ -93,15 +93,15 @@ namespace Barotrauma
// === ADD SPECIAL === //
GUILayoutGroup addSpecialLayout = new GUILayoutGroup(RectTransform(1.0f, 0.125f, layoutGroup));
new GUITextBlock(RectTransform(1.0f, 0.5f, addSpecialLayout), TextManager.Get("EventEditor.AddSpecial"), font: GUI.SubHeadingFont);
new GUITextBlock(RectTransform(1.0f, 0.5f, addSpecialLayout), TextManager.Get("EventEditor.AddSpecial"), font: GUIStyle.SubHeadingFont);
GUILayoutGroup addSpecialDropdownLayout = new GUILayoutGroup(RectTransform(1.0f, 0.5f, addSpecialLayout), isHorizontal: true, childAnchor: Anchor.CenterLeft);
GUIDropDown addSpecialDropdown = new GUIDropDown(RectTransform(0.8f, 1.0f, addSpecialDropdownLayout), elementCount: 1);
GUIButton addSpecialButton = new GUIButton(RectTransform(0.2f, 1.0f, addSpecialDropdownLayout), TextManager.Get("EventEditor.Add"));
// Add event prefabs with identifiers to the list
foreach (EventPrefab eventPrefab in EventSet.GetAllEventPrefabs().Where(prefab => !string.IsNullOrWhiteSpace(prefab.Identifier)).Distinct())
foreach (EventPrefab eventPrefab in EventSet.GetAllEventPrefabs().Where(prefab => !prefab.Identifier.IsEmpty).Distinct())
{
loadDropdown.AddItem(eventPrefab.Identifier, eventPrefab);
loadDropdown.AddItem(eventPrefab.Identifier.Value!, eventPrefab);
}
// Add all types that inherit the EventAction class
@@ -183,7 +183,7 @@ namespace Barotrauma
{
if (!nameInput.Text.Contains(illegalChar)) { continue; }
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUIStyle.Red);
return false;
}
@@ -195,7 +195,7 @@ namespace Barotrauma
ToolBox.OpenFileWithShell(path);
return true;
});
GUI.AddMessage($"XML exported to {path}", GUI.Style.Green);
GUI.AddMessage($"XML exported to {path}", GUIStyle.Green);
return true;
};
}
@@ -206,7 +206,7 @@ namespace Barotrauma
}
else
{
GUI.AddMessage("Unable to export because the project contains errors", GUI.Style.Red);
GUI.AddMessage("Unable to export because the project contains errors", GUIStyle.Red);
}
return true;
@@ -219,15 +219,15 @@ namespace Barotrauma
nodeList.Clear();
markedNodes.Clear();
selectedNodes.Clear();
projectName = TextManager.Get("EventEditor.Unnamed");
projectName = TextManager.Get("EventEditor.Unnamed").Value;
return true;
});
return true;
}
public static GUIMessageBox AskForConfirmation(string header, string body, Func<bool> onConfirm)
public static GUIMessageBox AskForConfirmation(LocalizedString header, LocalizedString body, Func<bool> onConfirm)
{
string[] buttons = { TextManager.Get("Ok"), TextManager.Get("Cancel") };
LocalizedString[] buttons = { TextManager.Get("Ok"), TextManager.Get("Cancel") };
GUIMessageBox msgBox = new GUIMessageBox(header, body, buttons);
// Cancel button
@@ -274,7 +274,7 @@ namespace Barotrauma
{
if (!nameInput.Text.Contains(illegalChar)) { continue; }
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUIStyle.Red);
return false;
}
@@ -283,7 +283,7 @@ namespace Barotrauma
XElement save = SaveEvent(projectName);
string filePath = System.IO.Path.Combine(directory, $"{projectName}.sevproj");
File.WriteAllText(Path.Combine(directory, $"{projectName}.sevproj"), save.ToString());
GUI.AddMessage($"Project saved to {filePath}", GUI.Style.Green);
GUI.AddMessage($"Project saved to {filePath}", GUIStyle.Green);
AskForConfirmation(TextManager.Get("EventEditor.TestPromptHeader"), TextManager.Get("EventEditor.TestPromptBody"), CreateTestSetupMenu);
return true;
@@ -342,11 +342,11 @@ namespace Barotrauma
Vector2 spawnPos = Cam.WorldViewCenter;
spawnPos.Y = -spawnPos.Y;
ConstructorInfo? constructor = type.GetConstructor(new Type[0]);
ConstructorInfo? constructor = type.GetConstructor(Array.Empty<Type>());
SpecialNode? newNode = null;
if (constructor != null)
{
newNode = constructor.Invoke(new object[0]) as SpecialNode;
newNode = constructor.Invoke(Array.Empty<object>()) as SpecialNode;
}
if (newNode != null)
{
@@ -358,10 +358,10 @@ namespace Barotrauma
return false;
}
private void CreateNodes(XElement element, ref bool hadNodes, EditorNode? parent = null, int ident = 0)
private void CreateNodes(ContentXElement element, ref bool hadNodes, EditorNode? parent = null, int ident = 0)
{
EditorNode? lastNode = null;
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
bool skip = true;
switch (subElement.Name.ToString().ToLowerInvariant())
@@ -404,9 +404,9 @@ namespace Barotrauma
hadNodes = false;
}
XElement? parentElement = subElement.Parent;
var parentElement = subElement.Parent;
foreach (XElement xElement in subElement.Elements())
foreach (var xElement in subElement.Elements())
{
if (xElement.Name.ToString().ToLowerInvariant() == "option")
{
@@ -515,7 +515,7 @@ namespace Barotrauma
public override void Select()
{
GUI.PreventPauseMenuToggle = false;
projectName = TextManager.Get("EventEditor.Unnamed");
projectName = TextManager.Get("EventEditor.Unnamed").Value;
base.Select();
}
@@ -627,14 +627,14 @@ namespace Barotrauma
private void Load(XElement saveElement)
{
nodeList.Clear();
projectName = saveElement.GetAttributeString("name", TextManager.Get("EventEditor.Unnamed"));
projectName = saveElement.GetAttributeString("name", TextManager.Get("EventEditor.Unnamed").Value);
foreach (XElement element in saveElement.Elements())
{
switch (element.Name.ToString().ToLowerInvariant())
{
case "nodes":
{
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
EditorNode? node = EditorNode.Load(subElement);
if (node != null)
@@ -647,7 +647,7 @@ namespace Barotrauma
}
case "allconnections":
{
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
int id = subElement.GetAttributeInt("i", -1);
EditorNode? node = nodeList.Find(editorNode => editorNode.ID == id);
@@ -702,31 +702,31 @@ namespace Barotrauma
var layout = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.5f), msgBox.Content.RectTransform));
new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.OutpostGenParams"), font: GUI.SubHeadingFont);
GUIDropDown paramInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, OutpostGenerationParams.Params.Count);
foreach (OutpostGenerationParams param in OutpostGenerationParams.Params)
new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.OutpostGenParams"), font: GUIStyle.SubHeadingFont);
GUIDropDown paramInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, OutpostGenerationParams.OutpostParams.Count());
foreach (OutpostGenerationParams param in OutpostGenerationParams.OutpostParams)
{
paramInput.AddItem(param.Identifier, param);
paramInput.AddItem(param.Identifier.Value!, param);
}
paramInput.OnSelected = (_, param) =>
{
lastTestParam = param as OutpostGenerationParams;
return true;
};
paramInput.SelectItem(lastTestParam ?? OutpostGenerationParams.Params.FirstOrDefault());
paramInput.SelectItem(lastTestParam ?? OutpostGenerationParams.OutpostParams.FirstOrDefault());
new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.LocationType"), font: GUI.SubHeadingFont);
GUIDropDown typeInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, LocationType.List.Count);
foreach (LocationType type in LocationType.List)
new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.LocationType"), font: GUIStyle.SubHeadingFont);
GUIDropDown typeInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, LocationType.Prefabs.Count());
foreach (LocationType type in LocationType.Prefabs)
{
typeInput.AddItem(type.Identifier, type);
typeInput.AddItem(type.Identifier.Value!, type);
}
typeInput.OnSelected = (_, type) =>
{
lastTestType = type as LocationType;
return true;
};
typeInput.SelectItem(lastTestType ?? LocationType.List.FirstOrDefault());
typeInput.SelectItem(lastTestType ?? LocationType.Prefabs.FirstOrDefault());
// Cancel button
msgBox.Buttons[0].OnClicked = (button, o) =>
@@ -783,8 +783,8 @@ namespace Barotrauma
if (type.IsEnum)
{
Array enums = Enum.GetValues(type);
GUIDropDown valueInput = new GUIDropDown(new RectTransform(Vector2.One, layout.RectTransform), newValue?.ToString(), enums.Length);
foreach (object? @enum in enums) { valueInput.AddItem(@enum?.ToString(), @enum); }
GUIDropDown valueInput = new GUIDropDown(new RectTransform(Vector2.One, layout.RectTransform), newValue?.ToString() ?? "", enums.Length);
foreach (object? @enum in enums) { valueInput.AddItem(@enum?.ToString() ?? "", @enum); }
valueInput.OnSelected += (component, o) =>
{
@@ -859,22 +859,22 @@ namespace Barotrauma
private bool TestEvent(OutpostGenerationParams? param, LocationType? type)
{
SubmarineInfo subInfo = SubmarineInfo.SavedSubmarines.FirstOrDefault(info => info.HasTag(SubmarineTag.Shuttle));
SubmarineInfo subInfo = SubmarineInfo.SavedSubmarines.FirstOrDefault(info => info.HasTag(SubmarineTag.Shuttle)) ?? throw new NullReferenceException("Could not test event: There are no shuttles available.");
XElement? eventXml = ExportXML();
EventPrefab? prefab;
if (eventXml != null)
{
prefab = new EventPrefab(eventXml);
prefab = new EventPrefab(eventXml.FromPackage(null), null);
}
else
{
GUI.AddMessage("Unable to open test enviroment because the event contains errors.", GUI.Style.Red);
GUI.AddMessage("Unable to open test enviroment because the event contains errors.", GUIStyle.Red);
return false;
}
GameSession gameSession = new GameSession(subInfo, "", GameModePreset.TestMode, CampaignSettings.Empty, null);
TestGameMode gameMode = (TestGameMode) gameSession.GameMode;
TestGameMode gameMode = ((TestGameMode?)gameSession.GameMode) ?? throw new InvalidCastException();
gameMode.SpawnOutpost = true;
gameMode.OutpostParams = param;
@@ -930,8 +930,8 @@ namespace Barotrauma
if (!string.IsNullOrWhiteSpace(DrawnTooltip))
{
string tooltip = ToolBox.WrapText(DrawnTooltip, 256.0f, GUI.SmallFont);
GUI.DrawString(spriteBatch, PlayerInput.MousePosition + new Vector2(32, 32), tooltip, Color.White, Color.Black * 0.8f, 4, GUI.SmallFont);
string tooltip = ToolBox.WrapText(DrawnTooltip, 256.0f, GUIStyle.SmallFont.Value);
GUI.DrawString(spriteBatch, PlayerInput.MousePosition + new Vector2(32, 32), tooltip, Color.White, Color.Black * 0.8f, 4, GUIStyle.SmallFont);
}
spriteBatch.End();
@@ -55,7 +55,14 @@ namespace Barotrauma
set
{
optionText = value;
actualValue = WrappedValue = TextManager.Get(value, true) is { } translated ? translated : value;
if (value is string)
{
actualValue = WrappedValue = TextManager.Get(value).Fallback(value).Value;
}
else
{
actualValue = WrappedValue = value;
}
}
}
@@ -74,7 +81,7 @@ namespace Barotrauma
overrideValue = value;
if (value is string str)
{
actualValue = WrappedValue = TextManager.Get(str, true) is { } translated ? translated : str;
actualValue = WrappedValue = TextManager.Get(str).Fallback(str).Value;
}
else
{
@@ -96,13 +103,13 @@ namespace Barotrauma
wrappedValue = null;
return;
}
Vector2 textSize = GUI.SmallFont.MeasureString(valueText);
Vector2 textSize = GUIStyle.SmallFont.MeasureString(valueText);
bool wasWrapped = false;
while (textSize.X > 96)
{
wasWrapped = true;
valueText = $"{valueText}...".Substring(0, valueText.Length - 4);
textSize = GUI.SmallFont.MeasureString($"{valueText}...");
textSize = GUIStyle.SmallFont.MeasureString($"{valueText}...");
}
if (wasWrapped)
@@ -178,20 +185,20 @@ namespace Barotrauma
Point pos = GetRenderPos(parentRectangle, yOffset);
DrawRectangle = new Rectangle(pos, new Point(16, 16));
GUI.DrawRectangle(spriteBatch, DrawRectangle, bgColor, isFilled: true);
GUI.DrawRectangle(spriteBatch, DrawRectangle, EndConversation ? GUI.Style.Red : outlineColor, isFilled: false, thickness: (int)Math.Max(1, 1.25f / camZoom));
GUI.DrawRectangle(spriteBatch, DrawRectangle, EndConversation ? GUIStyle.Red : outlineColor, isFilled: false, thickness: (int)Math.Max(1, 1.25f / camZoom));
string label = string.IsNullOrWhiteSpace(Attribute) ? Type.Label : Attribute;
float xPos = parentRectangle.Center.X > pos.X ? 24 : -8 - GUI.SmallFont.MeasureString(label).X;
float xPos = parentRectangle.Center.X > pos.X ? 24 : -8 - GUIStyle.SmallFont.MeasureString(label).X;
if (Type != NodeConnectionType.Out)
{
Vector2 size = GUI.SmallFont.MeasureString(label);
Vector2 size = GUIStyle.SmallFont.MeasureString(label);
Vector2 positon = new Vector2(pos.X + xPos, pos.Y);
Rectangle bgRect = new Rectangle(positon.ToPoint(), size.ToPoint());
bgRect.Inflate(4, 4);
GUI.DrawRectangle(spriteBatch, bgRect, Color.Black * 0.6f, isFilled: true);
GUI.DrawString(spriteBatch, positon, label, GetPropertyColor(ValueType), font: GUI.SmallFont);
GUI.DrawString(spriteBatch, positon, label, GetPropertyColor(ValueType), font: GUIStyle.SmallFont);
Vector2 mousePos = Screen.Selected.Cam.ScreenToWorld(PlayerInput.MousePosition);
mousePos.Y = -mousePos.Y;
@@ -250,13 +257,13 @@ namespace Barotrauma
{
float camZoom = Screen.Selected is EventEditorScreen eventEditor ? eventEditor.Cam.Zoom : 1.0f;
Rectangle valueRect = new Rectangle((int)pos.X, (int)pos.Y, 96, 20);
Vector2 textSize = GUI.SmallFont.MeasureString(text);
Vector2 textSize = GUIStyle.SmallFont.MeasureString(text);
Vector2 position = valueRect.Location.ToVector2() + valueRect.Size.ToVector2() / 2 - textSize / 2;
Rectangle drawRect = valueRect;
drawRect.Inflate(4, 4);
GUI.DrawRectangle(spriteBatch, drawRect, new Color(50, 50, 50), isFilled: true);
GUI.DrawRectangle(spriteBatch, drawRect, EndConversation ? GUI.Style.Red : outlineColor, isFilled: false, thickness: (int)Math.Max(1, 1.25f / camZoom));
GUI.DrawString(spriteBatch, position, text, GetPropertyColor(ValueType), font: GUI.SmallFont);
GUI.DrawRectangle(spriteBatch, drawRect, EndConversation ? GUIStyle.Red : outlineColor, isFilled: false, thickness: (int)Math.Max(1, 1.25f / camZoom));
GUI.DrawString(spriteBatch, position, text, GetPropertyColor(ValueType), font: GUIStyle.SmallFont);
DrawRectangle = Rectangle.Union(DrawRectangle, drawRect);
if (!string.IsNullOrWhiteSpace(fullText))
@@ -304,7 +311,7 @@ namespace Barotrauma
points[2].Y -= points[2].Y - points[1].Y;
}
Color drawColor = Parent is ValueNode ? GetPropertyColor(ValueType) : GUI.Style.Red;
Color drawColor = Parent is ValueNode ? GetPropertyColor(ValueType) : GUIStyle.Red;
if (overrideColor != null)
{
@@ -11,6 +11,8 @@ namespace Barotrauma
{
partial class GameScreen : Screen
{
public override bool IsEditor => GameMain.GameSession?.GameMode is TestGameMode;
private RenderTarget2D renderTargetBackground;
private RenderTarget2D renderTarget;
private RenderTarget2D renderTargetWater;
@@ -142,11 +144,11 @@ namespace Barotrauma
Vector2 position = Submarine.MainSubs[i].SubBody != null ? Submarine.MainSubs[i].WorldPosition : Submarine.MainSubs[i].HiddenSubPosition;
Color indicatorColor = i == 0 ? Color.LightBlue * 0.5f : GUI.Style.Red * 0.5f;
Color indicatorColor = i == 0 ? Color.LightBlue * 0.5f : GUIStyle.Red * 0.5f;
GUI.DrawIndicator(
spriteBatch, position, cam,
Math.Max(Submarine.MainSub.Borders.Width, Submarine.MainSub.Borders.Height),
GUI.SubmarineIcon, indicatorColor);
GUIStyle.SubmarineLocationIcon.Value.Sprite, indicatorColor);
}
}
@@ -390,14 +392,14 @@ namespace Barotrauma
float BlurStrength = 0.0f;
float DistortStrength = 0.0f;
Vector3 chromaticAberrationStrength = GameMain.Config.ChromaticAberrationEnabled ?
Vector3 chromaticAberrationStrength = GameSettings.CurrentConfig.Graphics.ChromaticAberration ?
new Vector3(-0.02f, -0.01f, 0.0f) : Vector3.Zero;
if (Character.Controlled != null)
{
BlurStrength = Character.Controlled.BlurStrength * 0.005f;
DistortStrength = Character.Controlled.DistortStrength;
if (GameMain.Config.EnableRadialDistortion)
if (GameSettings.CurrentConfig.Graphics.RadialDistortion)
{
chromaticAberrationStrength -= Vector3.One * Character.Controlled.RadialDistortStrength;
}
@@ -16,13 +16,9 @@ using Barotrauma.IO;
namespace Barotrauma
{
class LevelEditorScreen : Screen
class LevelEditorScreen : EditorScreen
{
private readonly Camera cam;
public override Camera Cam
{
get { return cam; }
}
public override Camera Cam { get; }
private readonly GUIFrame leftPanel, rightPanel, bottomPanel, topPanel;
@@ -46,7 +42,7 @@ namespace Barotrauma
public LevelEditorScreen()
{
cam = new Camera()
Cam = new Camera()
{
MinZoom = 0.01f,
MaxZoom = 1.0f
@@ -69,7 +65,7 @@ namespace Barotrauma
return true;
};
var ruinTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.ruinparams"), font: GUI.SubHeadingFont);
var ruinTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.ruinparams"), font: GUIStyle.SubHeadingFont);
ruinParamsList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.1f), paddedLeftPanel.RectTransform));
ruinParamsList.OnSelected += (GUIComponent component, object obj) =>
@@ -78,7 +74,7 @@ namespace Barotrauma
return true;
};
var caveTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.caveparams"), font: GUI.SubHeadingFont);
var caveTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.caveparams"), font: GUIStyle.SubHeadingFont);
caveParamsList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.1f), paddedLeftPanel.RectTransform));
caveParamsList.OnSelected += (GUIComponent component, object obj) =>
@@ -87,7 +83,7 @@ namespace Barotrauma
return true;
};
var outpostTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.outpostparams"), font: GUI.SubHeadingFont);
var outpostTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.outpostparams"), font: GUIStyle.SubHeadingFont);
GUITextBlock.AutoScaleAndNormalize(ruinTitle, caveTitle, outpostTitle);
outpostParamsList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), paddedLeftPanel.RectTransform));
@@ -185,13 +181,13 @@ namespace Barotrauma
levelData.ForceOutpostGenerationParams = outpostParamsList.SelectedData as OutpostGenerationParams;
Level.Generate(levelData, mirror: mirrorLevel.Selected);
GameMain.LightManager.AddLight(pointerLightSource);
if (!wasLevelLoaded || cam.Position.X < 0 || cam.Position.Y < 0 || cam.Position.Y > Level.Loaded.Size.X || cam.Position.Y > Level.Loaded.Size.Y)
if (!wasLevelLoaded || Cam.Position.X < 0 || Cam.Position.Y < 0 || Cam.Position.Y > Level.Loaded.Size.X || Cam.Position.Y > Level.Loaded.Size.Y)
{
cam.Position = new Vector2(Level.Loaded.Size.X / 2, Level.Loaded.Size.Y / 2);
Cam.Position = new Vector2(Level.Loaded.Size.X / 2, Level.Loaded.Size.Y / 2);
}
foreach (GUITextBlock param in paramsList.Content.Children)
{
param.TextColor = param.UserData == selectedParams ? GUI.Style.Green : param.Style.TextColor;
param.TextColor = param.UserData == selectedParams ? GUIStyle.Green : param.Style.TextColor;
}
seedBox.Deselect();
return true;
@@ -218,14 +214,13 @@ namespace Barotrauma
Submarine.MainSub.Remove();
}
//TODO: hacky workaround to check for wrecks and outposts, refactor SubmarineInfo and ContentType at some point
var nonPlayerFiles = ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.Wreck).ToList();
nonPlayerFiles.AddRange(ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.Outpost));
nonPlayerFiles.AddRange(ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.OutpostModule));
SubmarineInfo subInfo = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name.Equals(GameMain.Config.QuickStartSubmarineName, StringComparison.InvariantCultureIgnoreCase));
subInfo ??= SubmarineInfo.SavedSubmarines.GetRandom(s =>
var nonPlayerFiles = ContentPackageManager.EnabledPackages.All.SelectMany(p => p
.GetFiles<BaseSubFile>()
.Where(f => !(f is SubmarineFile))).ToArray();
SubmarineInfo subInfo = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == GameSettings.CurrentConfig.QuickStartSub);
subInfo ??= SubmarineInfo.SavedSubmarines.GetRandomUnsynced(s =>
s.IsPlayer && !s.HasTag(SubmarineTag.Shuttle) &&
!nonPlayerFiles.Any(f => f.Path.CleanUpPath().Equals(s.FilePath.CleanUpPath(), StringComparison.InvariantCultureIgnoreCase)));
!nonPlayerFiles.Any(f => f.Path == s.FilePath));
GameSession gameSession = new GameSession(subInfo, "", GameModePreset.TestMode, CampaignSettings.Empty, null);
gameSession.StartRound(Level.Loaded.LevelData);
(gameSession.GameMode as TestGameMode).OnRoundEnd = () =>
@@ -309,7 +304,7 @@ namespace Barotrauma
foreach (LevelGenerationParams genParams in LevelGenerationParams.LevelParams)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), paramsList.Content.RectTransform) { MinSize = new Point(0, 20) },
genParams.Identifier)
genParams.Identifier.Value)
{
Padding = Vector4.Zero,
UserData = genParams
@@ -354,7 +349,7 @@ namespace Barotrauma
editorContainer.ClearChildren();
outpostParamsList.Content.ClearChildren();
foreach (OutpostGenerationParams genParams in OutpostGenerationParams.Params)
foreach (OutpostGenerationParams genParams in OutpostGenerationParams.OutpostParams)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), outpostParamsList.Content.RectTransform) { MinSize = new Point(0, 20) },
genParams.Name)
@@ -373,7 +368,7 @@ namespace Barotrauma
int objectsPerRow = (int)Math.Ceiling(levelObjectList.Content.Rect.Width / Math.Max(100 * GUI.Scale, 100));
float relWidth = 1.0f / objectsPerRow;
foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.List)
foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.Prefabs)
{
var frame = new GUIFrame(new RectTransform(
new Vector2(relWidth, relWidth * ((float)levelObjectList.Content.Rect.Width / levelObjectList.Content.Rect.Height)),
@@ -384,7 +379,7 @@ namespace Barotrauma
var paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), frame.RectTransform, Anchor.Center), style: null);
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform, Anchor.BottomCenter),
text: ToolBox.LimitString(levelObjPrefab.Name, GUI.SmallFont, paddedFrame.Rect.Width), textAlignment: Alignment.Center, font: GUI.SmallFont)
text: ToolBox.LimitString(levelObjPrefab.Name, GUIStyle.SmallFont, paddedFrame.Rect.Width), textAlignment: Alignment.Center, font: GUIStyle.SmallFont)
{
CanBeFocused = false,
ToolTip = levelObjPrefab.Name
@@ -414,7 +409,7 @@ namespace Barotrauma
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.4f), commonnessContainer.RectTransform),
TextManager.GetWithVariable("leveleditor.levelobjcommonness", "[leveltype]", selectedParams.Identifier), textAlignment: Alignment.Center);
TextManager.GetWithVariable("leveleditor.levelobjcommonness", "[leveltype]", selectedParams.Identifier.Value), textAlignment: Alignment.Center);
new GUINumberInput(new RectTransform(new Vector2(0.5f, 0.4f), commonnessContainer.RectTransform), GUINumberInput.NumberType.Float)
{
MinValueFloat = 0,
@@ -443,14 +438,14 @@ namespace Barotrauma
};
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1f), locationTypeGroup.RectTransform), TextManager.Get("outpostmoduleallowedlocationtypes"), textAlignment: Alignment.CenterLeft);
HashSet<string> availableLocationTypes = new HashSet<string> { "any" };
foreach (LocationType locationType in LocationType.List) { availableLocationTypes.Add(locationType.Identifier); }
HashSet<Identifier> availableLocationTypes = new HashSet<Identifier> { "any".ToIdentifier() };
foreach (LocationType locationType in LocationType.Prefabs) { availableLocationTypes.Add(locationType.Identifier); }
var locationTypeDropDown = new GUIDropDown(new RectTransform(new Vector2(0.5f, 1f), locationTypeGroup.RectTransform),
text: string.Join(", ", outpostGenerationParams.AllowedLocationTypes.Select(lt => TextManager.Capitalize(lt)) ?? "any".ToEnumerable()), selectMultiple: true);
foreach (string locationType in availableLocationTypes)
text: LocalizedString.Join(", ", outpostGenerationParams.AllowedLocationTypes.Select(lt => TextManager.Capitalize(lt.Value)) ?? ((LocalizedString)"any").ToEnumerable()), selectMultiple: true);
foreach (Identifier locationType in availableLocationTypes)
{
locationTypeDropDown.AddItem(TextManager.Capitalize(locationType), locationType);
locationTypeDropDown.AddItem(TextManager.Capitalize(locationType.Value), locationType);
if (outpostGenerationParams.AllowedLocationTypes.Contains(locationType))
{
locationTypeDropDown.SelectItem(locationType);
@@ -463,7 +458,7 @@ namespace Barotrauma
locationTypeDropDown.OnSelected += (_, __) =>
{
outpostGenerationParams.SetAllowedLocationTypes(locationTypeDropDown.SelectedDataMultiple.Cast<string>());
outpostGenerationParams.SetAllowedLocationTypes(locationTypeDropDown.SelectedDataMultiple.Cast<Identifier>());
locationTypeDropDown.Text = ToolBox.LimitString(locationTypeDropDown.Text, locationTypeDropDown.Font, locationTypeDropDown.Rect.Width);
return true;
};
@@ -473,13 +468,13 @@ namespace Barotrauma
// module count -------------------------
var moduleLabel = new GUITextBlock(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(70 * GUI.Scale))), TextManager.Get("submarinetype.outpostmodules"), font: GUI.SubHeadingFont);
var moduleLabel = new GUITextBlock(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(70 * GUI.Scale))), TextManager.Get("submarinetype.outpostmodules"), font: GUIStyle.SubHeadingFont);
outpostParamsEditor.AddCustomContent(moduleLabel, 100);
foreach (KeyValuePair<string, int> moduleCount in outpostGenerationParams.ModuleCounts)
foreach (KeyValuePair<Identifier, int> moduleCount in outpostGenerationParams.ModuleCounts)
{
var moduleCountGroup = new GUILayoutGroup(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(25 * GUI.Scale))), isHorizontal: true, childAnchor: Anchor.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1f), moduleCountGroup.RectTransform), TextManager.Capitalize(moduleCount.Key), textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1f), moduleCountGroup.RectTransform), TextManager.Capitalize(moduleCount.Key.Value), textAlignment: Alignment.CenterLeft);
new GUINumberInput(new RectTransform(new Vector2(0.5f, 1f), moduleCountGroup.RectTransform), GUINumberInput.NumberType.Int)
{
MinValueInt = 0,
@@ -502,24 +497,24 @@ namespace Barotrauma
var addModuleCountGroup = new GUILayoutGroup(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(40 * GUI.Scale))), isHorizontal: true, childAnchor: Anchor.Center);
HashSet<string> availableFlags = new HashSet<string>();
foreach (string flag in OutpostGenerationParams.Params.SelectMany(p => p.ModuleCounts.Select(m => m.Key))) { availableFlags.Add(flag); }
HashSet<Identifier> availableFlags = new HashSet<Identifier>();
foreach (Identifier flag in OutpostGenerationParams.OutpostParams.SelectMany(p => p.ModuleCounts.Select(m => m.Key))) { availableFlags.Add(flag); }
foreach (var sub in SubmarineInfo.SavedSubmarines)
{
if (sub.OutpostModuleInfo == null) { continue; }
foreach (string flag in sub.OutpostModuleInfo.ModuleFlags) { availableFlags.Add(flag); }
foreach (Identifier flag in sub.OutpostModuleInfo.ModuleFlags) { availableFlags.Add(flag); }
}
var moduleTypeDropDown = new GUIDropDown(new RectTransform(new Vector2(0.8f, 0.8f), addModuleCountGroup.RectTransform),
text: TextManager.Get("leveleditor.addmoduletype"));
foreach (string flag in availableFlags)
foreach (Identifier flag in availableFlags)
{
if (outpostGenerationParams.ModuleCounts.Any(mc => mc.Key.Equals(flag, StringComparison.OrdinalIgnoreCase))) { continue; }
moduleTypeDropDown.AddItem(TextManager.Capitalize(flag), flag);
if (outpostGenerationParams.ModuleCounts.Any(mc => mc.Key == flag)) { continue; }
moduleTypeDropDown.AddItem(TextManager.Capitalize(flag.Value), flag);
}
moduleTypeDropDown.OnSelected += (_, userdata) =>
{
outpostGenerationParams.SetModuleCount(userdata as string, 1);
outpostGenerationParams.SetModuleCount((Identifier)userdata, 1);
outpostParamsList.Select(outpostParamsList.SelectedData);
return true;
};
@@ -532,14 +527,12 @@ namespace Barotrauma
{
editorContainer.ClearChildren();
var editor = new SerializableEntityEditor(editorContainer.Content.RectTransform, levelObjectPrefab, false, true, elementHeight: 20, titleFont: GUI.LargeFont);
var editor = new SerializableEntityEditor(editorContainer.Content.RectTransform, levelObjectPrefab, false, true, elementHeight: 20, titleFont: GUIStyle.LargeFont);
if (selectedParams != null)
{
List<string> availableIdentifiers = new List<string>();
{
if (selectedParams != null) { availableIdentifiers.Add(selectedParams.Identifier); }
}
List<Identifier> availableIdentifiers = new List<Identifier>();
if (selectedParams != null) { availableIdentifiers.Add(selectedParams.Identifier); }
foreach (var caveParam in CaveGenerationParams.CaveParams)
{
if (selectedParams != null && caveParam.GetCommonness(selectedParams, abyss: false) <= 0.0f) { continue; }
@@ -547,7 +540,7 @@ namespace Barotrauma
}
availableIdentifiers.Reverse();
foreach (string paramsId in availableIdentifiers)
foreach (Identifier paramsId in availableIdentifiers)
{
var commonnessContainer = new GUILayoutGroup(new RectTransform(new Point(editor.Rect.Width, 70)) { IsFixedSize = true },
isHorizontal: false, childAnchor: Anchor.TopCenter)
@@ -556,7 +549,7 @@ namespace Barotrauma
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.4f), commonnessContainer.RectTransform),
TextManager.GetWithVariable("leveleditor.levelobjcommonness", "[leveltype]", paramsId), textAlignment: Alignment.Center);
TextManager.GetWithVariable("leveleditor.levelobjcommonness", "[leveltype]", paramsId.Value), textAlignment: Alignment.Center);
new GUINumberInput(new RectTransform(new Vector2(0.5f, 0.4f), commonnessContainer.RectTransform), GUINumberInput.NumberType.Float)
{
MinValueFloat = 0,
@@ -599,7 +592,7 @@ namespace Barotrauma
}
//child object editing
new GUITextBlock(new RectTransform(new Point(editor.Rect.Width, 40), editorContainer.Content.RectTransform),
TextManager.Get("leveleditor.childobjects"), font: GUI.SubHeadingFont, textAlignment: Alignment.BottomCenter);
TextManager.Get("leveleditor.childobjects"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.BottomCenter);
foreach (LevelObjectPrefab.ChildObject childObj in levelObjectPrefab.ChildObjects)
{
var childObjFrame = new GUIFrame(new RectTransform(new Point(editor.Rect.Width, 30)));
@@ -610,7 +603,7 @@ namespace Barotrauma
};
var selectedChildObj = childObj;
var dropdown = new GUIDropDown(new RectTransform(new Vector2(0.5f, 1.0f), paddedFrame.RectTransform), elementCount: 10, selectMultiple: true);
foreach (LevelObjectPrefab objPrefab in LevelObjectPrefab.List)
foreach (LevelObjectPrefab objPrefab in LevelObjectPrefab.Prefabs)
{
dropdown.AddItem(objPrefab.Name, objPrefab);
if (childObj.AllowedNames.Contains(objPrefab.Name)) { dropdown.SelectItem(objPrefab); }
@@ -669,7 +662,7 @@ namespace Barotrauma
//light editing
new GUITextBlock(new RectTransform(new Point(editor.Rect.Width, 40), editorContainer.Content.RectTransform),
TextManager.Get("leveleditor.lightsources"), textAlignment: Alignment.BottomCenter, font: GUI.SubHeadingFont);
TextManager.Get("leveleditor.lightsources"), textAlignment: Alignment.BottomCenter, font: GUIStyle.SubHeadingFont);
foreach (LightSourceParams lightSourceParams in selectedLevelObject.LightSourceParams)
{
new SerializableEntityEditor(editorContainer.Content.RectTransform, lightSourceParams, inGame: false, showName: true);
@@ -696,9 +689,9 @@ namespace Barotrauma
{
var levelObj = levelObjFrame.UserData as LevelObjectPrefab;
float commonness = levelObj.GetCommonness(selectedParams);
levelObjFrame.Color = commonness > 0.0f ? GUI.Style.Green * 0.4f : Color.Transparent;
levelObjFrame.SelectedColor = commonness > 0.0f ? GUI.Style.Green * 0.6f : Color.White * 0.5f;
levelObjFrame.HoverColor = commonness > 0.0f ? GUI.Style.Green * 0.7f : Color.White * 0.6f;
levelObjFrame.Color = commonness > 0.0f ? GUIStyle.Green * 0.4f : Color.Transparent;
levelObjFrame.SelectedColor = commonness > 0.0f ? GUIStyle.Green * 0.6f : Color.White * 0.5f;
levelObjFrame.HoverColor = commonness > 0.0f ? GUIStyle.Green * 0.7f : Color.White * 0.6f;
levelObjFrame.GetAnyChild<GUIImage>().Color = commonness > 0.0f ? Color.White : Color.DarkGray;
if (commonness <= 0.0f)
@@ -735,20 +728,20 @@ namespace Barotrauma
{
if (lightingEnabled.Selected)
{
GameMain.LightManager.RenderLightMap(graphics, spriteBatch, cam);
GameMain.LightManager.RenderLightMap(graphics, spriteBatch, Cam);
}
graphics.Clear(Color.Black);
if (Level.Loaded != null)
{
Level.Loaded.DrawBack(graphics, spriteBatch, cam);
Level.Loaded.DrawFront(spriteBatch, cam);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.DepthRead, transformMatrix: cam.Transform);
Level.Loaded.DrawDebugOverlay(spriteBatch, cam);
Level.Loaded.DrawBack(graphics, spriteBatch, Cam);
Level.Loaded.DrawFront(spriteBatch, Cam);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.DepthRead, transformMatrix: Cam.Transform);
Level.Loaded.DrawDebugOverlay(spriteBatch, Cam);
Submarine.Draw(spriteBatch, false);
Submarine.DrawFront(spriteBatch);
Submarine.DrawDamageable(spriteBatch, null);
GUI.DrawRectangle(spriteBatch, new Rectangle(new Point(0, -Level.Loaded.Size.Y), Level.Loaded.Size), Color.Gray, thickness: (int)(1.0f / cam.Zoom));
GUI.DrawRectangle(spriteBatch, new Rectangle(new Point(0, -Level.Loaded.Size.Y), Level.Loaded.Size), Color.Gray, thickness: (int)(1.0f / Cam.Zoom));
for (int i = 0; i < Level.Loaded.Tunnels.Count; i++)
{
@@ -758,21 +751,21 @@ namespace Barotrauma
{
Vector2 start = new Vector2(tunnel.Nodes[j - 1].X, -tunnel.Nodes[j - 1].Y);
Vector2 end = new Vector2(tunnel.Nodes[j].X, -tunnel.Nodes[j].Y);
GUI.DrawLine(spriteBatch, start, end, tunnelColor, width: (int)(2.0f / cam.Zoom));
GUI.DrawLine(spriteBatch, start, end, tunnelColor, width: (int)(2.0f / Cam.Zoom));
}
}
foreach (Level.InterestingPosition interestingPos in Level.Loaded.PositionsOfInterest)
{
if (interestingPos.Position.X < cam.WorldView.X || interestingPos.Position.X > cam.WorldView.Right ||
interestingPos.Position.Y > cam.WorldView.Y || interestingPos.Position.Y < cam.WorldView.Y - cam.WorldView.Height)
if (interestingPos.Position.X < Cam.WorldView.X || interestingPos.Position.X > Cam.WorldView.Right ||
interestingPos.Position.Y > Cam.WorldView.Y || interestingPos.Position.Y < Cam.WorldView.Y - Cam.WorldView.Height)
{
continue;
}
Vector2 pos = new Vector2(interestingPos.Position.X, -interestingPos.Position.Y);
spriteBatch.DrawCircle(pos, 500, 6, Color.White * 0.5f, thickness: (int)(2 / cam.Zoom));
GUI.DrawString(spriteBatch, pos, interestingPos.PositionType.ToString(), Color.White, font: GUI.LargeFont);
spriteBatch.DrawCircle(pos, 500, 6, Color.White * 0.5f, thickness: (int)(2 / Cam.Zoom));
GUI.DrawString(spriteBatch, pos, interestingPos.PositionType.ToString(), Color.White, font: GUIStyle.LargeFont);
}
// TODO: Improve this temporary level editor debug solution (or remove it)
@@ -785,17 +778,17 @@ namespace Barotrauma
foreach (var resource in location.Resources)
{
Vector2 resourcePos = new Vector2(resource.Position.X, -resource.Position.Y);
spriteBatch.DrawCircle(resourcePos, 100, 6, Color.DarkGreen * 0.5f, thickness: (int)(2 / cam.Zoom));
GUI.DrawString(spriteBatch, resourcePos, resource.Name, Color.DarkGreen, font: GUI.LargeFont);
spriteBatch.DrawCircle(resourcePos, 100, 6, Color.DarkGreen * 0.5f, thickness: (int)(2 / Cam.Zoom));
GUI.DrawString(spriteBatch, resourcePos, resource.Name, Color.DarkGreen, font: GUIStyle.LargeFont);
var dist = Vector2.Distance(resourcePos, pathPointPos);
var lineStartPos = Vector2.Lerp(resourcePos, pathPointPos, 110 / dist);
var lineEndPos = Vector2.Lerp(pathPointPos, resourcePos, 310 / dist);
GUI.DrawLine(spriteBatch, lineStartPos, lineEndPos, Color.DarkGreen * 0.5f, width: (int)(2 / cam.Zoom));
GUI.DrawLine(spriteBatch, lineStartPos, lineEndPos, Color.DarkGreen * 0.5f, width: (int)(2 / Cam.Zoom));
}
}
var color = pathPoint.ShouldContainResources ? Color.DarkGreen : Color.DarkRed;
spriteBatch.DrawCircle(pathPointPos, 300, 6, color * 0.5f, thickness: (int)(2 / cam.Zoom));
GUI.DrawString(spriteBatch, pathPointPos, "Path Point\n" + pathPoint.Id, color, font: GUI.LargeFont);
spriteBatch.DrawCircle(pathPointPos, 300, 6, color * 0.5f, thickness: (int)(2 / Cam.Zoom));
GUI.DrawString(spriteBatch, pathPointPos, "Path Point\n" + pathPoint.Id, color, font: GUIStyle.LargeFont);
}
/*for (int i = 0; i < Level.Loaded.distanceField.Count; i++)
@@ -833,24 +826,24 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable);
if (Level.Loaded != null)
{
float crushDepthScreen = cam.WorldToScreen(new Vector2(0.0f, -Level.Loaded.CrushDepth)).Y;
float crushDepthScreen = Cam.WorldToScreen(new Vector2(0.0f, -Level.Loaded.CrushDepth)).Y;
if (crushDepthScreen > 0.0f && crushDepthScreen < GameMain.GraphicsHeight)
{
GUI.DrawLine(spriteBatch, new Vector2(0, crushDepthScreen), new Vector2(GameMain.GraphicsWidth, crushDepthScreen), GUI.Style.Red * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, crushDepthScreen), "Crush depth", GUI.Style.Red, backgroundColor: Color.Black);
GUI.DrawLine(spriteBatch, new Vector2(0, crushDepthScreen), new Vector2(GameMain.GraphicsWidth, crushDepthScreen), GUIStyle.Red * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, crushDepthScreen), "Crush depth", GUIStyle.Red, backgroundColor: Color.Black);
}
float abyssStartScreen = cam.WorldToScreen(new Vector2(0.0f, Level.Loaded.AbyssArea.Bottom)).Y;
float abyssStartScreen = Cam.WorldToScreen(new Vector2(0.0f, Level.Loaded.AbyssArea.Bottom)).Y;
if (abyssStartScreen > 0.0f && abyssStartScreen < GameMain.GraphicsHeight)
{
GUI.DrawLine(spriteBatch, new Vector2(0, abyssStartScreen), new Vector2(GameMain.GraphicsWidth, abyssStartScreen), GUI.Style.Blue * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, abyssStartScreen), "Abyss start", GUI.Style.Blue, backgroundColor: Color.Black);
GUI.DrawLine(spriteBatch, new Vector2(0, abyssStartScreen), new Vector2(GameMain.GraphicsWidth, abyssStartScreen), GUIStyle.Blue * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, abyssStartScreen), "Abyss start", GUIStyle.Blue, backgroundColor: Color.Black);
}
float abyssEndScreen = cam.WorldToScreen(new Vector2(0.0f, Level.Loaded.AbyssArea.Y)).Y;
float abyssEndScreen = Cam.WorldToScreen(new Vector2(0.0f, Level.Loaded.AbyssArea.Y)).Y;
if (abyssEndScreen > 0.0f && abyssEndScreen < GameMain.GraphicsHeight)
{
GUI.DrawLine(spriteBatch, new Vector2(0, abyssEndScreen), new Vector2(GameMain.GraphicsWidth, abyssEndScreen), GUI.Style.Blue * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, abyssEndScreen), "Abyss end", GUI.Style.Blue, backgroundColor: Color.Black);
GUI.DrawLine(spriteBatch, new Vector2(0, abyssEndScreen), new Vector2(GameMain.GraphicsWidth, abyssEndScreen), GUIStyle.Blue * 0.25f, width: 5);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, abyssEndScreen), "Abyss end", GUIStyle.Blue, backgroundColor: Color.Black);
}
}
GUI.Draw(Cam, spriteBatch);
@@ -863,17 +856,17 @@ namespace Barotrauma
{
foreach (Item item in Item.ItemList)
{
item?.GetComponent<Items.Components.LightComponent>()?.Update((float)deltaTime, cam);
item?.GetComponent<Items.Components.LightComponent>()?.Update((float)deltaTime, Cam);
}
}
GameMain.LightManager?.Update((float)deltaTime);
pointerLightSource.Position = cam.ScreenToWorld(PlayerInput.MousePosition);
pointerLightSource.Position = Cam.ScreenToWorld(PlayerInput.MousePosition);
pointerLightSource.Enabled = cursorLightEnabled.Selected;
pointerLightSource.IsBackground = true;
cam.MoveCamera((float)deltaTime, allowZoom: GUI.MouseOn == null);
cam.UpdateTransform();
Level.Loaded?.Update((float)deltaTime, cam);
Cam.MoveCamera((float)deltaTime, allowZoom: GUI.MouseOn == null);
Cam.UpdateTransform();
Level.Loaded?.Update((float)deltaTime, Cam);
if (editingSprite != null)
{
@@ -888,7 +881,7 @@ namespace Barotrauma
Indent = true,
NewLineOnAttributes = true
};
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelGenerationParameters))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<LevelGenerationParametersFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
@@ -899,7 +892,7 @@ namespace Barotrauma
{
if (element.IsOverride())
{
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
string id = element.GetAttributeString("identifier", null) ?? element.Name.ToString();
if (!id.Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
@@ -915,14 +908,14 @@ namespace Barotrauma
break;
}
}
using (var writer = XmlWriter.Create(configFile.Path, settings))
using (var writer = XmlWriter.Create(configFile.Path.Value, settings))
{
doc.WriteTo(writer);
writer.Flush();
}
}
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.CaveGenerationParameters))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<CaveGenerationParametersFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
@@ -933,7 +926,7 @@ namespace Barotrauma
{
if (element.IsOverride())
{
foreach (XElement subElement in element.Elements())
foreach (var subElement in element.Elements())
{
string id = subElement.GetAttributeString("identifier", null) ?? subElement.Name.ToString();
if (!id.Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
@@ -949,7 +942,7 @@ namespace Barotrauma
break;
}
}
using (var writer = XmlWriter.Create(configFile.Path, settings))
using (var writer = XmlWriter.Create(configFile.Path.Value, settings))
{
doc.WriteTo(writer);
writer.Flush();
@@ -957,22 +950,22 @@ namespace Barotrauma
}
settings.NewLineOnAttributes = false;
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<LevelObjectPrefabsFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.List)
foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.Prefabs)
{
foreach (XElement element in doc.Root.Elements())
{
string identifier = element.GetAttributeString("identifier", null);
if (!identifier.Equals(levelObjPrefab.Identifier, StringComparison.OrdinalIgnoreCase)) { continue; }
Identifier identifier = element.GetAttributeIdentifier("identifier", "");
if (identifier != levelObjPrefab.Identifier) { continue; }
levelObjPrefab.Save(element);
break;
}
}
using (var writer = XmlWriter.Create(configFile.Path, settings))
using (var writer = XmlWriter.Create(configFile.Path.Value, settings))
{
doc.WriteTo(writer);
writer.Flush();
@@ -984,7 +977,7 @@ namespace Barotrauma
private void Serialize(LevelGenerationParams genParams)
{
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelGenerationParameters))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<LevelGenerationParametersFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
@@ -1006,7 +999,7 @@ namespace Barotrauma
NewLineOnAttributes = true
};
using (var writer = XmlWriter.Create(configFile.Path, settings))
using (var writer = XmlWriter.Create(configFile.Path.Value, settings))
{
doc.WriteTo(writer);
writer.Flush();
@@ -1043,7 +1036,7 @@ namespace Barotrauma
public GUIMessageBox Create()
{
var box = new GUIMessageBox(TextManager.Get("leveleditor.createlevelobj"), string.Empty,
new string[] { TextManager.Get("cancel"), TextManager.Get("done") }, new Vector2(0.5f, 0.8f));
new LocalizedString[] { TextManager.Get("cancel"), TextManager.Get("done") }, new Vector2(0.5f, 0.8f));
box.Content.ChildAnchor = Anchor.TopCenter;
box.Content.AbsoluteSpacing = 20;
@@ -1057,14 +1050,15 @@ namespace Barotrauma
new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform),
TextManager.Get("leveleditor.levelobjtexturepath")) { CanBeFocused = false };
var texturePathBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform));
foreach (LevelObjectPrefab prefab in LevelObjectPrefab.List)
foreach (LevelObjectPrefab prefab in LevelObjectPrefab.Prefabs)
{
if (prefab.Sprites.FirstOrDefault() == null) continue;
texturePathBox.Text = Path.GetDirectoryName(prefab.Sprites.FirstOrDefault().FilePath);
texturePathBox.Text = Path.GetDirectoryName(prefab.Sprites.FirstOrDefault().FilePath.Value);
break;
}
newPrefab = new LevelObjectPrefab(null);
//this is nasty :(
newPrefab = new LevelObjectPrefab(null, null, Identifier.Empty);
new SerializableEntityEditor(listBox.Content.RectTransform, newPrefab, false, false);
@@ -1078,51 +1072,62 @@ namespace Barotrauma
{
if (string.IsNullOrEmpty(nameBox.Text))
{
nameBox.Flash(GUI.Style.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjnameempty"), GUI.Style.Red);
nameBox.Flash(GUIStyle.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjnameempty"), GUIStyle.Red);
return false;
}
if (LevelObjectPrefab.List.Any(obj => obj.Identifier.Equals(nameBox.Text, StringComparison.OrdinalIgnoreCase)))
if (LevelObjectPrefab.Prefabs.Any(obj => obj.Identifier == nameBox.Text))
{
nameBox.Flash(GUI.Style.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjnametaken"), GUI.Style.Red);
nameBox.Flash(GUIStyle.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjnametaken"), GUIStyle.Red);
return false;
}
if (!File.Exists(texturePathBox.Text))
{
texturePathBox.Flash(GUI.Style.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjtexturenotfound"), GUI.Style.Red);
texturePathBox.Flash(GUIStyle.Red);
GUI.AddMessage(TextManager.Get("leveleditor.levelobjtexturenotfound"), GUIStyle.Red);
return false;
}
newPrefab.Identifier = nameBox.Text;
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true };
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
var newElement = new XElement(newPrefab.Identifier);
newPrefab.Save(newElement);
newElement.Add(new XElement("Sprite",
new XAttribute("texture", texturePathBox.Text),
new XAttribute("sourcerect", "0,0,100,100"),
new XAttribute("origin", "0.5,0.5")));
doc.Root.Add(newElement);
using (var writer = XmlWriter.Create(configFile.Path, settings))
{
doc.WriteTo(writer);
writer.Flush();
}
// Recreate the prefab so that the sprite loads correctly: TODO: consider a better way to do this
newPrefab = new LevelObjectPrefab(newElement);
break;
}
var newElement = new XElement(nameBox.Text);
newPrefab.Save(newElement);
newElement.Add(new XElement("Sprite",
new XAttribute("texture", texturePathBox.Text),
new XAttribute("sourcerect", "0,0,100,100"),
new XAttribute("origin", "0.5,0.5")));
LevelObjectPrefab.List.Add(newPrefab);
// Create a new mod for the purpose of providing this new prefab
#warning TODO: add a clear way to tack it into an existing content package?
string modDir = Path.Combine(ContentPackage.LocalModsDir, nameBox.Text);
Directory.CreateDirectory(modDir);
string fileListPath = Path.Combine(modDir, ContentPackage.FileListFileName);
string prefabFilePath = Path.Combine(modDir, $"{nameBox.Text}.xml");
var newMod = new ModProject { Name = nameBox.Text };
var newFile = ModProject.File.FromPath<LevelObjectPrefabsFile>(prefabFilePath);
newMod.AddFile(newFile);
XDocument fileListDoc = newMod.ToXDocument();
Directory.CreateDirectory(Path.GetDirectoryName(fileListPath));
using (XmlWriter writer = XmlWriter.Create(fileListPath, settings)) { fileListDoc.Save(writer); }
XDocument prefabDoc = new XDocument();
var prefabFileRoot = new XElement("LevelObjects");
prefabFileRoot.Add(newElement);
prefabDoc.Add(prefabFileRoot);
using (XmlWriter writer = XmlWriter.Create(prefabFilePath, settings)) { prefabDoc.Save(writer); }
ContentPackageManager.UpdateContentPackageList();
var newRegularList = ContentPackageManager.EnabledPackages.Regular.ToList();
newRegularList.Add(ContentPackageManager.RegularPackages.First(p => p.Name == nameBox.Text));
ContentPackageManager.EnabledPackages.SetRegular(newRegularList);
GameMain.LevelEditorScreen.UpdateLevelObjectsList();
box.Close();
@@ -9,11 +9,13 @@ using Microsoft.Xna.Framework.Graphics;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using Barotrauma.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Barotrauma.Steam;
@@ -21,7 +23,7 @@ namespace Barotrauma
{
class MainMenuScreen : Screen
{
public enum Tab
private enum Tab
{
NewGame = 0,
LoadGame = 1,
@@ -38,20 +40,20 @@ namespace Barotrauma
private readonly GUIComponent buttonsParent;
private readonly GUIFrame[] menuTabs;
private readonly Dictionary<Tab, GUIFrame> menuTabs;
private SinglePlayerCampaignSetupUI campaignSetupUI;
private GUITextBox serverNameBox, /*portBox, queryPortBox,*/ passwordBox, maxPlayersBox;
private GUITextBox serverNameBox, passwordBox, maxPlayersBox;
private GUITickBox isPublicBox, wrongPasswordBanBox, karmaBox;
private readonly GUIFrame downloadingModsContainer, enableModsContainer;
private readonly GUIButton joinServerButton, hostServerButton, steamWorkshopButton;
private readonly GameMain game;
private GUIImage playstyleBanner;
private GUITextBlock playstyleDescription;
private GUIComponent remoteContentContainer;
private const string RemoteContentUrl = "http://www.barotraumagame.com/gamedata/";
private readonly GUIComponent remoteContentContainer;
private XDocument remoteContentDoc;
private Tab selectedTab = Tab.Empty;
@@ -62,28 +64,21 @@ namespace Barotrauma
private readonly CreditsPlayer creditsPlayer;
#if OSX
private bool firstLoadOnMac = true;
#endif
public static readonly Queue<ulong> WorkshopItemsToUpdate = new Queue<ulong>();
#region Creation
#region Creation
public MainMenuScreen(GameMain game)
{
GameMain.Instance.ResolutionChanged += () =>
{
if (Selected == this && selectedTab == Tab.Settings)
{
GameMain.Config.ResetSettingsFrame();
SelectTab(Tab.Settings);
}
CreateHostServerFields();
CreateCampaignSetupUI();
if (remoteContentDoc?.Root != null)
{
remoteContentContainer.ClearChildren();
foreach (XElement subElement in remoteContentDoc.Root.Elements())
foreach (var subElement in remoteContentDoc.Root.Elements())
{
GUIComponent.FromXML(subElement, remoteContentContainer.RectTransform);
GUIComponent.FromXML(subElement.FromPackage(null), remoteContentContainer.RectTransform);
}
}
};
@@ -118,9 +113,9 @@ namespace Barotrauma
var doc = XMLExtensions.TryLoadXml("Content/UI/MenuContent.xml");
if (doc?.Root != null)
{
foreach (XElement subElement in doc?.Root.Elements())
foreach (var subElement in doc?.Root.Elements())
{
GUIComponent.FromXML(subElement, remoteContentContainer.RectTransform);
GUIComponent.FromXML(subElement.FromPackage(null), remoteContentContainer.RectTransform);
}
}
#else
@@ -144,7 +139,7 @@ namespace Barotrauma
var campaignNavigation = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 0.75f), parent: campaignHolder.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.25f) });
new GUITextBlock(new RectTransform(new Vector2(1.0f, labelHeight), campaignNavigation.RectTransform),
TextManager.Get("CampaignLabel"), textAlignment: Alignment.Left, font: GUI.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = true };
TextManager.Get("CampaignLabel"), textAlignment: Alignment.Left, font: GUIStyle.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = ForceUpperCase.Yes };
var campaignButtons = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), parent: campaignNavigation.RectTransform), style: "MainMenuGUIFrame");
@@ -156,7 +151,7 @@ namespace Barotrauma
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), campaignList.RectTransform), TextManager.Get("TutorialButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.Tutorials,
OnClicked = (tb, userdata) =>
{
@@ -167,7 +162,7 @@ namespace Barotrauma
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), campaignList.RectTransform), TextManager.Get("LoadGameButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.LoadGame,
OnClicked = (tb, userdata) =>
{
@@ -178,7 +173,7 @@ namespace Barotrauma
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), campaignList.RectTransform), TextManager.Get("NewGameButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.NewGame,
OnClicked = (tb, userdata) =>
{
@@ -201,7 +196,7 @@ namespace Barotrauma
var multiplayerNavigation = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 0.75f), parent: multiplayerHolder.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.25f) });
new GUITextBlock(new RectTransform(new Vector2(1.0f, labelHeight), multiplayerNavigation.RectTransform),
TextManager.Get("MultiplayerLabel"), textAlignment: Alignment.Left, font: GUI.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = true };
TextManager.Get("MultiplayerLabel"), textAlignment: Alignment.Left, font: GUIStyle.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = ForceUpperCase.Yes };
var multiplayerButtons = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), parent: multiplayerNavigation.RectTransform), style: "MainMenuGUIFrame");
@@ -213,7 +208,7 @@ namespace Barotrauma
joinServerButton = new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), multiplayerList.RectTransform), TextManager.Get("JoinServerButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.JoinServer,
OnClicked = (tb, userdata) =>
{
@@ -223,7 +218,7 @@ namespace Barotrauma
};
hostServerButton = new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), multiplayerList.RectTransform), TextManager.Get("HostServerButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.HostServer,
OnClicked = (tb, userdata) =>
{
@@ -246,7 +241,7 @@ namespace Barotrauma
var customizeNavigation = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 0.75f), parent: customizeHolder.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.25f) });
new GUITextBlock(new RectTransform(new Vector2(1.0f, labelHeight), customizeNavigation.RectTransform),
TextManager.Get("CustomizeLabel"), textAlignment: Alignment.Left, font: GUI.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = true };
TextManager.Get("CustomizeLabel"), textAlignment: Alignment.Left, font: GUIStyle.LargeFont, textColor: Color.Black, style: "MainMenuGUITextBlock") { ForceUpperCase = ForceUpperCase.Yes };
var customizeButtons = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), parent: customizeNavigation.RectTransform), style: "MainMenuGUIFrame");
@@ -257,36 +252,18 @@ namespace Barotrauma
};
#if USE_STEAM
var steamWorkshopButtonContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), style: null);
steamWorkshopButton = new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), steamWorkshopButtonContainer.RectTransform), TextManager.Get("SteamWorkshopButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
steamWorkshopButton = new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("SteamWorkshopButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
Enabled = false,
ForceUpperCase = ForceUpperCase.Yes,
Enabled = true,
UserData = Tab.SteamWorkshop,
OnClicked = SelectTab
};
downloadingModsContainer = new GUIFrame(new RectTransform(new Vector2(1.4f, 0.9f), steamWorkshopButtonContainer.RectTransform,
Anchor.CenterRight, Pivot.CenterLeft)
{ RelativeOffset = new Vector2(0.3f, 0.0f) },
"MainMenuNotifBackground", Color.Yellow)
{
CanBeFocused = false,
UserData = "workshopnotif",
Visible = false
};
new GUITextBlock(new RectTransform(Vector2.One * 0.9f, downloadingModsContainer.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft) { RelativeOffset = new Vector2(0.05f, 0.0f) },
TextManager.Get("ModsDownloadingNotif"), Color.Black)
{
CanBeFocused = false,
};
#endif
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("SubEditorButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.SubmarineEditor,
OnClicked = (tb, userdata) =>
{
@@ -297,7 +274,7 @@ namespace Barotrauma
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("CharacterEditorButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.CharacterEditor,
OnClicked = (tb, userdata) =>
{
@@ -329,51 +306,37 @@ namespace Barotrauma
new GUIButton(new RectTransform(Vector2.One, settingsButtonContainer.RectTransform), TextManager.Get("SettingsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.Settings,
OnClicked = SelectTab
};
enableModsContainer = new GUIFrame(new RectTransform(new Vector2(1.4f, 0.9f), settingsButtonContainer.RectTransform,
Anchor.CenterRight, Pivot.CenterLeft) { RelativeOffset = new Vector2(0.5f, 0.0f) },
"MainMenuNotifBackground", Color.Yellow)
{
CanBeFocused = false,
UserData = "settingsnotif",
Visible = false
};
new GUITextBlock(new RectTransform(Vector2.One * 0.9f, enableModsContainer.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft) { RelativeOffset = new Vector2(0.05f, 0.0f) },
TextManager.Get("ModsInstalledNotif"), Color.Black)
{
CanBeFocused = false
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), TextManager.Get("EditorDisclaimerWikiLink"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
OnClicked = (button, userData) =>
{
string url = TextManager.Get("EditorDisclaimerWikiUrl", returnNull: true) ?? "https://barotraumagame.com/wiki";
string url = TextManager.Get("EditorDisclaimerWikiUrl").Fallback("https://barotraumagame.com/wiki").Value;
GameMain.Instance.ShowOpenUrlInWebBrowserPrompt(url, promptExtensionTag: "wikinotice");
return true;
}
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), TextManager.Get("CreditsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = Tab.Credits,
OnClicked = SelectTab
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), TextManager.Get("QuitButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
OnClicked = QuitClicked
};
//debug button for quickly starting a new round
#if DEBUG
new GUIButton(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(40, 80) },
"Quickstart (dev)", style: "GUIButtonLarge", color: GUI.Style.Red)
"Quickstart (dev)", style: "GUIButtonLarge", color: GUIStyle.Red)
{
IgnoreLayoutGroups = true,
UserData = Tab.Empty,
@@ -387,7 +350,7 @@ namespace Barotrauma
}
};
new GUIButton(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(40, 130) },
"Profiling", style: "GUIButtonLarge", color: GUI.Style.Red)
"Profiling", style: "GUIButtonLarge", color: GUIStyle.Red)
{
IgnoreLayoutGroups = true,
UserData = Tab.Empty,
@@ -404,7 +367,7 @@ namespace Barotrauma
}
};
new GUIButton(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(40, 180) },
"Join Localhost", style: "GUIButtonLarge", color: GUI.Style.Red)
"Join Localhost", style: "GUIButtonLarge", color: GUIStyle.Red)
{
IgnoreLayoutGroups = true,
UserData = Tab.Empty,
@@ -413,7 +376,7 @@ namespace Barotrauma
{
SelectTab(tb, userdata);
GameMain.Client = new GameClient(string.IsNullOrEmpty(GameMain.Config.PlayerName) ? SteamManager.GetUsername() : GameMain.Config.PlayerName,
GameMain.Client = new GameClient(MultiplayerPreferences.Instance.PlayerName.FallbackNullOrEmpty(SteamManager.GetUsername()),
IPAddress.Loopback.ToString(), 0, "localhost", 0, false);
return true;
@@ -430,18 +393,19 @@ namespace Barotrauma
var pivot = Pivot.CenterRight;
Vector2 relativeSpacing = new Vector2(0.05f, 0.0f);
menuTabs = new GUIFrame[Enum.GetValues(typeof(Tab)).Length + 1];
menuTabs = new Dictionary<Tab, GUIFrame>();
menuTabs[(int)Tab.Settings] = new GUIFrame(new RectTransform(new Vector2(relativeSize.X, 0.8f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing },
menuTabs[Tab.Settings] = new GUIFrame(new RectTransform(new Vector2(relativeSize.X, 0.8f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing },
style: null);
menuTabs[Tab.Settings].CanBeFocused = false;
menuTabs[(int)Tab.NewGame] = new GUIFrame(new RectTransform(relativeSize * new Vector2(1.0f, 1.15f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
menuTabs[(int)Tab.LoadGame] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
menuTabs[Tab.NewGame] = new GUIFrame(new RectTransform(relativeSize * new Vector2(1.0f, 1.15f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
menuTabs[Tab.LoadGame] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
CreateCampaignSetupUI();
var hostServerScale = new Vector2(0.7f, 1.2f);
menuTabs[(int)Tab.HostServer] = new GUIFrame(new RectTransform(
menuTabs[Tab.HostServer] = new GUIFrame(new RectTransform(
Vector2.Multiply(relativeSize, hostServerScale), GUI.Canvas, anchor, pivot, minSize.Multiply(hostServerScale), maxSize.Multiply(hostServerScale))
{ RelativeOffset = relativeSpacing });
@@ -449,36 +413,38 @@ namespace Barotrauma
//----------------------------------------------------------------------
menuTabs[(int)Tab.Tutorials] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
menuTabs[Tab.Tutorials] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeSpacing });
//PLACEHOLDER
var tutorialList = new GUIListBox(
new RectTransform(new Vector2(0.95f, 0.85f), menuTabs[(int)Tab.Tutorials].RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) });
foreach (Tutorial tutorial in Tutorial.Tutorials)
new RectTransform(new Vector2(0.95f, 0.85f), menuTabs[Tab.Tutorials].RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) });
var tutorialTypes = ReflectionUtils.GetDerivedNonAbstract<Tutorial>();
foreach (Type tutorialType in tutorialTypes)
{
var tutorialText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), tutorialList.Content.RectTransform), tutorial.DisplayName, textAlignment: Alignment.Center, font: GUI.LargeFont)
Tutorial tutorial = (Tutorial)Activator.CreateInstance(tutorialType);
var tutorialText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), tutorialList.Content.RectTransform), tutorial.DisplayName, textAlignment: Alignment.Center, font: GUIStyle.LargeFont)
{
UserData = tutorial
};
}
tutorialList.OnSelected += (component, obj) =>
{
TutorialMode.StartTutorial(obj as Tutorial);
(obj as Tutorial).Start();
return true;
};
this.game = game;
menuTabs[(int)Tab.Credits] = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas, Anchor.Center), style: null)
menuTabs[Tab.Credits] = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas, Anchor.Center), style: null)
{
CanBeFocused = false
};
new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, menuTabs[(int)Tab.Credits].RectTransform, Anchor.Center), style: "GUIBackgroundBlocker")
new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, menuTabs[Tab.Credits].RectTransform, Anchor.Center), style: "GUIBackgroundBlocker")
{
CanBeFocused = false
};
var creditsContainer = new GUIFrame(new RectTransform(new Vector2(0.75f, 1.5f), menuTabs[(int)Tab.Credits].RectTransform, Anchor.CenterRight), style: "OuterGlow", color: Color.Black * 0.8f);
var creditsContainer = new GUIFrame(new RectTransform(new Vector2(0.75f, 1.5f), menuTabs[Tab.Credits].RectTransform, Anchor.CenterRight), style: "OuterGlow", color: Color.Black * 0.8f);
creditsPlayer = new CreditsPlayer(new RectTransform(Vector2.One, creditsContainer.RectTransform), "Content/Texts/Credits.xml");
}
#endregion
@@ -486,6 +452,14 @@ namespace Barotrauma
#region Selection
public override void Select()
{
if (WorkshopItemsToUpdate.Any())
{
while (WorkshopItemsToUpdate.TryDequeue(out ulong workshopId))
{
SteamManager.Workshop.OnItemDownloadComplete(workshopId, forceInstall: true);
}
}
GUI.PreventPauseMenuToggle = false;
base.Select();
@@ -500,30 +474,6 @@ namespace Barotrauma
Submarine.Unload();
ResetButtonStates(null);
if (GameMain.SteamWorkshopScreen != null)
{
CoroutineManager.StartCoroutine(GameMain.SteamWorkshopScreen.RefreshDownloadState());
}
#if OSX
// Hack for adjusting the viewport properly after splash screens on older Macs
if (firstLoadOnMac)
{
firstLoadOnMac = false;
menuTabs[(int)Tab.Empty] = new GUIFrame(new RectTransform(new Vector2(1f, 1f), GUI.Canvas), "", Color.Transparent)
{
CanBeFocused = false
};
var emptyList = new GUIListBox(new RectTransform(new Vector2(0.0f, 0.0f), menuTabs[(int)Tab.Empty].RectTransform))
{
CanBeFocused = false
};
SelectTab(null, Tab.Empty);
}
#endif
}
public override void Deselect()
@@ -549,44 +499,19 @@ namespace Barotrauma
private bool SelectTab(Tab tab)
{
titleText.Visible = true;
if (GameMain.Config.UnsavedSettings)
{
var applyBox = new GUIMessageBox(
TextManager.Get("ApplySettingsLabel"),
TextManager.Get("ApplySettingsQuestion"),
new string[] { TextManager.Get("ApplySettingsYes"), TextManager.Get("ApplySettingsNo") });
applyBox.Buttons[0].UserData = tab;
applyBox.Buttons[0].OnClicked = (tb, userdata) =>
{
applyBox.Close();
ApplySettings();
SelectTab(tab);
return true;
};
applyBox.Buttons[1].UserData = tab;
applyBox.Buttons[1].OnClicked = (tb, userdata) =>
{
applyBox.Close();
DiscardSettings();
SelectTab(tab);
return true;
};
return false;
}
GameMain.Config.ResetSettingsFrame();
SettingsMenu.Instance?.Close();
#warning TODO: reimplement settings confirmation dialog
switch (tab)
{
case Tab.NewGame:
if (GameMain.Config.ShowTutorialSkipWarning)
if (GameSettings.CurrentConfig.TutorialSkipWarning)
{
selectedTab = Tab.Empty;
ShowTutorialSkipWarning(Tab.NewGame);
return true;
}
if (!GameMain.Config.CampaignDisclaimerShown)
if (!GameSettings.CurrentConfig.CampaignDisclaimerShown)
{
selectedTab = Tab.Empty;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.NewGame); });
@@ -602,19 +527,16 @@ namespace Barotrauma
campaignSetupUI.UpdateLoadMenu();
break;
case Tab.Settings:
GameMain.MainMenuScreen?.SetEnableModsNotification(false);
menuTabs[(int)Tab.Settings].RectTransform.ClearChildren();
GameMain.Config.SettingsFrame.RectTransform.Parent = menuTabs[(int)Tab.Settings].RectTransform;
GameMain.Config.SettingsFrame.RectTransform.RelativeSize = Vector2.One;
SettingsMenu.Create(menuTabs[Tab.Settings].RectTransform);
break;
case Tab.JoinServer:
if (GameMain.Config.ShowTutorialSkipWarning)
if (GameSettings.CurrentConfig.TutorialSkipWarning)
{
selectedTab = Tab.Empty;
ShowTutorialSkipWarning(Tab.JoinServer);
return true;
}
if (!GameMain.Config.CampaignDisclaimerShown)
if (!GameSettings.CurrentConfig.CampaignDisclaimerShown)
{
selectedTab = Tab.Empty;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.JoinServer); });
@@ -623,19 +545,13 @@ namespace Barotrauma
GameMain.ServerListScreen.Select();
break;
case Tab.HostServer:
if (GameMain.Config.ContentPackageSelectionDirty)
{
new GUIMessageBox(TextManager.Get("RestartRequiredLabel"), TextManager.Get("ServerRestartRequiredContentPackage", fallBackTag: "RestartRequiredGeneric"));
selectedTab = Tab.Empty;
return false;
}
if (GameMain.Config.ShowTutorialSkipWarning)
if (GameSettings.CurrentConfig.TutorialSkipWarning)
{
selectedTab = Tab.Empty;
ShowTutorialSkipWarning(tab);
return true;
}
if (!GameMain.Config.CampaignDisclaimerShown)
if (!GameSettings.CurrentConfig.CampaignDisclaimerShown)
{
selectedTab = Tab.Empty;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.HostServer); });
@@ -643,7 +559,7 @@ namespace Barotrauma
}
break;
case Tab.Tutorials:
if (!GameMain.Config.CampaignDisclaimerShown)
if (!GameSettings.CurrentConfig.CampaignDisclaimerShown)
{
selectedTab = Tab.Empty;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.Tutorials); });
@@ -659,8 +575,9 @@ namespace Barotrauma
CoroutineManager.StartCoroutine(SelectScreenWithWaitCursor(GameMain.SubEditorScreen));
break;
case Tab.SteamWorkshop:
if (!Steam.SteamManager.IsInitialized) return false;
CoroutineManager.StartCoroutine(SelectScreenWithWaitCursor(GameMain.SteamWorkshopScreen));
var settings = SettingsMenu.Create(menuTabs[Tab.Settings].RectTransform);
settings.SelectTab(SettingsMenu.Tab.Mods);
tab = Tab.Settings;
break;
case Tab.Credits:
titleText.Visible = false;
@@ -717,7 +634,7 @@ namespace Barotrauma
}
#endregion
public void QuickStart(bool fixedSeed = false, string sub = null, float difficulty = 50, LevelGenerationParams levelGenerationParams = null)
public void QuickStart(bool fixedSeed = false, Identifier sub = default, float difficulty = 50, LevelGenerationParams levelGenerationParams = null)
{
if (fixedSeed)
{
@@ -726,11 +643,12 @@ namespace Barotrauma
}
SubmarineInfo selectedSub = null;
string subName = sub ?? GameMain.Config.QuickStartSubmarineName;
if (!string.IsNullOrEmpty(subName))
Identifier subName = sub.IfEmpty(GameSettings.CurrentConfig.QuickStartSub);
if (!subName.IsEmpty)
{
DebugConsole.NewMessage($"Loading the predefined quick start sub \"{subName}\"", Color.White);
selectedSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name.ToLowerInvariant() == subName.ToLowerInvariant());
selectedSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == subName);
if (selectedSub == null)
{
DebugConsole.NewMessage($"Cannot find a sub that matches the name \"{subName}\".", Color.Red);
@@ -755,7 +673,7 @@ namespace Barotrauma
{
var jobPrefab = JobPrefab.Get(job);
var variant = Rand.Range(0, jobPrefab.Variants);
var characterInfo = new CharacterInfo(CharacterPrefab.HumanSpeciesName, jobPrefab: jobPrefab, variant: variant);
var characterInfo = new CharacterInfo(CharacterPrefab.HumanSpeciesName, jobOrJobPrefab: jobPrefab, variant: variant);
if (characterInfo.Job == null)
{
DebugConsole.ThrowError("Failed to find the job \"" + job + "\"!");
@@ -765,40 +683,29 @@ namespace Barotrauma
gamesession.CrewManager.InitSinglePlayerRound();
}
public void SetEnableModsNotification(bool visible)
{
if (enableModsContainer != null) { enableModsContainer.Visible = visible; }
}
public void SetDownloadingModsNotification(bool visible)
{
if (downloadingModsContainer != null) { downloadingModsContainer.Visible = visible; }
}
private void ShowTutorialSkipWarning(Tab tabToContinueTo)
{
var tutorialSkipWarning = new GUIMessageBox("", TextManager.Get("tutorialskipwarning"), new string[] { TextManager.Get("tutorialwarningskiptutorials"), TextManager.Get("tutorialwarningplaytutorials") });
tutorialSkipWarning.Buttons[0].OnClicked += (btn, userdata) =>
{
GameMain.Config.ShowTutorialSkipWarning = false;
GameMain.Config.SaveNewPlayerConfig();
tutorialSkipWarning.Close();
SelectTab(tabToContinueTo);
return true;
};
tutorialSkipWarning.Buttons[1].OnClicked += (btn, userdata) =>
{
GameMain.Config.ShowTutorialSkipWarning = false;
GameMain.Config.SaveNewPlayerConfig();
tutorialSkipWarning.Close();
SelectTab(Tab.Tutorials);
return true;
};
var tutorialSkipWarning = new GUIMessageBox("", TextManager.Get("tutorialskipwarning"), new LocalizedString[] { TextManager.Get("tutorialwarningskiptutorials"), TextManager.Get("tutorialwarningplaytutorials") });
GUIButton.OnClickedHandler proceedToTab(Tab tab)
=> (btn, userdata) =>
{
var config = GameSettings.CurrentConfig;
config.TutorialSkipWarning = false;
GameSettings.SetCurrentConfig(config);
GameSettings.SaveCurrentConfig();
tutorialSkipWarning.Close();
SelectTab(tab);
return true;
};
tutorialSkipWarning.Buttons[0].OnClicked += proceedToTab(tabToContinueTo);
tutorialSkipWarning.Buttons[1].OnClicked += proceedToTab(Tab.Tutorials);
}
private void UpdateTutorialList()
{
var tutorialList = menuTabs[(int)Tab.Tutorials].GetChild<GUIListBox>();
var tutorialList = menuTabs[Tab.Tutorials].GetChild<GUIListBox>();
int completedTutorials = 0;
@@ -814,7 +721,7 @@ namespace Barotrauma
{
if (i < completedTutorials + 1)
{
(tutorialList.Content.GetChild(i) as GUITextBlock).TextColor = GUI.Style.Green;
(tutorialList.Content.GetChild(i) as GUITextBlock).TextColor = GUIStyle.Green;
#if !DEBUG
(tutorialList.Content.GetChild(i) as GUITextBlock).CanBeFocused = true;
#endif
@@ -829,37 +736,6 @@ namespace Barotrauma
}
}
public void ResetSettingsFrame(GameSettings.Tab selectedTab = GameSettings.Tab.Graphics)
{
menuTabs[(int)Tab.Settings].RectTransform.ClearChildren();
GameMain.Config.ResetSettingsFrame();
GameMain.Config.CreateSettingsFrame(selectedTab);
GameMain.Config.SettingsFrame.RectTransform.Parent = menuTabs[(int)Tab.Settings].RectTransform;
GameMain.Config.SettingsFrame.RectTransform.RelativeSize = Vector2.One;
}
private bool ApplySettings()
{
GameMain.Config.SaveNewPlayerConfig();
if (GameMain.GraphicsWidth != GameMain.Config.GraphicsWidth ||
GameMain.GraphicsHeight != GameMain.Config.GraphicsHeight)
{
new GUIMessageBox(
TextManager.Get("RestartRequiredLabel"),
TextManager.Get("RestartRequiredGeneric"));
}
return true;
}
private bool DiscardSettings()
{
GameMain.Config.LoadPlayerConfig();
return true;
}
private bool ChangeMaxPlayers(GUIButton button, object obj)
{
int.TryParse(maxPlayersBox.Text, out int currMaxPlayers);
@@ -872,7 +748,7 @@ namespace Barotrauma
{
if (SubmarineInfo.SavedSubmarines.Any(s => s.CalculatingHash))
{
var waitBox = new GUIMessageBox(TextManager.Get("pleasewait"), TextManager.Get("waitforsubmarinehashcalculations"), new string[] { TextManager.Get("cancel") });
var waitBox = new GUIMessageBox(TextManager.Get("pleasewait"), TextManager.Get("waitforsubmarinehashcalculations"), new LocalizedString[] { TextManager.Get("cancel") });
var waitCoroutine = CoroutineManager.StartCoroutine(WaitForSubmarineHashCalculations(waitBox), "WaitForSubmarineHashCalculations");
waitBox.Buttons[0].OnClicked += (btn, userdata) =>
{
@@ -888,7 +764,7 @@ namespace Barotrauma
private IEnumerable<CoroutineStatus> WaitForSubmarineHashCalculations(GUIMessageBox messageBox)
{
string originalText = messageBox.Text.Text;
LocalizedString originalText = messageBox.Text.Text;
int doneCount = 0;
do
{
@@ -905,16 +781,10 @@ namespace Barotrauma
{
string name = serverNameBox.Text;
GameMain.NetLobbyScreen?.Release();
GameMain.NetLobbyScreen = new NetLobbyScreen();
GameMain.ResetNetLobbyScreen();
try
{
string exeName = ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.ServerExecutable)?.FirstOrDefault()?.Path;
if (string.IsNullOrEmpty(exeName))
{
DebugConsole.ThrowError("No server executable defined in the selected content packages. Attempting to use the default executable...");
exeName = "DedicatedServer.exe";
}
string exeName = "DedicatedServer.exe";
string arguments = "-name \"" + ToolBox.EscapeCharacters(name) + "\"" +
" -public " + isPublicBox.Selected.ToString() +
@@ -962,7 +832,8 @@ namespace Barotrauma
ChildServerRelay.Start(processInfo);
Thread.Sleep(1000); //wait until the server is ready before connecting
GameMain.Client = new GameClient(string.IsNullOrEmpty(GameMain.Config.PlayerName) ? name : GameMain.Config.PlayerName,
GameMain.Client = new GameClient(MultiplayerPreferences.Instance.PlayerName.FallbackNullOrEmpty(
SteamManager.GetUsername().FallbackNullOrEmpty(name)),
System.Net.IPAddress.Loopback.ToString(), Steam.SteamManager.GetSteamID(), name, ownerKey, true);
}
catch (Exception e)
@@ -980,9 +851,9 @@ namespace Barotrauma
public override void AddToGUIUpdateList()
{
Frame.AddToGUIUpdateList();
if (selectedTab < Tab.Empty && menuTabs[(int)selectedTab] != null)
if (selectedTab < Tab.Empty && menuTabs.TryGetValue(selectedTab, out GUIFrame tab) && tab != null)
{
menuTabs[(int)selectedTab].AddToGUIUpdateList();
tab.AddToGUIUpdateList();
switch (selectedTab)
{
case Tab.NewGame:
@@ -995,9 +866,9 @@ namespace Barotrauma
public override void Update(double deltaTime)
{
#if !DEBUG && USE_STEAM
if (GameMain.Config.UseSteamMatchmaking)
if (GameSettings.CurrentConfig.UseSteamMatchmaking)
{
hostServerButton.Enabled = Steam.SteamManager.IsInitialized;
hostServerButton.Enabled = Steam.SteamManager.IsInitialized;
}
steamWorkshopButton.Enabled = Steam.SteamManager.IsInitialized;
#elif USE_STEAM
@@ -1020,7 +891,7 @@ namespace Barotrauma
#if UNSTABLE
backgroundSprite = new Sprite("Content/UnstableBackground.png", sourceRectangle: null);
#endif
backgroundSprite ??= LocationType.List.Where(l => l.UseInMainMenu).GetRandom()?.GetPortrait(0);
backgroundSprite ??= (LocationType.Prefabs.Where(l => l.UseInMainMenu).GetRandomUnsynced())?.GetPortrait(0);
}
if (backgroundSprite != null)
@@ -1029,7 +900,7 @@ namespace Barotrauma
aberrationStrength: 0.0f);
}
var vignette = GUI.Style.GetComponentStyle("mainmenuvignette")?.GetDefaultSprite();
var vignette = GUIStyle.GetComponentStyle("mainmenuvignette")?.GetDefaultSprite();
if (vignette != null)
{
spriteBatch.Begin(blendState: BlendState.NonPremultiplied);
@@ -1039,9 +910,9 @@ namespace Barotrauma
}
}
readonly string[] legalCrap = new string[]
readonly LocalizedString[] legalCrap = new LocalizedString[]
{
TextManager.Get("privacypolicy", returnNull: true) ?? "Privacy policy",
TextManager.Get("privacypolicy").Fallback("Privacy policy"),
"© " + DateTime.Now.Year + " Undertow Games & FakeFish. All rights reserved.",
"© " + DateTime.Now.Year + " Daedalic Entertainment GmbH. The Daedalic logo is a trademark of Daedalic Entertainment GmbH, Germany. All rights reserved."
};
@@ -1054,28 +925,27 @@ namespace Barotrauma
GUI.Draw(Cam, spriteBatch);
if (selectedTab != Tab.Credits)
{
#if !UNSTABLE
string versionString = "Barotrauma v" + GameMain.Version + " (" + AssemblyInfo.BuildString + ", branch " + AssemblyInfo.GitBranch + ", revision " + AssemblyInfo.GitRevision + ")";
GUI.SmallFont.DrawString(spriteBatch, versionString, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUI.SmallFont.MeasureString(versionString).Y - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
GUIStyle.SmallFont.DrawString(spriteBatch, versionString, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUIStyle.SmallFont.MeasureString(versionString).Y - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
#endif
string gameAnalyticsStatus = TextManager.Get($"GameAnalyticsStatus.{GameAnalyticsManager.UserConsented}");
Vector2 textSize = GUI.SmallFont.MeasureString(gameAnalyticsStatus).ToPoint().ToVector2();
GUI.SmallFont.DrawString(spriteBatch, gameAnalyticsStatus, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUI.SmallFont.LineHeight * 2 - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
LocalizedString gameAnalyticsStatus = TextManager.Get($"GameAnalyticsStatus.{GameAnalyticsManager.UserConsented}");
Vector2 textSize = GUIStyle.SmallFont.MeasureString(gameAnalyticsStatus).ToPoint().ToVector2();
GUIStyle.SmallFont.DrawString(spriteBatch, gameAnalyticsStatus, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUIStyle.SmallFont.LineHeight * 2 - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
Vector2 textPos = new Vector2(GameMain.GraphicsWidth - HUDLayoutSettings.Padding, GameMain.GraphicsHeight - HUDLayoutSettings.Padding * 0.75f);
for (int i = legalCrap.Length - 1; i >= 0; i--)
{
textSize = GUI.SmallFont.MeasureString(legalCrap[i])
textSize = GUIStyle.SmallFont.MeasureString(legalCrap[i])
.ToPoint().ToVector2();
bool mouseOn = i == 0 &&
PlayerInput.MousePosition.X > textPos.X - textSize.X && PlayerInput.MousePosition.X < textPos.X &&
PlayerInput.MousePosition.Y > textPos.Y - textSize.Y && PlayerInput.MousePosition.Y < textPos.Y;
PlayerInput.MousePosition.X > textPos.X - textSize.X && PlayerInput.MousePosition.X < textPos.X &&
PlayerInput.MousePosition.Y > textPos.Y - textSize.Y && PlayerInput.MousePosition.Y < textPos.Y;
GUI.SmallFont.DrawString(spriteBatch,
GUIStyle.SmallFont.DrawString(spriteBatch,
legalCrap[i], textPos - textSize,
mouseOn ? Color.White : Color.White * 0.7f);
@@ -1163,10 +1033,10 @@ namespace Barotrauma
#region UI Methods
private void CreateCampaignSetupUI()
{
menuTabs[(int)Tab.NewGame].ClearChildren();
menuTabs[(int)Tab.LoadGame].ClearChildren();
menuTabs[Tab.NewGame].ClearChildren();
menuTabs[Tab.LoadGame].ClearChildren();
var innerNewGame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), menuTabs[(int)Tab.NewGame].RectTransform, Anchor.Center))
var innerNewGame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), menuTabs[Tab.NewGame].RectTransform, Anchor.Center))
{
Stretch = true,
RelativeSpacing = 0.02f
@@ -1174,7 +1044,7 @@ namespace Barotrauma
var newGameContent = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.95f), innerNewGame.RectTransform, Anchor.Center),
style: "InnerFrame");
var paddedLoadGame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), menuTabs[(int)Tab.LoadGame].RectTransform, Anchor.Center) { AbsoluteOffset = new Point(0, 10) },
var paddedLoadGame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), menuTabs[Tab.LoadGame].RectTransform, Anchor.Center) { AbsoluteOffset = new Point(0, 10) },
style: null);
campaignSetupUI = new SinglePlayerCampaignSetupUI(newGameContent, paddedLoadGame, SubmarineInfo.SavedSubmarines)
@@ -1186,7 +1056,7 @@ namespace Barotrauma
private void CreateHostServerFields()
{
menuTabs[(int)Tab.HostServer].ClearChildren();
menuTabs[Tab.HostServer].ClearChildren();
string name = "";
string password = "";
@@ -1226,14 +1096,14 @@ namespace Barotrauma
Alignment textAlignment = Alignment.CenterLeft;
Vector2 textFieldSize = new Vector2(0.5f, 1.0f);
Vector2 tickBoxSize = new Vector2(0.4f, 0.07f);
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.7f, 0.9f), menuTabs[(int)Tab.HostServer].RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.7f, 0.9f), menuTabs[Tab.HostServer].RectTransform, Anchor.Center), childAnchor: Anchor.TopCenter)
{
RelativeSpacing = 0.02f,
Stretch = true
};
GUIComponent parent = content;
new GUITextBlock(new RectTransform(textLabelSize, parent.RectTransform), TextManager.Get("HostServerButton"), textAlignment: Alignment.Center, font: GUI.LargeFont) { ForceUpperCase = true };
new GUITextBlock(new RectTransform(textLabelSize, parent.RectTransform), TextManager.Get("HostServerButton"), textAlignment: Alignment.Center, font: GUIStyle.LargeFont) { ForceUpperCase = ForceUpperCase.Yes };
//play style -----------------------------------------------------
@@ -1250,7 +1120,7 @@ namespace Barotrauma
new GUIFrame(new RectTransform(Vector2.One, playstyleBanner.RectTransform), "InnerGlow", color: Color.Black);
new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.05f), playstyleBanner.RectTransform) { RelativeOffset = new Vector2(0.01f, 0.03f) },
"playstyle name goes here", font: GUI.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader");
"playstyle name goes here", font: GUIStyle.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader");
new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), playstyleContainer.RectTransform, Anchor.CenterLeft)
{ RelativeOffset = new Vector2(0.02f, 0.0f), MaxSize = new Point(int.MaxValue, (int)(150 * GUI.Scale)) },
@@ -1278,10 +1148,10 @@ namespace Barotrauma
}
};
string longestPlayStyleStr = "";
LocalizedString longestPlayStyleStr = "";
foreach (PlayStyle playStyle in Enum.GetValues(typeof(PlayStyle)))
{
string playStyleStr = TextManager.Get("servertagdescription." + playStyle);
LocalizedString playStyleStr = TextManager.Get("servertagdescription." + playStyle);
if (playStyleStr.Length > longestPlayStyleStr.Length) { longestPlayStyleStr = playStyleStr; }
}
@@ -1289,7 +1159,7 @@ namespace Barotrauma
longestPlayStyleStr, style: null, wrap: true)
{
Color = Color.Black * 0.8f,
TextColor = GUI.Style.GetComponentStyle("GUITextBlock").TextColor
TextColor = GUIStyle.GetComponentStyle("GUITextBlock").TextColor
};
playstyleDescription.Padding = Vector4.One * 10.0f * GUI.Scale;
playstyleDescription.CalculateHeightFromText(padding: (int)(15 * GUI.Scale));
@@ -1399,8 +1269,8 @@ namespace Barotrauma
if (isPublicBox.Selected && ForbiddenWordFilter.IsForbidden(name, out string forbiddenWord))
{
var msgBox = new GUIMessageBox("",
TextManager.GetWithVariables("forbiddenservernameverification", new string[] { "[forbiddenword]", "[servername]" }, new string[] { forbiddenWord, name }),
new string[] { TextManager.Get("yes"), TextManager.Get("no") });
TextManager.GetWithVariables("forbiddenservernameverification", ("[forbiddenword]", forbiddenWord), ("[servername]", name)),
new LocalizedString[] { TextManager.Get("yes"), TextManager.Get("no") });
msgBox.Buttons[0].OnClicked += (_, __) =>
{
TryStartServer();
@@ -1437,10 +1307,10 @@ namespace Barotrauma
private void FetchRemoteContent()
{
if (string.IsNullOrEmpty(GameMain.Config.RemoteContentUrl)) { return; }
if (string.IsNullOrEmpty(RemoteContentUrl)) { return; }
try
{
var client = new RestClient(GameMain.Config.RemoteContentUrl);
var client = new RestClient(RemoteContentUrl);
var request = new RestRequest("MenuContent.xml", Method.GET);
client.ExecuteAsync(request, RemoteContentReceived);
CoroutineManager.StartCoroutine(WairForRemoteContentReceived());
@@ -1482,9 +1352,9 @@ namespace Barotrauma
if (!string.IsNullOrWhiteSpace(xml))
{
remoteContentDoc = XDocument.Parse(xml);
foreach (XElement subElement in remoteContentDoc?.Root.Elements())
foreach (var subElement in remoteContentDoc?.Root.Elements())
{
GUIComponent.FromXML(subElement, remoteContentContainer.RectTransform);
GUIComponent.FromXML(subElement.FromPackage(null), remoteContentContainer.RectTransform);
}
}
}
@@ -0,0 +1,296 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Barotrauma.IO;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Steamworks.Data;
using Color = Microsoft.Xna.Framework.Color;
using ServerContentPackage = Barotrauma.Networking.ClientPeer.ServerContentPackage;
namespace Barotrauma
{
class ModDownloadScreen : Screen
{
private readonly Queue<ServerContentPackage> pendingDownloads =
new Queue<ServerContentPackage>();
private ServerContentPackage? currentDownload;
private readonly List<ContentPackage> downloadedPackages = new List<ContentPackage>();
private bool confirmDownload;
private void Reset()
{
pendingDownloads.Clear();
downloadedPackages.Clear();
currentDownload = null;
confirmDownload = false;
}
public override void Select()
{
base.Select();
Reset();
Frame.ClearChildren();
var mainVisibleFrame = new GUIFrame(new RectTransform((0.6f, 0.8f), Frame.RectTransform, Anchor.Center));
GUILayoutGroup mainLayout = new GUILayoutGroup(new RectTransform(Vector2.One * 0.93f, mainVisibleFrame.RectTransform, Anchor.Center));
void mainLayoutSpacing()
=> new GUIFrame(new RectTransform((1.0f, 0.02f), mainLayout.RectTransform), style: null);
var serverName = new GUITextBlock(new RectTransform((1.0f, 0.08f), mainLayout.RectTransform),
"", font: GUIStyle.LargeFont,
textAlignment: Alignment.CenterLeft)
{
TextGetter = () => GameMain.NetLobbyScreen.ServerName.Text
};
mainLayoutSpacing();
var downloadList = new GUIListBox(new RectTransform((1.0f, 0.76f), mainLayout.RectTransform));
mainLayoutSpacing();
var disconnectButton = new GUIButton(new RectTransform((0.3f, 0.1f), mainLayout.RectTransform),
TextManager.Get("Disconnect"))
{
OnClicked = (guiButton, o) =>
{
GameMain.Client.Disconnect();
GameMain.MainMenuScreen.Select();
return false;
}
};
var missingPackages = GameMain.Client.ClientPeer.ServerContentPackages
.Where(sp => sp.ContentPackage is null).ToArray();
if (!missingPackages.Any())
{
GameMain.NetLobbyScreen.Select();
return;
}
GUIMessageBox msgBox = new GUIMessageBox(
TextManager.Get("WorkshopItemDownloadTitle"),
"",
Array.Empty<LocalizedString>(),
relativeSize: (0.5f, 0.75f));
GUILayoutGroup innerLayout = msgBox.Content;
innerLayout.Stretch = true;
void innerLayoutSpacing(float height)
=> new GUIFrame(new RectTransform((1.0f, height), innerLayout.RectTransform), style: null);
GUITextBlock textBlock(LocalizedString str, GUIFont font, Alignment alignment = Alignment.CenterLeft)
{
var tb = new GUITextBlock(new RectTransform(Point.Zero, innerLayout.RectTransform), str,
wrap: true, textAlignment: alignment, font: font);
new GUICustomComponent(new RectTransform(Vector2.Zero, tb.RectTransform), onUpdate:
(deltaTime, component) =>
{
if (tb.RectTransform.NonScaledSize.X != innerLayout.Rect.Width)
{
tb.RectTransform.NonScaledSize = (innerLayout.Rect.Width, 0);
tb.RectTransform.NonScaledSize = (innerLayout.Rect.Width,
(int)tb.Font.MeasureString(tb.WrappedText).Y);
}
});
return tb;
}
var title = textBlock(TextManager.Get("ModDownloadTitle"), GUIStyle.SubHeadingFont, Alignment.Center);
innerLayoutSpacing(0.05f);
var header = textBlock(TextManager.Get("ModDownloadHeader"), GUIStyle.Font);
innerLayoutSpacing(0.05f);
var msgBoxModList = new GUIListBox(new RectTransform(Vector2.One, innerLayout.RectTransform));
innerLayoutSpacing(0.05f);
var footer = textBlock(TextManager.Get("ModDownloadFooter"), GUIStyle.Font, Alignment.Center);
innerLayoutSpacing(0.05f);
GUILayoutGroup buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), innerLayout.RectTransform), isHorizontal: true);
void buttonContainerSpacing(float width)
=> new GUIFrame(new RectTransform((width, 1.0f), buttonContainer.RectTransform), style: null);
void button(LocalizedString text, Action action)
=> new GUIButton(new RectTransform((0.3f, 1.0f), buttonContainer.RectTransform), text)
{
OnClicked = (_, __) =>
{
action();
msgBox.Close();
return false;
}
};
buttonContainerSpacing(0.1f);
button(TextManager.Get("Yes"), () => confirmDownload = true);
buttonContainerSpacing(0.2f);
button(TextManager.Get("No"), () =>
{
GameMain.Client.Disconnect();
GameMain.MainMenuScreen.Select();
});
buttonContainerSpacing(0.1f);
foreach (var p in missingPackages)
{
pendingDownloads.Enqueue(p);
//Message box frame
new GUITextBlock(new RectTransform((1.0f, 0.1f), msgBoxModList.Content.RectTransform), p.Name)
{
CanBeFocused = false
};
//Download progress frame
var downloadFrame = new GUIFrame(new RectTransform((1.0f, 0.06f), downloadList.Content.RectTransform),
style: "ListBoxElement")
{
UserData = p,
CanBeFocused = false
};
new GUITextBlock(new RectTransform((0.5f, 1.0f), downloadFrame.RectTransform), p.Name)
{
CanBeFocused = false
};
var downloadProgress = new GUIProgressBar(
new RectTransform((0.5f, 0.75f), downloadFrame.RectTransform, Anchor.CenterRight),
0.0f, color: GUIStyle.Green);
downloadProgress.ProgressGetter = () =>
{
if (currentDownload == p)
{
FileReceiver.FileTransferIn? getTransfer() => GameMain.Client.FileReceiver.ActiveTransfers.FirstOrDefault(t => t.FileType == FileTransferType.Mod);
if (downloadProgress.GetAnyChild<GUITextBlock>() is null)
{
GUILayoutGroup progressBarLayout
= new GUILayoutGroup(new RectTransform(Vector2.One, downloadProgress.RectTransform), isHorizontal: true);
void progressBarText(float width, Alignment textAlignment, Func<string> getter)
{
var textContainer = new GUIFrame(new RectTransform((width, 1.0f), progressBarLayout.RectTransform),
style: null);
var textShadow = new GUITextBlock(new RectTransform(Vector2.One, textContainer.RectTransform) { AbsoluteOffset = new Point(GUI.IntScale(3)) }, "",
textColor: Color.Black, textAlignment: textAlignment);
var text = new GUITextBlock(new RectTransform(Vector2.One, textContainer.RectTransform), "",
textAlignment: textAlignment);
new GUICustomComponent(new RectTransform(Vector2.Zero, textContainer.RectTransform), onUpdate:
(f, component) =>
{
string str = getter();
if (text.Text?.SanitizedValue != str)
{
text.Text = str;
textShadow.Text = str;
}
});
}
progressBarText(0.475f, Alignment.CenterRight, () => MathUtils.GetBytesReadable(getTransfer()?.Received ?? 0));
progressBarText(0.05f, Alignment.Center, () => "/");
progressBarText(0.475f, Alignment.CenterLeft, () => MathUtils.GetBytesReadable(getTransfer()?.FileSize ?? 0));
}
return getTransfer()?.Progress ?? 0.0f;
}
if (!pendingDownloads.Contains(p))
{
downloadProgress.ClearChildren();
return 1.0f;
}
return 0.0f;
};
}
}
public override void Deselect()
{
Reset();
base.Deselect();
}
public override void Update(double deltaTime)
{
base.Update(deltaTime);
if (GameMain.Client is null) { return; }
if (!confirmDownload) { return; }
if (currentDownload is null)
{
if (pendingDownloads.TryDequeue(out currentDownload))
{
GameMain.Client.RequestFile(FileTransferType.Mod, currentDownload.Name, currentDownload.Hash.StringRepresentation);
}
else
{
var serverPackages = GameMain.Client.ClientPeer.ServerContentPackages;
CorePackage corePackage
= downloadedPackages.FirstOrDefault(p => p is CorePackage) as CorePackage
?? serverPackages.FirstOrDefault(p => p.CorePackage != null)
?.CorePackage
?? throw new Exception($"Failed to find core package to enable");
RegularPackage[] regularPackages
= serverPackages.Where(p => p.CorePackage is null)
.Select(p =>
p.RegularPackage
?? downloadedPackages.FirstOrDefault(d => d is RegularPackage && d.Hash.Equals(p.Hash))
?? throw new Exception($"Could not find regular package \"{p.Name}\""))
.Cast<RegularPackage>()
.ToArray();
foreach (var regularPackage in regularPackages)
{
DebugConsole.NewMessage($"Enabling \"{regularPackage.Name}\" ({regularPackage.Dir})", Color.Lime);
}
ContentPackageManager.EnabledPackages.BackUp();
ContentPackageManager.EnabledPackages.SetCore(corePackage);
ContentPackageManager.EnabledPackages.SetRegular(regularPackages);
GameMain.NetLobbyScreen.Select();
}
}
}
public void CurrentDownloadFinished(FileReceiver.FileTransferIn transfer)
{
if (currentDownload is null) { throw new Exception("Current download is null"); }
string path = transfer.FilePath;
if (!path.EndsWith(ModReceiver.Extension, StringComparison.OrdinalIgnoreCase))
{
return;
}
string dir = path.RemoveFromEnd(ModReceiver.Extension, StringComparison.OrdinalIgnoreCase);
SaveUtil.DecompressToDirectory(path, dir, file => { });
ContentPackage newPackage
= ContentPackage.TryLoad($"{dir}/{ContentPackage.FileListFileName}")
?? throw new Exception($"Failed to load downloaded mod \"{currentDownload.Name}\"");
if (!currentDownload.Hash.Equals(newPackage.Hash))
{
throw new Exception($"Hash mismatch for downloaded mod \"{currentDownload.Name}\" (expected {currentDownload.Hash}, got {newPackage.Hash})");
}
downloadedPackages.Add(newPackage);
currentDownload = null;
}
public override void Draw(double deltaTime, GraphicsDevice graphics, SpriteBatch spriteBatch)
{
GameMain.MainMenuScreen.DrawBackground(graphics, spriteBatch); //wtf
spriteBatch.Begin(SpriteSortMode.Deferred, null, GUI.SamplerState, null, GameMain.ScissorTestEnable);
GUI.Draw(Cam, spriteBatch);
spriteBatch.End();
}
}
}
@@ -264,7 +264,7 @@ namespace Barotrauma
}
}
public List<Pair<JobPrefab, int>> JobPreferences
public List<JobVariant> JobPreferences
{
get
{
@@ -272,13 +272,13 @@ namespace Barotrauma
// (e.g. the player has a pre-existing campaign character)
if (JobList?.Content == null)
{
return new List<Pair<JobPrefab, int>>();
return new List<JobVariant>();
}
List<Pair<JobPrefab, int>> jobPreferences = new List<Pair<JobPrefab, int>>();
List<JobVariant> jobPreferences = new List<JobVariant>();
foreach (GUIComponent child in JobList.Content.Children)
{
if (!(child.UserData is Pair<JobPrefab, int> jobPrefab)) { continue; }
if (!(child.UserData is JobVariant jobPrefab)) { continue; }
jobPreferences.Add(jobPrefab);
}
return jobPreferences;
@@ -384,14 +384,14 @@ namespace Barotrauma
Stretch = true,
RelativeSpacing = 0.05f
};
FileTransferTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), fileTransferContent.RectTransform), "", font: GUI.SmallFont);
FileTransferTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), fileTransferContent.RectTransform), "", font: GUIStyle.SmallFont);
var fileTransferBottom = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), fileTransferContent.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true
};
FileTransferProgressBar = new GUIProgressBar(new RectTransform(new Vector2(0.6f, 1.0f), fileTransferBottom.RectTransform), 0.0f, Color.DarkGreen);
FileTransferProgressText = new GUITextBlock(new RectTransform(Vector2.One, FileTransferProgressBar.RectTransform), "",
font: GUI.SmallFont, textAlignment: Alignment.CenterLeft);
font: GUIStyle.SmallFont, textAlignment: Alignment.CenterLeft);
new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), fileTransferBottom.RectTransform), TextManager.Get("cancel"), style: "GUIButtonSmall")
{
OnClicked = (btn, userdata) =>
@@ -527,7 +527,7 @@ namespace Barotrauma
chatInput = new GUITextBox(new RectTransform(new Vector2(0.95f, 1.0f), chatRow.RectTransform))
{
MaxTextLength = ChatMessage.MaxLength,
Font = GUI.SmallFont,
Font = GUIStyle.SmallFont,
DeselectAfterMessage = false
};
@@ -578,7 +578,7 @@ namespace Barotrauma
serverLogFilter = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.07f), serverLogHolder.RectTransform))
{
MaxTextLength = ChatMessage.MaxLength,
Font = GUI.SmallFont
Font = GUIStyle.SmallFont
};
roundControlsHolder = new GUILayoutGroup(new RectTransform(Vector2.One, bottomBarRight.RectTransform),
@@ -618,7 +618,7 @@ namespace Barotrauma
//autorestart ------------------------------------------------------------------
autoRestartText = new GUITextBlock(new RectTransform(Vector2.One, bottomBarMid.RectTransform), "", font: GUI.SmallFont, style: "TextFrame", textAlignment: Alignment.Center);
autoRestartText = new GUITextBlock(new RectTransform(Vector2.One, bottomBarMid.RectTransform), "", font: GUIStyle.SmallFont, style: "TextFrame", textAlignment: Alignment.Center);
GUIFrame autoRestartBoxContainer = new GUIFrame(new RectTransform(Vector2.One, bottomBarMid.RectTransform), style: "TextFrame");
autoRestartBox = new GUITickBox(new RectTransform(new Vector2(0.95f, 0.75f), autoRestartBoxContainer.RectTransform, Anchor.Center), TextManager.Get("AutoRestart"))
{
@@ -704,13 +704,13 @@ namespace Barotrauma
HideElementsOutsideFrame = true
};
new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.05f), serverBanner.RectTransform) { RelativeOffset = new Vector2(0.01f, 0.04f) },
"", font: GUI.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader")
"", font: GUIStyle.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader")
{
CanBeFocused = false
};
publicOrPrivate = new GUITextBlock(new RectTransform(new Vector2(0.15f, 1.0f), serverBanner.RectTransform, Anchor.BottomRight, Pivot.BottomRight),
"", font: GUI.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader")
"", font: GUIStyle.SmallFont, textAlignment: Alignment.Center, textColor: Color.White, style: "GUISlopedHeader")
{
CanBeFocused = false
};
@@ -719,7 +719,7 @@ namespace Barotrauma
ServerMessage = new GUITextBox(new RectTransform(Vector2.One, serverMessageContainer.Content.RectTransform),
style: "GUITextBoxNoBorder", wrap: true, textAlignment: Alignment.TopLeft);
var serverMessageHint = new GUITextBlock(new RectTransform(Vector2.One, ServerMessage.RectTransform),
textColor: Color.DarkGray * 0.6f, textAlignment: Alignment.TopLeft, font: GUI.Style.Font, text: TextManager.Get("ClickToWriteServerMessage"));
textColor: Color.DarkGray * 0.6f, textAlignment: Alignment.TopLeft, font: GUIStyle.Font, text: TextManager.Get("ClickToWriteServerMessage"));
void updateServerMessageScrollBasedOnCaret()
{
@@ -786,7 +786,7 @@ namespace Barotrauma
Stretch = true
};
var subLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), subHolder.RectTransform) { MinSize = new Point(0, 25) }, TextManager.Get("Submarine"), font: GUI.SubHeadingFont);
var subLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), subHolder.RectTransform) { MinSize = new Point(0, 25) }, TextManager.Get("Submarine"), font: GUIStyle.SubHeadingFont);
SubVisibilityButton
= new GUIButton(
@@ -806,8 +806,8 @@ namespace Barotrauma
{
Stretch = true
};
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("serverlog.filter"), textAlignment: Alignment.CenterLeft, font: GUI.Font);
subSearchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform, Anchor.CenterRight), font: GUI.Font, createClearButton: true);
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("serverlog.filter"), textAlignment: Alignment.CenterLeft, font: GUIStyle.Font);
subSearchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform, Anchor.CenterRight), font: GUIStyle.Font, createClearButton: true);
filterContainer.RectTransform.MinSize = subSearchBox.RectTransform.MinSize;
subSearchBox.OnSelected += (sender, userdata) => { searchTitle.Visible = false; };
subSearchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
@@ -895,7 +895,7 @@ namespace Barotrauma
Stretch = true
};
var modeLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), gameModeHolder.RectTransform) { MinSize = new Point(0, 25) }, TextManager.Get("GameMode"), font: GUI.SubHeadingFont);
var modeLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), gameModeHolder.RectTransform) { MinSize = new Point(0, 25) }, TextManager.Get("GameMode"), font: GUIStyle.SubHeadingFont);
voteText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), modeLabel.RectTransform, Anchor.TopRight),
TextManager.Get("Votes"), textAlignment: Alignment.CenterRight)
{
@@ -922,8 +922,8 @@ namespace Barotrauma
Stretch = true
};
var modeTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), modeContent.RectTransform), mode.Name, font: GUI.SubHeadingFont);
var modeDescription = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), modeContent.RectTransform), mode.Description, font: GUI.SmallFont, wrap: true);
var modeTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), modeContent.RectTransform), mode.Name, font: GUIStyle.SubHeadingFont);
var modeDescription = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), modeContent.RectTransform), mode.Description, font: GUIStyle.SmallFont, wrap: true);
modeTitle.HoverColor = modeDescription.HoverColor = modeTitle.SelectedColor = modeDescription.SelectedColor = Color.Transparent;
modeTitle.HoverTextColor = modeDescription.HoverTextColor = modeTitle.TextColor;
modeTitle.TextColor = modeDescription.TextColor = modeTitle.TextColor * 0.5f;
@@ -953,7 +953,7 @@ namespace Barotrauma
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), campaignContent.RectTransform),
TextManager.Get("gamemode.multiplayercampaign"), font: GUI.SubHeadingFont, textAlignment: Alignment.Center);
TextManager.Get("gamemode.multiplayercampaign"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.Center);
ContinueCampaignButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.3f), campaignContent.RectTransform),
TextManager.Get("campaigncontinue"), textAlignment: Alignment.Center)
{
@@ -981,9 +981,9 @@ namespace Barotrauma
{
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), missionHolder.RectTransform) { MinSize = new Point(0, 25) },
TextManager.Get("MissionType"), font: GUI.SubHeadingFont);
TextManager.Get("MissionType"), font: GUIStyle.SubHeadingFont);
missionTypeList = new GUIListBox(new RectTransform(Vector2.One, missionHolder.RectTransform))
{
OnSelected = (component, obj) =>
@@ -1020,7 +1020,7 @@ namespace Barotrauma
TextManager.Get("MissionType." + missionType.ToString()))
{
UserData = (int)missionType,
ToolTip = TextManager.Get("MissionTypeDescription." + missionType.ToString(), returnNull: true),
ToolTip = TextManager.Get("MissionTypeDescription." + missionType.ToString()),
OnSelected = (tickbox) =>
{
int missionTypeOr = tickbox.Selected ? (int)tickbox.UserData : (int)MissionType.None;
@@ -1045,7 +1045,7 @@ namespace Barotrauma
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.055f), settingsHolder.RectTransform) { MinSize = new Point(0, 25) },
TextManager.Get("Settings"), font: GUI.SubHeadingFont);
TextManager.Get("Settings"), font: GUIStyle.SubHeadingFont);
var settingsFrame = new GUIFrame(new RectTransform(Vector2.One, settingsHolder.RectTransform), style: "InnerFrame");
var settingsContent = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), settingsFrame.RectTransform, Anchor.Center))
{
@@ -1089,11 +1089,11 @@ namespace Barotrauma
};
levelDifficultyScrollBar.OnMoved = (scrollbar, value) =>
{
if (EventManagerSettings.List.Count == 0) { return true; }
if (!EventManagerSettings.Prefabs.Any()) { return true; }
difficultyName.Text =
EventManagerSettings.List[Math.Min((int)Math.Floor(value * EventManagerSettings.List.Count), EventManagerSettings.List.Count - 1)].Name
EventManagerSettings.GetByDifficultyPercentile(value).Name
+ " (" + ((int)Math.Round(scrollbar.BarScrollValue)) + " %)";
difficultyName.TextColor = ToolBox.GradientLerp(scrollbar.BarScroll, GUI.Style.Green, GUI.Style.Orange, GUI.Style.Red);
difficultyName.TextColor = ToolBox.GradientLerp(scrollbar.BarScroll, GUIStyle.Green, GUIStyle.Orange, GUIStyle.Red);
return true;
};
@@ -1214,8 +1214,8 @@ namespace Barotrauma
public IEnumerable<CoroutineStatus> WaitForStartRound(GUIButton startButton)
{
GUI.SetCursorWaiting();
string headerText = TextManager.Get("RoundStartingPleaseWait");
var msgBox = new GUIMessageBox(headerText, TextManager.Get("RoundStarting"), new string[0]);
LocalizedString headerText = TextManager.Get("RoundStartingPleaseWait");
var msgBox = new GUIMessageBox(headerText, TextManager.Get("RoundStarting"), Array.Empty<LocalizedString>());
if (startButton != null)
{
@@ -1405,7 +1405,7 @@ namespace Barotrauma
if (characterInfo == null || CampaignCharacterDiscarded)
{
characterInfo = new CharacterInfo(CharacterPrefab.HumanSpeciesName, GameMain.Client.Name, null);
characterInfo.RecreateHead(GameMain.Config.PlayerCharacterCustomization);
characterInfo.RecreateHead(MultiplayerPreferences.Instance);
GameMain.Client.CharacterInfo = characterInfo;
characterInfo.OmitJobInPortraitClothing = false;
}
@@ -1517,20 +1517,20 @@ namespace Barotrauma
for (int i = 0; i < 3; i++)
{
Pair<JobPrefab, int> jobPrefab = null;
while (i < GameMain.Config.JobPreferences.Count)
JobVariant jobPrefab = null;
while (i < MultiplayerPreferences.Instance.JobPreferences.Count)
{
var jobIdentifier = GameMain.Config.JobPreferences[i];
if (!JobPrefab.Prefabs.ContainsKey(jobIdentifier.First))
var jobPreference = MultiplayerPreferences.Instance.JobPreferences[i];
if (!JobPrefab.Prefabs.ContainsKey(jobPreference.JobIdentifier))
{
GameMain.Config.JobPreferences.RemoveAt(i);
MultiplayerPreferences.Instance.JobPreferences.RemoveAt(i);
continue;
}
// The old job variant system used one-based indexing
// so let's make sure no one get to pick a variant which doesn't exist
var prefab = JobPrefab.Prefabs[jobIdentifier.First];
var variant = Math.Min(jobIdentifier.Second, prefab.Variants - 1);
jobPrefab = new Pair<JobPrefab, int>(prefab, variant);
var prefab = JobPrefab.Prefabs[jobPreference.JobIdentifier];
var variant = Math.Min(jobPreference.Variant, prefab.Variants - 1);
jobPrefab = new JobVariant(prefab, variant);
break;
}
@@ -1553,20 +1553,20 @@ namespace Barotrauma
{
characterInfo.CreateIcon(new RectTransform(new Vector2(0.6f, 0.16f), infoContainer.RectTransform, Anchor.TopCenter));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContainer.RectTransform), characterInfo.Job.Name, textAlignment: Alignment.Center, font: GUI.SubHeadingFont, wrap: true)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContainer.RectTransform), characterInfo.Job.Name, textAlignment: Alignment.Center, font: GUIStyle.SubHeadingFont, wrap: true)
{
HoverColor = Color.Transparent,
SelectedColor = Color.Transparent
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContainer.RectTransform), TextManager.Get("Skills"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContainer.RectTransform), TextManager.Get("Skills"), font: GUIStyle.SubHeadingFont);
foreach (Skill skill in characterInfo.Job.Skills)
{
Color textColor = Color.White * (0.5f + skill.Level / 200.0f);
var skillText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContainer.RectTransform),
" - " + TextManager.AddPunctuation(':', TextManager.Get("SkillName." + skill.Identifier), ((int)skill.Level).ToString()),
textColor,
font: GUI.SmallFont);
font: GUIStyle.SmallFont);
}
// Spacing
@@ -1644,15 +1644,15 @@ namespace Barotrauma
SelectedTextColor = Color.White
};
TeamPreferenceListBox.Select(GameMain.Config.TeamPreference);
TeamPreferenceListBox.Select(MultiplayerPreferences.Instance.TeamPreference);
TeamPreferenceListBox.OnSelected += (component, obj) =>
{
if ((CharacterTeamType)obj == GameMain.Config.TeamPreference) { return true; }
if ((CharacterTeamType)obj == MultiplayerPreferences.Instance.TeamPreference) { return true; }
GameMain.Config.TeamPreference = (CharacterTeamType)obj;
MultiplayerPreferences.Instance.TeamPreference = (CharacterTeamType)obj;
GameMain.Client.ForceNameAndJobUpdate();
GameMain.Config.SaveNewPlayerConfig();
GameSettings.SaveCurrentConfig();
return true;
};
@@ -1685,7 +1685,7 @@ namespace Barotrauma
IgnoreLayoutGroups = true
};
var text = new GUITextBlock(new RectTransform(Vector2.One, changesPendingText.RectTransform, Anchor.Center),
TextManager.Get("tabmenu.characterchangespending"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, style: null);
TextManager.Get("tabmenu.characterchangespending"), textColor: GUIStyle.Orange, textAlignment: Alignment.Center, style: null);
changesPendingText.RectTransform.MinSize = new Point((int)(text.TextSize.X * 1.2f), (int)(text.TextSize.Y * 2.0f));
}
@@ -1698,7 +1698,7 @@ namespace Barotrauma
Color = Color.Black
};
new GUITextBlock(new RectTransform(Vector2.One, changesPendingFrame.RectTransform, Anchor.Center),
TextManager.Get("tabmenu.characterchangespending"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, style: null)
TextManager.Get("tabmenu.characterchangespending"), textColor: GUIStyle.Orange, textAlignment: Alignment.Center, style: null)
{
AutoScaleHorizontal = true
};
@@ -1709,7 +1709,7 @@ namespace Barotrauma
jobVariantTooltip = new GUIFrame(new RectTransform(new Point((int)(400 * GUI.Scale), (int)(180 * GUI.Scale)), GUI.Canvas, pivot: Pivot.BottomRight),
style: "GUIToolTip")
{
UserData = new Pair<JobPrefab, int>(jobPrefab, variant)
UserData = new JobVariant(jobPrefab, variant)
};
jobVariantTooltip.RectTransform.AbsoluteOffset = new Point(parentSlot.Rect.Right, parentSlot.Rect.Y);
@@ -1718,8 +1718,8 @@ namespace Barotrauma
Stretch = true,
AbsoluteSpacing = (int)(15 * GUI.Scale)
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), TextManager.GetWithVariable("startingequipmentname", "[number]", (variant + 1).ToString()), font: GUI.SubHeadingFont, textAlignment: Alignment.Center);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), TextManager.GetWithVariable("startingequipmentname", "[number]", (variant + 1).ToString()), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.Center);
var itemIdentifiers = jobPrefab.PreviewItems[variant]
.Where(it => it.ShowPreview)
@@ -1730,7 +1730,7 @@ namespace Barotrauma
int rows = (int)Math.Max(Math.Ceiling(itemIdentifiers.Count() / (float)itemsPerRow), 1);
new GUICustomComponent(new RectTransform(new Vector2(1.0f, 0.4f * rows), content.RectTransform, Anchor.BottomCenter),
onDraw: (sb, component) => { DrawJobVariantItems(sb, component, new Pair<JobPrefab, int>(jobPrefab, variant), itemsPerRow); });
onDraw: (sb, component) => { DrawJobVariantItems(sb, component, new JobVariant(jobPrefab, variant), itemsPerRow); });
jobVariantTooltip.RectTransform.MinSize = new Point(0, content.RectTransform.Children.Sum(c => c.Rect.Height + content.AbsoluteSpacing));
}
@@ -1818,12 +1818,12 @@ namespace Barotrauma
int buttonSize = (int)(frame.Rect.Height * 0.8f);
var subTextBlock = new GUITextBlock(new RectTransform(new Vector2(0.8f, 1.0f), frame.RectTransform, Anchor.CenterLeft) /*{ AbsoluteOffset = new Point(buttonSize + 5, 0) }*/,
ToolBox.LimitString(sub.DisplayName, GUI.Font, subList.Rect.Width - 65), textAlignment: Alignment.CenterLeft)
ToolBox.LimitString(sub.DisplayName.Value, GUIStyle.Font, subList.Rect.Width - 65), textAlignment: Alignment.CenterLeft)
{
CanBeFocused = false
};
var matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name && s.MD5Hash?.Hash == sub.MD5Hash?.Hash);
var matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name && s.MD5Hash?.StringRepresentation == sub.MD5Hash?.StringRepresentation);
if (matchingSub == null) matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name);
if (matchingSub == null)
@@ -1831,7 +1831,7 @@ namespace Barotrauma
subTextBlock.TextColor = new Color(subTextBlock.TextColor, 0.5f);
frame.ToolTip = TextManager.Get("SubNotFound");
}
else if (matchingSub?.MD5Hash == null || matchingSub.MD5Hash?.Hash != sub.MD5Hash?.Hash)
else if (matchingSub?.MD5Hash == null || matchingSub.MD5Hash?.StringRepresentation != sub.MD5Hash?.StringRepresentation)
{
subTextBlock.TextColor = new Color(subTextBlock.TextColor, 0.5f);
frame.ToolTip = TextManager.Get("SubDoesntMatch");
@@ -1847,7 +1847,7 @@ namespace Barotrauma
if (!sub.RequiredContentPackagesInstalled)
{
subTextBlock.TextColor = Color.Lerp(subTextBlock.TextColor, Color.DarkRed, 0.5f);
frame.ToolTip = TextManager.Get("ContentPackageMismatch") + "\n\n" + frame.RawToolTip;
frame.ToolTip = TextManager.Get("ContentPackageMismatch") + "\n\n" + frame.ToolTip.SanitizedString;
}
CreateSubmarineClassText(
@@ -1866,10 +1866,10 @@ namespace Barotrauma
if (sub.HasTag(SubmarineTag.Shuttle))
{
var shuttleText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), parent.RectTransform, Anchor.CenterRight) { AbsoluteOffset = new Point(GUI.IntScale(20), 0) },
TextManager.Get("Shuttle", fallBackTag: "RespawnShuttle"), textAlignment: Alignment.CenterRight, font: GUI.SmallFont)
TextManager.Get("Shuttle", "RespawnShuttle"), textAlignment: Alignment.CenterRight, font: GUIStyle.SmallFont)
{
TextColor = subTextBlock.TextColor * 0.8f,
ToolTip = subTextBlock.RawToolTip,
ToolTip = subTextBlock.ToolTip?.SanitizedString,
CanBeFocused = false
};
//make shuttles more dim in the sub list (selecting a shuttle as the main sub is allowed but not recommended)
@@ -1885,11 +1885,11 @@ namespace Barotrauma
else
{
var classText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), parent.RectTransform, Anchor.CenterRight) { AbsoluteOffset = new Point(GUI.IntScale(20), 0) },
TextManager.Get($"submarineclass.{sub.SubmarineClass}"), textAlignment: Alignment.CenterRight, font: GUI.SmallFont)
TextManager.Get($"submarineclass.{sub.SubmarineClass}"), textAlignment: Alignment.CenterRight, font: GUIStyle.SmallFont)
{
UserData = "classtext",
TextColor = subTextBlock.TextColor * 0.8f,
ToolTip = subTextBlock.RawToolTip,
ToolTip = subTextBlock.ToolTip,
CanBeFocused = false
};
}
@@ -1911,7 +1911,7 @@ namespace Barotrauma
selectedSub.RequiredContentPackages.Any() ?
TextManager.GetWithVariable("ContentPackageMismatchWarning", "[requiredcontentpackages]", string.Join(", ", selectedSub.RequiredContentPackages)) :
TextManager.Get("ContentPackageMismatchWarningGeneric"),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = msgBox.Close;
msgBox.Buttons[0].OnClicked += (button, obj) =>
@@ -1941,14 +1941,14 @@ namespace Barotrauma
{
if (GameMain.Client.HasPermission(ClientPermissions.SelectMode))
{
string presetName = ((GameModePreset)component.UserData).Identifier;
Identifier presetName = ((GameModePreset)component.UserData).Identifier;
//display a verification prompt when switching away from the campaign
if (HighlightedModeIndex == SelectedModeIndex &&
(GameMain.NetLobbyScreen.ModeList.SelectedData as GameModePreset) == GameModePreset.MultiPlayerCampaign &&
presetName != GameModePreset.MultiPlayerCampaign.Identifier)
{
var verificationBox = new GUIMessageBox("", TextManager.Get("endcampaignverification"), new string[] { TextManager.Get("yes"), TextManager.Get("no") });
var verificationBox = new GUIMessageBox("", TextManager.Get("endcampaignverification"), new LocalizedString[] { TextManager.Get("yes"), TextManager.Get("no") });
verificationBox.Buttons[0].OnClicked += (btn, userdata) =>
{
GameMain.Client.RequestSelectMode(component.Parent.GetChildIndex(component));
@@ -1962,7 +1962,7 @@ namespace Barotrauma
GameMain.Client.RequestSelectMode(component.Parent.GetChildIndex(component));
HighlightMode(SelectedModeIndex);
if (presetName.Equals("multiplayercampaign", StringComparison.OrdinalIgnoreCase))
if (presetName == "multiplayercampaign")
{
GUI.SetCursorWaiting(endCondition: () =>
{
@@ -1970,7 +1970,7 @@ namespace Barotrauma
});
}
return !presetName.Equals("multiplayercampaign", StringComparison.OrdinalIgnoreCase);
return presetName != "multiplayercampaign";
}
return false;
}
@@ -1994,7 +1994,7 @@ namespace Barotrauma
public void AddPlayer(Client client)
{
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.1f), PlayerList.Content.RectTransform) { MinSize = new Point(0, (int)(30 * GUI.Scale)) },
client.Name, textAlignment: Alignment.CenterLeft, font: GUI.SmallFont, style: null)
client.Name, textAlignment: Alignment.CenterLeft, font: GUIStyle.SmallFont, style: null)
{
Padding = Vector4.One * 10.0f * GUI.Scale,
Color = Color.White * 0.25f,
@@ -2006,7 +2006,7 @@ namespace Barotrauma
UserData = client
};
var soundIcon = new GUIImage(new RectTransform(new Point((int)(textBlock.Rect.Height * 0.8f)), textBlock.RectTransform, Anchor.CenterRight) { AbsoluteOffset = new Point(5, 0) },
sprite: GUI.Style.GetComponentStyle("GUISoundIcon").GetDefaultSprite(), scaleToFit: true)
sprite: GUIStyle.GetComponentStyle("GUISoundIcon").GetDefaultSprite(), scaleToFit: true)
{
UserData = new Pair<string, float>("soundicon", 0.0f),
CanBeFocused = false,
@@ -2170,7 +2170,7 @@ namespace Barotrauma
{
permissionOptions.Add(new ContextMenuOption(rank.Name, isEnabled: true, onSelected: () =>
{
string label = TextManager.GetWithVariables(rank.Permissions == ClientPermissions.None ? "clearrankprompt" : "giverankprompt", new []{ "[user]", "[rank]" }, new []{ client.Name, rank.Name });
LocalizedString label = TextManager.GetWithVariables(rank.Permissions == ClientPermissions.None ? "clearrankprompt" : "giverankprompt", ("[user]", client.Name), ("[rank]", rank.Name));
GUIMessageBox msgBox = new GUIMessageBox(string.Empty, label, new[] { TextManager.Get("Yes"), TextManager.Get("Cancel") });
msgBox.Buttons[0].OnClicked = delegate
@@ -2257,7 +2257,7 @@ namespace Barotrauma
};
var nameText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), headerContainer.RectTransform),
text: selectedClient.Name, font: GUI.LargeFont);
text: selectedClient.Name, font: GUIStyle.LargeFont);
nameText.Text = ToolBox.LimitString(nameText.Text, nameText.Font, (int)(nameText.Rect.Width * 0.95f));
if (hasManagePermissions)
@@ -2265,7 +2265,7 @@ namespace Barotrauma
PlayerFrame.UserData = selectedClient;
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), paddedPlayerFrame.RectTransform),
TextManager.Get("Rank"), font: GUI.SubHeadingFont);
TextManager.Get("Rank"), font: GUIStyle.SubHeadingFont);
var rankDropDown = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.1f), paddedPlayerFrame.RectTransform),
TextManager.Get("Rank"))
{
@@ -2303,9 +2303,9 @@ namespace Barotrauma
Stretch = true,
RelativeSpacing = 0.05f
};
var permissionLabel = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), permissionLabels.RectTransform), TextManager.Get("Permissions"), font: GUI.SubHeadingFont);
var permissionLabel = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), permissionLabels.RectTransform), TextManager.Get("Permissions"), font: GUIStyle.SubHeadingFont);
var consoleCommandLabel = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), permissionLabels.RectTransform),
TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUI.SubHeadingFont);
TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUIStyle.SubHeadingFont);
GUITextBlock.AutoScaleAndNormalize(permissionLabel, consoleCommandLabel);
var permissionContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.4f), paddedPlayerFrame.RectTransform), isHorizontal: true)
@@ -2320,7 +2320,7 @@ namespace Barotrauma
RelativeSpacing = 0.05f
};
new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), listBoxContainerLeft.RectTransform), TextManager.Get("all", fallBackTag: "clientpermission.all"))
new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), listBoxContainerLeft.RectTransform), TextManager.Get("all", "clientpermission.all"))
{
Enabled = !myClient,
OnSelected = (tickbox) =>
@@ -2351,7 +2351,7 @@ namespace Barotrauma
if (permission == ClientPermissions.None || permission == ClientPermissions.All) continue;
var permissionTick = new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), permissionsBox.Content.RectTransform),
TextManager.Get("ClientPermission." + permission), font: GUI.SmallFont)
TextManager.Get("ClientPermission." + permission), font: GUIStyle.SmallFont)
{
UserData = permission,
Selected = selectedClient.HasPermission(permission),
@@ -2387,7 +2387,7 @@ namespace Barotrauma
RelativeSpacing = 0.05f
};
new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), listBoxContainerRight.RectTransform), TextManager.Get("all", fallBackTag: "clientpermission.all"))
new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), listBoxContainerRight.RectTransform), TextManager.Get("all", "clientpermission.all"))
{
Enabled = !myClient,
OnSelected = (tickbox) =>
@@ -2415,7 +2415,7 @@ namespace Barotrauma
foreach (DebugConsole.Command command in DebugConsole.Commands)
{
var commandTickBox = new GUITickBox(new RectTransform(new Vector2(0.15f, 0.15f), commandList.Content.RectTransform),
command.names[0], font: GUI.SmallFont)
command.names[0], font: GUIStyle.SmallFont)
{
Selected = selectedClient.PermittedConsoleCommands.Contains(command),
Enabled = !myClient,
@@ -2521,7 +2521,7 @@ namespace Barotrauma
viewSteamProfileButton.TextBlock.AutoScaleHorizontal = true;
viewSteamProfileButton.OnClicked = (bt, userdata) =>
{
Steamworks.SteamFriends.OpenWebOverlay("https://steamcommunity.com/profiles/" + selectedClient.SteamID.ToString());
SteamManager.OverlayCustomURL("https://steamcommunity.com/profiles/" + selectedClient.SteamID.ToString());
return true;
};
}
@@ -2605,26 +2605,22 @@ namespace Barotrauma
if (GameMain.Client == null) { return; }
string currMicStyle = micIcon.Style.Element.Name.LocalName;
Identifier currMicStyle = micIcon.Style.Element.NameAsIdentifier();
string targetMicStyle = "GUIMicrophoneEnabled";
if (GameMain.Config.CaptureDeviceNames == null)
Identifier targetMicStyle = "GUIMicrophoneEnabled".ToIdentifier();
var voipCaptureDeviceNames = VoipCapture.CaptureDeviceNames;
if (voipCaptureDeviceNames.Count == 0)
{
GameMain.Config.CaptureDeviceNames = OpenAL.Alc.GetStringList(IntPtr.Zero, OpenAL.Alc.CaptureDeviceSpecifier);
targetMicStyle = "GUIMicrophoneUnavailable".ToIdentifier();
}
else if (GameSettings.CurrentConfig.Audio.VoiceSetting == VoiceMode.Disabled)
{
targetMicStyle = "GUIMicrophoneDisabled".ToIdentifier();
}
if (GameMain.Config.CaptureDeviceNames.Count == 0)
if (targetMicStyle != currMicStyle)
{
targetMicStyle = "GUIMicrophoneUnavailable";
}
else if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.Disabled)
{
targetMicStyle = "GUIMicrophoneDisabled";
}
if (!targetMicStyle.Equals(currMicStyle, StringComparison.OrdinalIgnoreCase))
{
GUI.Style.Apply(micIcon, targetMicStyle);
GUIStyle.Apply(micIcon, targetMicStyle);
}
foreach (GUIComponent child in PlayerList.Content.Children)
@@ -2672,12 +2668,11 @@ namespace Barotrauma
JobSelectionFrame.Visible = false;
}
if (GUI.MouseOn?.UserData is Pair<JobPrefab, int> jobPrefab && GUI.MouseOn.Style?.Name == "JobVariantButton")
if (GUI.MouseOn?.UserData is JobVariant jobPrefab && GUI.MouseOn.Style?.Name == "JobVariantButton")
{
var prevVisibleVariant = jobVariantTooltip?.UserData as Pair<JobPrefab, int>;
if (jobVariantTooltip == null || prevVisibleVariant.First != jobPrefab.First || prevVisibleVariant.Second != jobPrefab.Second)
if (!(jobVariantTooltip?.UserData is JobVariant prevVisibleVariant) || prevVisibleVariant.Prefab != jobPrefab.Prefab || prevVisibleVariant.Variant != jobPrefab.Variant)
{
CreateJobVariantTooltip(jobPrefab.First, jobPrefab.Second, GUI.MouseOn.Parent);
CreateJobVariantTooltip(jobPrefab.Prefab, jobPrefab.Variant, GUI.MouseOn.Parent);
}
}
if (jobVariantTooltip != null)
@@ -2730,9 +2725,9 @@ namespace Barotrauma
publicOrPrivate.RectTransform.NonScaledSize = (publicOrPrivate.Font.MeasureString(publicOrPrivate.Text) + new Vector2(25, 8) * GUI.Scale).ToPoint();
}
private void DrawJobVariantItems(SpriteBatch spriteBatch, GUICustomComponent component, Pair<JobPrefab, int> jobPrefab, int itemsPerRow)
private void DrawJobVariantItems(SpriteBatch spriteBatch, GUICustomComponent component, JobVariant jobPrefab, int itemsPerRow)
{
var itemIdentifiers = jobPrefab.First.PreviewItems[jobPrefab.Second]
var itemIdentifiers = jobPrefab.Prefab.PreviewItems[jobPrefab.Variant]
.Where(it => it.ShowPreview)
.Select(it => it.ItemIdentifier)
.Distinct();
@@ -2753,8 +2748,8 @@ namespace Barotrauma
}
int i = 0;
Rectangle tooltipRect = Rectangle.Empty;
string tooltip = null;
foreach (var itemIdentifier in itemIdentifiers)
LocalizedString tooltip = null;
foreach (Identifier itemIdentifier in itemIdentifiers)
{
if (!(MapEntityPrefab.Find(null, identifier: itemIdentifier, showErrorMessages: false) is ItemPrefab itemPrefab)) { continue; }
@@ -2769,15 +2764,15 @@ namespace Barotrauma
scale: slotSize.X / (float)Inventory.SlotSpriteSmall.SourceRect.Width,
color: slotRect.Contains(PlayerInput.MousePosition) ? Color.White : Color.White * 0.6f);
Sprite icon = itemPrefab.InventoryIcon ?? itemPrefab.sprite;
Sprite icon = itemPrefab.InventoryIcon ?? itemPrefab.Sprite;
float iconScale = Math.Min(Math.Min(slotSize.X / icon.size.X, slotSize.Y / icon.size.Y), 2.0f) * 0.9f;
icon.Draw(spriteBatch, slotPos + slotSize.ToVector2() * 0.5f, scale: iconScale);
int count = jobPrefab.First.PreviewItems[jobPrefab.Second].Count(it => it.ShowPreview && it.ItemIdentifier == itemIdentifier);
int count = jobPrefab.Prefab.PreviewItems[jobPrefab.Variant].Count(it => it.ShowPreview && it.ItemIdentifier == itemIdentifier);
if (count > 1)
{
string itemCountText = "x" + count;
GUI.Font.DrawString(spriteBatch, itemCountText, slotPos + slotSize.ToVector2() - GUI.Font.MeasureString(itemCountText) - Vector2.UnitX * 5, Color.White);
GUIStyle.Font.DrawString(spriteBatch, itemCountText, slotPos + slotSize.ToVector2() - GUIStyle.Font.MeasureString(itemCountText) - Vector2.UnitX * 5, Color.White);
}
if (slotRect.Contains(PlayerInput.MousePosition))
@@ -2787,7 +2782,7 @@ namespace Barotrauma
}
i++;
}
if (!string.IsNullOrEmpty(tooltip))
if (!tooltip.IsNullOrEmpty())
{
GUIComponent.DrawToolTip(spriteBatch, tooltip, tooltipRect);
}
@@ -2803,11 +2798,10 @@ namespace Barotrauma
}
GUITextBlock msg = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), chatBox.Content.RectTransform),
text: ChatMessage.GetTimeStamp() + (message.Type == ChatMessageType.Private ? TextManager.Get("PrivateMessageTag") + " " : "") + message.TextWithSender,
text: RichString.Rich(ChatMessage.GetTimeStamp() + (message.Type == ChatMessageType.Private ? TextManager.Get("PrivateMessageTag") + " " : "") + message.TextWithSender),
textColor: message.Color,
color: ((chatBox.CountChildren % 2) == 0) ? Color.Transparent : Color.Black * 0.1f,
wrap: true, font: GUI.SmallFont,
parseRichText: true)
wrap: true, font: GUIStyle.SmallFont)
{
UserData = message,
CanBeFocused = false
@@ -2876,14 +2870,25 @@ namespace Barotrauma
},
OnSliderReleased = SaveHead
};
return false;
}
private bool SaveHead(GUIScrollBar scrollBar, float barScroll) => StoreHead(true);
private bool StoreHead(bool save)
{
GameMain.Config.PlayerCharacterCustomization = GameMain.Client.CharacterInfo.Head;
var info = GameMain.Client.CharacterInfo;
var characterConfig = MultiplayerPreferences.Instance;
characterConfig.TagSet.Clear(); characterConfig.TagSet.UnionWith(info.Head.Preset.TagSet);
characterConfig.HairIndex = info.Head.HairIndex;
characterConfig.BeardIndex = info.Head.BeardIndex;
characterConfig.MoustacheIndex = info.Head.MoustacheIndex;
characterConfig.FaceAttachmentIndex = info.Head.FaceAttachmentIndex;
characterConfig.HairColor = info.Head.HairColor;
characterConfig.FacialHairColor = info.Head.FacialHairColor;
characterConfig.SkinColor = info.Head.SkinColor;
if (save)
{
if (GameMain.GameSession?.IsRunning ?? false)
@@ -2891,14 +2896,14 @@ namespace Barotrauma
TabMenu.PendingChanges = true;
CreateChangesPendingText();
}
GameMain.Config.SaveNewPlayerConfig();
GameSettings.SaveCurrentConfig();
}
return true;
}
private bool SwitchJob(GUIButton _, object obj)
{
if (JobList == null) { return false; }
if (JobList == null || GameMain.Client == null) { return false; }
int childIndex = JobList.SelectedIndex;
var child = JobList.SelectedComponent;
@@ -2906,11 +2911,11 @@ namespace Barotrauma
bool moveToNext = obj != null;
var jobPrefab = (obj as Pair<JobPrefab, int>)?.First;
var jobPrefab = (obj as JobVariant)?.Prefab;
var prevObj = child.UserData;
var existingChild = JobList.Content.FindChild(d => (d.UserData is Pair<JobPrefab, int> prefab) && (prefab.First == jobPrefab));
var existingChild = JobList.Content.FindChild(d => (d.UserData is JobVariant prefab) && (prefab.Prefab == jobPrefab));
if (existingChild != null && obj != null)
{
existingChild.UserData = prevObj;
@@ -2981,13 +2986,13 @@ namespace Barotrauma
GUIButton jobButton = null;
var availableJobs = JobPrefab.Prefabs.Where(jobPrefab =>
jobPrefab.MaxNumber > 0 && JobList.Content.Children.All(c => !(c.UserData is Pair<JobPrefab, int> prefab) || prefab.First != jobPrefab)
).Select(j => new Pair<JobPrefab, int>(j, 0));
jobPrefab.MaxNumber > 0 && JobList.Content.Children.All(c => !(c.UserData is JobVariant prefab) || prefab.Prefab != jobPrefab)
).Select(j => new JobVariant(j, 0));
availableJobs = availableJobs.Concat(
JobPrefab.Prefabs.Where(jobPrefab =>
jobPrefab.MaxNumber > 0 && JobList.Content.Children.Any(c => (c.UserData is Pair<JobPrefab, int> prefab) && prefab.First == jobPrefab)
).Select(j => JobList.Content.FindChild(c => (c.UserData is Pair<JobPrefab, int> prefab) && prefab.First == j).UserData as Pair<JobPrefab, int>));
jobPrefab.MaxNumber > 0 && JobList.Content.Children.Any(c => (c.UserData is JobVariant prefab) && prefab.Prefab == jobPrefab)
).Select(j => (JobVariant)JobList.Content.FindChild(c => (c.UserData is JobVariant prefab) && prefab.Prefab == j).UserData));
availableJobs = availableJobs.ToList();
@@ -3012,11 +3017,11 @@ namespace Barotrauma
};
itemsInRow++;
var images = AddJobSpritesToGUIComponent(jobButton, jobPrefab.First, selectedByPlayer: false);
var images = AddJobSpritesToGUIComponent(jobButton, jobPrefab.Prefab, selectedByPlayer: false);
if (images != null && images.Length > 1)
{
jobPrefab.Second = Math.Min(jobPrefab.Second, images.Length);
int currVisible = jobPrefab.Second;
jobPrefab.Variant = Math.Min(jobPrefab.Variant, images.Length);
int currVisible = jobPrefab.Variant;
GUIButton currSelected = null;
for (int variantIndex = 0; variantIndex < images.Length; variantIndex++)
{
@@ -3029,7 +3034,7 @@ namespace Barotrauma
variantButton.OnClicked = (btn, obj) =>
{
if (currSelected != null) { currSelected.Selected = false; }
int k = ((Pair<JobPrefab, int>)obj).Second;
int k = ((JobVariant)obj).Variant;
btn.Parent.UserData = obj;
for (int j = 0; j < images.Length; j++)
{
@@ -3062,14 +3067,14 @@ namespace Barotrauma
private GUIImage[][] AddJobSpritesToGUIComponent(GUIComponent parent, JobPrefab jobPrefab, bool selectedByPlayer)
{
GUIFrame innerFrame = null;
List<JobPrefab.OutfitPreview> outfitPreviews = jobPrefab.GetJobOutfitSprites(Gender.Male, useInventoryIcon: true, out var maxDimensions);
List<JobPrefab.OutfitPreview> outfitPreviews = jobPrefab.GetJobOutfitSprites(CharacterPrefab.HumanPrefab.CharacterInfoPrefab, useInventoryIcon: true, out var maxDimensions);
innerFrame = new GUIFrame(new RectTransform(Vector2.One * 0.85f, parent.RectTransform, Anchor.Center), style: null)
{
CanBeFocused = false
};
GUIImage[][] retVal = new GUIImage[0][];
GUIImage[][] retVal = Array.Empty<GUIImage[]>();
if (outfitPreviews != null && outfitPreviews.Any())
{
retVal = new GUIImage[outfitPreviews.Count][];
@@ -3212,7 +3217,7 @@ namespace Barotrauma
{
CampaignSetupFrame.ClearChildren();
new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.5f), CampaignSetupFrame.RectTransform, Anchor.Center),
TextManager.Get("campaignstarting"), font: GUI.SubHeadingFont, textAlignment: Alignment.Center, wrap: true);
TextManager.Get("campaignstarting"), font: GUIStyle.SubHeadingFont, textAlignment: Alignment.Center, wrap: true);
}
}
}
@@ -3284,9 +3289,9 @@ namespace Barotrauma
private bool ViewJobInfo(GUIButton button, object obj)
{
if (!(button.UserData is Pair<JobPrefab, int> jobPrefab)) { return false; }
if (!(button.UserData is JobVariant jobPrefab)) { return false; }
JobInfoFrame = jobPrefab.First.CreateInfoFrame(out GUIComponent buttonContainer);
JobInfoFrame = jobPrefab.Prefab.CreateInfoFrame(out GUIComponent buttonContainer);
GUIButton closeButton = new GUIButton(new RectTransform(new Vector2(0.25f, 0.05f), buttonContainer.RectTransform, Anchor.BottomRight),
TextManager.Get("Close"))
{
@@ -3315,7 +3320,7 @@ namespace Barotrauma
/*foreach (Sprite sprite in jobPreferenceSprites) { sprite.Remove(); }
jobPreferenceSprites.Clear();*/
List<Pair<string, int>> jobNamePreferences = new List<Pair<string, int>>();
List<MultiplayerPreferences.JobPreference> jobPreferences = new List<MultiplayerPreferences.JobPreference>();
bool disableNext = false;
for (int i = 0; i < listBox.Content.CountChildren; i++)
@@ -3325,15 +3330,15 @@ namespace Barotrauma
slot.ClearChildren();
slot.CanBeFocused = !disableNext;
if (slot.UserData is Pair<JobPrefab, int> jobPrefab)
if (slot.UserData is JobVariant jobPrefab)
{
var images = AddJobSpritesToGUIComponent(slot, jobPrefab.First, selectedByPlayer: true);
var images = AddJobSpritesToGUIComponent(slot, jobPrefab.Prefab, selectedByPlayer: true);
for (int variantIndex = 0; variantIndex < images.Length; variantIndex++)
{
foreach (GUIImage image in images[variantIndex])
{
//jobPreferenceSprites.Add(image.Sprite);
int selectedVariantIndex = Math.Min(jobPrefab.Second, images.Length);
int selectedVariantIndex = Math.Min(jobPrefab.Variant, images.Length);
image.Visible = images.Length == 1 || selectedVariantIndex == variantIndex;
}
if (images.Length > 1)
@@ -3372,14 +3377,14 @@ namespace Barotrauma
}
};
jobNamePreferences.Add(new Pair<string, int>(jobPrefab.First.Identifier, jobPrefab.Second));
jobPreferences.Add(new MultiplayerPreferences.JobPreference(jobPrefab.Prefab.Identifier, jobPrefab.Variant));
}
else
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.6f), slot.RectTransform), (i + 1).ToString(),
textColor: Color.White * (disableNext ? 0.15f : 0.5f),
textAlignment: Alignment.Center,
font: GUI.LargeFont)
font: GUIStyle.LargeFont)
{
CanBeFocused = false
};
@@ -3387,7 +3392,7 @@ namespace Barotrauma
if (!disableNext)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.4f), slot.RectTransform, Anchor.BottomCenter), TextManager.Get("clicktoselectjob"),
font: GUI.SmallFont,
font: GUIStyle.SmallFont,
wrap: true,
textAlignment: Alignment.Center)
{
@@ -3400,7 +3405,7 @@ namespace Barotrauma
}
GameMain.Client.ForceNameAndJobUpdate();
if (!GameMain.Config.AreJobPreferencesEqual(jobNamePreferences))
if (!MultiplayerPreferences.Instance.AreJobPreferencesEqual(jobPreferences))
{
if (GameMain.GameSession?.IsRunning ?? false)
{
@@ -3408,12 +3413,13 @@ namespace Barotrauma
CreateChangesPendingText();
}
GameMain.Config.JobPreferences = jobNamePreferences;
GameMain.Config.SaveNewPlayerConfig();
MultiplayerPreferences.Instance.JobPreferences.Clear();
MultiplayerPreferences.Instance.JobPreferences.AddRange(jobPreferences);
GameSettings.SaveCurrentConfig();
}
}
private GUIButton CreateJobVariantButton(Pair<JobPrefab, int> jobPrefab, int variantIndex, int variantCount, GUIComponent slot)
private GUIButton CreateJobVariantButton(JobVariant jobPrefab, int variantIndex, int variantCount, GUIComponent slot)
{
float relativeSize = 0.15f;
@@ -3421,8 +3427,8 @@ namespace Barotrauma
{ RelativeOffset = new Vector2(relativeSize * 1.3f * (variantIndex - (variantCount - 1) / 2.0f), 0.02f) },
(variantIndex + 1).ToString(), style: "JobVariantButton")
{
Selected = jobPrefab.Second == variantIndex,
UserData = new Pair<JobPrefab, int>(jobPrefab.First, variantIndex),
Selected = jobPrefab.Variant == variantIndex,
UserData = new JobVariant(jobPrefab.Prefab, variantIndex),
};
return btn;
@@ -3440,6 +3446,7 @@ namespace Barotrauma
public static bool operator ==(FailedSubInfo a, FailedSubInfo b)
=> StringsEqual(a.Name, b.Name) && StringsEqual(a.Hash, b.Hash);
public static bool operator !=(FailedSubInfo a, FailedSubInfo b)
=> !(a == b);
}
@@ -3462,7 +3469,7 @@ namespace Barotrauma
}
SubmarineInfo sub = subList.Content.Children
.FirstOrDefault(c => c.UserData is SubmarineInfo s && s.Name == subName && s.MD5Hash?.Hash == md5Hash)?
.FirstOrDefault(c => c.UserData is SubmarineInfo s && s.Name == subName && s.MD5Hash?.StringRepresentation == md5Hash)?
.UserData as SubmarineInfo;
//matching sub found and already selected, all good
@@ -3473,7 +3480,7 @@ namespace Barotrauma
CreateSubPreview(sub);
}
if (subList.SelectedData is SubmarineInfo selectedSub && selectedSub.MD5Hash?.Hash == md5Hash && Barotrauma.IO.File.Exists(sub.FilePath))
if (subList.SelectedData is SubmarineInfo selectedSub && selectedSub.MD5Hash?.StringRepresentation == md5Hash && Barotrauma.IO.File.Exists(sub.FilePath))
{
return true;
}
@@ -3507,7 +3514,7 @@ namespace Barotrauma
FailedSelectedShuttle = null;
//hashes match, all good
if (sub.MD5Hash?.Hash == md5Hash && SubmarineInfo.SavedSubmarines.Contains(sub))
if (sub.MD5Hash?.StringRepresentation == md5Hash && SubmarineInfo.SavedSubmarines.Contains(sub))
{
return true;
}
@@ -3525,21 +3532,23 @@ namespace Barotrauma
FailedSelectedShuttle = new FailedSubInfo(subName, md5Hash);
}
string errorMsg = "";
LocalizedString errorMsg = "";
if (sub == null || !SubmarineInfo.SavedSubmarines.Contains(sub))
{
errorMsg = TextManager.GetWithVariable("SubNotFoundError", "[subname]", subName) + " ";
}
else if (sub.MD5Hash?.Hash == null)
else if (sub.MD5Hash?.StringRepresentation == null)
{
errorMsg = TextManager.GetWithVariable("SubLoadError", "[subname]", subName) + " ";
GUITextBlock textBlock = subList.Content.GetChildByUserData(sub)?.GetChild<GUITextBlock>();
if (textBlock != null) { textBlock.TextColor = GUI.Style.Red; }
if (textBlock != null) { textBlock.TextColor = GUIStyle.Red; }
}
else
{
errorMsg = TextManager.GetWithVariables("SubDoesntMatchError", new string[3] { "[subname]" , "[myhash]", "[serverhash]" },
new string[3] { sub.Name, sub.MD5Hash.ShortHash, Md5Hash.GetShortHash(md5Hash) }) + " ";
errorMsg = TextManager.GetWithVariables("SubDoesntMatchError",
("[subname]", sub.Name),
("[myhash]", sub.MD5Hash.ShortRepresentation),
("[serverhash]", Md5Hash.GetShortHash(md5Hash))) + " ";
}
//already showing a message about the same sub
@@ -3553,7 +3562,7 @@ namespace Barotrauma
errorMsg += TextManager.Get("DownloadSubQuestion");
var requestFileBox = new GUIMessageBox(TextManager.Get("DownloadSubLabel"), errorMsg,
new string[] { TextManager.Get("Yes"), TextManager.Get("No") })
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") })
{
UserData = "request" + subName
};
@@ -3590,7 +3599,7 @@ namespace Barotrauma
return false;
}
SubmarineInfo purchasableSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == serverSubmarine.Name && s.MD5Hash?.Hash == serverSubmarine.MD5Hash?.Hash);
SubmarineInfo purchasableSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == serverSubmarine.Name && s.MD5Hash?.StringRepresentation == serverSubmarine.MD5Hash?.StringRepresentation);
if (purchasableSub != null)
{
return true;
@@ -3598,21 +3607,23 @@ namespace Barotrauma
purchasableSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == serverSubmarine.Name);
string errorMsg = "";
LocalizedString errorMsg = "";
if (purchasableSub == null)
{
errorMsg = TextManager.GetWithVariable("SubNotFoundError", "[subname]", serverSubmarine.Name) + " ";
}
else if (purchasableSub.MD5Hash?.Hash == null)
else if (purchasableSub.MD5Hash?.StringRepresentation == null)
{
errorMsg = TextManager.GetWithVariable("SubLoadError", "[subname]", serverSubmarine.Name) + " ";
/*GUITextBlock textBlock = subList.Content.GetChildByUserData(sub)?.GetChild<GUITextBlock>();
if (textBlock != null) { textBlock.TextColor = GUI.Style.Red; }*/
if (textBlock != null) { textBlock.TextColor = GUIStyle.Red; }*/
}
else
{
errorMsg = TextManager.GetWithVariables("SubDoesntMatchError", new string[3] { "[subname]", "[myhash]", "[serverhash]" },
new string[3] { purchasableSub.Name, purchasableSub.MD5Hash.ShortHash, Md5Hash.GetShortHash(serverSubmarine.MD5Hash.Hash) }) + " ";
errorMsg = TextManager.GetWithVariables("SubDoesntMatchError",
("[subname]", purchasableSub.Name),
("[myhash]", purchasableSub.MD5Hash.ShortRepresentation),
("[serverhash]", Md5Hash.GetShortHash(serverSubmarine.MD5Hash.StringRepresentation))) + " ";
}
errorMsg += TextManager.Get("DownloadSubQuestion");
@@ -3624,11 +3635,11 @@ namespace Barotrauma
}
var requestFileBox = new GUIMessageBox(TextManager.Get("DownloadSubLabel"), errorMsg,
new string[] { TextManager.Get("Yes"), TextManager.Get("No") })
new LocalizedString[] { TextManager.Get("Yes"), TextManager.Get("No") })
{
UserData = "request" + serverSubmarine.Name
};
requestFileBox.Buttons[0].UserData = new FailedSubInfo(serverSubmarine.Name, serverSubmarine.MD5Hash.Hash);
requestFileBox.Buttons[0].UserData = new FailedSubInfo(serverSubmarine.Name, serverSubmarine.MD5Hash.StringRepresentation);
requestFileBox.Buttons[0].OnClicked += requestFileBox.Close;
requestFileBox.Buttons[0].OnClicked += (GUIButton button, object userdata) =>
{
@@ -3675,7 +3686,7 @@ namespace Barotrauma
private void CreateSubmarineVisibilityMenu()
{
var messageBox = new GUIMessageBox(TextManager.Get("SubmarineVisibility"), "",
buttons: Array.Empty<string>(),
buttons: Array.Empty<LocalizedString>(),
relativeSize: new Vector2(0.75f, 0.75f));
messageBox.Content.ChildAnchor = Anchor.TopCenter;
var columns = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.9f), messageBox.Content.RectTransform), isHorizontal: true);
@@ -3,6 +3,7 @@ using Microsoft.Xna.Framework;
using Barotrauma.Particles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using Barotrauma.Extensions;
@@ -110,7 +111,7 @@ namespace Barotrauma
};
var emitterListBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.25f), paddedRightPanel.RectTransform));
new SerializableEntityEditor(emitterListBox.Content.RectTransform, emitterProperties, false, true, elementHeight: 20, titleFont: GUI.SubHeadingFont);
new SerializableEntityEditor(emitterListBox.Content.RectTransform, emitterProperties, false, true, elementHeight: 20, titleFont: GUIStyle.SubHeadingFont);
var listBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.6f), paddedRightPanel.RectTransform));
@@ -120,8 +121,8 @@ namespace Barotrauma
UserData = "filterarea"
};
filterLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.Font) { IgnoreLayoutGroups = true };
filterBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.Font);
filterLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUIStyle.Font) { IgnoreLayoutGroups = true };
filterBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUIStyle.Font);
filterBox.OnTextChanged += (textBox, text) => { FilterEmitters(text); return true; };
new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), filterArea.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "GUICancelButton")
{
@@ -136,7 +137,7 @@ namespace Barotrauma
emitterPrefab = new ParticleEmitterPrefab(selectedPrefab, emitterProperties);
emitter = new ParticleEmitter(emitterPrefab);
listBox.ClearChildren();
new SerializableEntityEditor(listBox.Content.RectTransform, selectedPrefab, false, true, elementHeight: 20, titleFont: GUI.SubHeadingFont);
new SerializableEntityEditor(listBox.Content.RectTransform, selectedPrefab, false, true, elementHeight: 20, titleFont: GUIStyle.SubHeadingFont);
//listBox.Content.RectTransform.NonScaledSize = particlePrefabEditor.RectTransform.NonScaledSize;
//listBox.UpdateScrollBarSize();
return true;
@@ -167,7 +168,7 @@ namespace Barotrauma
foreach (ParticlePrefab particlePrefab in particlePrefabs)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), prefabList.Content.RectTransform) { MinSize = new Point(0, 20) },
particlePrefab.DisplayName)
particlePrefab.Name)
{
Padding = Vector4.Zero,
UserData = particlePrefab
@@ -196,7 +197,7 @@ namespace Barotrauma
private void SerializeAll()
{
Barotrauma.IO.Validation.SkipValidationInDebugBuilds = true;
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.Particles))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<ParticlesFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
@@ -218,7 +219,7 @@ namespace Barotrauma
NewLineOnAttributes = true
};
using (var writer = XmlWriter.Create(configFile.Path, settings))
using (var writer = XmlWriter.Create(configFile.Path.Value, settings))
{
doc.WriteTo(writer);
writer.Flush();
@@ -265,7 +266,7 @@ namespace Barotrauma
};
XElement originalElement = null;
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.Particles))
foreach (var configFile in ContentPackageManager.AllPackages.SelectMany(p => p.GetFiles<ParticlesFile>()))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
if (doc == null) { continue; }
@@ -273,7 +274,7 @@ namespace Barotrauma
var prefabList = GameMain.ParticleManager.GetPrefabList();
foreach (ParticlePrefab otherPrefab in prefabList)
{
foreach (XElement subElement in doc.Root.Elements())
foreach (var subElement in doc.Root.Elements())
{
if (!subElement.Name.ToString().Equals(prefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
SerializableProperty.SerializeProperties(prefab, subElement, true);
@@ -9,7 +9,7 @@ namespace Barotrauma
{
private Sprite backgroundSprite;
private RoundSummary roundSummary;
private string loadText;
private LocalizedString loadText;
private RectTransform prevGuiElementParent;
@@ -47,9 +47,9 @@ namespace Barotrauma
GUI.Draw(Cam, spriteBatch);
string loadingText = loadText + new string('.', (int)Timing.TotalTime % 3 + 1);
Vector2 textSize = GUI.LargeFont.MeasureString(loadText);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, GameMain.GraphicsHeight * 0.95f) - textSize / 2, loadingText, Color.White, font: GUI.LargeFont);
LocalizedString loadingText = loadText + new string('.', (int)Timing.TotalTime % 3 + 1);
Vector2 textSize = GUIStyle.LargeFont.MeasureString(loadText);
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth / 2, GameMain.GraphicsHeight * 0.95f) - textSize / 2, loadingText, Color.White, font: GUIStyle.LargeFont);
spriteBatch.End();
}
@@ -5,7 +5,7 @@ using System.Collections.Generic;
namespace Barotrauma
{
partial class Screen
abstract partial class Screen
{
private GUIFrame frame;
public GUIFrame Frame
@@ -70,6 +70,7 @@ namespace Barotrauma
public virtual void Release()
{
if (frame is null) { return; }
frame.RectTransform.Parent = null;
frame = null;
}
@@ -44,34 +44,6 @@ namespace Barotrauma
private GUIButton friendsDropdownButton;
private GUIListBox friendsDropdown;
//Workshop downloads
public struct PendingWorkshopDownload
{
public readonly string ExpectedHash;
public readonly ulong Id;
public readonly Steamworks.Ugc.Item? Item;
public PendingWorkshopDownload(string expectedHash, Steamworks.Ugc.Item item)
{
ExpectedHash = expectedHash;
Item = item;
Id = item.Id;
}
public PendingWorkshopDownload(string expectedHash, ulong id)
{
ExpectedHash = expectedHash;
Item = null;
Id = id;
}
}
private GUIFrame workshopDownloadsFrame = null;
private Steamworks.Ugc.Item? currentlyDownloadingWorkshopItem = null;
private Dictionary<ulong, PendingWorkshopDownload> pendingWorkshopDownloads = null;
private string autoConnectName;
private string autoConnectEndpoint;
private enum TernaryOption
{
Any,
@@ -84,7 +56,7 @@ namespace Barotrauma
public UInt64 SteamID;
public string Name;
public Sprite Sprite;
public string StatusText;
public LocalizedString StatusText;
public bool PlayingThisGame;
public bool PlayingAnotherGame;
public string ConnectName;
@@ -95,7 +67,7 @@ namespace Barotrauma
{
get
{
return PlayingThisGame && !string.IsNullOrWhiteSpace(StatusText) && (!string.IsNullOrWhiteSpace(ConnectEndpoint) || ConnectLobby != 0);
return PlayingThisGame && !StatusText.IsNullOrWhiteSpace() && (!string.IsNullOrWhiteSpace(ConnectEndpoint) || ConnectLobby != 0);
}
}
}
@@ -182,10 +154,10 @@ namespace Barotrauma
private GUITickBox filterFull;
private GUITickBox filterEmpty;
private GUITickBox filterWhitelisted;
private Dictionary<string, GUIDropDown> ternaryFilters;
private Dictionary<string, GUITickBox> filterTickBoxes;
private Dictionary<string, GUITickBox> playStyleTickBoxes;
private Dictionary<string, GUITickBox> gameModeTickBoxes;
private Dictionary<Identifier, GUIDropDown> ternaryFilters;
private Dictionary<Identifier, GUITickBox> filterTickBoxes;
private Dictionary<Identifier, GUITickBox> playStyleTickBoxes;
private Dictionary<Identifier, GUITickBox> gameModeTickBoxes;
private GUITickBox filterOffensive;
//GUIDropDown sends the OnSelected event before SelectedData is set, so we have to cache it manually.
@@ -212,7 +184,7 @@ namespace Barotrauma
CreateUI();
}
private void AddTernaryFilter(RectTransform parent, float elementHeight, string tag, Action<TernaryOption> valueSetter)
private void AddTernaryFilter(RectTransform parent, float elementHeight, Identifier tag, Action<TernaryOption> valueSetter)
{
var filterLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, elementHeight), parent), isHorizontal: true)
{
@@ -239,7 +211,7 @@ namespace Barotrauma
{
UserData = TextManager.Get("servertag." + tag + ".label")
};
GUI.Style.Apply(filterLabel, "GUITextBlock", null);
GUIStyle.Apply(filterLabel, "GUITextBlock", null);
var dropDown = new GUIDropDown(new RectTransform(new Vector2(0.4f, 1.0f) * textBlockScale, filterLayoutGroup.RectTransform, Anchor.CenterLeft), elementCount: 3);
dropDown.AddItem(TextManager.Get("any"), TernaryOption.Any);
@@ -249,6 +221,7 @@ namespace Barotrauma
dropDown.OnSelected = (_, data) => {
valueSetter((TernaryOption)data);
FilterServers();
StoreServerFilters();
return true;
};
@@ -271,10 +244,10 @@ namespace Barotrauma
var topRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform)) { Stretch = true };
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.33f), topRow.RectTransform), TextManager.Get("JoinServer"), font: GUI.LargeFont)
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.33f), topRow.RectTransform), TextManager.Get("JoinServer"), font: GUIStyle.LargeFont)
{
Padding = Vector4.Zero,
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
AutoScaleHorizontal = true
};
@@ -282,10 +255,10 @@ namespace Barotrauma
var clientNameHolder = new GUILayoutGroup(new RectTransform(new Vector2(sidebarWidth, 1.0f), infoHolder.RectTransform)) { RelativeSpacing = 0.05f };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), clientNameHolder.RectTransform), TextManager.Get("YourName"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), clientNameHolder.RectTransform), TextManager.Get("YourName"), font: GUIStyle.SubHeadingFont);
ClientNameBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.5f), clientNameHolder.RectTransform), "")
{
Text = GameMain.Config.PlayerName,
Text = MultiplayerPreferences.Instance.PlayerName,
MaxTextLength = Client.MaxNameLength,
OverflowClip = true
};
@@ -296,7 +269,7 @@ namespace Barotrauma
}
ClientNameBox.OnTextChanged += (textbox, text) =>
{
GameMain.Config.PlayerName = text;
MultiplayerPreferences.Instance.PlayerName = text;
return true;
};
@@ -366,7 +339,7 @@ namespace Barotrauma
};
float elementHeight = 0.05f;
var filterTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), filtersHolder.RectTransform), TextManager.Get("FilterServers"), font: GUI.SubHeadingFont)
var filterTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), filtersHolder.RectTransform), TextManager.Get("FilterServers"), font: GUIStyle.SubHeadingFont)
{
Padding = Vector4.Zero,
AutoScaleHorizontal = true,
@@ -405,115 +378,79 @@ namespace Barotrauma
};
filterToggle.Children.ForEach(c => c.SpriteEffects = SpriteEffects.FlipHorizontally);
ternaryFilters = new Dictionary<string, GUIDropDown>();
filterTickBoxes = new Dictionary<string, GUITickBox>();
ternaryFilters = new Dictionary<Identifier, GUIDropDown>();
filterTickBoxes = new Dictionary<Identifier, GUITickBox>();
filterSameVersion = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterSameVersion"))
GUITickBox addTickBox(Identifier key, LocalizedString text = null, bool defaultState = false, bool addTooltip = false)
{
UserData = TextManager.Get("FilterSameVersion"),
Selected = true,
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterSameVersion", filterSameVersion);
text ??= TextManager.Get(key);
var tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), text)
{
UserData = text,
Selected = defaultState,
ToolTip = addTooltip ? text : null,
OnSelected = (tickBox) =>
{
FilterServers();
StoreServerFilters();
return true;
}
};
filterTickBoxes.Add(key, tickBox);
return tickBox;
}
filterPassword = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterPassword"))
{
UserData = TextManager.Get("FilterPassword"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterPassword", filterPassword);
filterIncompatible = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterIncompatibleServers"))
{
UserData = TextManager.Get("FilterIncompatibleServers"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterIncompatibleServers", filterIncompatible);
filterFull = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterFullServers"))
{
UserData = TextManager.Get("FilterFullServers"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterFullServers", filterFull);
filterEmpty = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterEmptyServers"))
{
UserData = TextManager.Get("FilterEmptyServers"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterEmptyServers", filterEmpty);
filterWhitelisted = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterWhitelistedServers"))
{
UserData = TextManager.Get("FilterWhitelistedServers"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterWhitelistedServers", filterWhitelisted);
filterOffensive = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("FilterOffensiveServers"))
{
UserData = TextManager.Get("FilterOffensiveServers"),
ToolTip = TextManager.Get("FilterOffensiveServersToolTip"),
OnSelected = (tickBox) => { FilterServers(); return true; }
};
filterTickBoxes.Add("FilterOffensiveServers", filterOffensive);
filterSameVersion = addTickBox("FilterSameVersion".ToIdentifier(), defaultState: true);
filterPassword = addTickBox("FilterPassword".ToIdentifier());
filterIncompatible = addTickBox("FilterIncompatibleServers".ToIdentifier());
filterFull = addTickBox("FilterFullServers".ToIdentifier());
filterEmpty = addTickBox("FilterEmptyServers".ToIdentifier());
filterWhitelisted = addTickBox("FilterWhitelistedServers".ToIdentifier());
filterOffensive = addTickBox("FilterOffensiveServers".ToIdentifier());
// Filter Tags
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("servertags"), font: GUI.SubHeadingFont)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("servertags"), font: GUIStyle.SubHeadingFont)
{
CanBeFocused = false
};
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "karma", (value) => { filterKarmaValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "traitors", (value) => { filterTraitorValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "friendlyfire", (value) => { filterFriendlyFireValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "voip", (value) => { filterVoipValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "modded", (value) => { filterModdedValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "karma".ToIdentifier(), (value) => { filterKarmaValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "traitors".ToIdentifier(), (value) => { filterTraitorValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "friendlyfire".ToIdentifier(), (value) => { filterFriendlyFireValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "voip".ToIdentifier(), (value) => { filterVoipValue = value; });
AddTernaryFilter(filters.Content.RectTransform, elementHeight, "modded".ToIdentifier(), (value) => { filterModdedValue = value; });
// Play Style Selection
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("ServerSettingsPlayStyle"), font: GUI.SubHeadingFont)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("ServerSettingsPlayStyle"), font: GUIStyle.SubHeadingFont)
{
CanBeFocused = false
};
playStyleTickBoxes = new Dictionary<string, GUITickBox>();
playStyleTickBoxes = new Dictionary<Identifier, GUITickBox>();
foreach (PlayStyle playStyle in Enum.GetValues(typeof(PlayStyle)))
{
var selectionTick = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), TextManager.Get("servertag." + playStyle))
{
ToolTip = TextManager.Get("servertag." + playStyle),
Selected = true,
OnSelected = (tickBox) => { FilterServers(); return true; },
UserData = playStyle
};
playStyleTickBoxes.Add("servertag." + playStyle, selectionTick);
filterTickBoxes.Add("servertag." + playStyle, selectionTick);
var selectionTick = addTickBox($"servertag.{playStyle}".ToIdentifier(), defaultState: true, addTooltip: true);
selectionTick.UserData = playStyle;
playStyleTickBoxes.Add($"servertag.{playStyle}".ToIdentifier(), selectionTick);
}
// Game mode Selection
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("gamemode"), font: GUI.SubHeadingFont) { CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), filters.Content.RectTransform), TextManager.Get("gamemode"), font: GUIStyle.SubHeadingFont) { CanBeFocused = false };
gameModeTickBoxes = new Dictionary<string, GUITickBox>();
gameModeTickBoxes = new Dictionary<Identifier, GUITickBox>();
foreach (GameModePreset mode in GameModePreset.List)
{
if (mode.IsSinglePlayer) continue;
if (mode.IsSinglePlayer) { continue; }
var selectionTick = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), filters.Content.RectTransform), mode.Name)
{
ToolTip = mode.Name,
Selected = true,
OnSelected = (tickBox) => { FilterServers(); return true; },
UserData = mode.Identifier
};
var selectionTick = addTickBox(mode.Identifier, mode.Name, defaultState: true, addTooltip: true);
selectionTick.UserData = mode.Identifier;
gameModeTickBoxes.Add(mode.Identifier, selectionTick);
filterTickBoxes.Add(mode.Identifier, selectionTick);
}
filters.Content.RectTransform.SizeChanged += () =>
{
filters.Content.RectTransform.RecalculateChildren(true, true);
filterTickBoxes.ForEach(t => t.Value.Text = t.Value.UserData as string);
filterTickBoxes.ForEach(t => t.Value.Text = t.Value.UserData is LocalizedString lStr ? lStr : t.Value.UserData.ToString());
gameModeTickBoxes.ForEach(tb => tb.Value.Text = tb.Value.ToolTip);
playStyleTickBoxes.ForEach(tb => tb.Value.Text = tb.Value.ToolTip);
GUITextBlock.AutoScaleAndNormalize(
@@ -543,7 +480,7 @@ namespace Barotrauma
text: TextManager.Get(columnLabel[i]), textAlignment: Alignment.Center, style: "GUIButtonSmall")
{
ToolTip = TextManager.Get(columnLabel[i]),
ForceUpperCase = true,
ForceUpperCase = ForceUpperCase.Yes,
UserData = columnLabel[i],
OnClicked = SortList
};
@@ -734,7 +671,7 @@ namespace Barotrauma
XDocument playStylesDoc = XMLExtensions.TryLoadXml("Content/UI/Server/PlayStyles.xml");
XElement rootElement = playStylesDoc.Root;
var rootElement = playStylesDoc.Root.FromPackage(ContentPackageManager.VanillaCorePackage);
foreach (var element in rootElement.Elements())
{
switch (element.Name.ToString().ToLowerInvariant())
@@ -839,7 +776,7 @@ namespace Barotrauma
info.LobbyID = SteamManager.CurrentLobbyID;
info.IP = ip;
info.Port = port;
info.GameMode = GameMain.NetLobbyScreen.SelectedMode?.Identifier ?? "";
info.GameMode = GameMain.NetLobbyScreen.SelectedMode?.Identifier ?? Identifier.Empty;
info.GameStarted = Screen.Selected != GameMain.NetLobbyScreen;
info.GameVersion = GameMain.Version.ToString();
info.MaxPlayers = serverSettings.MaxPlayers;
@@ -1018,21 +955,21 @@ namespace Barotrauma
{
base.Select();
ContentPackagesByWorkshopId = ContentPackage.AllPackages
ContentPackagesByWorkshopId = ContentPackageManager.AllPackages
.Select(p => new KeyValuePair<UInt64, ContentPackage>(p.SteamWorkshopId, p))
.Where(p => p.Key != 0)
.GroupBy(x => x.Key).Select(g => g.First())
.ToImmutableDictionary();
ContentPackagesByHash = ContentPackage.AllPackages
.Select(p => new KeyValuePair<string, ContentPackage>(p.MD5hash.Hash, p))
ContentPackagesByHash = ContentPackageManager.AllPackages
.Select(p => new KeyValuePair<string, ContentPackage>(p.Hash.StringRepresentation, p))
.GroupBy(x => x.Key).Select(g => g.First())
.ToImmutableDictionary();
SelectedTab = ServerListTab.All;
LoadServerFilters(GameMain.Config.ServerFilterElement);
if (GameSettings.ShowOffensiveServerPrompt)
GameMain.ServerListScreen.LoadServerFilters();
if (GameSettings.CurrentConfig.ShowOffensiveServerPrompt)
{
var filterOffensivePrompt = new GUIMessageBox(string.Empty, TextManager.Get("filteroffensiveserversprompt"), new string[] { TextManager.Get("yes"), TextManager.Get("no") });
var filterOffensivePrompt = new GUIMessageBox(string.Empty, TextManager.Get("filteroffensiveserversprompt"), new LocalizedString[] { TextManager.Get("yes"), TextManager.Get("no") });
filterOffensivePrompt.Buttons[0].OnClicked = (btn, userData) =>
{
filterOffensive.Selected = true;
@@ -1040,7 +977,10 @@ namespace Barotrauma
return true;
};
filterOffensivePrompt.Buttons[1].OnClicked = filterOffensivePrompt.Close;
GameSettings.ShowOffensiveServerPrompt = false;
var config = GameSettings.CurrentConfig;
config.ShowOffensiveServerPrompt = false;
GameSettings.SetCurrentConfig(config);
}
Steamworks.SteamMatchmaking.ResetActions();
@@ -1060,10 +1000,7 @@ namespace Barotrauma
ContentPackagesByHash = ImmutableDictionary<string, ContentPackage>.Empty;
base.Deselect();
GameMain.Config.SaveNewPlayerConfig();
pendingWorkshopDownloads?.Clear();
workshopDownloadsFrame = null;
GameSettings.SaveCurrentConfig();
}
public override void Update(double deltaTime)
@@ -1083,62 +1020,6 @@ namespace Barotrauma
friendsDropdown.Visible = false;
}
}
if (currentlyDownloadingWorkshopItem == null)
{
if (pendingWorkshopDownloads?.Any() ?? false)
{
Steamworks.Ugc.Item? item = pendingWorkshopDownloads.Values.FirstOrDefault(it => it.Item != null).Item;
if (item != null)
{
ulong itemId = item.Value.Id;
currentlyDownloadingWorkshopItem = item;
SteamManager.ForceRedownload(item.Value.Id, () =>
{
if (!(item?.IsSubscribed ?? false))
{
TaskPool.Add("SubscribeToServerMod", item?.Subscribe(), (t) => { });
}
PendingWorkshopDownload clearedDownload = pendingWorkshopDownloads[itemId];
pendingWorkshopDownloads.Remove(itemId);
currentlyDownloadingWorkshopItem = null;
void onInstall(ContentPackage resultingPackage)
{
if (!resultingPackage.MD5hash.Hash.Equals(clearedDownload.ExpectedHash))
{
workshopDownloadsFrame?.FindChild((c) => c.UserData is ulong l && l == itemId, true)?.Flash(GUI.Style.Red);
CancelWorkshopDownloads();
GameMain.Client?.Disconnect();
GameMain.Client = null;
new GUIMessageBox(
TextManager.Get("ConnectionLost"),
TextManager.GetWithVariable("DisconnectMessage.MismatchedWorkshopMod", "[incompatiblecontentpackage]", $"\"{resultingPackage.Name}\" (hash {resultingPackage.MD5hash.ShortHash})"));
}
}
if (SteamManager.CheckWorkshopItemInstalled(item))
{
SteamManager.UninstallWorkshopItem(item, false, out _);
}
if (SteamManager.InstallWorkshopItem(item, out string errorMsg, enableContentPackage: false, suppressInstallNotif: true, onInstall: onInstall))
{
workshopDownloadsFrame?.FindChild((c) => c.UserData is ulong l && l == itemId, true)?.Flash(GUI.Style.Green);
}
else
{
workshopDownloadsFrame?.FindChild((c) => c.UserData is ulong l && l == itemId, true)?.Flash(GUI.Style.Red);
DebugConsole.ThrowError(errorMsg);
}
});
}
}
else if (!string.IsNullOrEmpty(autoConnectEndpoint))
{
JoinServer(autoConnectEndpoint, autoConnectName);
autoConnectEndpoint = null;
}
}
}
private void FilterServers()
@@ -1207,8 +1088,8 @@ namespace Barotrauma
foreach (GUITickBox tickBox in gameModeTickBoxes.Values)
{
var gameMode = (string)tickBox.UserData;
if (!tickBox.Selected && serverInfo.GameMode != null && serverInfo.GameMode.Equals(gameMode, StringComparison.OrdinalIgnoreCase))
var gameMode = (Identifier)tickBox.UserData;
if (!tickBox.Selected && serverInfo.GameMode != null && serverInfo.GameMode == gameMode)
{
child.Visible = false;
break;
@@ -1253,7 +1134,7 @@ namespace Barotrauma
private void ShowDirectJoinPrompt()
{
var msgBox = new GUIMessageBox(TextManager.Get("ServerListDirectJoin"), "",
new string[] { TextManager.Get("ServerListJoin"), TextManager.Get("AddToFavorites"), TextManager.Get("Cancel") },
new LocalizedString[] { TextManager.Get("ServerListJoin"), TextManager.Get("AddToFavorites"), TextManager.Get("Cancel") },
relativeSize: new Vector2(0.25f, 0.2f), minSize: new Point(400, 150));
msgBox.Content.ChildAnchor = Anchor.TopCenter;
@@ -1597,7 +1478,7 @@ namespace Barotrauma
{
friendsDropdownButton = new GUIButton(new RectTransform(Vector2.One, friendsButtonHolder.RectTransform, Anchor.BottomRight, Pivot.BottomRight, scaleBasis: ScaleBasis.BothHeight), "\u2022 \u2022 \u2022", style: "GUIButtonFriendsDropdown")
{
Font = GUI.GlobalFont,
Font = GUIStyle.GlobalFont,
OnClicked = (button, udt) =>
{
friendsDropdown.RectTransform.NonScaledSize = new Point(friendsButtonHolder.Rect.Height * 5 * 166 / 100, friendsButtonHolder.Rect.Height * 4 * 166 / 100);
@@ -1680,10 +1561,10 @@ namespace Barotrauma
var textBlock = new GUITextBlock(new RectTransform(Vector2.One * 0.8f, friendFrame.RectTransform, Anchor.CenterLeft, scaleBasis: ScaleBasis.BothHeight) { RelativeOffset = new Vector2(1.0f / 7.7f, 0.0f) }, friend.Name + "\n" + friend.StatusText)
{
Font = GUI.SmallFont
Font = GUIStyle.SmallFont
};
if (friend.PlayingThisGame) { textBlock.TextColor = GUI.Style.Green; }
if (friend.PlayingAnotherGame) { textBlock.TextColor = GUI.Style.Blue; }
if (friend.PlayingThisGame) { textBlock.TextColor = GUIStyle.Green; }
if (friend.PlayingAnotherGame) { textBlock.TextColor = GUIStyle.Blue; }
if (friend.InServer)
{
@@ -1744,7 +1625,7 @@ namespace Barotrauma
}
recentServers.Concat(favoriteServers).ForEach(si => si.OwnerVerified = false);
if (GameMain.Config.UseSteamMatchmaking)
if (GameSettings.CurrentConfig.UseSteamMatchmaking)
{
serverList.ClearChildren();
if (!SteamManager.GetServers(AddToServerList, ServerQueryFinished))
@@ -1768,11 +1649,6 @@ namespace Barotrauma
scanServersButton.Enabled = true;
}
}
else
{
CoroutineManager.StartCoroutine(SendMasterServerRequest());
waitingForRefresh = false;
}
refreshDisableTimer = DateTime.Now + AllowedRefreshInterval;
@@ -1998,14 +1874,14 @@ namespace Barotrauma
if (serverInfo.LobbyID == 0 && (string.IsNullOrWhiteSpace(serverInfo.IP) || string.IsNullOrWhiteSpace(serverInfo.Port)))
{
string toolTip = TextManager.Get("ServerOffline");
LocalizedString toolTip = TextManager.Get("ServerOffline");
serverContent.Children.ForEach(c => c.ToolTip = toolTip);
serverName.TextColor *= 0.8f;
serverPlayers.TextColor *= 0.8f;
}
else if (GameMain.Config.UseSteamMatchmaking && serverInfo.RespondedToSteamQuery.HasValue && serverInfo.RespondedToSteamQuery.Value == false)
else if (GameSettings.CurrentConfig.UseSteamMatchmaking && serverInfo.RespondedToSteamQuery.HasValue && serverInfo.RespondedToSteamQuery.Value == false)
{
string toolTip = TextManager.Get("ServerListNoSteamQueryResponse");
LocalizedString toolTip = TextManager.Get("ServerListNoSteamQueryResponse");
compatibleBox.Selected = false;
serverContent.Children.ForEach(c => c.ToolTip = toolTip);
serverName.TextColor *= 0.8f;
@@ -2014,7 +1890,7 @@ namespace Barotrauma
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), " ? ", GUI.Style.Orange * 0.85f, textAlignment: Alignment.Center)
new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), compatibleBox.Box.RectTransform, Anchor.Center), " ? ", GUIStyle.Orange * 0.85f, textAlignment: Alignment.Center)
{
ToolTip = TextManager.Get(string.IsNullOrEmpty(serverInfo.GameVersion) ?
"ServerListUnknownVersion" :
@@ -2023,27 +1899,30 @@ namespace Barotrauma
}
else if (!compatibleBox.Selected)
{
string toolTip = "";
LocalizedString toolTip = "";
if (serverInfo.GameVersion != GameMain.Version.ToString())
{
toolTip = TextManager.GetWithVariable("ServerListIncompatibleVersion", "[version]", serverInfo.GameVersion);
}
for (int i = 0; i < serverInfo.ContentPackageNames.Count; i++)
{
bool listAsIncompatible = false;
if (serverInfo.ContentPackageWorkshopIds[i] == 0)
{
listAsIncompatible = !GameMain.Config.AllEnabledPackages.Any(cp => cp.MD5hash.Hash == serverInfo.ContentPackageHashes[i]);
listAsIncompatible = !ContentPackageManager.EnabledPackages.All.Any(contentPackage => contentPackage.Hash.StringRepresentation == serverInfo.ContentPackageHashes[i]);
}
else
{
listAsIncompatible = GameMain.Config.AllEnabledPackages.Any(cp => cp.MD5hash.Hash != serverInfo.ContentPackageHashes[i] &&
cp.SteamWorkshopId == serverInfo.ContentPackageWorkshopIds[i]);
listAsIncompatible = ContentPackageManager.EnabledPackages.All.Any(contentPackage => contentPackage.Hash.StringRepresentation != serverInfo.ContentPackageHashes[i] &&
contentPackage.SteamWorkshopId == serverInfo.ContentPackageWorkshopIds[i]);
}
if (listAsIncompatible)
{
if (toolTip != "") toolTip += "\n";
toolTip += TextManager.GetWithVariables("ServerListIncompatibleContentPackage", new string[2] { "[contentpackage]", "[hash]" },
new string[2] { serverInfo.ContentPackageNames[i], Md5Hash.GetShortHash(serverInfo.ContentPackageHashes[i]) });
toolTip += TextManager.GetWithVariables("ServerListIncompatibleContentPackage",
("[contentpackage]", serverInfo.ContentPackageNames[i]),
("[hash]", Md5Hash.GetShortHash(serverInfo.ContentPackageHashes[i])));
}
}
@@ -2054,12 +1933,12 @@ namespace Barotrauma
}
else
{
string toolTip = "";
LocalizedString toolTip = "";
for (int i = 0; i < serverInfo.ContentPackageNames.Count; i++)
{
if (!GameMain.Config.AllEnabledPackages.Any(cp => cp.MD5hash.Hash == serverInfo.ContentPackageHashes[i]))
if (!ContentPackageManager.EnabledPackages.All.Any(contentPackage => contentPackage.Hash.StringRepresentation == serverInfo.ContentPackageHashes[i]))
{
if (toolTip != "") toolTip += "\n";
if (toolTip != "") { toolTip += "\n"; }
toolTip += TextManager.GetWithVariable("ServerListIncompatibleContentPackageWorkshopAvailable", "[contentpackage]", serverInfo.ContentPackageNames[i]);
break;
}
@@ -2116,163 +1995,12 @@ namespace Barotrauma
waitingForRefresh = false;
}
private IEnumerable<CoroutineStatus> 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 != HttpStatusCode.OK)
{
serverList.ClearChildren();
switch (masterServerResponse.StatusCode)
{
case HttpStatusCode.NotFound:
new GUIMessageBox(TextManager.Get("MasterServerErrorLabel"),
TextManager.GetWithVariable("MasterServerError404", "[masterserverurl]", NetConfig.MasterServerUrl));
break;
case 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;
}
private void MasterServerCallBack(IRestResponse response)
{
masterServerResponse = response;
masterServerResponded = true;
}
public void DownloadWorkshopItems(IEnumerable<PendingWorkshopDownload> downloads, string serverName, string endPointString)
{
if (workshopDownloadsFrame != null) { return; }
int rowCount = downloads.Count() + 2;
autoConnectName = serverName; autoConnectEndpoint = endPointString;
workshopDownloadsFrame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), null, Color.Black * 0.5f);
currentlyDownloadingWorkshopItem = null;
pendingWorkshopDownloads = new Dictionary<ulong, PendingWorkshopDownload>();
var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.1f + 0.03f * rowCount), workshopDownloadsFrame.RectTransform, Anchor.Center, Pivot.Center));
var innerLayout = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, (float)rowCount / (float)(rowCount + 3)), innerFrame.RectTransform, Anchor.Center, Pivot.Center));
foreach (PendingWorkshopDownload entry in downloads)
{
pendingWorkshopDownloads.Add(entry.Id, entry);
var itemLayout = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f / rowCount), innerLayout.RectTransform), true, Anchor.CenterLeft)
{
UserData = entry.Id
};
TaskPool.Add("RetrieveWorkshopItemData", Steamworks.SteamUGC.QueryFileAsync(entry.Id), (t) =>
{
if (t.IsFaulted)
{
TaskPool.PrintTaskExceptions(t, $"Failed to retrieve Workshop item info (ID {entry.Id})");
return;
}
t.TryGetResult(out Steamworks.Ugc.Item? item);
if (!item.HasValue)
{
DebugConsole.ThrowError($"Failed to find a Steam Workshop item with the ID {entry.Id}.");
return;
}
if (pendingWorkshopDownloads.ContainsKey(entry.Id))
{
pendingWorkshopDownloads[entry.Id] = new PendingWorkshopDownload(entry.ExpectedHash, item.Value);
new GUITextBlock(new RectTransform(new Vector2(0.4f, 0.67f), itemLayout.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft), item.Value.Title);
new GUIProgressBar(new RectTransform(new Vector2(0.6f, 0.67f), itemLayout.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft), 0f, Color.Lime)
{
ProgressGetter = () =>
{
if (item.Value.IsInstalled) { return 1.0f; }
else if (!item.Value.IsDownloading) { return 0.0f; }
return item.Value.DownloadAmount;
}
};
}
});
}
var buttonLayout = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 2.0f / rowCount), innerLayout.RectTransform), true, Anchor.CenterLeft)
{
UserData = "buttons"
};
new GUIButton(new RectTransform(new Vector2(0.3f, 0.67f), buttonLayout.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft), TextManager.Get("Cancel"))
{
OnClicked = (btn, obj) =>
{
CancelWorkshopDownloads();
return true;
}
};
}
public void CancelWorkshopDownloads()
{
autoConnectEndpoint = null;
autoConnectName = null;
pendingWorkshopDownloads.Clear();
currentlyDownloadingWorkshopItem = null;
workshopDownloadsFrame = null;
}
private bool JoinServer(string endpoint, string serverName)
{
if (string.IsNullOrWhiteSpace(ClientNameBox.Text))
@@ -2283,8 +2011,8 @@ namespace Barotrauma
return false;
}
GameMain.Config.PlayerName = ClientNameBox.Text;
GameMain.Config.SaveNewPlayerConfig();
MultiplayerPreferences.Instance.PlayerName = ClientNameBox.Text;
GameSettings.SaveCurrentConfig();
CoroutineManager.StartCoroutine(ConnectToServer(endpoint, serverName), "ConnectToServer");
@@ -2301,7 +2029,7 @@ namespace Barotrauma
try
{
#endif
GameMain.Client = new GameClient(GameMain.Config.PlayerName, serverIP, serverSteamID, serverName);
GameMain.Client = new GameClient(MultiplayerPreferences.Instance.PlayerName.FallbackNullOrEmpty(SteamManager.GetUsername()), serverIP, serverSteamID, serverName);
#if !DEBUG
}
catch (Exception e)
@@ -2345,7 +2073,7 @@ namespace Barotrauma
private Color GetPingTextColor(int ping)
{
if (ping < 0) { return Color.DarkRed; }
return ToolBox.GradientLerp(ping / 200.0f, GUI.Style.Green, GUI.Style.Orange, GUI.Style.Red);
return ToolBox.GradientLerp(ping / 200.0f, GUIStyle.Green, GUIStyle.Orange, GUIStyle.Red);
}
public async Task<int> PingServerAsync(string ip, int timeOut)
@@ -2425,35 +2153,35 @@ namespace Barotrauma
menu.AddToGUIUpdateList();
friendPopup?.AddToGUIUpdateList();
friendsDropdown?.AddToGUIUpdateList();
workshopDownloadsFrame?.AddToGUIUpdateList();
}
public void SaveServerFilters(XElement element)
public void StoreServerFilters()
{
element.RemoveAttributes();
foreach (KeyValuePair<string, GUITickBox> filterBox in filterTickBoxes)
foreach (KeyValuePair<Identifier, GUITickBox> filterBox in filterTickBoxes)
{
element.Add(new XAttribute(filterBox.Key, filterBox.Value.Selected.ToString()));
ServerListFilters.Instance.SetAttribute(filterBox.Key, filterBox.Value.Selected.ToString());
}
foreach (KeyValuePair<string, GUIDropDown> ternaryFilter in ternaryFilters)
foreach (KeyValuePair<Identifier, GUIDropDown> ternaryFilter in ternaryFilters)
{
element.Add(new XAttribute(ternaryFilter.Key, ternaryFilter.Value.SelectedData.ToString()));
ServerListFilters.Instance.SetAttribute(ternaryFilter.Key, ternaryFilter.Value.SelectedData.ToString());
}
}
public void LoadServerFilters(XElement element)
public void LoadServerFilters()
{
if (element == null) { return; }
foreach (KeyValuePair<string, GUITickBox> filterBox in filterTickBoxes)
XDocument currentConfigDoc = XMLExtensions.TryLoadXml(GameSettings.PlayerConfigPath);
ServerListFilters.Init(currentConfigDoc.Root.GetChildElement("serverfilters"));
foreach (KeyValuePair<Identifier, GUITickBox> filterBox in filterTickBoxes)
{
filterBox.Value.Selected = element.GetAttributeBool(filterBox.Key, filterBox.Value.Selected);
filterBox.Value.Selected =
ServerListFilters.Instance.GetAttributeBool(filterBox.Key, filterBox.Value.Selected);
}
foreach (KeyValuePair<string, GUIDropDown> ternaryFilter in ternaryFilters)
foreach (KeyValuePair<Identifier, GUIDropDown> ternaryFilter in ternaryFilters)
{
string valueStr = element.GetAttributeString(ternaryFilter.Key, "");
TernaryOption ternaryOption = (TernaryOption)ternaryFilter.Value.SelectedData;
Enum.TryParse<TernaryOption>(valueStr, true, out ternaryOption);
TernaryOption ternaryOption =
ServerListFilters.Instance.GetAttributeEnum(
ternaryFilter.Key,
(TernaryOption)ternaryFilter.Value.SelectedData);
var child = ternaryFilter.Value.ListBox.Content.GetChildByUserData(ternaryOption);
ternaryFilter.Value.Select(ternaryFilter.Value.ListBox.Content.GetChildIndex(child));
@@ -14,7 +14,7 @@ using Barotrauma.IO;
namespace Barotrauma
{
class SpriteEditorScreen : Screen
class SpriteEditorScreen : EditorScreen
{
private GUIListBox textureList, spriteList;
@@ -30,22 +30,19 @@ namespace Barotrauma
private GUITextBlock texturePathText;
private GUITextBlock xmlPathText;
private GUIScrollBar zoomBar;
private List<Sprite> selectedSprites = new List<Sprite>();
private List<Sprite> dirtySprites = new List<Sprite>();
private Texture2D selectedTexture;
private Sprite lastSelected;
private readonly List<Sprite> selectedSprites = new List<Sprite>();
private readonly List<Sprite> dirtySprites = new List<Sprite>();
private Sprite selectedTexture;
private Rectangle textureRect;
private float zoom = 1;
private float minZoom = 0.25f;
private float maxZoom;
private int spriteCount;
private const float MinZoom = 0.25f, MaxZoom = 10.0f;
private GUITextBox filterSpritesBox;
private GUITextBlock filterSpritesLabel;
private GUITextBox filterTexturesBox;
private GUITextBlock filterTexturesLabel;
private string originLabel, positionLabel, sizeLabel;
private LocalizedString originLabel, positionLabel, sizeLabel;
private bool editBackgroundColor;
private Color backgroundColor = new Color(0.051f, 0.149f, 0.271f, 1.0f);
@@ -92,8 +89,8 @@ namespace Barotrauma
RefreshLists();
textureList.Select(firstSelected.Texture, autoScroll: false);
selected.ForEachMod(s => spriteList.Select(s, autoScroll: false));
texturePathText.Text = TextManager.GetWithVariable("spriteeditor.texturesreloaded", "[filepath]", firstSelected.FilePath);
texturePathText.TextColor = GUI.Style.Green;
texturePathText.Text = TextManager.GetWithVariable("spriteeditor.texturesreloaded", "[filepath]", firstSelected.FilePath.Value);
texturePathText.TextColor = GUIStyle.Green;
return true;
}
};
@@ -107,7 +104,7 @@ namespace Barotrauma
if (selectedTexture == null) { return false; }
foreach (Sprite sprite in loadedSprites)
{
if (sprite.Texture != selectedTexture) { continue; }
if (sprite.FullPath != selectedTexture.FullPath) { continue; }
var element = sprite.SourceElement;
if (element == null) { continue; }
// Not all sprites have a sourcerect defined, in which case we'll want to use the current source rect instead of an empty rect.
@@ -116,7 +113,7 @@ namespace Barotrauma
}
ResetWidgets();
xmlPathText.Text = TextManager.Get("spriteeditor.resetsuccessful");
xmlPathText.TextColor = GUI.Style.Green;
xmlPathText.TextColor = GUIStyle.Green;
return true;
}
};
@@ -153,7 +150,7 @@ namespace Barotrauma
Step = 0.01f,
OnMoved = (scrollBar, value) =>
{
zoom = MathHelper.Lerp(minZoom, maxZoom, value);
zoom = MathHelper.Lerp(MinZoom, MaxZoom, value);
viewAreaOffset = Point.Zero;
return true;
}
@@ -200,8 +197,8 @@ namespace Barotrauma
Stretch = true,
UserData = "filterarea"
};
filterTexturesLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.Font, textAlignment: Alignment.CenterLeft) { IgnoreLayoutGroups = true }; ;
filterTexturesBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.Font, createClearButton: true);
filterTexturesLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUIStyle.Font, textAlignment: Alignment.CenterLeft) { IgnoreLayoutGroups = true }; ;
filterTexturesBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUIStyle.Font, createClearButton: true);
filterArea.RectTransform.MinSize = filterTexturesBox.RectTransform.MinSize;
filterTexturesBox.OnTextChanged += (textBox, text) => { FilterTextures(text); return true; };
@@ -209,9 +206,9 @@ namespace Barotrauma
{
OnSelected = (listBox, userData) =>
{
var previousTexture = selectedTexture;
selectedTexture = userData as Texture2D;
if (previousTexture != selectedTexture)
var previousSprite = selectedTexture;
selectedTexture = userData as Sprite;
if (previousSprite != selectedTexture)
{
ResetZoom();
}
@@ -219,12 +216,12 @@ namespace Barotrauma
{
var textBlock = (GUITextBlock)child;
var sprite = (Sprite)textBlock.UserData;
textBlock.TextColor = new Color(textBlock.TextColor, sprite.Texture == selectedTexture ? 1.0f : 0.4f);
if (sprite.Texture == selectedTexture) { textBlock.Visible = true; }
textBlock.TextColor = new Color(textBlock.TextColor, sprite.FilePath == selectedTexture.FilePath ? 1.0f : 0.4f);
if (sprite.FilePath == selectedTexture.FilePath) { textBlock.Visible = true; }
}
if (selectedSprites.None(s => s.Texture == selectedTexture))
if (selectedSprites.None(s => s.FilePath == selectedTexture.FilePath))
{
spriteList.Select(loadedSprites.First(s => s.Texture == selectedTexture), autoScroll: false);
spriteList.Select(loadedSprites.First(s => s.FilePath == selectedTexture.FilePath), autoScroll: false);
UpdateScrollBar(spriteList);
}
texturePathText.TextColor = Color.LightGray;
@@ -245,8 +242,8 @@ namespace Barotrauma
Stretch = true,
UserData = "filterarea"
};
filterSpritesLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.Font, textAlignment: Alignment.CenterLeft) { IgnoreLayoutGroups = true };
filterSpritesBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.Font, createClearButton: true);
filterSpritesLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUIStyle.Font, textAlignment: Alignment.CenterLeft) { IgnoreLayoutGroups = true };
filterSpritesBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUIStyle.Font, createClearButton: true);
filterArea.RectTransform.MinSize = filterSpritesBox.RectTransform.MinSize;
filterSpritesBox.OnTextChanged += (textBox, text) => { FilterSprites(text); return true; };
@@ -282,7 +279,7 @@ namespace Barotrauma
RelativeSpacing = 0.01f
};
var fields = new GUIComponent[4];
string[] colorComponentLabels = { TextManager.Get("spriteeditor.colorcomponentr"), TextManager.Get("spriteeditor.colorcomponentg"), TextManager.Get("spriteeditor.colorcomponentb") };
LocalizedString[] colorComponentLabels = { TextManager.Get("spriteeditor.colorcomponentr"), TextManager.Get("spriteeditor.colorcomponentg"), TextManager.Get("spriteeditor.colorcomponentb") };
for (int i = 2; i >= 0; i--)
{
var element = new GUIFrame(new RectTransform(new Vector2(0.2f, 1), inputArea.RectTransform)
@@ -291,23 +288,23 @@ namespace Barotrauma
MaxSize = new Point(100, 50)
}, style: null, color: Color.Black * 0.6f);
var colorLabel = new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), element.RectTransform, Anchor.CenterLeft), colorComponentLabels[i],
font: GUI.SmallFont, textAlignment: Alignment.CenterLeft);
font: GUIStyle.SmallFont, textAlignment: Alignment.CenterLeft);
var numberInput = new GUINumberInput(new RectTransform(new Vector2(0.7f, 1), element.RectTransform, Anchor.CenterRight), GUINumberInput.NumberType.Int)
{
Font = GUI.SmallFont
Font = GUIStyle.SmallFont
};
numberInput.MinValueInt = 0;
numberInput.MaxValueInt = 255;
numberInput.Font = GUI.SmallFont;
numberInput.Font = GUIStyle.SmallFont;
switch (i)
{
case 0:
colorLabel.TextColor = GUI.Style.Red;
colorLabel.TextColor = GUIStyle.Red;
numberInput.IntValue = backgroundColor.R;
numberInput.OnValueChanged += (numInput) => backgroundColor.R = (byte)(numInput.IntValue);
break;
case 1:
colorLabel.TextColor = GUI.Style.Green;
colorLabel.TextColor = GUIStyle.Green;
numberInput.IntValue = backgroundColor.G;
numberInput.OnValueChanged += (numInput) => backgroundColor.G = (byte)(numInput.IntValue);
break;
@@ -325,7 +322,7 @@ namespace Barotrauma
{
loadedSprites.ForEach(s => s.Remove());
loadedSprites.Clear();
var contentPackages = GameMain.Config.AllEnabledPackages.ToList();
var contentPackages = ContentPackageManager.EnabledPackages.All.ToList();
#if !DEBUG
var vanilla = GameMain.VanillaContent;
@@ -343,16 +340,15 @@ namespace Barotrauma
XDocument doc = XMLExtensions.TryLoadXml(file.Path);
if (doc != null)
{
LoadSprites(doc.Root);
LoadSprites(doc.Root.FromPackage(file.Path.ContentPackage));
}
}
}
}
void LoadSprites(XElement element)
void LoadSprites(ContentXElement element)
{
string[] spriteElementNames = new string[]
{
string[] spriteElementNames = {
"Sprite",
"DeformableSprite",
"BackgroundSprite",
@@ -371,34 +367,33 @@ namespace Barotrauma
foreach (string spriteElementName in spriteElementNames)
{
element.Elements(spriteElementName).ForEach(s => CreateSprite(s));
element.Elements(spriteElementName.ToLowerInvariant()).ForEach(s => CreateSprite(s));
element.GetChildElements(spriteElementName).ForEach(s => CreateSprite(s));
}
element.Elements().ForEach(e => LoadSprites(e));
}
void CreateSprite(XElement element)
void CreateSprite(ContentXElement element)
{
string spriteFolder = "";
string textureElement = "";
ContentPath texturePath = null;
if (element.Attribute("texture") != null)
{
textureElement = element.GetAttributeString("texture", "");
texturePath = element.GetAttributeContentPath("texture");
}
else
{
if (element.Name.ToString().ToLower() == "vinesprite")
{
textureElement = element.Parent.GetAttributeString("vineatlas", "");
texturePath = element.Parent.GetAttributeContentPath("vineatlas");
}
}
if (string.IsNullOrEmpty(textureElement)) { return; }
if (texturePath.IsNullOrEmpty()) { return; }
// TODO: parse and create?
if (textureElement.Contains("[GENDER]") || textureElement.Contains("[HEADID]") || textureElement.Contains("[RACE]") || textureElement.Contains("[VARIANT]")) { return; }
if (!textureElement.Contains("/"))
if (texturePath.Value.Contains("[GENDER]") || texturePath.Value.Contains("[HEADID]") || texturePath.Value.Contains("[RACE]") || texturePath.Value.Contains("[VARIANT]")) { return; }
if (!texturePath.Value.Contains("/"))
{
var parsedPath = element.ParseContentPathFromUri();
spriteFolder = Path.GetDirectoryName(parsedPath);
@@ -409,7 +404,7 @@ namespace Barotrauma
//{
// loadedSprites.Add(new Sprite(element, spriteFolder));
//}
loadedSprites.Add(new Sprite(element, spriteFolder, textureElement));
loadedSprites.Add(new Sprite(element, spriteFolder, texturePath.Value, lazyLoad: true));
}
}
@@ -420,7 +415,7 @@ namespace Barotrauma
HashSet<XDocument> docsToSave = new HashSet<XDocument>();
foreach (Sprite sprite in sprites)
{
if (sprite.Texture != selectedTexture) { continue; }
if (sprite.FullPath != selectedTexture.FullPath) { continue; }
var element = sprite.SourceElement;
if (element == null) { continue; }
element.SetAttributeValue("sourcerect", XMLExtensions.RectToString(sprite.SourceRect));
@@ -448,7 +443,7 @@ namespace Barotrauma
doc.SaveSafe(xmlPath);
#endif
}
xmlPathText.TextColor = GUI.Style.Green;
xmlPathText.TextColor = GUIStyle.Green;
return true;
}
#endregion
@@ -478,7 +473,7 @@ namespace Barotrauma
{
foreach (Sprite sprite in loadedSprites)
{
if (sprite.Texture != selectedTexture) continue;
if (sprite.FullPath != selectedTexture.FullPath) { continue; }
if (PlayerInput.PrimaryMouseButtonClicked())
{
var scaledRect = new Rectangle(textureRect.Location + sprite.SourceRect.Location.Multiply(zoom), sprite.SourceRect.Size.Multiply(zoom));
@@ -498,7 +493,7 @@ namespace Barotrauma
{
if (PlayerInput.ScrollWheelSpeed != 0)
{
zoom = MathHelper.Clamp(zoom + PlayerInput.ScrollWheelSpeed * (float)deltaTime * 0.05f * zoom, minZoom, maxZoom);
zoom = MathHelper.Clamp(zoom + PlayerInput.ScrollWheelSpeed * (float)deltaTime * 0.05f * zoom, MinZoom, MaxZoom);
zoomBar.BarScroll = GetBarScrollValue();
}
widgets.Values.ForEach(w => w.Update((float)deltaTime));
@@ -645,17 +640,17 @@ namespace Barotrauma
if (selectedTexture != null)
{
textureRect = new Rectangle(
(int)(viewArea.Center.X - selectedTexture.Bounds.Width / 2f * zoom),
(int)(viewArea.Center.Y - selectedTexture.Bounds.Height / 2f * zoom),
(int)(selectedTexture.Bounds.Width * zoom),
(int)(selectedTexture.Bounds.Height * zoom));
(int)(viewArea.Center.X - selectedTexture.Texture.Bounds.Width / 2f * zoom),
(int)(viewArea.Center.Y - selectedTexture.Texture.Bounds.Height / 2f * zoom),
(int)(selectedTexture.Texture.Bounds.Width * zoom),
(int)(selectedTexture.Texture.Bounds.Height * zoom));
spriteBatch.Draw(selectedTexture,
spriteBatch.Draw(selectedTexture.Texture,
viewArea.Center.ToVector2(),
sourceRectangle: null,
color: Color.White,
rotation: 0.0f,
origin: new Vector2(selectedTexture.Bounds.Width / 2.0f, selectedTexture.Bounds.Height / 2.0f),
origin: new Vector2(selectedTexture.Texture.Bounds.Width / 2.0f, selectedTexture.Texture.Bounds.Height / 2.0f),
scale: zoom,
effects: SpriteEffects.None,
layerDepth: 0);
@@ -670,10 +665,8 @@ namespace Barotrauma
foreach (GUIComponent element in spriteList.Content.Children)
{
Sprite sprite = element.UserData as Sprite;
if (sprite == null) { continue; }
if (sprite.Texture != selectedTexture) continue;
spriteCount++;
if (!(element.UserData is Sprite sprite)) { continue; }
if (sprite.FullPath != selectedTexture.FullPath) { continue; }
Rectangle sourceRect = new Rectangle(
textureRect.X + (int)(sprite.SourceRect.X * zoom),
@@ -682,10 +675,10 @@ namespace Barotrauma
(int)(sprite.SourceRect.Height * zoom));
bool isSelected = selectedSprites.Contains(sprite);
GUI.DrawRectangle(spriteBatch, sourceRect, isSelected ? GUI.Style.Orange : GUI.Style.Red * 0.5f, thickness: isSelected ? 2 : 1);
GUI.DrawRectangle(spriteBatch, sourceRect, isSelected ? GUIStyle.Orange : GUIStyle.Red * 0.5f, thickness: isSelected ? 2 : 1);
string id = sprite.ID;
if (!string.IsNullOrEmpty(id))
Identifier id = sprite.Identifier;
if (!id.IsEmpty)
{
int widgetSize = 10;
Vector2 GetTopLeft() => sprite.SourceRect.Location.ToVector2();
@@ -759,8 +752,6 @@ namespace Barotrauma
GUI.Draw(Cam, spriteBatch);
spriteCount = 0;
spriteBatch.End();
}
@@ -829,7 +820,7 @@ namespace Barotrauma
foreach (GUIComponent child in textureList.Content.Children)
{
if (!(child is GUITextBlock textBlock)) { continue; }
textBlock.Visible = textBlock.Text.ToLower().Contains(text);
textBlock.Visible = textBlock.Text.Contains(text, StringComparison.OrdinalIgnoreCase);
}
}
private void FilterSprites(string text)
@@ -845,7 +836,7 @@ namespace Barotrauma
foreach (GUIComponent child in spriteList.Content.Children)
{
if (!(child is GUITextBlock textBlock)) { continue; }
textBlock.Visible = textBlock.Text.ToLower().Contains(text);
textBlock.Visible = textBlock.Text.Contains(text, StringComparison.OrdinalIgnoreCase);
}
}
@@ -854,25 +845,7 @@ namespace Barotrauma
base.Select();
LoadSprites();
RefreshLists();
// Store the reference, because lastSelected is reassigned when the texture is selected.
Sprite lastSprite = lastSelected;
// Select the last selected texture if any.
// TODO: Does not work if the texture has been disposed. This happens when it's not used by any sprite -> is there a better way to identify the textures? id or something?
if (selectedTexture != null && textureList.Content.Children.Any(c => c.UserData as Texture2D == selectedTexture))
{
textureList.Select(selectedTexture, autoScroll: false);
UpdateScrollBar(textureList);
// Select the last selected sprite if any
if (lastSprite != null && spriteList.Content.Children.FirstOrDefault(c => c.UserData is Sprite s && s.ID == lastSprite.ID)?.UserData is Sprite sprite)
{
spriteList.Select(sprite, autoScroll: false);
UpdateScrollBar(spriteList);
}
}
else
{
spriteList.Select(0, autoScroll: false);
}
spriteList.Select(0, autoScroll: false);
}
public override void Deselect()
@@ -887,7 +860,7 @@ namespace Barotrauma
{
foreach (var s in Sprite.LoadedSprites)
{
if (s.Texture == sprite.Texture && !reloadedSprites.Contains(s))
if (s.FullPath == sprite.FullPath && !reloadedSprites.Contains(s))
{
s.ReloadXML();
reloadedSprites.Add(s);
@@ -907,7 +880,7 @@ namespace Barotrauma
RefreshLists();
}
if (selectedSprites.Any(s => s.Texture != selectedTexture))
if (selectedSprites.Any(s => s.FullPath != selectedTexture.FullPath))
{
ResetWidgets();
}
@@ -921,7 +894,6 @@ namespace Barotrauma
{
selectedSprites.Add(sprite);
dirtySprites.Add(sprite);
lastSelected = sprite;
}
}
else
@@ -929,9 +901,8 @@ namespace Barotrauma
selectedSprites.Clear();
selectedSprites.Add(sprite);
dirtySprites.Add(sprite);
lastSelected = sprite;
}
if (selectedTexture != sprite.Texture)
if (selectedTexture?.FullPath != sprite.FullPath)
{
textureList.Select(sprite.Texture, autoScroll: false);
UpdateScrollBar(textureList);
@@ -939,7 +910,7 @@ namespace Barotrauma
xmlPathText.Text = string.Empty;
foreach (var s in selectedSprites)
{
texturePathText.Text = s.FilePath;
texturePathText.Text = s.FilePath.Value;
var element = s.SourceElement;
if (element != null)
{
@@ -962,18 +933,18 @@ namespace Barotrauma
ResetWidgets();
HashSet<string> textures = new HashSet<string>();
// Create texture list
foreach (Sprite sprite in loadedSprites.OrderBy(s => Path.GetFileNameWithoutExtension(s.FilePath)))
foreach (Sprite sprite in loadedSprites.OrderBy(s => Path.GetFileNameWithoutExtension(s.FilePath.Value)))
{
//ignore sprites that don't have a file path (e.g. submarine pics)
if (string.IsNullOrEmpty(sprite.FilePath)) continue;
string normalizedFilePath = Path.GetFullPath(sprite.FilePath);
if (sprite.FilePath.IsNullOrEmpty()) continue;
string normalizedFilePath = sprite.FilePath.FullPath;
if (!textures.Contains(normalizedFilePath))
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), textureList.Content.RectTransform) { MinSize = new Point(0, 20) },
Path.GetFileName(sprite.FilePath))
Path.GetFileName(sprite.FilePath.Value))
{
ToolTip = sprite.FilePath,
UserData = sprite.Texture
ToolTip = sprite.FilePath.Value,
UserData = sprite
};
textures.Add(normalizedFilePath);
}
@@ -981,7 +952,7 @@ namespace Barotrauma
// Create sprite list
// TODO: allow the user to choose whether to sort by file name or by texture sheet
//foreach (Sprite sprite in loadedSprites.OrderBy(s => GetSpriteName(s)))
foreach (Sprite sprite in loadedSprites.OrderBy(s => s.SourceElement.GetAttributeString("texture", string.Empty)))
foreach (Sprite sprite in loadedSprites.OrderBy(s => s.SourceElement.GetAttributeContentPath("texture")?.Value ?? string.Empty))
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), spriteList.Content.RectTransform) { MinSize = new Point(0, 20) },
GetSpriteName(sprite) + " (" + sprite.SourceRect.X + ", " + sprite.SourceRect.Y + ", " + sprite.SourceRect.Width + ", " + sprite.SourceRect.Height + ")")
@@ -996,9 +967,8 @@ namespace Barotrauma
{
if (selectedTexture == null) { return; }
var viewArea = GetViewArea;
float width = viewArea.Width / (float)selectedTexture.Width;
float height = viewArea.Height / (float)selectedTexture.Height;
maxZoom = 10; // TODO: user-definable?
float width = viewArea.Width / (float)selectedTexture.Texture.Width;
float height = viewArea.Height / (float)selectedTexture.Texture.Height;
zoom = Math.Min(1, Math.Min(width, height));
zoomBar.BarScroll = GetBarScrollValue();
viewAreaOffset = Point.Zero;
@@ -1017,7 +987,7 @@ namespace Barotrauma
}
}
private float GetBarScrollValue() => MathHelper.Lerp(0, 1, MathUtils.InverseLerp(minZoom, maxZoom, zoom));
private float GetBarScrollValue() => MathHelper.Lerp(0, 1, MathUtils.InverseLerp(MinZoom, MaxZoom, zoom));
private string GetSpriteName(Sprite sprite)
{
@@ -1032,7 +1002,7 @@ namespace Barotrauma
{
name = sourceElement.Parent.GetAttributeString("name", string.Empty);
}
return string.IsNullOrEmpty(name) ? Path.GetFileNameWithoutExtension(sprite.FilePath) : name;
return string.IsNullOrEmpty(name) ? Path.GetFileNameWithoutExtension(sprite.FilePath.Value) : name;
}
private void UpdateScrollBar(GUIListBox listBox)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -22,15 +22,15 @@ namespace Barotrauma
private Submarine? submarine;
private Character? dummyCharacter;
public static Effect BlueprintEffect;
private GUIFrame container;
public static Effect BlueprintEffect = null!;
private GUIFrame container = null!;
private TabMenu tabMenu;
private TabMenu? tabMenu;
public TestScreen()
{
Cam = new Camera();
BlueprintEffect = GameMain.GameScreen.BlueprintEffect;
BlueprintEffect = GameMain.GameScreen.BlueprintEffect!;
new GUIButton(new RectTransform(new Point(256, 256), Frame.RectTransform), "Reload shader")
{
@@ -38,7 +38,7 @@ namespace Barotrauma
{
BlueprintEffect.Dispose();
GameMain.Instance.Content.Unload();
BlueprintEffect = GameMain.Instance.Content.Load<Effect>("Effects/blueprintshader_opengl");
BlueprintEffect = GameMain.Instance.Content.Load<Effect>("Effects/blueprintshader_opengl")!;
GameMain.GameScreen.BlueprintEffect = BlueprintEffect;
return true;
}
@@ -47,7 +47,7 @@ namespace Barotrauma
}
public override void Select()
{
{
base.Select();
container = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas, Anchor.Center), style: "InnerGlow", color: Color.Black);
var tab = new GUIFrame(new RectTransform(Vector2.One, container.RectTransform), color: Color.Black * 0.9f);
@@ -79,7 +79,7 @@ namespace Barotrauma
public override void Update(double deltaTime)
{
base.Update(deltaTime);
tabMenu.Update();
tabMenu!.Update();
if (dummyCharacter is { } dummy)
{