(bcb06cc5c) Unstable v0.9.9.0

This commit is contained in:
Juan Pablo Arce
2020-03-27 15:22:59 -03:00
parent c81486a993
commit b143329701
326 changed files with 9692 additions and 4364 deletions
@@ -21,7 +21,7 @@ namespace Barotrauma
private GUIButton loadGameButton, deleteMpSaveButton;
public Action<Submarine, string, string> StartNewGame;
public Action<SubmarineInfo, string, string> StartNewGame;
public Action<string> LoadGame;
public GUIButton StartButton
@@ -32,7 +32,7 @@ namespace Barotrauma
private readonly bool isMultiplayer;
public CampaignSetupUI(bool isMultiplayer, GUIComponent newGameContainer, GUIComponent loadGameContainer, IEnumerable<Submarine> submarines, IEnumerable<string> saveFiles = null)
public CampaignSetupUI(bool isMultiplayer, GUIComponent newGameContainer, GUIComponent loadGameContainer, IEnumerable<SubmarineInfo> submarines, IEnumerable<string> saveFiles = null)
{
this.isMultiplayer = isMultiplayer;
this.newGameContainer = newGameContainer;
@@ -115,12 +115,12 @@ namespace Barotrauma
return false;
}
Submarine selectedSub = null;
SubmarineInfo selectedSub = null;
if (!isMultiplayer)
{
if (!(subList.SelectedData is Submarine)) { return false; }
selectedSub = subList.SelectedData as Submarine;
if (!(subList.SelectedData is SubmarineInfo)) { return false; }
selectedSub = subList.SelectedData as SubmarineInfo;
}
else
{
@@ -226,7 +226,7 @@ namespace Barotrauma
{
foreach (GUIComponent child in subList.Content.Children)
{
var sub = child.UserData as Submarine;
var sub = child.UserData as SubmarineInfo;
if (sub == null) { return; }
child.Visible = string.IsNullOrEmpty(filter) ? true : sub.DisplayName.ToLower().Contains(filter.ToLower());
}
@@ -238,7 +238,7 @@ namespace Barotrauma
(subPreviewContainer.Parent as GUILayoutGroup)?.Recalculate();
subPreviewContainer.ClearChildren();
Submarine sub = obj as Submarine;
SubmarineInfo sub = obj as SubmarineInfo;
if (sub == null) { return true; }
sub.CreatePreviewWindow(subPreviewContainer);
@@ -278,7 +278,7 @@ namespace Barotrauma
saveNameBox.Text = Path.GetFileNameWithoutExtension(savePath);
}
public void UpdateSubList(IEnumerable<Submarine> submarines)
public void UpdateSubList(IEnumerable<SubmarineInfo> submarines)
{
#if !DEBUG
var subsToShow = submarines.Where(s => !s.HasTag(SubmarineTag.HideInMenus));
@@ -288,7 +288,7 @@ namespace Barotrauma
subList.ClearChildren();
foreach (Submarine sub in subsToShow)
foreach (SubmarineInfo sub in subsToShow)
{
var textBlock = new GUITextBlock(
new RectTransform(new Vector2(1, 0.1f), subList.Content.RectTransform) { MinSize = new Point(0, 30) },
@@ -319,7 +319,7 @@ namespace Barotrauma
};
}
}
if (Submarine.SavedSubmarines.Any())
if (SubmarineInfo.SavedSubmarines.Any())
{
var nonShuttles = subsToShow.Where(s => !s.HasTag(SubmarineTag.Shuttle)).ToList();
if (nonShuttles.Count > 0)
@@ -392,18 +392,19 @@ namespace Barotrauma
{
nameText.Text = Path.GetFileNameWithoutExtension(saveFile);
XDocument doc = SaveUtil.LoadGameSessionDoc(saveFile);
if (doc.Root.GetChildElement("multiplayercampaign") != null)
{
//multiplayer campaign save in the wrong folder -> don't show the save
saveList.Content.RemoveChild(saveFrame);
continue;
}
if (doc?.Root == null)
{
DebugConsole.ThrowError("Error loading save file \"" + saveFile + "\". The file may be corrupted.");
nameText.TextColor = GUI.Style.Red;
continue;
}
if (doc.Root.GetChildElement("multiplayercampaign") != null)
{
//multiplayer campaign save in the wrong folder -> don't show the save
saveList.Content.RemoveChild(saveFrame);
continue;
}
subName = doc.Root.GetAttributeString("submarine", "");
saveTime = doc.Root.GetAttributeString("savetime", "");
contentPackageStr = doc.Root.GetAttributeString("selectedcontentpackages", "");
@@ -119,8 +119,8 @@ namespace Barotrauma.CharacterEditor
if (Submarine.MainSub == null)
{
ResetVariables();
Submarine.MainSub = new Submarine("Content/AnimEditor.sub");
Submarine.MainSub.Load(unloadPrevious: false, showWarningMessages: false);
var subInfo = new SubmarineInfo("Content/AnimEditor.sub");
Submarine.MainSub = new Submarine(subInfo);
Submarine.MainSub.PhysicsBody.Enabled = false;
originalWall = new WallGroup(new List<Structure>(Structure.WallList));
CloneWalls();
@@ -3347,6 +3347,7 @@ namespace Barotrauma.CharacterEditor
void CreateCloseButton(SerializableEntityEditor editor, Action onButtonClicked, float size = 1)
{
if (editor == null) { return; }
int height = 30;
var parent = new GUIFrame(new RectTransform(new Point(editor.Rect.Width, (int)(height * size * GUI.yScale)), editor.RectTransform, isFixedSize: true), style: null)
{
@@ -3366,6 +3367,7 @@ namespace Barotrauma.CharacterEditor
void CreateAddButtonAtLast(ParamsEditor editor, Action onButtonClicked, string text)
{
if (editor == null) { return; }
var parentFrame = new GUIFrame(new RectTransform(new Point(editor.EditorBox.Rect.Width, (int)(50 * GUI.yScale)), editor.EditorBox.Content.RectTransform), style: null, color: ParamsEditor.Color)
{
CanBeFocused = false
@@ -3383,6 +3385,7 @@ namespace Barotrauma.CharacterEditor
void CreateAddButton(SerializableEntityEditor editor, Action onButtonClicked, string text)
{
if (editor == null) { return; }
var parent = new GUIFrame(new RectTransform(new Point(editor.Rect.Width, (int)(60 * GUI.yScale)), editor.RectTransform), style: null)
{
CanBeFocused = false
@@ -4386,7 +4389,7 @@ namespace Barotrauma.CharacterEditor
ResetParamsEditor();
}
limb.PullJointWorldAnchorA = ScreenToSim(PlayerInput.MousePosition);
TryUpdateLimbParam(limb, "pullpos", ConvertUnits.ToDisplayUnits(limb.PullJointLocalAnchorA / limb.Params.Ragdoll.LimbScale));
TryUpdateLimbParam(limb, "pullpos", ConvertUnits.ToDisplayUnits(limb.PullJointLocalAnchorA / limb.Params.Scale / limb.Params.Ragdoll.LimbScale));
GUI.DrawLine(spriteBatch, SimToScreen(limb.SimPosition), tformedPullPos, Color.MediumPurple);
});
}
@@ -4469,7 +4472,7 @@ namespace Barotrauma.CharacterEditor
if (joint.BodyA == limb.body.FarseerBody)
{
joint.LocalAnchorA += input;
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / RagdollParams.JointScale);
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / joint.Scale);
TryUpdateJointParam(joint, "limb1anchor", transformedValue);
// Snap all selected joints to the first selected
if (copyJointSettings)
@@ -4484,7 +4487,7 @@ namespace Barotrauma.CharacterEditor
else if (joint.BodyB == limb.body.FarseerBody)
{
joint.LocalAnchorB += input;
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / RagdollParams.JointScale);
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / joint.Scale);
TryUpdateJointParam(joint, "limb2anchor", transformedValue);
// Snap all selected joints to the first selected
if (copyJointSettings)
@@ -4504,12 +4507,12 @@ namespace Barotrauma.CharacterEditor
if (joint.BodyA == limb.body.FarseerBody && otherJoint.BodyA == otherLimb.body.FarseerBody)
{
otherJoint.LocalAnchorA = joint.LocalAnchorA;
TryUpdateJointParam(otherJoint, "limb1anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / RagdollParams.JointScale));
TryUpdateJointParam(otherJoint, "limb1anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / joint.Scale));
}
else if (joint.BodyB == limb.body.FarseerBody && otherJoint.BodyB == otherLimb.body.FarseerBody)
{
otherJoint.LocalAnchorB = joint.LocalAnchorB;
TryUpdateJointParam(otherJoint, "limb2anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / RagdollParams.JointScale));
TryUpdateJointParam(otherJoint, "limb2anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / joint.Scale));
}
});
}
@@ -4873,10 +4876,10 @@ namespace Barotrauma.CharacterEditor
{
// We want the collider to be slightly smaller than the source rect, because the source rect is usually a bit bigger than the graphic.
float multiplier = 0.85f;
l.body.SetSize(new Vector2(ConvertUnits.ToSimUnits(width), ConvertUnits.ToSimUnits(height)) * RagdollParams.LimbScale * RagdollParams.TextureScale * multiplier);
TryUpdateLimbParam(l, "radius", ConvertUnits.ToDisplayUnits(l.body.radius / RagdollParams.LimbScale / RagdollParams.TextureScale));
TryUpdateLimbParam(l, "width", ConvertUnits.ToDisplayUnits(l.body.width / RagdollParams.LimbScale / RagdollParams.TextureScale));
TryUpdateLimbParam(l, "height", ConvertUnits.ToDisplayUnits(l.body.height / RagdollParams.LimbScale / RagdollParams.TextureScale));
l.body.SetSize(new Vector2(ConvertUnits.ToSimUnits(width), ConvertUnits.ToSimUnits(height)) * l.Scale * RagdollParams.TextureScale * multiplier);
TryUpdateLimbParam(l, "radius", ConvertUnits.ToDisplayUnits(l.body.radius / l.Params.Scale / RagdollParams.LimbScale / RagdollParams.TextureScale));
TryUpdateLimbParam(l, "width", ConvertUnits.ToDisplayUnits(l.body.width / l.Params.Scale / RagdollParams.LimbScale / RagdollParams.TextureScale));
TryUpdateLimbParam(l, "height", ConvertUnits.ToDisplayUnits(l.body.height / l.Params.Scale / RagdollParams.LimbScale / RagdollParams.TextureScale));
}
void RecalculateOrigin(Limb l)
{
@@ -4963,7 +4966,7 @@ namespace Barotrauma.CharacterEditor
{
continue;
}
Vector2 tformedJointPos = jointPos = jointPos / RagdollParams.JointScale / limb.TextureScale * spriteSheetZoom;
Vector2 tformedJointPos = jointPos = jointPos / joint.Scale / limb.TextureScale * spriteSheetZoom;
tformedJointPos.Y = -tformedJointPos.Y;
tformedJointPos.X *= character.AnimController.Dir;
tformedJointPos += limbScreenPos;
@@ -4991,11 +4994,11 @@ namespace Barotrauma.CharacterEditor
Vector2 input = ConvertUnits.ToSimUnits(scaledMouseSpeed);
input.Y = -input.Y;
input.X *= character.AnimController.Dir;
input *= RagdollParams.JointScale * limb.TextureScale / spriteSheetZoom;
input *= joint.Scale * limb.TextureScale / spriteSheetZoom;
if (joint.BodyA == limb.body.FarseerBody)
{
joint.LocalAnchorA += input;
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / RagdollParams.JointScale);
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / joint.Scale);
TryUpdateJointParam(joint, "limb1anchor", transformedValue);
// Snap all selected joints to the first selected
if (copyJointSettings)
@@ -5010,7 +5013,7 @@ namespace Barotrauma.CharacterEditor
else if (joint.BodyB == limb.body.FarseerBody)
{
joint.LocalAnchorB += input;
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / RagdollParams.JointScale);
Vector2 transformedValue = ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / joint.Scale);
TryUpdateJointParam(joint, "limb2anchor", transformedValue);
// Snap all selected joints to the first selected
if (copyJointSettings)
@@ -5029,12 +5032,12 @@ namespace Barotrauma.CharacterEditor
if (joint.BodyA == limb.body.FarseerBody && otherJoint.BodyA == otherLimb.body.FarseerBody)
{
otherJoint.LocalAnchorA = joint.LocalAnchorA;
TryUpdateJointParam(otherJoint, "limb1anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / RagdollParams.JointScale));
TryUpdateJointParam(otherJoint, "limb1anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorA / joint.Scale));
}
else if (joint.BodyB == limb.body.FarseerBody && otherJoint.BodyB == otherLimb.body.FarseerBody)
{
otherJoint.LocalAnchorB = joint.LocalAnchorB;
TryUpdateJointParam(otherJoint, "limb2anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / RagdollParams.JointScale));
TryUpdateJointParam(otherJoint, "limb2anchor", ConvertUnits.ToDisplayUnits(joint.LocalAnchorB / joint.Scale));
}
});
}
@@ -394,7 +394,7 @@ namespace Barotrauma.CharacterEditor
return false;
}
var path = Path.GetFileName(TexturePath);
if (!path.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
if (!path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
{
GUI.AddMessage(TextManager.Get("WrongFileType"), GUI.Style.Red);
texturePathElement.Flash(GUI.Style.Red);
@@ -724,8 +724,8 @@ namespace Barotrauma.CharacterEditor
{
ParseLimbsFromGUIElements();
ParseJointsFromGUIElements();
var main = LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.ToLowerInvariant() == "torso").FirstOrDefault() ??
LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.ToLowerInvariant() == "head").FirstOrDefault();
var main = LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.Equals("torso", StringComparison.OrdinalIgnoreCase)).FirstOrDefault() ??
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);
@@ -91,7 +91,13 @@ namespace Barotrauma
c.DoVisibilityCheck(cam);
if (c.IsVisible != wasVisible)
{
c.AnimController.Limbs.ForEach(l => { if (l.LightSource != null) l.LightSource.Enabled = c.IsVisible; });
c.AnimController.Limbs.ForEach(l =>
{
if (l.LightSource != null)
{
l.LightSource.Enabled = c.IsVisible;
}
});
}
}
@@ -116,10 +122,12 @@ namespace Barotrauma
{
if (Submarine.MainSubs[i] == null) continue;
if (Level.Loaded != null && Submarine.MainSubs[i].WorldPosition.Y < Level.MaxEntityDepth) continue;
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;
GUI.DrawIndicator(
spriteBatch, Submarine.MainSubs[i].WorldPosition, cam,
spriteBatch, position, cam,
Math.Max(Submarine.MainSub.Borders.Width, Submarine.MainSub.Borders.Height),
GUI.SubmarineIcon, indicatorColor);
}
@@ -282,14 +290,23 @@ namespace Barotrauma
}
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.None, null, null, cam.Transform);
foreach (Character c in Character.CharacterList) c.DrawFront(spriteBatch, cam);
if (Level.Loaded != null) Level.Loaded.DrawFront(spriteBatch, cam);
if (GameMain.DebugDraw && GameMain.GameSession?.EventManager != null)
foreach (Character c in Character.CharacterList)
{
GameMain.GameSession.EventManager.DebugDraw(spriteBatch);
c.DrawFront(spriteBatch, cam);
}
if (Level.Loaded != null)
{
Level.Loaded.DrawFront(spriteBatch, cam);
}
if (GameMain.DebugDraw)
{
MapEntity.mapEntityList.ForEach(me => me.AiTarget?.Draw(spriteBatch));
Character.CharacterList.ForEach(c => c.AiTarget?.Draw(spriteBatch));
if (GameMain.GameSession?.EventManager != null)
{
GameMain.GameSession.EventManager.DebugDraw(spriteBatch);
}
}
spriteBatch.End();
if (GameMain.LightManager.LosEnabled && GameMain.LightManager.LosMode != LosMode.None && Character.Controlled != null)
@@ -466,6 +466,7 @@ namespace Barotrauma
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.White, thickness: (int)(1.0f / cam.Zoom));
spriteBatch.End();
if (lightingEnabled.Selected)
@@ -517,8 +518,21 @@ namespace Barotrauma
{
foreach (XElement element in doc.Root.Elements())
{
if (element.Name.ToString().ToLowerInvariant() != genParams.Name.ToLowerInvariant()) continue;
SerializableProperty.SerializeProperties(genParams, element, true);
XElement levelParamElement = element;
if (element.IsOverride())
{
foreach (XElement subElement in element.Elements())
{
if (subElement.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase))
{
SerializableProperty.SerializeProperties(genParams, subElement, true);
}
}
}
else if (element.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase))
{
SerializableProperty.SerializeProperties(genParams, element, true);
}
break;
}
}
@@ -539,7 +553,7 @@ namespace Barotrauma
{
foreach (XElement element in doc.Root.Elements())
{
if (element.Name.ToString().ToLowerInvariant() != levelObjPrefab.Name.ToLowerInvariant()) continue;
if (!element.Name.ToString().Equals(levelObjPrefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
levelObjPrefab.Save(element);
break;
}
@@ -564,7 +578,7 @@ namespace Barotrauma
bool elementFound = false;
foreach (XElement element in doc.Root.Elements())
{
if (element.Name.ToString().ToLowerInvariant() != genParams.Name.ToLowerInvariant()) continue;
if (!element.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
SerializableProperty.SerializeProperties(genParams, element, true);
elementFound = true;
}
@@ -78,9 +78,7 @@ namespace Barotrauma
private IEnumerable<object> LoadRound()
{
GameMain.GameSession.StartRound(campaignUI.SelectedLevel,
reloadSub: true,
loadSecondSub: false,
GameMain.GameSession.StartRound(campaignUI.SelectedLevel,
mirrorLevel: GameMain.GameSession.Map.CurrentLocation != GameMain.GameSession.Map.SelectedConnection.Locations[0]);
GameMain.GameScreen.Select();
@@ -31,6 +31,7 @@ namespace Barotrauma
private GUITextBox serverNameBox, /*portBox, queryPortBox,*/ passwordBox, maxPlayersBox;
private GUITickBox isPublicBox, wrongPasswordBanBox, karmaEnabledBox;
private GUIDropDown karmaPresetDD;
private readonly GUIFrame downloadingModsContainer, enableModsContainer;
private readonly GUIButton joinServerButton, hostServerButton, steamWorkshopButton;
private readonly GameMain game;
@@ -230,13 +231,31 @@ namespace Barotrauma
};
#if USE_STEAM
steamWorkshopButton = new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("SteamWorkshopButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
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")
{
ForceUpperCase = true,
Enabled = false,
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")
@@ -280,12 +299,28 @@ namespace Barotrauma
RelativeSpacing = 0.035f
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), TextManager.Get("SettingsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
var settingsButtonContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), style: null);
new GUIButton(new RectTransform(Vector2.One, settingsButtonContainer.RectTransform), TextManager.Get("SettingsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
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("CreditsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
@@ -401,12 +436,18 @@ namespace Barotrauma
GameMain.Client = null;
}
GameMain.SubEditorScreen?.ClearBackedUpSubInfo();
Submarine.Unload();
ResetButtonStates(null);
GameAnalyticsManager.SetCustomDimension01("");
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)
@@ -495,12 +536,13 @@ namespace Barotrauma
}
campaignSetupUI.CreateDefaultSaveName();
campaignSetupUI.RandomizeSeed();
campaignSetupUI.UpdateSubList(Submarine.SavedSubmarines);
campaignSetupUI.UpdateSubList(SubmarineInfo.SavedSubmarines);
break;
case Tab.LoadGame:
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;
@@ -631,12 +673,12 @@ namespace Barotrauma
Rand.SetLocalRandom(1);
}
Submarine selectedSub = null;
SubmarineInfo selectedSub = null;
string subName = GameMain.Config.QuickStartSubmarineName;
if (!string.IsNullOrEmpty(subName))
{
DebugConsole.NewMessage($"Loading the predefined quick start sub \"{subName}\"", Color.White);
selectedSub = Submarine.SavedSubmarines.FirstOrDefault(s =>
selectedSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s =>
s.Name.ToLower() == subName.ToLower());
if (selectedSub == null)
@@ -647,7 +689,7 @@ namespace Barotrauma
if (selectedSub == null)
{
DebugConsole.NewMessage("Loading a random sub.", Color.White);
var subs = Submarine.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.Shuttle) && !s.HasTag(SubmarineTag.HideInMenus));
var subs = SubmarineInfo.SavedSubmarines.Where(s => !s.HasTag(SubmarineTag.Shuttle) && !s.HasTag(SubmarineTag.HideInMenus));
selectedSub = subs.ElementAt(Rand.Int(subs.Count()));
}
var gamesession = new GameSession(
@@ -684,6 +726,16 @@ namespace Barotrauma
}
}
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") });
@@ -990,7 +1042,7 @@ namespace Barotrauma
spriteBatch.End();
}
private void StartGame(Submarine selectedSub, string saveName, string mapSeed)
private void StartGame(SubmarineInfo selectedSub, string saveName, string mapSeed)
{
if (string.IsNullOrEmpty(saveName)) return;
@@ -1027,7 +1079,7 @@ namespace Barotrauma
return;
}
selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");
selectedSub = new SubmarineInfo(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"));
GameMain.GameSession = new GameSession(selectedSub, saveName,
GameModePreset.List.Find(g => g.Identifier == "singleplayercampaign"));
@@ -1072,7 +1124,7 @@ namespace Barotrauma
var paddedLoadGame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), menuTabs[(int)Tab.LoadGame].RectTransform, Anchor.Center) { AbsoluteOffset = new Point(0, 10) },
style: null);
campaignSetupUI = new CampaignSetupUI(false, paddedNewGame, paddedLoadGame, Submarine.SavedSubmarines)
campaignSetupUI = new CampaignSetupUI(false, paddedNewGame, paddedLoadGame, SubmarineInfo.SavedSubmarines)
{
LoadGame = LoadGame,
StartNewGame = StartGame
@@ -208,15 +208,15 @@ namespace Barotrauma
private set;
}
public Submarine SelectedSub
public SubmarineInfo SelectedSub
{
get { return subList.SelectedData as Submarine; }
get { return subList.SelectedData as SubmarineInfo; }
set { subList.Select(value); }
}
public Submarine SelectedShuttle
public SubmarineInfo SelectedShuttle
{
get { return shuttleList.SelectedData as Submarine; }
get { return shuttleList.SelectedData as SubmarineInfo; }
}
public bool UsingShuttle
@@ -443,7 +443,7 @@ namespace Barotrauma
{
OnClicked = (btn, userdata) =>
{
if (!(userdata is FileReceiver.FileTransferIn transfer)) { return false; }
if (!(FileTransferFrame.UserData is FileReceiver.FileTransferIn transfer)) { return false; }
GameMain.Client?.CancelFileTransfer(transfer);
GameMain.Client.FileReceiver.StopTransfer(transfer);
return true;
@@ -658,7 +658,7 @@ namespace Barotrauma
OnClicked = (btn, obj) =>
{
GameMain.Client.RequestStartRound();
CoroutineManager.StartCoroutine(WaitForStartRound(StartButton, allowCancel: true), "WaitForStartRound");
CoroutineManager.StartCoroutine(WaitForStartRound(StartButton, allowCancel: false), "WaitForStartRound");
return true;
}
};
@@ -1147,6 +1147,22 @@ namespace Barotrauma
clientDisabledElements.AddRange(botSpawnModeButtons);
}
public void StopWaitingForStartRound()
{
CoroutineManager.StopCoroutines("WaitForStartRound");
GUIMessageBox.CloseAll();
if (StartButton != null)
{
StartButton.Enabled = true;
}
if (campaignUI?.StartButton != null)
{
campaignUI.StartButton.Enabled = true;
}
GUI.ClearCursorWait();
}
public IEnumerable<object> WaitForStartRound(GUIButton startButton, bool allowCancel)
{
GUI.SetCursorWaiting();
@@ -1173,7 +1189,8 @@ namespace Barotrauma
}
DateTime timeOut = DateTime.Now + new TimeSpan(0, 0, 10);
while (Selected == GameMain.NetLobbyScreen && DateTime.Now < timeOut)
while (Selected == GameMain.NetLobbyScreen &&
DateTime.Now < timeOut)
{
msgBox.Header.Text = headerText + new string('.', ((int)Timing.TotalTime % 3 + 1));
yield return CoroutineStatus.Running;
@@ -1322,6 +1339,8 @@ namespace Barotrauma
if (GameMain.Client == null) return;
spectateButton.Visible = true;
spectateButton.Enabled = true;
StartButton.Visible = false;
}
public void SetCampaignCharacterInfo(CharacterInfo newCampaignCharacterInfo)
@@ -1609,19 +1628,19 @@ namespace Barotrauma
MissionType = missionType;
}
public void UpdateSubList(GUIComponent subList, List<Submarine> submarines)
public void UpdateSubList(GUIComponent subList, List<SubmarineInfo> submarines)
{
if (subList == null) { return; }
subList.ClearChildren();
foreach (Submarine sub in submarines)
foreach (SubmarineInfo sub in submarines)
{
AddSubmarine(subList, sub);
}
}
private void AddSubmarine(GUIComponent subList, Submarine sub)
private void AddSubmarine(GUIComponent subList, SubmarineInfo sub)
{
if (subList is GUIListBox)
{
@@ -1646,8 +1665,8 @@ namespace Barotrauma
CanBeFocused = false
};
var matchingSub = Submarine.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name && s.MD5Hash?.Hash == sub.MD5Hash?.Hash);
if (matchingSub == null) matchingSub = Submarine.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name);
var matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name && s.MD5Hash?.Hash == sub.MD5Hash?.Hash);
if (matchingSub == null) matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == sub.Name);
if (matchingSub == null)
{
@@ -1704,7 +1723,7 @@ namespace Barotrauma
{
if (!GameMain.Client.ServerSettings.Voting.AllowSubVoting)
{
var selectedSub = component.UserData as Submarine;
var selectedSub = component.UserData as SubmarineInfo;
if (!selectedSub.RequiredContentPackagesInstalled)
{
var msgBox = new GUIMessageBox(TextManager.Get("ContentPackageMismatch"),
@@ -1729,7 +1748,7 @@ namespace Barotrauma
}
return false;
}
if (component.UserData is Submarine sub)
if (component.UserData is SubmarineInfo sub)
{
CreateSubPreview(sub);
}
@@ -1761,7 +1780,7 @@ namespace Barotrauma
}
GameMain.Client.RequestSelectMode(component.Parent.GetChildIndex(component));
HighlightMode(SelectedModeIndex);
return (presetName.ToLowerInvariant() != "multiplayercampaign");
return !presetName.Equals("multiplayercampaign", StringComparison.OrdinalIgnoreCase);
}
return false;
}
@@ -1793,6 +1812,7 @@ namespace Barotrauma
SelectedColor = Color.White * 0.85f,
OutlineColor = Color.White * 0.5f,
TextColor = Color.White,
SelectedTextColor = Color.Black,
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) },
@@ -1884,7 +1904,7 @@ namespace Barotrauma
OnClicked = (btn, userdata) => { if (GUI.MouseOn == btn || GUI.MouseOn == btn.TextBlock) ClosePlayerFrame(btn, userdata); return true; }
};
Vector2 frameSize = GameMain.Client.HasPermission(ClientPermissions.ManagePermissions) ? new Vector2(.24f, .5f) : new Vector2(.24f, .24f);
Vector2 frameSize = GameMain.Client.HasPermission(ClientPermissions.ManagePermissions) ? new Vector2(.28f, .5f) : new Vector2(.28f, .24f);
var playerFrameInner = new GUIFrame(new RectTransform(frameSize, playerFrame.RectTransform, Anchor.Center) { MinSize = new Point(550, 0) });
var paddedPlayerFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.88f), playerFrameInner.RectTransform, Anchor.Center))
@@ -2111,7 +2131,7 @@ namespace Barotrauma
{
if (GameMain.Client.HasPermission(ClientPermissions.Ban))
{
var banButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaTop.RectTransform),
var banButton = new GUIButton(new RectTransform(new Vector2(0.34f, 1.0f), buttonAreaTop.RectTransform),
TextManager.Get("Ban"))
{
UserData = selectedClient
@@ -2119,7 +2139,7 @@ namespace Barotrauma
banButton.OnClicked = (bt, userdata) => { BanPlayer(selectedClient); return true; };
banButton.OnClicked += ClosePlayerFrame;
var rangebanButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaTop.RectTransform),
var rangebanButton = new GUIButton(new RectTransform(new Vector2(0.34f, 1.0f), buttonAreaTop.RectTransform),
TextManager.Get("BanRange"))
{
UserData = selectedClient
@@ -2132,7 +2152,7 @@ namespace Barotrauma
if (GameMain.Client != null && GameMain.Client.ServerSettings.Voting.AllowVoteKick &&
selectedClient != null && selectedClient.AllowKicking)
{
var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaLower.RectTransform),
var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.34f, 1.0f), buttonAreaLower.RectTransform),
TextManager.Get("VoteToKick"))
{
Enabled = !selectedClient.HasKickVoteFromID(GameMain.Client.ID),
@@ -2144,7 +2164,7 @@ namespace Barotrauma
if (GameMain.Client.HasPermission(ClientPermissions.Kick) &&
selectedClient != null && selectedClient.AllowKicking)
{
var kickButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaLower.RectTransform),
var kickButton = new GUIButton(new RectTransform(new Vector2(0.34f, 1.0f), buttonAreaLower.RectTransform),
TextManager.Get("Kick"))
{
UserData = selectedClient
@@ -2153,6 +2173,9 @@ namespace Barotrauma
kickButton.OnClicked += ClosePlayerFrame;
}
GUITextBlock.AutoScaleAndNormalize(
buttonAreaTop.Children.Select(c => ((GUIButton)c).TextBlock).Concat(buttonAreaLower.Children.Select(c => ((GUIButton)c).TextBlock)));
new GUITickBox(new RectTransform(new Vector2(0.25f, 1.0f), buttonAreaTop.RectTransform, Anchor.TopRight),
TextManager.Get("Mute"))
{
@@ -2162,7 +2185,7 @@ namespace Barotrauma
};
}
var closeButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaLower.RectTransform, Anchor.BottomRight),
var closeButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), buttonAreaLower.RectTransform, Anchor.TopRight),
TextManager.Get("Close"))
{
IgnoreLayoutGroups = true,
@@ -2241,7 +2264,7 @@ namespace Barotrauma
targetMicStyle = "GUIMicrophoneDisabled";
}
if (targetMicStyle.ToLowerInvariant() != currMicStyle.ToLowerInvariant())
if (!targetMicStyle.Equals(currMicStyle, StringComparison.OrdinalIgnoreCase))
{
GUI.Style.Apply(micIcon, targetMicStyle);
}
@@ -2597,7 +2620,7 @@ namespace Barotrauma
GUILayoutGroup row = null;
int itemsInRow = 0;
XElement headElement = info.Ragdoll.MainElement.Elements().FirstOrDefault(e => e.GetAttributeString("type", "").ToLowerInvariant() == "head");
XElement headElement = info.Ragdoll.MainElement.Elements().FirstOrDefault(e => e.GetAttributeString("type", "").Equals("head", StringComparison.OrdinalIgnoreCase));
XElement headSpriteElement = headElement.Element("sprite");
string spritePathWithTags = headSpriteElement.Attribute("texture").Value;
@@ -2655,8 +2678,11 @@ namespace Barotrauma
private bool SwitchJob(GUIButton button, object obj)
{
if (JobList == null) { return false; }
int childIndex = JobList.SelectedIndex;
var child = JobList.SelectedComponent;
if (child == null) { return false; }
bool moveToNext = obj != null;
@@ -2745,11 +2771,11 @@ namespace Barotrauma
availableJobs = availableJobs.ToList();
int itemsInRow = 1;
int itemsInRow = 0;
foreach (var jobPrefab in availableJobs)
{
if (itemsInRow >= 4)
if (itemsInRow >= 3)
{
row = new GUILayoutGroup(new RectTransform(Vector2.One, rows.RectTransform), true);
itemsInRow = 0;
@@ -3025,7 +3051,7 @@ namespace Barotrauma
}*/
}
public void TryDisplayCampaignSubmarine(Submarine submarine)
public void TryDisplayCampaignSubmarine(SubmarineInfo submarine)
{
string name = submarine?.Name;
bool displayed = false;
@@ -3034,13 +3060,13 @@ namespace Barotrauma
subPreviewContainer.ClearChildren();
foreach (GUIComponent child in subList.Content.Children)
{
if (!(child.UserData is Submarine sub)) { continue; }
if (!(child.UserData is SubmarineInfo sub)) { continue; }
//just check the name, even though the campaign sub may not be the exact same version
//we're selecting the sub just for show, the selection is not actually used for anything
if (sub.Name == name)
{
subList.Select(sub);
if (Submarine.SavedSubmarines.Contains(sub))
if (SubmarineInfo.SavedSubmarines.Contains(sub))
{
CreateSubPreview(sub);
displayed = true;
@@ -3200,10 +3226,10 @@ namespace Barotrauma
{
return false;
}
Submarine sub = subList.Content.Children
.FirstOrDefault(c => c.UserData is Submarine s && s.Name == subName && s.MD5Hash?.Hash == md5Hash)?
.UserData as Submarine;
SubmarineInfo sub = subList.Content.Children
.FirstOrDefault(c => c.UserData is SubmarineInfo s && s.Name == subName && s.MD5Hash?.Hash == md5Hash)?
.UserData as SubmarineInfo;
//matching sub found and already selected, all good
if (sub != null)
@@ -3212,7 +3238,7 @@ namespace Barotrauma
{
CreateSubPreview(sub);
}
if (subList.SelectedData is Submarine selectedSub && selectedSub.MD5Hash?.Hash == md5Hash && System.IO.File.Exists(sub.FilePath))
if (subList.SelectedData is SubmarineInfo selectedSub && selectedSub.MD5Hash?.Hash == md5Hash && System.IO.File.Exists(sub.FilePath))
{
return true;
}
@@ -3222,8 +3248,8 @@ namespace Barotrauma
if (sub == null)
{
sub = subList.Content.Children
.FirstOrDefault(c => c.UserData is Submarine s && s.Name == subName)?
.UserData as Submarine;
.FirstOrDefault(c => c.UserData is SubmarineInfo s && s.Name == subName)?
.UserData as SubmarineInfo;
}
//found a sub that at least has the same name, select it
@@ -3246,7 +3272,7 @@ namespace Barotrauma
FailedSelectedShuttle = null;
//hashes match, all good
if (sub.MD5Hash?.Hash == md5Hash && Submarine.SavedSubmarines.Contains(sub))
if (sub.MD5Hash?.Hash == md5Hash && SubmarineInfo.SavedSubmarines.Contains(sub))
{
return true;
}
@@ -3261,7 +3287,7 @@ namespace Barotrauma
FailedSelectedShuttle = new Pair<string, string>(subName, md5Hash);
string errorMsg = "";
if (sub == null || !Submarine.SavedSubmarines.Contains(sub))
if (sub == null || !SubmarineInfo.SavedSubmarines.Contains(sub))
{
errorMsg = TextManager.GetWithVariable("SubNotFoundError", "[subname]", subName) + " ";
}
@@ -3303,7 +3329,7 @@ namespace Barotrauma
return false;
}
private void CreateSubPreview(Submarine sub)
private void CreateSubPreview(SubmarineInfo sub)
{
subPreviewContainer?.ClearChildren();
sub.CreatePreviewWindow(subPreviewContainer);
@@ -237,7 +237,7 @@ namespace Barotrauma
{
foreach (XElement element in doc.Root.Elements())
{
if (element.Name.ToString().ToLowerInvariant() != prefab.Name.ToLowerInvariant()) continue;
if (!element.Name.ToString().Equals(prefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; }
SerializableProperty.SerializeProperties(prefab, element, true);
}
}
@@ -965,7 +965,7 @@ namespace Barotrauma
child.Visible =
serverInfo.OwnerVerified &&
serverInfo.ServerName.ToLowerInvariant().Contains(searchBox.Text.ToLowerInvariant()) &&
serverInfo.ServerName.Contains(searchBox.Text, StringComparison.OrdinalIgnoreCase) &&
(!filterSameVersion.Selected || (remoteVersion != null && NetworkMember.IsCompatible(remoteVersion, GameMain.Version))) &&
(!filterPassword.Selected || !serverInfo.HasPassword) &&
(!filterIncompatible.Selected || !incompatible) &&
@@ -996,7 +996,7 @@ namespace Barotrauma
foreach (GUITickBox tickBox in gameModeTickBoxes)
{
var gameMode = (string)tickBox.UserData;
if (!tickBox.Selected && (serverInfo.GameMode == gameMode.ToLowerInvariant() || serverInfo.GameMode == gameMode))
if (!tickBox.Selected && serverInfo.GameMode.Equals(gameMode, StringComparison.OrdinalIgnoreCase))
{
child.Visible = false;
break;
@@ -1304,6 +1304,8 @@ namespace Barotrauma
{
#if DEBUG
DebugConsole.ThrowError($"Failed to parse a Steam friend's connect command ({connectCommand})", e);
#else
DebugConsole.Log($"Failed to parse a Steam friend's connect command ({connectCommand})\n" + e.StackTrace);
#endif
info.ConnectName = null;
info.ConnectEndpoint = null;
@@ -1512,7 +1514,7 @@ namespace Barotrauma
{
serverList.ClearChildren();
if (masterServerData.Substring(0, 5).ToLowerInvariant() == "error")
if (masterServerData.Substring(0, 5).Equals("error", StringComparison.OrdinalIgnoreCase))
{
DebugConsole.ThrowError("Error while connecting to master server (" + masterServerData + ")!");
return;
@@ -26,10 +26,24 @@ namespace Barotrauma
//listbox that shows the files included in the item being created
private GUIListBox createItemFileList;
private FileSystemWatcher createItemWatcher;
private readonly List<GUIButton> tabButtons = new List<GUIButton>();
private readonly HashSet<string> pendingPreviewImageDownloads = new HashSet<string>();
private readonly Dictionary<string, Sprite> itemPreviewSprites = new Dictionary<string, Sprite>();
private class PendingPreviewImageDownload
{
/// <summary>
/// Was the image downloaded
/// </summary>
public bool Downloaded = false;
/// <summary>
/// How many tasks are looking to create a preview image based on this download
/// </summary>
public int PendingLoads = 1;
}
private readonly Dictionary<ulong, PendingPreviewImageDownload> pendingPreviewImageDownloads = new Dictionary<ulong, PendingPreviewImageDownload>();
private Dictionary<string, Sprite> itemPreviewSprites = new Dictionary<string, Sprite>();
private enum Tab
{
@@ -54,6 +68,8 @@ namespace Barotrauma
{
GameMain.Instance.OnResolutionChanged += CreateUI;
CreateUI();
Steamworks.SteamUGC.GlobalOnItemInstalled += OnItemInstalled;
}
private void CreateUI()
@@ -199,7 +215,7 @@ namespace Barotrauma
{
if (GUI.MouseOn is GUIButton || GUI.MouseOn?.Parent is GUIButton) { return false; }
publishedItemList.Deselect();
if (userdata is Submarine sub)
if (userdata is SubmarineInfo sub)
{
CreateWorkshopItem(sub);
}
@@ -215,6 +231,8 @@ namespace Barotrauma
createItemFrame = new GUIFrame(new RectTransform(new Vector2(0.58f, 1.0f), tabs[(int)Tab.Publish].RectTransform, Anchor.TopRight), style: null);
SelectTab(Tab.Mods);
subscribedCoroutine = CoroutineManager.StartCoroutine(PollSubscribedItems());
}
public override void Select()
@@ -230,11 +248,37 @@ namespace Barotrauma
SelectTab(Tab.Mods);
}
private void OnItemInstalled(ulong itemId)
{
RefreshSubscribedItems();
}
CoroutineHandle subscribedCoroutine;
private IEnumerable<object> PollSubscribedItems()
{
if (!SteamManager.IsInitialized) { yield return CoroutineStatus.Success; }
uint numSubscribed = 0;
while (true)
{
while (CoroutineManager.IsCoroutineRunning("Load")) { yield return new WaitForSeconds(1.0f); }
uint newNumSubscribed = Steamworks.SteamUGC.NumSubscribedItems;
if (newNumSubscribed != numSubscribed)
{
RefreshSubscribedItems();
numSubscribed = newNumSubscribed;
}
yield return new WaitForSeconds(1.0f);
}
}
private void SelectTab(Tab tab)
{
for (int i = 0; i < tabs.Length; i++)
{
tabButtons[i].Selected = tabs[i].Visible = i == (int)tab;
tabButtons[i].Selected = tabs[i].Visible = i == (int)tab;
}
if (createItemFrame.CountChildren == 0)
@@ -246,6 +290,7 @@ namespace Barotrauma
};
}
createItemWatcher?.Dispose(); createItemWatcher = null;
if (Screen.Selected == this)
{
switch (tab)
@@ -272,6 +317,25 @@ namespace Barotrauma
GameMain.SteamWorkshopScreen.Select();
}
public IEnumerable<object> RefreshDownloadState()
{
bool isDownloading = true;
while (true)
{
SteamManager.GetSubscribedWorkshopItems((items) =>
{
isDownloading = items.Any(it => it.IsDownloading || it.IsDownloadPending);
GameMain.MainMenuScreen.SetDownloadingModsNotification(isDownloading);
});
if (!isDownloading) { break; }
yield return new WaitForSeconds(0.5f);
}
yield return CoroutineStatus.Success;
}
private void RefreshSubscribedItems()
{
SteamManager.GetSubscribedWorkshopItems((items) =>
@@ -279,6 +343,8 @@ namespace Barotrauma
//filter out the items published by the player (they're shown in the publish tab)
var mySteamID = SteamManager.GetSteamID();
OnItemsReceived(GetVisibleItems(items.Where(it => it.Owner.Id != mySteamID)), subscribedItemList);
GameMain.MainMenuScreen.SetDownloadingModsNotification(items.Any(it => it.IsDownloading || it.IsDownloadPending));
});
}
@@ -312,7 +378,7 @@ namespace Barotrauma
{
CanBeFocused = false
};
foreach (Submarine sub in Submarine.SavedSubmarines)
foreach (SubmarineInfo sub in SubmarineInfo.SavedSubmarines)
{
if (sub.HasTag(SubmarineTag.HideInMenus)) { continue; }
string subPath = Path.GetFullPath(sub.FilePath);
@@ -414,7 +480,7 @@ namespace Barotrauma
CanBeFocused = false
};
}
else
else if (Screen.Selected == this)
{
new GUIImage(new RectTransform(new Point(iconSize), innerFrame.RectTransform), SteamManager.DefaultPreviewImage, scaleToFit: true)
{
@@ -430,16 +496,20 @@ namespace Barotrauma
bool isNewImage;
lock (pendingPreviewImageDownloads)
{
isNewImage = !pendingPreviewImageDownloads.Contains(item?.PreviewImageUrl);
if (isNewImage) { pendingPreviewImageDownloads.Add(item?.PreviewImageUrl); }
isNewImage = !pendingPreviewImageDownloads.ContainsKey(item.Value.Id);
if (isNewImage)
{
if (File.Exists(imagePreviewPath))
{
File.Delete(imagePreviewPath);
}
pendingPreviewImageDownloads.Add(item.Value.Id, new PendingPreviewImageDownload());
}
}
if (isNewImage)
{
if (File.Exists(imagePreviewPath))
{
File.Delete(imagePreviewPath);
}
Directory.CreateDirectory(SteamManager.WorkshopItemPreviewImageFolder);
Uri baseAddress = new Uri(item?.PreviewImageUrl);
@@ -450,16 +520,23 @@ namespace Barotrauma
var request = new RestRequest(fileName, Method.GET);
client.ExecuteAsync(request, response =>
{
lock (pendingPreviewImageDownloads)
{
pendingPreviewImageDownloads.Remove(item?.PreviewImageUrl);
}
OnPreviewImageDownloaded(response, imagePreviewPath);
CoroutineManager.StartCoroutine(WaitForItemPreviewDownloaded(item, listBox, imagePreviewPath));
OnPreviewImageDownloaded(response, imagePreviewPath,
() =>
{
lock (pendingPreviewImageDownloads)
{
pendingPreviewImageDownloads[item.Value.Id].Downloaded = true;
}
CoroutineManager.StartCoroutine(WaitForItemPreviewDownloaded(item, listBox, imagePreviewPath));
});
});
}
else
{
lock (pendingPreviewImageDownloads)
{
pendingPreviewImageDownloads[item.Value.Id].PendingLoads++;
}
CoroutineManager.StartCoroutine(WaitForItemPreviewDownloaded(item, listBox, imagePreviewPath));
}
}
@@ -468,7 +545,7 @@ namespace Barotrauma
{
lock (pendingPreviewImageDownloads)
{
pendingPreviewImageDownloads.Remove(item?.PreviewImageUrl);
pendingPreviewImageDownloads.Remove(item.Value.Id);
}
DebugConsole.ThrowError("Downloading the preview image of the Workshop item \"" + item?.Title + "\" failed.", e);
}
@@ -488,10 +565,11 @@ namespace Barotrauma
CanBeFocused = false
};
if ((item?.IsSubscribed ?? false) && (item?.IsInstalled ?? false))
if ((item?.IsSubscribed ?? false) && (item?.IsInstalled ?? false) && Directory.Exists(item?.Directory))
{
GUITickBox enabledTickBox = null;
try
bool installed = SteamManager.CheckWorkshopItemEnabled(item);
if (!installed)
{
bool? compatible = SteamManager.CheckWorkshopItemCompatibility(item);
if (compatible.HasValue && !compatible.Value)
@@ -504,63 +582,32 @@ namespace Barotrauma
}
else
{
enabledTickBox = new GUITickBox(new RectTransform(new Point(32, 32), rightColumn.RectTransform), null)
{
ToolTip = TextManager.Get("WorkshopItemEnabled"),
UserData = item,
};
enabledTickBox.Selected = SteamManager.CheckWorkshopItemEnabled(item);
enabledTickBox.OnSelected = ToggleItemEnabled;
}
}
catch (Exception e)
{
if (enabledTickBox != null) { enabledTickBox.Enabled = false; }
itemFrame.ToolTip = e.Message;
itemFrame.Color = GUI.Style.Red;
itemFrame.HoverColor = GUI.Style.Red;
itemFrame.SelectedColor = GUI.Style.Red;
titleText.TextColor = GUI.Style.Red;
installed = SteamManager.EnableWorkShopItem(item, true, out string errorMsg, Screen.Selected == this);
if (item?.IsSubscribed ?? false)
{
new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), rightColumn.RectTransform), TextManager.Get("WorkshopItemUnsubscribe"))
if (!installed)
{
UserData = item,
OnClicked = (btn, userdata) =>
{
item?.Unsubscribe();
subscribedItemList.RemoveChild(subscribedItemList.Content.GetChildByUserData(item));
return true;
}
};
}
}
if (listBox != publishedItemList && SteamManager.CheckWorkshopItemEnabled(item) && !SteamManager.CheckWorkshopItemUpToDate(item))
{
new GUIButton(new RectTransform(new Vector2(0.4f, 0.5f), rightColumn.RectTransform, Anchor.BottomLeft), text: TextManager.Get("WorkshopItemUpdate"))
{
UserData = "updatebutton",
Font = GUI.SmallFont,
OnClicked = (btn, userdata) =>
{
if (SteamManager.UpdateWorkshopItem(item, out string errorMsg))
{
new GUIMessageBox("", TextManager.GetWithVariable("WorkshopItemUpdated", "[itemname]", item?.Title));
}
else
{
DebugConsole.ThrowError(errorMsg);
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item?.Title, errorMsg }));
}
btn.Enabled = false;
btn.Visible = false;
return true;
DebugConsole.ThrowError(errorMsg);
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { TextManager.EnsureUTF8(item?.Title), errorMsg }));
}
};
}
}
if (installed)
{
bool upToDate = SteamManager.CheckWorkshopItemUpToDate(item);
if (!upToDate)
{
if (!SteamManager.UpdateWorkshopItem(item, out string errorMsg))
{
DebugConsole.ThrowError(errorMsg);
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { TextManager.EnsureUTF8(item?.Title), errorMsg }));
}
}
}
}
@@ -568,7 +615,11 @@ namespace Barotrauma
{
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.5f), rightColumn.RectTransform), TextManager.Get("WorkshopItemDownloading"));
}
else
else if (item?.IsDownloadPending ?? false)
{
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.5f), rightColumn.RectTransform), TextManager.Get("WorkshopItemDownloadPending"));
}
else if (!(item?.IsSubscribed ?? false))
{
var downloadBtn = new GUIButton(new RectTransform(new Point((int)(32 * GUI.Scale)), rightColumn.RectTransform), "", style: "GUIPlusButton")
{
@@ -579,10 +630,66 @@ namespace Barotrauma
downloadBtn.OnClicked = (btn, userdata) => { DownloadItem(itemFrame, downloadBtn, item); return true; };
}
if ((item?.IsSubscribed ?? false) && listBox == subscribedItemList)
{
var reinstallBtn = new GUIButton(new RectTransform(new Point((int)(32 * GUI.Scale)), rightColumn.RectTransform), "", style: "GUIReloadButton")
{
ToolTip = TextManager.Get("WorkshopItemReinstall"),
ForceUpperCase = true,
UserData = "reinstall"
};
reinstallBtn.OnClicked = (btn, userdata) =>
{
var elem = subscribedItemList.Content.GetChildByUserData(item);
try
{
bool reselect = GameMain.Config.SelectedContentPackages.Any(cp => !string.IsNullOrWhiteSpace(cp.SteamWorkshopUrl) && cp.SteamWorkshopUrl == item?.Url);
if (!SteamManager.DisableWorkShopItem(item, false, out string errorMsg) ||
!SteamManager.EnableWorkShopItem(item, true, out errorMsg, reselect, true))
{
DebugConsole.ThrowError($"Failed to reinstall \"{item?.Title}\": {errorMsg}", null, true);
elem.Flash(GUI.Style.Red);
}
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to reinstall \"{item?.Title}\"", e, true);
elem.Flash(GUI.Style.Red);
}
return true;
};
var unsubBtn = new GUIButton(new RectTransform(new Point((int)(32 * GUI.Scale)), rightColumn.RectTransform), "", style: "GUIMinusButton")
{
ToolTip = TextManager.Get("WorkshopItemUnsubscribe"),
ForceUpperCase = true,
UserData = "unsubscribe"
};
unsubBtn.OnClicked = (btn, userdata) =>
{
SteamManager.DisableWorkShopItem(item, true, out _);
item?.Unsubscribe();
subscribedItemList.RemoveChild(subscribedItemList.Content.GetChildByUserData(item));
return true;
};
}
innerFrame.Recalculate();
listBox.RecalculateChildren();
}
public void SetReinstallButtonStatus(Steamworks.Ugc.Item? item, bool enabled, Color? flashColor)
{
var child = subscribedItemList.Content.FindChild((component) => { return (component.UserData is Steamworks.Ugc.Item?) && (component.UserData as Steamworks.Ugc.Item?)?.Id == item?.Id; });
if (child != null)
{
var reinstallBtn = child.FindChild("reinstall", true);
if (reinstallBtn != null) { reinstallBtn.Enabled = enabled; }
var unsubBtn = child.FindChild("unsubscribe", true);
if (unsubBtn != null) { unsubBtn.Enabled = enabled; }
if (flashColor.HasValue) { child.Flash(flashColor); }
}
}
private void RemoveItemFromLists(ulong itemID)
{
RemoveItemFromList(publishedItemList);
@@ -596,7 +703,7 @@ namespace Barotrauma
}
}
private void CreateMyItemFrame(Submarine submarine, GUIListBox listBox)
private void CreateMyItemFrame(SubmarineInfo submarine, GUIListBox listBox)
{
var itemFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), listBox.Content.RectTransform, minSize: new Point(0, 80)),
style: "ListBoxElement")
@@ -629,21 +736,27 @@ namespace Barotrauma
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.4f), innerFrame.RectTransform), contentPackage.Name, textAlignment: Alignment.CenterLeft);
}
private void OnPreviewImageDownloaded(IRestResponse response, string previewImagePath)
private void OnPreviewImageDownloaded(IRestResponse response, string previewImagePath, Action action)
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
try
{
File.WriteAllBytes(previewImagePath, response.RawBytes);
}
catch (Exception e)
{
string errorMsg = "Failed to save workshop item preview image to \"" + previewImagePath + "\".";
GameAnalyticsManager.AddErrorEventOnce("SteamWorkshopScreen.OnItemPreviewDownloaded:WriteAllBytesFailed" + previewImagePath,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + e.Message);
return;
}
TaskPool.Add(WritePreviewImageAsync(response, previewImagePath), (task) => { action?.Invoke(); });
}
}
private async Task WritePreviewImageAsync(IRestResponse response, string previewImagePath)
{
await Task.Yield();
try
{
File.WriteAllBytes(previewImagePath, response.RawBytes);
}
catch (Exception e)
{
string errorMsg = "Failed to save workshop item preview image to \"" + previewImagePath + "\".";
GameAnalyticsManager.AddErrorEventOnce("SteamWorkshopScreen.OnItemPreviewDownloaded:WriteAllBytesFailed" + previewImagePath,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + e.Message);
return;
}
}
@@ -653,47 +766,67 @@ namespace Barotrauma
{
lock (pendingPreviewImageDownloads)
{
if (!pendingPreviewImageDownloads.Contains(item?.PreviewImageUrl)) { break; }
if (pendingPreviewImageDownloads[item.Value.Id].Downloaded){ break; }
}
yield return CoroutineStatus.Running;
yield return new WaitForSeconds(0.2f);
}
if (File.Exists(previewImagePath))
{
Sprite newSprite;
if (itemPreviewSprites.ContainsKey(item?.PreviewImageUrl))
TaskPool.Add(LoadPreviewImageAsync(item?.PreviewImageUrl, previewImagePath),
new Tuple<Steamworks.Ugc.Item?, GUIListBox>(item, listBox),
(task, tuple) =>
{
newSprite = itemPreviewSprites[item?.PreviewImageUrl];
}
else
{
newSprite = new Sprite(previewImagePath, sourceRectangle: null);
itemPreviewSprites.Add(item?.PreviewImageUrl, newSprite);
}
(var it, var lb) = tuple;
var previewImage = lb.Content.FindChild(item)?.GetChildByUserData("previewimage") as GUIImage;
if (previewImage != null)
{
previewImage.Sprite = task.Result;
}
else
{
CreateWorkshopItemFrame(it, lb);
}
if (listBox.Content.FindChild(item)?.GetChildByUserData("previewimage") is GUIImage previewImage)
{
previewImage.Sprite = newSprite;
}
else
{
CreateWorkshopItemFrame(item, listBox);
}
if (modsPreviewFrame.FindChild(it) != null)
{
ShowItemPreview(it, modsPreviewFrame);
}
if (browsePreviewFrame.FindChild(item) != null)
{
ShowItemPreview(it, browsePreviewFrame);
}
if (modsPreviewFrame.FindChild(item) != null)
{
ShowItemPreview(item, modsPreviewFrame);
}
if (browsePreviewFrame.FindChild(item) != null)
{
ShowItemPreview(item, browsePreviewFrame);
}
lock (pendingPreviewImageDownloads)
{
pendingPreviewImageDownloads[it.Value.Id].PendingLoads--;
if (pendingPreviewImageDownloads[it.Value.Id].PendingLoads <= 0) { pendingPreviewImageDownloads.Remove(it.Value.Id); }
}
});
}
yield return CoroutineStatus.Success;
}
private async Task<Sprite> LoadPreviewImageAsync(string previewImageUrl, string previewImagePath)
{
await Task.Yield();
lock (itemPreviewSprites)
{
if (itemPreviewSprites.ContainsKey(previewImageUrl))
{
return itemPreviewSprites[previewImageUrl];
}
else
{
Sprite newSprite = new Sprite(previewImagePath, sourceRectangle: null);
itemPreviewSprites.Add(previewImageUrl, newSprite);
return newSprite;
}
}
}
private bool DownloadItem(GUIComponent frame, GUIButton downloadButton, Steamworks.Ugc.Item? item)
{
if (item == null) { return false; }
@@ -721,49 +854,6 @@ namespace Barotrauma
return true;
}
private bool ToggleItemEnabled(GUITickBox tickBox)
{
if (!(tickBox.UserData is Steamworks.Ugc.Item?)) { return false; }
var item = tickBox.UserData as Steamworks.Ugc.Item?;
if (item == null) { return false; }
//currently editing the item, don't allow enabling/disabling it
if (itemEditor?.FileId == item?.Id) { tickBox.Selected = true; return false; }
var updateButton = tickBox.Parent.FindChild("updatebutton");
string errorMsg;
if (tickBox.Selected)
{
if (!SteamManager.EnableWorkShopItem(item, false, out errorMsg))
{
tickBox.Visible = false;
tickBox.Selected = false;
if (tickBox.Parent.GetChildByUserData("titletext") is GUITextBlock titleText) { titleText.TextColor = GUI.Style.Red; }
}
}
else
{
if (!SteamManager.DisableWorkShopItem(item, false, out errorMsg))
{
tickBox.Enabled = false;
}
GameMain.Config.EnsureCoreContentPackageSelected();
}
if (updateButton != null)
{
//cannot update if enabling/disabling the item failed or if the item is not enabled
updateButton.Enabled = tickBox.Enabled && tickBox.Selected;
}
if (!string.IsNullOrEmpty(errorMsg))
{
new GUIMessageBox(TextManager.Get("Error"), errorMsg);
}
return true;
}
private void ShowItemPreview(Steamworks.Ugc.Item? item, GUIFrame itemPreviewFrame)
{
itemPreviewFrame.ClearChildren();
@@ -920,7 +1010,7 @@ namespace Barotrauma
};
}
private void CreateWorkshopItem(Submarine sub)
private void CreateWorkshopItem(SubmarineInfo sub)
{
string destinationFolder = Path.Combine("Mods", sub.Name);
itemContentPackage = ContentPackage.CreatePackage(sub.Name, Path.Combine(destinationFolder, SteamManager.MetadataFileName), corePackage: false);
@@ -940,8 +1030,8 @@ namespace Barotrauma
itemContentPackage.AddFile(sub.FilePath, ContentType.Submarine);
itemContentPackage.Name = sub.Name;
itemContentPackage.Save(itemContentPackage.Path);
ContentPackage.List.Add(itemContentPackage);
GameMain.Config.SelectContentPackage(itemContentPackage);
//ContentPackage.List.Add(itemContentPackage);
//GameMain.Config.SelectContentPackage(itemContentPackage);
itemEditor = itemEditor?.WithTitle(sub.Name).WithTag("Submarine").WithDescription(sub.Description);
@@ -1097,7 +1187,7 @@ namespace Barotrauma
var tagBtn = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tagHolder.Content.RectTransform, anchor: Anchor.CenterLeft),
tag.CapitaliseFirstInvariant(), style: "GUIButtonRound");
tagBtn.TextBlock.AutoScaleHorizontal = true;
tagBtn.Selected = itemEditor?.Tags?.Any(t => t.ToLowerInvariant() == tag) ?? false;
tagBtn.Selected = itemEditor?.Tags?.Any(t => t.Equals(tag, StringComparison.OrdinalIgnoreCase)) ?? false;
tagBtn.OnClicked = (btn, userdata) =>
{
@@ -1108,7 +1198,7 @@ namespace Barotrauma
}
else
{
itemEditor?.Tags?.RemoveAll(t => t.ToLowerInvariant() == tagBtn.Text.ToLowerInvariant());
itemEditor?.Tags?.RemoveAll(t => t.Equals(tagBtn.Text, StringComparison.OrdinalIgnoreCase));
tagBtn.Selected = false;
}
return true;
@@ -1201,6 +1291,16 @@ namespace Barotrauma
OnClicked = (btn, userdata) => { ToolBox.OpenFileWithShell(Path.GetFullPath(Path.GetDirectoryName(itemContentPackage.Path))); return true; }
};
createItemFileList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.35f), createItemContent.RectTransform));
createItemWatcher?.Dispose();
createItemWatcher = new FileSystemWatcher(Path.GetDirectoryName(itemContentPackage.Path))
{
Filter = "*",
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName
};
createItemWatcher.Created += OnFileSystemChanges;
createItemWatcher.Deleted += OnFileSystemChanges;
createItemWatcher.Renamed += OnFileSystemChanges;
createItemWatcher.EnableRaisingEvents = true;
RefreshCreateItemFileList();
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), createItemContent.RectTransform), isHorizontal: true)
@@ -1447,23 +1547,54 @@ namespace Barotrauma
{
destinationPath = Path.Combine(modFolder, filePathRelativeToModFolder);
}
itemContentPackage.AddFile(destinationPath, ContentType.None);
}
itemContentPackage.Save(itemContentPackage.Path);
RefreshCreateItemFileList();
}
volatile bool refreshFileList = false;
private void OnFileSystemChanges(object sender, FileSystemEventArgs e)
{
refreshFileList = true;
}
private void RefreshCreateItemFileList()
{
createItemFileList.ClearChildren();
if (itemContentPackage == null) return;
var contentTypes = Enum.GetValues(typeof(ContentType));
foreach (ContentFile contentFile in itemContentPackage.Files)
List<ContentFile> files = itemContentPackage.Files.ToList();
foreach (ContentFile contentFile in files)
{
bool fileExists = File.Exists(contentFile.Path);
if (!fileExists) { itemContentPackage.Files.Remove(contentFile); continue; }
}
List<ContentFile> allFiles = Directory.GetFiles(Path.GetDirectoryName(itemContentPackage.Path), "*", SearchOption.AllDirectories)
.Select(f => new ContentFile(f, ContentType.None))
.Where(file => Path.GetFileName(file.Path) != SteamManager.MetadataFileName &&
Path.GetFileName(file.Path) != SteamManager.PreviewImageName)
.ToList();
for (int i=0;i<allFiles.Count;i++)
{
ContentFile file = allFiles[i];
ContentFile otherFile = itemContentPackage.Files.Find(f => string.Equals(Path.GetFullPath(f.Path).CleanUpPath(),
Path.GetFullPath(file.Path).CleanUpPath(),
StringComparison.InvariantCultureIgnoreCase));
if (otherFile != null)
{
//replace the generated ContentFile object with the one that's present in the
//content package to determine which tickboxes should already be checked
allFiles[i] = otherFile;
}
}
foreach (ContentFile contentFile in allFiles)
{
bool illegalPath = !ContentPackage.IsModFilePathAllowed(contentFile);
//string pathInStagingFolder = Path.Combine(SteamManager.WorkshopItemStagingFolder, contentFile.Path);
//bool fileInStagingFolder = File.Exists(pathInStagingFolder);
bool fileExists = File.Exists(contentFile.Path);
var fileFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.12f), createItemFileList.Content.RectTransform) { MinSize = new Point(0, 20) },
@@ -1479,11 +1610,25 @@ namespace Barotrauma
RelativeSpacing = 0.05f
};
var tickBox = new GUITickBox(new RectTransform(new Vector2(0.1f, 0.8f), content.RectTransform), "")
var tickBox = new GUITickBox(new RectTransform(Vector2.One, content.RectTransform, scaleBasis: ScaleBasis.BothHeight), "")
{
Selected = fileExists && !illegalPath,
Enabled = false,
ToolTip = TextManager.Get(illegalPath ? "WorkshopItemFileNotIncluded" : "WorkshopItemFileIncluded")
Selected = itemContentPackage.Files.Contains(contentFile),
UserData = contentFile
};
tickBox.OnSelected = (tb) =>
{
ContentFile f = tb.UserData as ContentFile;
if (tb.Selected)
{
if (!itemContentPackage.Files.Contains(f)) { itemContentPackage.Files.Add(f); }
}
else
{
if (itemContentPackage.Files.Contains(f)) { itemContentPackage.Files.Remove(f); }
}
return true;
};
var nameText = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), content.RectTransform, Anchor.CenterLeft), contentFile.Path, font: GUI.SmallFont)
@@ -1523,10 +1668,29 @@ namespace Barotrauma
{
OnClicked = (btn, userdata) =>
{
itemContentPackage.RemoveFile(contentFile);
itemContentPackage.Save(itemContentPackage.Path);
RefreshCreateItemFileList();
RefreshMyItemList();
var msgBox = new GUIMessageBox(TextManager.Get("ConfirmFileDeletionHeader"),
TextManager.GetWithVariable("ConfirmFileDeletion", "[file]", contentFile.Path),
new string[] { TextManager.Get("Yes"), TextManager.Get("Cancel") })
{
UserData = "verificationprompt"
};
msgBox.Buttons[0].OnClicked = (applyButton, obj) =>
{
try
{
File.Delete(contentFile.Path);
if (contentFile.Type == ContentType.Submarine) { SubmarineInfo.RefreshSavedSub(contentFile.Path); }
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to delete \"${contentFile.Path}\".", e);
}
//RefreshCreateItemFileList();
RefreshMyItemList();
return true;
};
msgBox.Buttons[0].OnClicked += msgBox.Close;
msgBox.Buttons[1].OnClicked = msgBox.Close;
return true;
}
};
@@ -1536,6 +1700,8 @@ namespace Barotrauma
new Point(0, (int)(content.RectTransform.Children.Max(c => c.MinSize.Y) / content.RectTransform.RelativeSize.Y));
nameText.Text = ToolBox.LimitString(nameText.Text, nameText.Font, maxWidth: nameText.Rect.Width);
}
itemContentPackage.Save(itemContentPackage.Path);
}
private void PublishWorkshopItem()
@@ -1640,6 +1806,11 @@ namespace Barotrauma
public override void Update(double deltaTime)
{
if (refreshFileList)
{
RefreshCreateItemFileList();
refreshFileList = false;
}
}
#endregion
@@ -7,6 +7,8 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using EventInput;
using Microsoft.Xna.Framework.Input;
namespace Barotrauma
{
@@ -30,6 +32,8 @@ namespace Barotrauma
private readonly Camera cam;
private SubmarineInfo backedUpSubInfo;
private Point screenResolution;
private bool lightingEnabled;
@@ -88,6 +92,9 @@ namespace Barotrauma
private GUITextBlock submarineDescriptionCharacterCount;
private Mode mode;
// Prevent the mode from changing
private bool lockMode;
public override Camera Cam
{
@@ -96,9 +103,9 @@ namespace Barotrauma
public string GetSubDescription()
{
string localizedDescription = TextManager.Get("submarine.description." + (Submarine.MainSub?.Name ?? ""), true);
string localizedDescription = TextManager.Get("submarine.description." + (Submarine.MainSub?.Info.Name ?? ""), true);
if (localizedDescription != null) { return localizedDescription; }
return (Submarine.MainSub == null) ? "" : Submarine.MainSub.Description;
return (Submarine.MainSub == null) ? "" : Submarine.MainSub.Info.Description;
}
private string GetTotalHullVolume()
@@ -214,63 +221,10 @@ namespace Barotrauma
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine");
subNameLabel = new GUITextBlock(new RectTransform(new Vector2(0.3f, 0.9f), paddedTopPanel.RectTransform, Anchor.CenterLeft),
TextManager.Get("unspecifiedsubfilename"), font: GUI.LargeFont, textAlignment: Alignment.CenterLeft);
linkedSubBox = new GUIDropDown(new RectTransform(new Vector2(0.15f, 0.9f), paddedTopPanel.RectTransform),
TextManager.Get("AddSubButton"), elementCount: 20)
new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "TestButton")
{
ToolTip = TextManager.Get("AddSubToolTip")
};
foreach (Submarine sub in Submarine.SavedSubmarines)
{
linkedSubBox.AddItem(sub.Name, sub);
}
linkedSubBox.OnSelected += SelectLinkedSub;
linkedSubBox.OnDropped += (component, obj) =>
{
MapEntity.SelectedList.Clear();
return true;
};
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine");
defaultModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "EditSubButton")
{
ToolTip = TextManager.Get("SubEditorEditingMode"),
OnSelected = (GUITickBox tBox) =>
{
if (tBox.Selected) { SetMode(Mode.Default); }
return true;
}
};
characterModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "CharacterModeButton")
{
ToolTip = TextManager.Get("CharacterModeButton") + '\n' + TextManager.Get("CharacterModeToolTip"),
OnSelected = (GUITickBox tBox) =>
{
SetMode(tBox.Selected ? Mode.Character : Mode.Default);
return true;
}
};
wiringModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "WiringModeButton")
{
ToolTip = TextManager.Get("WiringModeButton") + '\n' + TextManager.Get("WiringModeToolTip"),
OnSelected = (GUITickBox tBox) =>
{
SetMode(tBox.Selected ? Mode.Wiring : Mode.Default);
return true;
}
};
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine");
new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "GenerateWaypointsButton")
{
ToolTip = TextManager.Get("GenerateWaypointsButton") + '\n' + TextManager.Get("GenerateWaypointsToolTip"),
OnClicked = GenerateWaypoints
ToolTip = TextManager.Get("TestSubButton"),
OnClicked = TestSubmarine
};
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine");
@@ -282,7 +236,7 @@ namespace Barotrauma
{
previouslyUsedPanel.Visible = false;
showEntitiesPanel.Visible = !showEntitiesPanel.Visible;
showEntitiesPanel.RectTransform.AbsoluteOffset = new Point(btn.Rect.X, TopPanel.Rect.Height);
showEntitiesPanel.RectTransform.AbsoluteOffset = new Point(Math.Max(Math.Max(btn.Rect.X, entityCountPanel.Rect.Right), saveAssemblyFrame.Rect.Right), TopPanel.Rect.Height);
return true;
}
};
@@ -294,7 +248,110 @@ namespace Barotrauma
{
showEntitiesPanel.Visible = false;
previouslyUsedPanel.Visible = !previouslyUsedPanel.Visible;
previouslyUsedPanel.RectTransform.AbsoluteOffset = new Point(btn.Rect.X, TopPanel.Rect.Height);
previouslyUsedPanel.RectTransform.AbsoluteOffset = new Point(Math.Max(Math.Max(btn.Rect.X, entityCountPanel.Rect.Right), saveAssemblyFrame.Rect.Right), TopPanel.Rect.Height);
return true;
}
};
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine");
subNameLabel = new GUITextBlock(new RectTransform(new Vector2(0.3f, 0.9f), paddedTopPanel.RectTransform, Anchor.CenterLeft),
TextManager.Get("unspecifiedsubfilename"), font: GUI.LargeFont, textAlignment: Alignment.CenterLeft);
linkedSubBox = new GUIDropDown(new RectTransform(new Vector2(0.15f, 0.9f), paddedTopPanel.RectTransform),
TextManager.Get("AddSubButton"), elementCount: 20)
{
ToolTip = TextManager.Get("AddSubToolTip")
};
foreach (SubmarineInfo sub in SubmarineInfo.SavedSubmarines)
{
linkedSubBox.AddItem(sub.Name, sub);
}
linkedSubBox.OnSelected += SelectLinkedSub;
linkedSubBox.OnDropped += (component, obj) =>
{
MapEntity.SelectedList.Clear();
return true;
};
var spacing = new GUIFrame(new RectTransform(new Vector2(0.02f, 1.0f), paddedTopPanel.RectTransform), style: null);
new GUIFrame(new RectTransform(new Vector2(0.1f, 0.9f), spacing.RectTransform, Anchor.Center), style: "VerticalLine");
defaultModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "EditSubButton")
{
ToolTip = TextManager.Get("SubEditorEditingMode"),
OnSelected = (GUITickBox tBox) =>
{
if (!lockMode)
{
if (tBox.Selected) { SetMode(Mode.Default); }
return true;
}
else { return false; }
}
};
characterModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "CharacterModeButton")
{
ToolTip = TextManager.Get("CharacterModeButton") + '\n' + TextManager.Get("CharacterModeToolTip"),
OnSelected = (GUITickBox tBox) =>
{
if (!lockMode)
{
SetMode(tBox.Selected ? Mode.Character : Mode.Default);
return true;
}
else { return false; }
}
};
wiringModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "WiringModeButton")
{
ToolTip = TextManager.Get("WiringModeButton") + '\n' + TextManager.Get("WiringModeToolTip"),
OnSelected = (GUITickBox tBox) =>
{
if (!lockMode)
{
SetMode(tBox.Selected ? Mode.Wiring : Mode.Default);
return true;
}
else { return false; }
}
};
spacing = new GUIFrame(new RectTransform(new Vector2(0.02f, 1.0f), paddedTopPanel.RectTransform), style: null);
new GUIFrame(new RectTransform(new Vector2(0.1f, 0.9f), spacing.RectTransform, Anchor.Center), style: "VerticalLine");
new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "GenerateWaypointsButton")
{
ToolTip = TextManager.Get("GenerateWaypointsButton") + '\n' + TextManager.Get("GenerateWaypointsToolTip"),
OnClicked = (btn, userdata) =>
{
if (WayPoint.WayPointList.Any())
{
var generateWaypointsVerification = new GUIMessageBox("", TextManager.Get("generatewaypointsverification"), new string[] { TextManager.Get("ok"), TextManager.Get("cancel") });
generateWaypointsVerification.Buttons[0].OnClicked = (btn, userdata) =>
{
if (GenerateWaypoints())
{
GUI.AddMessage(TextManager.Get("waypointsgeneratedsuccesfully"), GUI.Style.Green);
}
WayPoint.ShowWayPoints = true;
generateWaypointsVerification.Close();
return true;
};
generateWaypointsVerification.Buttons[1].OnClicked = generateWaypointsVerification.Close;
}
else
{
if (GenerateWaypoints())
{
GUI.AddMessage(TextManager.Get("waypointsgeneratedsuccesfully"), GUI.Style.Green);
}
WayPoint.ShowWayPoints = true;
}
return true;
}
};
@@ -325,8 +382,7 @@ namespace Barotrauma
showEntitiesPanel = new GUIFrame(new RectTransform(new Vector2(0.08f, 0.5f), GUI.Canvas)
{
MinSize = new Point(170, 0),
AbsoluteOffset = new Point(visibilityButton.Rect.X, TopPanel.Rect.Height)
MinSize = new Point(170, 0)
})
{
Visible = false
@@ -613,6 +669,41 @@ namespace Barotrauma
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
}
private bool TestSubmarine(GUIButton button, object obj)
{
List<string> errorMsgs = new List<string>();
if (!Hull.hullList.Any())
{
errorMsgs.Add(TextManager.Get("NoHullsWarning"));
}
if (!WayPoint.WayPointList.Any(wp => wp.ShouldBeSaved && wp.SpawnType == SpawnType.Human))
{
errorMsgs.Add(TextManager.Get("NoHumanSpawnpointWarning"));
}
if (errorMsgs.Any())
{
new GUIMessageBox(TextManager.Get("Error"), string.Join("\n\n", errorMsgs), new Vector2(0.25f, 0.0f), new Point(400, 200));
return true;
}
backedUpSubInfo = new SubmarineInfo(Submarine.MainSub);
GameMain.GameScreen.Select();
GameSession gameSession = new GameSession(backedUpSubInfo, "", GameModePreset.List.Find(gm => gm.Identifier == "subtest"), null);
gameSession.StartRound(null, false);
return true;
}
public void ClearBackedUpSubInfo()
{
backedUpSubInfo = null;
}
private void UpdateEntityList()
{
entityList.Content.ClearChildren();
@@ -741,9 +832,20 @@ namespace Barotrauma
{
base.Select();
GameMain.LightManager.AmbientLight =
Level.Loaded?.GenerationParams?.AmbientLightColor ??
LevelGenerationParams.LevelParams?.FirstOrDefault()?.AmbientLightColor ??
new Color(20, 20, 20, 255);
UpdateEntityList();
string name = (Submarine.MainSub == null) ? TextManager.Get("unspecifiedsubfilename") : Submarine.MainSub.Name;
if (backedUpSubInfo != null)
{
Submarine.Unload();
}
string name = (Submarine.MainSub == null) ? TextManager.Get("unspecifiedsubfilename") : Submarine.MainSub.Info.Name;
if (backedUpSubInfo != null) { name = backedUpSubInfo.Name; }
subNameLabel.Text = ToolBox.LimitString(name, subNameLabel.Font, subNameLabel.Rect.Width);
foreach (MapEntityPrefab prefab in MapEntityPrefab.List)
@@ -760,23 +862,26 @@ namespace Barotrauma
GUI.ForceMouseOn(null);
SetMode(Mode.Default);
if (Submarine.MainSub != null)
if (backedUpSubInfo != null)
{
Submarine.MainSub.SetPrevTransform(Submarine.MainSub.Position);
Submarine.MainSub.UpdateTransform();
cam.Position = Submarine.MainSub.Position + Submarine.MainSub.HiddenSubPosition;
Submarine.MainSub = new Submarine(backedUpSubInfo);
backedUpSubInfo = null;
}
else
else if (Submarine.MainSub == null)
{
Submarine.MainSub = new Submarine(Path.Combine(Submarine.SavePath, TextManager.Get("UnspecifiedSubFileName") + ".sub"), "", false);
cam.Position = Submarine.MainSub.Position;
var subInfo = new SubmarineInfo();
Submarine.MainSub = new Submarine(subInfo);
}
Submarine.MainSub.SetPrevTransform(Submarine.MainSub.Position);
Submarine.MainSub.UpdateTransform(interpolate: false);
cam.Position = Submarine.MainSub.Position + Submarine.MainSub.HiddenSubPosition;
GameMain.SoundManager.SetCategoryGainMultiplier("default", 0.0f, 0);
GameMain.SoundManager.SetCategoryGainMultiplier("waterambience", 0.0f, 0);
linkedSubBox.ClearChildren();
foreach (Submarine sub in Submarine.SavedSubmarines)
foreach (SubmarineInfo sub in SubmarineInfo.SavedSubmarines)
{
linkedSubBox.AddItem(sub.Name, sub);
}
@@ -987,27 +1092,37 @@ namespace Barotrauma
nameBox.Flash();
return false;
}
foreach (char illegalChar in Path.GetInvalidFileNameChars())
var result = SaveSubToFile(nameBox.Text);
saveFrame = null;
return result;
}
private bool SaveSubToFile(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
if (nameBox.Text.Contains(illegalChar))
{
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
nameBox.Flash();
return false;
}
GUI.AddMessage(TextManager.Get("SubNameMissingWarning"), GUI.Style.Red);
return false;
}
string savePath = nameBox.Text + ".sub";
string prevSavePath = null;
if (Submarine.MainSub != null)
foreach (var illegalChar in Path.GetInvalidFileNameChars())
{
prevSavePath = Submarine.MainSub.FilePath;
savePath = Path.Combine(Path.GetDirectoryName(Submarine.MainSub.FilePath), savePath);
if (!name.Contains(illegalChar)) continue;
GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
return false;
}
string savePath = name + ".sub";
string prevSavePath = null;
if (!string.IsNullOrEmpty(Submarine.MainSub?.Info.FilePath) &&
Submarine.MainSub.Info.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
prevSavePath = Submarine.MainSub.Info.FilePath.CleanUpPath();
savePath = Path.Combine(Path.GetDirectoryName(Submarine.MainSub.Info.FilePath), savePath).CleanUpPath();
}
else
{
savePath = Path.Combine(Submarine.SavePath, savePath);
savePath = Path.Combine(SubmarineInfo.SavePath, savePath);
}
#if !DEBUG
@@ -1015,8 +1130,8 @@ namespace Barotrauma
if (vanilla != null)
{
var vanillaSubs = vanilla.GetFilesOfType(ContentType.Submarine);
string pathToCompare = savePath.Replace(@"\", @"/").ToLowerInvariant();
if (vanillaSubs.Any(sub => sub.Replace(@"\", @"/").ToLowerInvariant() == pathToCompare))
string pathToCompare = savePath.Replace(@"\", @"/");
if (vanillaSubs.Any(sub => sub.Replace(@"\", @"/").Equals(pathToCompare, StringComparison.OrdinalIgnoreCase)))
{
GUI.AddMessage(TextManager.Get("CannotEditVanillaSubs"), GUI.Style.Red, font: GUI.LargeFont);
return false;
@@ -1024,38 +1139,35 @@ namespace Barotrauma
}
#endif
if (previewImage.Sprite?.Texture != null)
if (previewImage?.Sprite?.Texture != null)
{
using (MemoryStream imgStream = new MemoryStream())
{
previewImage.Sprite.Texture.SaveAsPng(imgStream, previewImage.Sprite.Texture.Width, previewImage.Sprite.Texture.Height);
Submarine.SaveCurrent(savePath, imgStream);
Submarine.MainSub.SaveAs(savePath, imgStream);
}
}
else
{
Submarine.SaveCurrent(savePath);
Submarine.MainSub.SaveAs(savePath);
}
Submarine.MainSub.CheckForErrors();
Submarine.MainSub?.CheckForErrors();
GUI.AddMessage(TextManager.GetWithVariable("SubSavedNotification", "[filepath]", Submarine.MainSub.FilePath), GUI.Style.Green);
Submarine.RefreshSavedSub(savePath);
GUI.AddMessage(TextManager.GetWithVariable("SubSavedNotification", "[filepath]", savePath), GUI.Style.Green);
SubmarineInfo.RefreshSavedSub(savePath);
if (prevSavePath != null && prevSavePath != savePath)
{
Submarine.RefreshSavedSub(prevSavePath);
SubmarineInfo.RefreshSavedSub(prevSavePath);
}
linkedSubBox.ClearChildren();
foreach (Submarine sub in Submarine.SavedSubmarines)
foreach (SubmarineInfo sub in SubmarineInfo.SavedSubmarines)
{
linkedSubBox.AddItem(sub.Name, sub);
}
subNameLabel.Text = ToolBox.LimitString(Submarine.MainSub.Name, subNameLabel.Font, subNameLabel.Rect.Width);
subNameLabel.Text = ToolBox.LimitString(Submarine.MainSub.Info.Name, subNameLabel.Font, subNameLabel.Rect.Width);
saveFrame = null;
return false;
}
@@ -1160,15 +1272,15 @@ namespace Barotrauma
crewSizeMin.OnValueChanged += (numberInput) =>
{
crewSizeMax.IntValue = Math.Max(crewSizeMax.IntValue, numberInput.IntValue);
Submarine.MainSub.RecommendedCrewSizeMin = crewSizeMin.IntValue;
Submarine.MainSub.RecommendedCrewSizeMax = crewSizeMax.IntValue;
Submarine.MainSub.Info.RecommendedCrewSizeMin = crewSizeMin.IntValue;
Submarine.MainSub.Info.RecommendedCrewSizeMax = crewSizeMax.IntValue;
};
crewSizeMax.OnValueChanged += (numberInput) =>
{
crewSizeMin.IntValue = Math.Min(crewSizeMin.IntValue, numberInput.IntValue);
Submarine.MainSub.RecommendedCrewSizeMin = crewSizeMin.IntValue;
Submarine.MainSub.RecommendedCrewSizeMax = crewSizeMax.IntValue;
Submarine.MainSub.Info.RecommendedCrewSizeMin = crewSizeMin.IntValue;
Submarine.MainSub.Info.RecommendedCrewSizeMax = crewSizeMax.IntValue;
};
var crewExpArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), leftColumn.RectTransform), isHorizontal: true)
@@ -1191,7 +1303,7 @@ namespace Barotrauma
if (currentIndex < 0) currentIndex = crewExperienceLevels.Length - 1;
experienceText.UserData = crewExperienceLevels[currentIndex];
experienceText.Text = TextManager.Get(crewExperienceLevels[currentIndex]);
Submarine.MainSub.RecommendedCrewExperience = (string)experienceText.UserData;
Submarine.MainSub.Info.RecommendedCrewExperience = (string)experienceText.UserData;
return true;
};
@@ -1202,18 +1314,18 @@ namespace Barotrauma
if (currentIndex >= crewExperienceLevels.Length) currentIndex = 0;
experienceText.UserData = crewExperienceLevels[currentIndex];
experienceText.Text = TextManager.Get(crewExperienceLevels[currentIndex]);
Submarine.MainSub.RecommendedCrewExperience = (string)experienceText.UserData;
Submarine.MainSub.Info.RecommendedCrewExperience = (string)experienceText.UserData;
return true;
};
if (Submarine.MainSub != null)
{
int min = Submarine.MainSub.RecommendedCrewSizeMin;
int max = Submarine.MainSub.RecommendedCrewSizeMax;
int min = Submarine.MainSub.Info.RecommendedCrewSizeMin;
int max = Submarine.MainSub.Info.RecommendedCrewSizeMax;
crewSizeMin.IntValue = min;
crewSizeMax.IntValue = max;
experienceText.UserData = string.IsNullOrEmpty(Submarine.MainSub.RecommendedCrewExperience) ?
crewExperienceLevels[0] : Submarine.MainSub.RecommendedCrewExperience;
experienceText.UserData = string.IsNullOrEmpty(Submarine.MainSub.Info.RecommendedCrewExperience) ?
crewExperienceLevels[0] : Submarine.MainSub.Info.RecommendedCrewExperience;
experienceText.Text = TextManager.Get((string)experienceText.UserData);
}
@@ -1222,7 +1334,7 @@ namespace Barotrauma
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), rightColumn.RectTransform), TextManager.Get("SubPreviewImage"), font: GUI.SubHeadingFont);
var previewImageHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.5f), rightColumn.RectTransform), style: null) { Color = Color.Black, CanBeFocused = false };
previewImage = new GUIImage(new RectTransform(Vector2.One, previewImageHolder.RectTransform), Submarine.MainSub?.PreviewImage, scaleToFit: true);
previewImage = new GUIImage(new RectTransform(Vector2.One, previewImageHolder.RectTransform), Submarine.MainSub?.Info.PreviewImage, scaleToFit: true);
var previewImageButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f };
@@ -1236,7 +1348,7 @@ namespace Barotrauma
previewImage.Sprite = new Sprite(TextureLoader.FromStream(imgStream), null, null);
if (Submarine.MainSub != null)
{
Submarine.MainSub.PreviewImage = previewImage.Sprite;
Submarine.MainSub.Info.PreviewImage = previewImage.Sprite;
}
}
return true;
@@ -1258,7 +1370,7 @@ namespace Barotrauma
previewImage.Sprite = new Sprite(file, sourceRectangle: null);
if (Submarine.MainSub != null)
{
Submarine.MainSub.PreviewImage = previewImage.Sprite;
Submarine.MainSub.Info.PreviewImage = previewImage.Sprite;
}
};
FileSelection.ClearFileTypeFilters();
@@ -1288,7 +1400,7 @@ namespace Barotrauma
var tagTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), tagContainer.Content.RectTransform),
tagStr, font: GUI.SmallFont)
{
Selected = Submarine.MainSub == null ? false : Submarine.MainSub.HasTag(tag),
Selected = Submarine.MainSub == null ? false : Submarine.MainSub.Info.HasTag(tag),
UserData = tag,
OnSelected = (GUITickBox tickBox) =>
@@ -1296,11 +1408,11 @@ namespace Barotrauma
if (Submarine.MainSub == null) return false;
if (tickBox.Selected)
{
Submarine.MainSub.AddTag((SubmarineTag)tickBox.UserData);
Submarine.MainSub.Info.AddTag((SubmarineTag)tickBox.UserData);
}
else
{
Submarine.MainSub.RemoveTag((SubmarineTag)tickBox.UserData);
Submarine.MainSub.Info.RemoveTag((SubmarineTag)tickBox.UserData);
}
return true;
}
@@ -1313,7 +1425,7 @@ namespace Barotrauma
var contentPackList = new GUIListBox(new RectTransform(new Vector2(0.5f, 1.0f - contentPackagesLabel.RectTransform.RelativeSize.Y),
horizontalArea.RectTransform, Anchor.BottomRight));
List<string> contentPacks = Submarine.MainSub.RequiredContentPackages.ToList();
List<string> contentPacks = Submarine.MainSub.Info.RequiredContentPackages.ToList();
foreach (ContentPackage contentPack in ContentPackage.List)
{
//don't show content packages that only define submarine files
@@ -1326,18 +1438,18 @@ namespace Barotrauma
{
var cpTickBox = new GUITickBox(new RectTransform(new Vector2(0.2f, 0.2f), contentPackList.Content.RectTransform), contentPackageName, font: GUI.SmallFont)
{
Selected = Submarine.MainSub.RequiredContentPackages.Contains(contentPackageName),
Selected = Submarine.MainSub.Info.RequiredContentPackages.Contains(contentPackageName),
UserData = contentPackageName
};
cpTickBox.OnSelected += (GUITickBox tickBox) =>
{
if (tickBox.Selected)
{
Submarine.MainSub.RequiredContentPackages.Add((string)tickBox.UserData);
Submarine.MainSub.Info.RequiredContentPackages.Add((string)tickBox.UserData);
}
else
{
Submarine.MainSub.RequiredContentPackages.Remove((string)tickBox.UserData);
Submarine.MainSub.Info.RequiredContentPackages.Remove((string)tickBox.UserData);
}
return true;
};
@@ -1363,7 +1475,7 @@ namespace Barotrauma
};
paddedSaveFrame.Recalculate();
leftColumn.Recalculate();
descriptionBox.Text = Submarine.MainSub == null ? "" : Submarine.MainSub.Description;
descriptionBox.Text = Submarine.MainSub == null ? "" : Submarine.MainSub.Info.Description;
submarineDescriptionCharacterCount.Text = descriptionBox.Text.Length + " / " + submarineDescriptionLimit;
}
@@ -1513,7 +1625,7 @@ namespace Barotrauma
#if DEBUG
deleteBtn.Enabled = true;
#else
deleteBtn.Enabled = userData is Submarine sub && !sub.IsVanillaSubmarine();
deleteBtn.Enabled = userData is Submarine sub && !sub.Info.IsVanillaSubmarine();
#endif
}
return true;
@@ -1524,7 +1636,7 @@ namespace Barotrauma
searchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
searchBox.OnTextChanged += (textBox, text) => { FilterSubs(subList, text); return true; };
foreach (Submarine sub in Submarine.SavedSubmarines)
foreach (SubmarineInfo sub in SubmarineInfo.SavedSubmarines)
{
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.1f), subList.Content.RectTransform) { MinSize = new Point(0, 30) },
ToolBox.LimitString(sub.Name, GUI.Font, subList.Rect.Width - 80))
@@ -1554,7 +1666,7 @@ namespace Barotrauma
{
if (subList.SelectedComponent != null)
{
TryDeleteSub(subList.SelectedComponent.UserData as Submarine);
TryDeleteSub(subList.SelectedComponent.UserData as SubmarineInfo);
}
deleteButton.Enabled = false;
return true;
@@ -1586,7 +1698,7 @@ namespace Barotrauma
foreach (GUIComponent child in subList.Content.Children)
{
if (!(child.UserData is Submarine sub)) { return; }
child.Visible = string.IsNullOrEmpty(filter) ? true : sub.Name.ToLower().Contains(filter.ToLower());
child.Visible = string.IsNullOrEmpty(filter) ? true : sub.Info.Name.ToLower().Contains(filter.ToLower());
}
}
@@ -1606,14 +1718,14 @@ namespace Barotrauma
}
if (subList.SelectedComponent == null) { return false; }
if (!(subList.SelectedComponent.UserData is Submarine selectedSub)) { return false; }
if (!(subList.SelectedComponent.UserData is SubmarineInfo selectedSubInfo)) { return false; }
selectedSub.Load(true);
Submarine.Unload();
var selectedSub = new Submarine(selectedSubInfo);
Submarine.MainSub = selectedSub;
Submarine.MainSub.SetPrevTransform(Submarine.MainSub.Position);
Submarine.MainSub.UpdateTransform();
Submarine.MainSub.UpdateTransform(interpolate: false);
string name = Submarine.MainSub.Name;
string name = Submarine.MainSub.Info.Name;
subNameLabel.Text = ToolBox.LimitString(name, subNameLabel.Font, subNameLabel.Rect.Width);
cam.Position = Submarine.MainSub.Position + Submarine.MainSub.HiddenSubPosition;
@@ -1624,10 +1736,13 @@ namespace Barotrauma
foreach (Item item in Item.ItemList)
{
var lightComponent = item.GetComponent<LightComponent>();
if (lightComponent != null) lightComponent.Light.Enabled = item.ParentInventory == null;
if (lightComponent != null)
{
lightComponent.Light.Enabled = item.ParentInventory == null;
}
}
if (selectedSub.GameVersion < new Version("0.8.9.0"))
if (selectedSub.Info.GameVersion < new Version("0.8.9.0"))
{
var adjustLightsPrompt = new GUIMessageBox(TextManager.Get("Warning"), TextManager.Get("AdjustLightsPrompt"),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
@@ -1649,7 +1764,7 @@ namespace Barotrauma
return true;
}
private void TryDeleteSub(Submarine sub)
private void TryDeleteSub(SubmarineInfo sub)
{
if (sub == null) { return; }
@@ -1674,9 +1789,9 @@ namespace Barotrauma
{
try
{
sub.Remove();
sub.Dispose();
File.Delete(sub.FilePath);
Submarine.RefreshSavedSubs();
SubmarineInfo.RefreshSavedSubs();
CreateLoadScreen();
}
catch (Exception e)
@@ -1754,18 +1869,20 @@ namespace Barotrauma
return true;
}
public void SetMode(Mode mode)
public void SetMode(Mode newMode)
{
if (mode == this.mode) { return; }
this.mode = mode;
if (newMode == mode) { return; }
mode = newMode;
defaultModeTickBox.Selected = mode == Mode.Default;
lockMode = true;
defaultModeTickBox.Selected = newMode == Mode.Default;
defaultModeTickBox.CanBeFocused = !defaultModeTickBox.Selected;
characterModeTickBox.Selected = mode == Mode.Character;
wiringModeTickBox.Selected = mode == Mode.Wiring;
switch (mode)
characterModeTickBox.Selected = newMode == Mode.Character;
wiringModeTickBox.Selected = newMode == Mode.Wiring;
lockMode = false;
switch (newMode)
{
case Mode.Character:
CreateDummyCharacter();
@@ -1790,6 +1907,7 @@ namespace Barotrauma
}
MapEntity.DeselectAll();
MapEntity.FilteredSelectedList.Clear();
}
private void RemoveDummyCharacter()
@@ -1954,7 +2072,7 @@ namespace Barotrauma
return false;
}
if (Submarine.MainSub != null) Submarine.MainSub.Name = text;
if (Submarine.MainSub != null) Submarine.MainSub.Info.Name = text;
textBox.Deselect();
textBox.Text = text;
@@ -1968,7 +2086,7 @@ namespace Barotrauma
{
if (Submarine.MainSub != null)
{
Submarine.MainSub.Description = text;
Submarine.MainSub.Info.Description = text;
}
else
{
@@ -1994,6 +2112,7 @@ namespace Barotrauma
{
previouslyUsedPanel.Visible = false;
showEntitiesPanel.Visible = true;
showEntitiesPanel.RectTransform.AbsoluteOffset = new Point(Math.Max(entityCountPanel.Rect.Right, saveAssemblyFrame.Rect.Right), TopPanel.Rect.Height);
matchingTickBox.Selected = true;
matchingTickBox.Flash(GUI.Style.Green);
}
@@ -2004,12 +2123,10 @@ namespace Barotrauma
return false;
}
private bool GenerateWaypoints(GUIButton button, object obj)
private bool GenerateWaypoints()
{
if (Submarine.MainSub == null) return false;
WayPoint.GenerateSubWaypoints(Submarine.MainSub);
return true;
if (Submarine.MainSub == null) { return false; }
return WayPoint.GenerateSubWaypoints(Submarine.MainSub);
}
private void AddPreviouslyUsed(MapEntityPrefab mapEntityPrefab)
@@ -2406,12 +2523,53 @@ namespace Barotrauma
hullVolumeFrame.Visible = MapEntity.SelectedList.Any(s => s is Hull);
saveAssemblyFrame.Visible = MapEntity.SelectedList.Count > 0;
if (PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Tab))
if (GUI.KeyboardDispatcher.Subscriber == null)
{
entityFilterBox.Select();
// TODO adjust when the new inventory stuff rolls in
if (PlayerInput.KeyHit(Keys.Q) && mode == Mode.Default)
{
toggleEntityMenuButton.OnClicked?.Invoke(toggleEntityMenuButton, toggleEntityMenuButton.UserData);
}
if (PlayerInput.KeyHit(Keys.Tab))
{
entityFilterBox.Select();
}
if (PlayerInput.KeyDown(Keys.LeftControl))
{
// Save menu
if (PlayerInput.KeyHit(Keys.S))
{
if (PlayerInput.KeyDown(Keys.LeftShift))
{
// Save the sub without a menu
if (subNameLabel != null)
{
SaveSubToFile(subNameLabel.Text);
}
}
else
{
// Save menu
if (saveFrame == null)
{
CreateSaveScreen();
}
}
}
// 1-3 keys on the keyboard for switching modes
if (PlayerInput.KeyHit(Keys.D1)) { SetMode(Mode.Default); }
if (PlayerInput.KeyHit(Keys.D2)) { SetMode(Mode.Character); }
if (PlayerInput.KeyHit(Keys.D3)) { SetMode(Mode.Wiring); }
}
else
{
cam.MoveCamera((float) deltaTime, true);
}
}
cam.MoveCamera((float)deltaTime, true);
if (PlayerInput.MidButtonHeld())
{
Vector2 moveSpeed = PlayerInput.MouseSpeed * (float)deltaTime * 100.0f / cam.Zoom;
@@ -2647,11 +2805,30 @@ namespace Barotrauma
if (Submarine.MainSub != null)
{
Vector2 position = Submarine.MainSub.SubBody != null ? Submarine.MainSub.WorldPosition : Submarine.MainSub.HiddenSubPosition;
GUI.DrawIndicator(
spriteBatch, Submarine.MainSub.WorldPosition, cam,
spriteBatch, position, cam,
cam.WorldView.Width,
GUI.SubmarineIcon, Color.LightBlue * 0.5f);
}
var notificationIcon = GUI.Style.GetComponentStyle("GUINotificationButton");
var tooltipStyle = GUI.Style.GetComponentStyle("GUIToolTip");
foreach (Gap gap in Gap.GapList)
{
if (gap.linkedTo.Count == 2 && gap.linkedTo[0] == gap.linkedTo[1])
{
Vector2 screenPos = Cam.WorldToScreen(gap.WorldPosition);
Rectangle rect = new Rectangle(screenPos.ToPoint() - new Point(20), new Point(40));
tooltipStyle.Sprites[GUIComponent.ComponentState.None][0].Draw(spriteBatch, rect, Color.White);
notificationIcon.Sprites[GUIComponent.ComponentState.None][0].Draw(spriteBatch, rect, GUI.Style.Orange);
if (Vector2.Distance(PlayerInput.MousePosition, screenPos) < 30 * Cam.Zoom)
{
GUIComponent.DrawToolTip(spriteBatch, TextManager.Get("gapinsidehullwarning"), new Rectangle(screenPos.ToPoint(), new Point(10)));
}
}
}
if ((CharacterMode || WiringMode) && dummyCharacter != null)
{