(7788ec72a) Test issuing orders automatically.

This commit is contained in:
Joonas Rikkonen
2019-05-16 05:03:49 +03:00
parent d00e2975ba
commit 60f52375e6
202 changed files with 2714 additions and 5825 deletions

View File

@@ -43,12 +43,8 @@
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\MultiPlayerCampaign.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\SinglePlayerCampaign.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\BasicTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\CaptainTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\DoctorTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\ContextualTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\EditorTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\EngineerTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\MechanicTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\OfficerTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\ScenarioTutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\Tutorial.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\GameSession\GameModes\Tutorials\TutorialMode.cs" />
@@ -188,7 +184,6 @@
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\CampaignSetupUI.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\CampaignUI.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\CharacterEditorScreen.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\CreditsPlayer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\GameScreen.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\LevelEditorScreen.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Source\Screens\LobbyScreen.cs" />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -1,3 +1,3 @@
#!/bin/sh
./Barotrauma
exec mono "./Barotrauma.exe" MONO_LOG_LEVEL=debug "$@"

View File

@@ -56,30 +56,13 @@
<Prefer32Bit>true</Prefer32Bit>
<WarningLevel>0</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseLinux|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\ReleaseLinux\</OutputPath>
<DefineConstants>TRACE;LINUX;CLIENT</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugLinux|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\DebugLinux\</OutputPath>
<DefineConstants>TRACE;DEBUG;LINUX;CLIENT</DefineConstants>
<WarningLevel>0</WarningLevel>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Concentus, Version=1.1.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\Concentus.1.1.7\lib\portable-net45+win+wpa81+wp80\Concentus.dll</HintPath>
</Reference>
<Reference Include="GameAnalytics.Mono, Version=1.0.6710.29255, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\GameAnalytics.Mono.SDK.1.1.12\lib\net45\GameAnalytics.Mono.dll</HintPath>
</Reference>
@@ -149,10 +132,6 @@
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Libraries\Concentus\CSharp\Concentus\Concentus.csproj">
<Project>{0e7fee6a-15e5-4a4e-943c-80276003478c}</Project>
<Name>Concentus</Name>
</ProjectReference>
<ProjectReference Include="..\..\Libraries\Facepunch.Steamworks\Facepunch.Steamworks.csproj">
<Project>{3af0347c-5a9b-4421-868c-8ee3dbfaebc6}</Project>
<Name>Facepunch.Steamworks</Name>
@@ -207,73 +186,13 @@
<None Include="Content\Effects\watershader_opengl.xnb">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="lib64\libMonoPosixHelper.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="libopenal.so.1">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="libsteam_api64.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="libvlc.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="Barotrauma">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Barotrauma.bin.x86">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Barotrauma.bin.x86_64">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Mono.Posix.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Mono.Security.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="monoconfig">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="monomachineconfig">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="mscorlib.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Configuration.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Core.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Data.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Drawing.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Numerics.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Runtime.Serialization.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Security.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Xml.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Xml.Linq.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup />
<ItemGroup>
@@ -298,12 +217,7 @@
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
-->
<Target Name="AfterBuild">
<!-- Write version number to a "Version.txt" file in the output folder -->
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="CurrentAssembly" />
</GetAssemblyIdentity>
<Exec Command="echo v%(CurrentAssembly.Version) > $(TargetDir)Version.txt"></Exec>
</Target>
-->
</Project>

View File

@@ -55,30 +55,13 @@
<Prefer32Bit>true</Prefer32Bit>
<WarningLevel>0</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseMac|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\ReleaseMac\</OutputPath>
<DefineConstants>TRACE;OSX;CLIENT</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugMac|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\DebugMac\</OutputPath>
<DefineConstants>TRACE;DEBUG;OSX;CLIENT</DefineConstants>
<WarningLevel>0</WarningLevel>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Concentus, Version=1.1.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\Concentus.1.1.7\lib\portable-net45+win+wpa81+wp80\Concentus.dll</HintPath>
</Reference>
<Reference Include="GameAnalytics.Mono, Version=1.0.6710.29255, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\GameAnalytics.Mono.SDK.1.1.12\lib\net45\GameAnalytics.Mono.dll</HintPath>
</Reference>
@@ -148,10 +131,6 @@
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Libraries\Concentus\CSharp\Concentus\Concentus.csproj">
<Project>{0e7fee6a-15e5-4a4e-943c-80276003478c}</Project>
<Name>Concentus</Name>
</ProjectReference>
<ProjectReference Include="..\..\Libraries\Facepunch.Steamworks\Facepunch.Steamworks.csproj">
<Project>{3af0347c-5a9b-4421-868c-8ee3dbfaebc6}</Project>
<Name>Facepunch.Steamworks</Name>
@@ -209,62 +188,7 @@
<None Include="libvlc.dylib">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="libMonoPosixHelper.dylib">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="Barotrauma">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Barotrauma.bin.osx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Mono.Posix.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Mono.Security.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="monoconfig">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="monomachineconfig">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="mscorlib.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Configuration.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Core.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Data.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Drawing.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Numerics.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Runtime.Serialization.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Security.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Xml.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="System.Xml.Linq.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="barotrauma.icns" />
</ItemGroup>
<ItemGroup />
<Import Project="ClientCode.projitems" Label="Shared" />
@@ -284,12 +208,7 @@
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
-->
<Target Name="AfterBuild">
<!-- Write version number to a "Version.txt" file in the output folder -->
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="CurrentAssembly" />
</GetAssemblyIdentity>
<Exec Command="echo v%(CurrentAssembly.Version) > $(TargetDir)Version.txt"></Exec>
</Target>
-->
</Project>

View File

@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.10.0")]
[assembly: AssemblyFileVersion("0.8.10.0")]
[assembly: AssemblyVersion("0.8.9.10")]
[assembly: AssemblyFileVersion("0.8.9.10")]

View File

@@ -98,7 +98,7 @@ namespace Barotrauma
if (distSqrd > 10.0f || !character.AllowInput)
{
Collider.TargetRotation = newRotation;
SetPosition(newPosition, lerp: distSqrd < 5.0f, ignorePlatforms: false);
SetPosition(newPosition, lerp: distSqrd < 5.0f);
}
else
{
@@ -238,16 +238,20 @@ namespace Barotrauma
}
float errorMagnitude = positionError.Length();
if (errorMagnitude > 0.5f)
{
character.MemLocalState.Clear();
SetPosition(serverPos.Position, lerp: true, ignorePlatforms: false);
}
else if (errorMagnitude > 0.01f)
if (errorMagnitude > 0.01f)
{
Collider.TargetPosition = Collider.SimPosition + positionError;
Collider.TargetRotation = Collider.Rotation + rotationError;
Collider.MoveToTargetPosition(lerp: true);
if (errorMagnitude > 0.5f)
{
character.MemLocalState.Clear();
foreach (Limb limb in Limbs)
{
limb.body.TargetPosition = limb.body.SimPosition + positionError;
limb.body.MoveToTargetPosition(lerp: true);
}
}
}
}
@@ -260,17 +264,57 @@ namespace Barotrauma
partial void ImpactProjSpecific(float impact, Body body)
{
float volume = MathHelper.Clamp(impact - 3.0f, 0.5f, 1.0f);
float volume = Math.Min(impact - 3.0f, 1.0f);
if (body.UserData is Limb limb && character.Stun <= 0f)
partial void UpdateNetPlayerPositionProjSpecific(float deltaTime, float lowestSubPos)
{
if (character != GameMain.Client.Character || !character.AllowInput)
{
if (impact > 3.0f) { PlayImpactSound(limb); }
}
else if (body.UserData is Limb || body == Collider.FarseerBody)
{
if (!character.IsRemotePlayer && impact > ImpactTolerance)
Limb limb = (Limb)body.UserData;
if (impact > 3.0f && limb.LastImpactSoundTime < Timing.TotalTime - Limb.SoundInterval)
{
SoundPlayer.PlayDamageSound("LimbBlunt", strongestImpact, Collider);
limb.LastImpactSoundTime = (float)Timing.TotalTime;
if (!string.IsNullOrWhiteSpace(limb.HitSoundTag))
{
SoundPlayer.PlaySound(limb.HitSoundTag, volume, impact * 100.0f, limb.WorldPosition, character.CurrentHull);
}
//unconscious/dead characters can't correct their position using AnimController movement
// -> we need to correct it manually
if (!character.AllowInput)
{
float mainLimbDistSqrd = Vector2.DistanceSquared(MainLimb.PullJointWorldAnchorA, Collider.SimPosition);
float mainLimbErrorTolerance = 0.1f;
//if the main limb is roughly at the correct position and the collider isn't moving (much at least),
//don't attempt to correct the position.
if (mainLimbDistSqrd > mainLimbErrorTolerance || Collider.LinearVelocity.LengthSquared() > 0.05f)
{
SoundPlayer.PlaySound(wearable.Sound, volume, impact * 100.0f, limb.WorldPosition, character.CurrentHull);
}
}
}
character.MemLocalState.Clear();
}
else
{
if (!character.IsRemotePlayer)
{
if (character.Submarine == null)
{
//transform in-sub coordinates to outside coordinates
if (character.MemLocalState[i].Position.Y > lowestSubPos)
{
character.MemLocalState[i].TransformInToOutside();
}
}
else if (currentHull?.Submarine != null)
{
//transform outside coordinates to in-sub coordinates
if (character.MemLocalState[i].Position.Y < lowestSubPos)
{
character.MemLocalState[i].TransformOutToInside(currentHull.Submarine);
}
}
}
}
if (Character.Controlled == character)
@@ -279,29 +323,6 @@ namespace Barotrauma
}
}
public void PlayImpactSound(Limb limb)
{
limb.LastImpactSoundTime = (float)Timing.TotalTime;
if (!string.IsNullOrWhiteSpace(limb.HitSoundTag))
{
bool inWater = limb.inWater;
if (character.CurrentHull != null &&
character.CurrentHull.Surface > character.CurrentHull.Rect.Y - character.CurrentHull.Rect.Height &&
limb.SimPosition.Y < ConvertUnits.ToSimUnits(character.CurrentHull.Rect.Y - character.CurrentHull.Rect.Height) + limb.body.GetMaxExtent())
{
inWater = true;
}
SoundPlayer.PlaySound(inWater ? "footstep_water" : limb.HitSoundTag, limb.WorldPosition, hullGuess: character.CurrentHull);
}
foreach (WearableSprite wearable in limb.WearingItems)
{
if (limb.type == wearable.Limb && !string.IsNullOrWhiteSpace(wearable.Sound))
{
SoundPlayer.PlaySound(wearable.Sound, limb.WorldPosition, hullGuess: character.CurrentHull);
}
}
}
partial void Splash(Limb limb, Hull limbHull)
{
//create a splash particle
@@ -364,8 +385,6 @@ namespace Barotrauma
partial void UpdateProjSpecific(float deltaTime)
{
if (!character.Enabled || SimplePhysicsEnabled) { return; }
LimbJoints.ForEach(j => j.UpdateDeformations(deltaTime));
foreach (var deformation in SpriteDeformations)
{
@@ -396,7 +415,7 @@ namespace Barotrauma
}
}
partial void SeverLimbJointProjSpecific(LimbJoint limbJoint, bool playSound = true)
partial void SeverLimbJointProjSpecific(LimbJoint limbJoint)
{
foreach (Limb limb in new Limb[] { limbJoint.LimbA, limbJoint.LimbB })
{
@@ -414,11 +433,6 @@ namespace Barotrauma
character.CurrentHull?.AddDecal(character.BloodDecalName, limb.WorldPosition, MathHelper.Clamp(limb.Mass, 0.5f, 2.0f));
}
}
if (playSound)
{
SoundPlayer.PlayDamageSound("Gore", 1.0f, limbJoint.LimbA.body);
}
}
public virtual void Draw(SpriteBatch spriteBatch, Camera cam)
@@ -436,15 +450,14 @@ namespace Barotrauma
return;
}
Color? color = null;
if (character.ExternalHighlight)
{
color = Color.Lerp(Color.White, Color.OrangeRed, (float)Math.Sin(Timing.TotalTime * 3.5f));
}
//foreach (Limb limb in Limbs)
//{
// limb.Draw(spriteBatch, cam);
//}
for (int i = 0; i < limbs.Length; i++)
{
inversedLimbDrawOrder[i].Draw(spriteBatch, cam, color);
inversedLimbDrawOrder[i].Draw(spriteBatch, cam);
}
LimbJoints.ForEach(j => j.Draw(spriteBatch));
}

View File

@@ -50,7 +50,7 @@ namespace Barotrauma
if (sound != null)
{
SoundPlayer.PlaySound(sound.Sound, worldPosition, sound.Volume, sound.Range);
SoundPlayer.PlaySound(sound.Sound, sound.Volume, sound.Range, worldPosition);
}
}
}

View File

@@ -46,7 +46,8 @@ namespace Barotrauma
if (controlled == value) return;
controlled = value;
if (controlled != null) controlled.Enabled = true;
CharacterHealth.OpenHealthWindow = null;
CharacterHealth.OpenHealthWindow = null;
}
}
@@ -110,33 +111,6 @@ namespace Barotrauma
get { return gibEmitters; }
}
public class ObjectiveEntity
{
public Entity Entity;
public Sprite Sprite;
public Color Color;
public ObjectiveEntity(Entity entity, Sprite sprite, Color? color = null)
{
Entity = entity;
Sprite = sprite;
if (color.HasValue)
{
Color = color.Value;
}
else
{
Color = Color.White;
}
}
}
private List<ObjectiveEntity> activeObjectiveEntities = new List<ObjectiveEntity>();
public IEnumerable<ObjectiveEntity> ActiveObjectiveEntities
{
get { return activeObjectiveEntities; }
}
partial void InitProjSpecific(XDocument doc)
{
soundInterval = doc.Root.GetAttributeFloat("soundinterval", 10.0f);
@@ -164,6 +138,7 @@ namespace Barotrauma
break;
}
}
}
hudProgressBars = new Dictionary<object, HUDProgressBar>();
}
@@ -756,24 +731,10 @@ namespace Barotrauma
var matchingSoundsList = matchingSounds.ToList();
var selectedSound = matchingSoundsList[Rand.Int(matchingSoundsList.Count)];
soundChannel = SoundPlayer.PlaySound(selectedSound.Sound, AnimController.WorldPosition, selectedSound.Volume, selectedSound.Range, CurrentHull);
soundChannel = SoundPlayer.PlaySound(selectedSound.Sound, selectedSound.Volume, selectedSound.Range, AnimController.WorldPosition, CurrentHull);
soundTimer = soundInterval;
}
public void AddActiveObjectiveEntity(Entity entity, Sprite sprite, Color? color = null)
{
if (activeObjectiveEntities.Any(aoe => aoe.Entity == entity)) return;
ObjectiveEntity objectiveEntity = new ObjectiveEntity(entity, sprite, color);
activeObjectiveEntities.Add(objectiveEntity);
}
public void RemoveActiveObjectiveEntity(Entity entity)
{
ObjectiveEntity found = activeObjectiveEntities.Find(aoe => aoe.Entity == entity);
if (found == null) return;
activeObjectiveEntities.Remove(found);
}
partial void ImplodeFX()
{
Vector2 centerOfMass = AnimController.GetCenterOfMass();

View File

@@ -85,8 +85,7 @@ namespace Barotrauma
{
if (character.Inventory != null)
{
if (!character.LockHands && character.Stun < 0.1f &&
(character.SelectedConstruction == null || character.SelectedConstruction.GetComponent<Controller>() == null))
if (!character.LockHands && character.Stun < 0.1f)
{
character.Inventory.Update(deltaTime, cam);
}
@@ -169,12 +168,7 @@ namespace Barotrauma
DrawOrderIndicator(spriteBatch, cam, character, character.CurrentOrder, 1.0f);
}
}
foreach (Character.ObjectiveEntity objectiveEntity in character.ActiveObjectiveEntities)
{
DrawObjectiveIndicator(spriteBatch, cam, character, objectiveEntity, 1.0f);
}
foreach (Item brokenItem in brokenItems)
{
float dist = Vector2.Distance(character.WorldPosition, brokenItem.WorldPosition);
@@ -321,7 +315,6 @@ namespace Barotrauma
}
if (character.Inventory != null && !character.LockHands)
{
character.Inventory.Locked = (character.SelectedConstruction != null && character.SelectedConstruction.GetComponent<Controller>() != null);
character.Inventory.DrawOwn(spriteBatch);
character.Inventory.CurrentLayout = CharacterHealth.OpenHealthWindow == null && character.SelectedCharacter == null ?
CharacterInventory.Layout.Default :
@@ -366,33 +359,17 @@ namespace Barotrauma
private static void DrawOrderIndicator(SpriteBatch spriteBatch, Camera cam, Character character, Order order, float iconAlpha = 1.0f)
{
if (order.TargetAllCharacters && !order.HasAppropriateJob(character)) { return; }
if (order.TargetAllCharacters && !order.HasAppropriateJob(character)) return;
Entity target = order.ConnectedController != null ? order.ConnectedController.Item : order.TargetEntity;
if (target == null) { return; }
if (target == null) return;
//don't show the indicator if far away and not inside the same sub
//prevents exploiting the indicators in locating the sub
if (character.Submarine != target.Submarine &&
Vector2.DistanceSquared(character.WorldPosition, target.WorldPosition) > 1000.0f * 1000.0f)
{
return;
}
if (!orderIndicatorCount.ContainsKey(target)) { orderIndicatorCount.Add(target, 0); }
if (!orderIndicatorCount.ContainsKey(target)) orderIndicatorCount.Add(target, 0);
Vector2 drawPos = target.WorldPosition + Vector2.UnitX * order.SymbolSprite.size.X * 1.5f * orderIndicatorCount[target];
GUI.DrawIndicator(spriteBatch, drawPos, cam, 100.0f, order.SymbolSprite, order.Color * iconAlpha);
orderIndicatorCount[target] = orderIndicatorCount[target] + 1;
}
private static void DrawObjectiveIndicator(SpriteBatch spriteBatch, Camera cam, Character character, Character.ObjectiveEntity objectiveEntity, float iconAlpha = 1.0f)
{
if (objectiveEntity == null) return;
Vector2 drawPos = objectiveEntity.Entity.WorldPosition;// + Vector2.UnitX * objectiveEntity.Sprite.size.X * 1.5f;
GUI.DrawIndicator(spriteBatch, drawPos, cam, 100.0f, objectiveEntity.Sprite, objectiveEntity.Color * iconAlpha);
}
}
}

View File

@@ -50,7 +50,7 @@ namespace Barotrauma
Job.Name, textColor: Job.Prefab.UIColor, font: font);
}
if (personalityTrait != null && TextManager.Language == "English")
if (personalityTrait != null)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform),
TextManager.Get("PersonalityTrait") + ": " + personalityTrait.Name, font: font);

View File

@@ -96,11 +96,6 @@ namespace Barotrauma
private const float UpdateDisplayedAfflictionsInterval = 0.5f;
private List<Affliction> currentDisplayedAfflictions = new List<Affliction>();
public bool MouseOnElement
{
get { return highlightedLimbIndex > -1 || GUI.MouseOn == dropItemArea; }
}
private static CharacterHealth openHealthWindow;
public static CharacterHealth OpenHealthWindow
{
@@ -136,17 +131,6 @@ namespace Barotrauma
}
}
public GUIButton CPRButton
{
get { return cprButton; }
}
public float HealthBarPulsateTimer
{
get { return healthBarPulsateTimer; }
set { healthBarPulsateTimer = MathHelper.Clamp(value, 0.0f, 10.0f); }
}
static CharacterHealth()
{
damageOverlay = new Sprite("Content/UI/damageOverlay.png", Vector2.Zero);
@@ -188,16 +172,18 @@ namespace Barotrauma
afflictionInfoContainer = new GUIListBox(new RectTransform(new Vector2(0.7f, 0.85f), paddedInfoFrame.RectTransform, Anchor.BottomLeft));
lowSkillIndicator = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), paddedInfoFrame.RectTransform, Anchor.TopRight),
TextManager.Get("LowMedicalSkillWarning"), Color.Orange, textAlignment: Alignment.TopRight, font: GUI.SmallFont, wrap: true)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.08f), paddedInfoFrame.RectTransform), TextManager.Get("SuitableTreatments"), textAlignment: Alignment.TopRight);
lowSkillIndicator = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.07f), paddedInfoFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, 0.08f) },
TextManager.Get("LowMedicalSkillWarning"), Color.Orange, textAlignment: Alignment.Center, font: GUI.SmallFont, wrap: true)
{
Visible = false
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), paddedInfoFrame.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.05f) }, TextManager.Get("SuitableTreatments"), textAlignment: Alignment.BottomRight);
recommendedTreatmentContainer = new GUIListBox(new RectTransform(new Vector2(0.28f, 0.5f), paddedInfoFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, 0.12f) });
recommendedTreatmentContainer = new GUIListBox(new RectTransform(new Vector2(0.28f, 0.5f), paddedInfoFrame.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, 0.15f) })
{
Spacing = 10
};
dropItemArea = new GUIFrame(new RectTransform(new Vector2(0.28f, 0.3f), paddedInfoFrame.RectTransform, Anchor.BottomRight)
{ RelativeOffset = new Vector2(0.02f, 0.0f) }, style: null)
{ RelativeOffset = new Vector2(0.0f, 0.0f) }, style: null)
{
ToolTip = TextManager.Get("HealthItemUseTip")
};
@@ -598,18 +584,9 @@ namespace Barotrauma
var affliction = GetAllAfflictions(a => a.Prefab.IndicatorLimb != LimbType.None)
.OrderByDescending(a => a.DamagePerSecond)
.ThenByDescending(a => a.Strength).FirstOrDefault();
if (affliction.DamagePerSecond > 0 || affliction.Strength > 0)
var limbHealth = GetMathingLimbHealth(affliction);
if (limbHealth != null)
{
var limbHealth = GetMathingLimbHealth(affliction);
if (limbHealth != null)
{
selectedLimbIndex = limbHealths.IndexOf(limbHealth);
}
}
else
{
// If no affliction is critical, select the limb which has most damage.
var limbHealth = limbHealths.OrderByDescending(l => l.TotalDamage).FirstOrDefault();
selectedLimbIndex = limbHealths.IndexOf(limbHealth);
}
}
@@ -951,7 +928,7 @@ namespace Barotrauma
{
afflictionInfoContainer.Content.ClearChildren();
recommendedTreatmentContainer.Content.ClearChildren();
float characterSkillLevel = Character.Controlled == null ? 0.0f : Character.Controlled.GetSkillLevel("medical");
//random variance is 200% when the skill is 0
@@ -1046,15 +1023,14 @@ namespace Barotrauma
{
ItemPrefab item = MapEntityPrefab.Find(name: null, identifier: treatment.Key, showErrorMessages: false) as ItemPrefab;
if (item == null) continue;
int slotSize = (int)(recommendedTreatmentContainer.Content.Rect.Width * 0.5f);
int slotSize = (int)(recommendedTreatmentContainer.Content.Rect.Width * 0.8f);
var itemSlot = new GUIFrame(new RectTransform(new Point(recommendedTreatmentContainer.Content.Rect.Width, slotSize), recommendedTreatmentContainer.Content.RectTransform, Anchor.TopCenter),
style: "InnerGlow")
var itemSlot = new GUIButton(new RectTransform(new Point(slotSize), recommendedTreatmentContainer.Content.RectTransform, Anchor.TopCenter),
text: "", style: "InventorySlotSmall")
{
UserData = item,
CanBeFocused = false
UserData = item
};
itemSlot.Color = ToolBox.GradientLerp(treatment.Value, Color.Red, Color.Orange, Color.LightGreen);
itemSlot.Color = ToolBox.GradientLerp(treatment.Value, Color.Red, Color.White, Color.LightGreen);
Sprite itemSprite = item.InventoryIcon ?? item.sprite;
Color itemColor = itemSprite == item.sprite ? item.SpriteColor : item.InventoryIconColor;
@@ -1438,8 +1414,6 @@ namespace Barotrauma
{
foreach (Limb limb in Character.AnimController.Limbs)
{
if (limb.HealthIndex < 0 || limb.HealthIndex >= limbHealths.Count) { continue; }
limb.BurnOverlayStrength = 0.0f;
limb.DamageOverlayStrength = 0.0f;
if (limbHealths[limb.HealthIndex].Afflictions.Count == 0) continue;

View File

@@ -20,7 +20,7 @@ namespace Barotrauma
var skillContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.45f, 0.5f), paddedFrame.RectTransform)
{ RelativeOffset = new Vector2(0.0f, 0.2f + descriptionBlock.RectTransform.RelativeSize.Y) });
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), skillContainer.RectTransform),
TextManager.Get("Skills"), font: GUI.LargeFont);
TextManager.Get("Skills") + ": ", font: GUI.LargeFont);
foreach (SkillPrefab skill in Skills)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), skillContainer.RectTransform),
@@ -30,7 +30,7 @@ namespace Barotrauma
var itemContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.45f, 0.5f), paddedFrame.RectTransform, Anchor.TopRight)
{ RelativeOffset = new Vector2(0.0f, 0.2f + descriptionBlock.RectTransform.RelativeSize.Y) });
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), itemContainer.RectTransform),
TextManager.Get("Items", fallBackTag: "mapentitycategory.equipment"), font: GUI.LargeFont);
TextManager.Get("Items") + ": ", font: GUI.LargeFont);
foreach (string itemName in ItemNames)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), itemContainer.RectTransform),

View File

@@ -292,10 +292,10 @@ namespace Barotrauma
if (!string.IsNullOrWhiteSpace(damageModifier.DamageSound))
{
damageSoundType = damageModifier.DamageSound;
SoundPlayer.PlayDamageSound(damageSoundType, Math.Max(damage, bleedingDamage), WorldPosition);
break;
}
}
SoundPlayer.PlayDamageSound(damageSoundType, Math.Max(damage, bleedingDamage), WorldPosition);
}
// Always spawn damage particles

View File

@@ -29,7 +29,7 @@ namespace Barotrauma
if (!CheatsEnabled && IsCheat)
{
NewMessage("You need to enable cheats using the command \"enablecheats\" before you can use the command \"" + names[0] + "\".", Color.Red);
if (Steam.SteamManager.USE_STEAM)
if (GameMain.Config.UseSteam)
{
NewMessage("Enabling cheats will disable Steam achievements during this play session.", Color.Red);
}
@@ -340,7 +340,7 @@ namespace Barotrauma
CheatsEnabled = true;
SteamAchievementManager.CheatsEnabled = true;
NewMessage("Enabled cheat commands.", Color.Red);
if (Steam.SteamManager.USE_STEAM)
if (GameMain.Config.UseSteam)
{
NewMessage("Steam achievements have been disabled during this play session.", Color.Red);
}
@@ -377,27 +377,23 @@ namespace Barotrauma
GameMain.SubEditorScreen.Select();
}));
commands.Add(new Command("editparticles|particleeditor", "editparticles/particleeditor: Switch to the Particle Editor to edit particle effects.", (string[] args) =>
commands.Add(new Command("editparticles|particleeditor", "", (string[] args) =>
{
GameMain.ParticleEditorScreen.Select();
}));
commands.Add(new Command("editlevels|leveleditor", "editlevels/leveleditor: Switch to the Level Editor to edit levels.", (string[] args) =>
commands.Add(new Command("editlevels|editlevel|leveleditor", "", (string[] args) =>
{
GameMain.LevelEditorScreen.Select();
}));
commands.Add(new Command("editsprites|spriteeditor", "editsprites/spriteeditor: Switch to the Sprite Editor to edit the source rects and origins of sprites.", (string[] args) =>
commands.Add(new Command("editsprites|editsprite|spriteeditor|spriteedit", "", (string[] args) =>
{
GameMain.SpriteEditorScreen.Select();
}));
commands.Add(new Command("editcharacters|charactereditor", "editcharacters/charactereditor: Switch to the Character Editor to edit/create the ragdolls and animations of characters.", (string[] args) =>
commands.Add(new Command("charactereditor|editcharacter|editcharacters|editanimation|editanimations|animedit|animationeditor|animeditor|animationedit", "charactereditor: Edit characters, animations, ragdolls....", (string[] args) =>
{
if (Screen.Selected == GameMain.GameScreen)
{
NewMessage("WARNING: Switching between the character editor and the game view may cause odd behaviour or bugs. Use with caution.", Color.Orange);
}
GameMain.CharacterEditorScreen.Select();
}));
@@ -1096,8 +1092,8 @@ namespace Barotrauma
List<string> lines = new List<string>();
foreach (MapEntityPrefab me in MapEntityPrefab.List)
{
lines.Add("<EntityName." + me.Identifier + ">" + me.Name + "</EntityName." + me.Identifier + ">");
lines.Add("<EntityDescription." + me.Identifier + ">" + me.Description + "</EntityDescription." + me.Identifier + ">");
lines.Add("<EntityName." + me.Identifier + ">" + me.Name + "</" + me.Identifier + ".Name>");
lines.Add("<EntityDescription." + me.Identifier + ">" + me.Description + "</" + me.Identifier + ".Description>");
}
File.WriteAllLines(filePath, lines);
}));
@@ -1527,7 +1523,7 @@ namespace Barotrauma
character.AnimController.ResetRagdoll();
}, isCheat: true));
commands.Add(new Command("reloadwearables", "Reloads the sprites of all limbs and wearable sprites (clothing) of the controlled character. Provide id or name if you want to target another character.", args =>
commands.Add(new Command("reloadwearables|reloadlimbs", "Reloads the sprites of all limbs and wearable sprites (clothing) of the controlled character. Provide id or name if you want to target another character.", args =>
{
var character = (args.Length == 0) ? Character.Controlled : FindMatchingCharacter(args, true);
if (character == null)
@@ -1538,26 +1534,6 @@ namespace Barotrauma
ReloadWearables(character);
}, isCheat: true));
commands.Add(new Command("loadwearable", "Force select certain variant for the selected character.", args =>
{
var character = Character.Controlled;
if (character == null)
{
ThrowError("Not controlling any character.");
return;
}
if (args.Length == 0)
{
ThrowError("No arguments provided! Give an index number for the variant starting from 1.");
return;
}
if (int.TryParse(args[0], out int variant))
{
ReloadWearables(character, variant);
}
}, isCheat: true));
commands.Add(new Command("reloadsprite|reloadsprites", "Reloads the sprites of the selected item(s)/structure(s) (hovering over or selecting in the subeditor) or the controlled character. Can also reload sprites by entity id or by the name attribute (sprite element). Example 1: reloadsprite id itemid. Example 2: reloadsprite name \"Sprite name\"", args =>
{
if (Screen.Selected is SpriteEditorScreen)
@@ -1705,7 +1681,7 @@ namespace Barotrauma
}, isCheat: true));
}
private static void ReloadWearables(Character character, int variant = 0)
private static void ReloadWearables(Character character)
{
foreach (var limb in character.AnimController.Limbs)
{
@@ -1714,17 +1690,11 @@ namespace Barotrauma
limb.DeformSprite?.Sprite.ReloadTexture();
foreach (var wearable in limb.WearingItems)
{
if (variant > 0 && wearable.Variant > 0)
{
wearable.Variant = variant;
}
wearable.RefreshPath();
wearable.Sprite.ReloadXML();
wearable.Sprite.ReloadTexture();
}
foreach (var wearable in limb.OtherWearables)
{
wearable.RefreshPath();
wearable.Sprite.ReloadXML();
wearable.Sprite.ReloadTexture();
}

View File

@@ -155,9 +155,6 @@ namespace EventInput
return SetWindowLongPtr(hWnd, nIndex, dwNewLong);
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
#endif
@@ -176,8 +173,8 @@ namespace EventInput
#if WINDOWS
hookProcDelegate = HookProc;
prevWndProc = TrySetWindowLong(window.Handle, GWL_WNDPROC,
Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
prevWndProc = SetWindowLongPtr(window.Handle, GWL_WNDPROC,
Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
hIMC = ImmGetContext(window.Handle);
#else

View File

@@ -56,11 +56,11 @@ namespace Barotrauma
}
public ScalableFont(XElement element, GraphicsDevice gd = null)
: this (element.GetAttributeString("file", ""), (uint)element.GetAttributeInt("size", 14), gd, element.GetAttributeBool("dynamicloading", false))
: this (element.GetAttributeString("file", ""), (uint)element.GetAttributeInt("size", 14), gd)
{
}
public ScalableFont(string filename, uint size, GraphicsDevice gd = null, bool dynamicLoading = false)
public ScalableFont(string filename, uint size, GraphicsDevice gd = null)
{
if (Lib == null) Lib = new Library();
this.filename = filename;
@@ -390,14 +390,10 @@ namespace Barotrauma
if (text[i] == '\n')
{
currentLineX = 0.0f;
retVal.Y += baseHeight * 1.8f;
retVal.Y += baseHeight * 18 / 10;
continue;
}
uint charIndex = text[i];
if (DynamicLoading && !texCoords.ContainsKey(charIndex))
{
DynamicRenderAtlas(graphicsDevice, charIndex);
}
if (texCoords.TryGetValue(charIndex, out GlyphData gd))
{
currentLineX += gd.advance;
@@ -411,10 +407,6 @@ namespace Barotrauma
{
Vector2 retVal = Vector2.Zero;
retVal.Y = baseHeight * 1.8f;
if (DynamicLoading && !texCoords.ContainsKey(c))
{
DynamicRenderAtlas(graphicsDevice, c);
}
if (texCoords.TryGetValue(c, out GlyphData gd))
{
retVal.X = gd.advance;

View File

@@ -18,7 +18,9 @@ namespace Barotrauma
private GUITextBox inputBox;
private GUIButton toggleButton;
private GUIButton radioButton;
private Point screenResolution;
private bool isSinglePlayer;
@@ -58,7 +60,12 @@ namespace Barotrauma
{
get { return guiFrame; }
}
public GUIButton RadioButton
{
get { return radioButton; }
}
public GUITextBox InputBox
{
get { return inputBox; }
@@ -102,7 +109,31 @@ namespace Barotrauma
{
gui.Text = "";
};
radioButton = new GUIButton(new RectTransform(new Vector2(0.1f, 2.0f), inputBox.RectTransform,
HUDLayoutSettings.ChatBoxAlignment == Alignment.Right ? Anchor.BottomRight : Anchor.BottomLeft,
HUDLayoutSettings.ChatBoxAlignment == Alignment.Right ? Pivot.TopRight : Pivot.TopLeft),
style: null);
new GUIImage(new RectTransform(Vector2.One, radioButton.RectTransform), radioIcon, scaleToFit: true);
radioButton.OnClicked = (GUIButton btn, object userData) =>
{
if (inputBox.Selected)
{
inputBox.Text = "";
inputBox.Deselect();
}
else
{
inputBox.Select();
var radioItem = Character.Controlled?.Inventory?.Items.FirstOrDefault(i => i?.GetComponent<WifiComponent>() != null);
if (radioItem != null && Character.Controlled.HasEquippedItem(radioItem) && radioItem.GetComponent<WifiComponent>().CanTransmit())
{
inputBox.Text = "r; ";
}
}
return true;
};
ToggleOpen = GameMain.Config.ChatOpen;
}
@@ -337,6 +368,7 @@ namespace Barotrauma
}
openState = MathHelper.Clamp(openState, 0.0f, 1.0f);
int hiddenBoxOffset = guiFrame.Rect.Width + toggleButton.Rect.Width;
if (radioButton != null) hiddenBoxOffset += (int)(radioButton.Rect.Width * 1.5f);
guiFrame.RectTransform.AbsoluteOffset =
new Point((int)MathHelper.SmoothStep(hiddenBoxOffset * (HUDLayoutSettings.ChatBoxAlignment == Alignment.Left ? -1 : 1), 0, openState), 0);
}

View File

@@ -129,8 +129,6 @@ namespace Barotrauma
get { return pauseMenuOpen; }
}
public static bool PreventPauseMenuToggle = false;
public static Color ScreenOverlayColor
{
get;
@@ -1415,7 +1413,6 @@ namespace Barotrauma
public static void TogglePauseMenu()
{
if (Screen.Selected == GameMain.MainMenuScreen) return;
if (PreventPauseMenuToggle) return;
settingsMenuOpen = false;
@@ -1549,9 +1546,9 @@ namespace Barotrauma
if (GameMain.GameSession != null)
{
if (Tutorial.Initialized)
if (ContextualTutorial.Initialized && GameMain.GameSession.GameMode is SinglePlayerCampaign)
{
((TutorialMode)GameMain.GameSession.GameMode).Tutorial.Stop();
((SinglePlayerCampaign)GameMain.GameSession.GameMode).ContextualTutorial.Stop();
}
if (GameSettings.SendUserStatistics)
@@ -1571,7 +1568,7 @@ namespace Barotrauma
}
/// <summary>
/// Displays a message at the center of the screen, automatically preventing overlapping with other centered messages. TODO: Allow to show messages at the middle of the screen (instead of the top center).
/// Displays a message at the center of the screen, automatically preventing overlapping with other centered messages
/// </summary>
public static void AddMessage(string message, Color color, float? lifeTime = null, bool playSound = true, ScalableFont font = null)
{

View File

@@ -174,11 +174,6 @@ namespace Barotrauma
if (frame != null) frame.ApplyStyle(style);
}
public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectInflate = null)
{
Frame.Flash(color, flashDuration, useRectangleFlash, flashRectInflate);
}
protected override void Draw(SpriteBatch spriteBatch)
{
//do nothing

View File

@@ -121,22 +121,17 @@ namespace Barotrauma
protected Color selectedColor;
protected Color pressedColor;
private CoroutineHandle pulsateCoroutine;
protected ComponentState state;
protected Color flashColor;
protected float flashDuration = 1.5f;
private bool useRectangleFlash;
public virtual float FlashTimer
{
get { return flashTimer; }
}
protected float flashTimer;
private Vector2 flashRectInflate;
public bool IgnoreLayoutGroups;
public bool IgnoreLayoutGroups;
public virtual ScalableFont Font
{
get;
@@ -166,7 +161,9 @@ namespace Barotrauma
get { return enabled; }
set { enabled = value; }
}
public bool TileSprites;
private static GUITextBlock toolTipBlock;
public Vector2 Center
@@ -267,8 +264,6 @@ namespace Barotrauma
set { pressedColor = value; }
}
public bool ExternalHighlight = false;
private RectTransform rectTransform;
public RectTransform RectTransform
{
@@ -441,21 +436,11 @@ namespace Barotrauma
int flashCycleCount = (int)Math.Max(flashDuration, 1);
float flashCycleDuration = flashDuration / flashCycleCount;
Rectangle flashRect = Rect;
flashRect.Inflate(flashRectInflate.X, flashRectInflate.Y);
//MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0,
//i.e. quickly bumps up from almost full brightness to full and then fades out
if (!useRectangleFlash)
{
GUI.UIGlow.Draw(spriteBatch,
flashRect,
flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f));
}
else
{
GUI.DrawRectangle(spriteBatch, flashRect, flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f), true);
}
GUI.UIGlow.Draw(spriteBatch,
rect,
flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f));
}
}
@@ -503,11 +488,9 @@ namespace Barotrauma
color = new Color(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, a);
}
public virtual void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectInflate = null)
public virtual void Flash(Color? color = null, float flashDuration = 1.5f)
{
flashTimer = flashDuration;
this.flashRectInflate = flashRectInflate ?? Vector2.Zero;
this.useRectangleFlash = useRectangleFlash;
this.flashDuration = flashDuration;
flashColor = (color == null) ? Color.Red : (Color)color;
}
@@ -525,7 +508,9 @@ namespace Barotrauma
while (t < duration)
{
t += CoroutineManager.DeltaTime;
SetAlpha(MathHelper.Lerp(startA, to, t / duration));
yield return CoroutineStatus.Running;
}
@@ -538,30 +523,9 @@ namespace Barotrauma
yield return CoroutineStatus.Success;
}
#endregion
public void Pulsate(Vector2 startScale, Vector2 endScale, float duration)
{
if (CoroutineManager.IsCoroutineRunning(pulsateCoroutine))
{
return;
}
pulsateCoroutine = CoroutineManager.StartCoroutine(DoPulsate(startScale, endScale, duration), "Pulsate" + ToString());
}
private IEnumerable<object> DoPulsate(Vector2 startScale, Vector2 endScale, float duration)
{
float t = 0.0f;
while (t < duration)
{
t += CoroutineManager.DeltaTime;
RectTransform.LocalScale = Vector2.Lerp(startScale, endScale, (float)Math.Sin(t / duration * MathHelper.Pi));
yield return CoroutineStatus.Running;
}
RectTransform.LocalScale = startScale;
yield return CoroutineStatus.Success;
}
public virtual void ApplyStyle(GUIComponentStyle style)
protected virtual void SetAlpha(float a)
{
if (style == null) return;
@@ -574,7 +538,13 @@ namespace Barotrauma
OutlineColor = style.OutlineColor;
this.style = style;
public virtual void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectInflate = null)
{
flashTimer = flashDuration;
this.flashRectInflate = flashRectInflate ?? Vector2.Zero;
this.useRectangleFlash = useRectangleFlash;
this.flashDuration = flashDuration;
flashColor = (color == null) ? Color.Red : (Color)color;
}
}
}

View File

@@ -108,18 +108,18 @@ namespace Barotrauma
{
float scale = Math.Min(Rect.Width / uiSprite.Sprite.size.X, Rect.Height / uiSprite.Sprite.size.Y);
spriteBatch.Draw(uiSprite.Sprite.Texture, Rect.Center.ToVector2(), uiSprite.Sprite.SourceRect, currColor * (currColor.A / 255.0f), Rotation, uiSprite.Sprite.size / 2,
Scale * scale, SpriteEffects, 0.0f);
Scale * scale, SpriteEffects.None, 0.0f);
}
else
{
uiSprite.Draw(spriteBatch, Rect, currColor * (currColor.A / 255.0f), SpriteEffects);
uiSprite.Draw(spriteBatch, Rect, currColor * (currColor.A / 255.0f), SpriteEffects.None);
}
}
}
else if (sprite?.Texture != null)
{
spriteBatch.Draw(sprite.Texture, Rect.Center.ToVector2(), sourceRect, currColor * (currColor.A / 255.0f), Rotation, sprite.size / 2,
Scale, SpriteEffects, 0.0f);
Scale, SpriteEffects.None, 0.0f);
}
}

View File

@@ -511,8 +511,10 @@ namespace Barotrauma
pos = 0;
totalSize += child.Rect.Width + spacing;
}
pos += child.Rect.Height + spacing;
else
{
pos += child.Rect.Height + spacing;
}
if (child == children.Last())
{
totalSize += child.Rect.Width + spacing;
@@ -525,7 +527,10 @@ namespace Barotrauma
pos = 0;
totalSize += child.Rect.Height + spacing;
}
pos += child.Rect.Width + spacing;
else
{
pos += child.Rect.Width + spacing;
}
if (child == children.Last())
{

View File

@@ -41,22 +41,33 @@ namespace Barotrauma
InnerFrame = new GUIFrame(new RectTransform(new Point(width, height), RectTransform, Anchor.Center) { IsFixedSize = false }, style: null);
GUI.Style.Apply(InnerFrame, "", this);
InnerFrame = new GUIFrame(new RectTransform(new Point(width, height), RectTransform, Anchor.Center) { IsFixedSize = false }, style: null);
GUI.Style.Apply(InnerFrame, "", this);
Content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), InnerFrame.RectTransform, Anchor.Center)) { AbsoluteSpacing = 5 };
Tag = tag;
if (height == 0)
{
string wrappedText = ToolBox.WrapText(text, Content.Rect.Width, GUI.Font);
string[] lines = wrappedText.Split('\n');
foreach (string line in lines)
{
height += (int)GUI.Font.MeasureString(line).Y;
}
height += string.IsNullOrWhiteSpace(headerText) ? 220 : 220 - headerHeight;
}
InnerFrame.RectTransform.NonScaledSize = new Point(InnerFrame.Rect.Width, height);
Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform),
headerText, textAlignment: Alignment.Center, wrap: true);
GUI.Style.Apply(Header, "", this);
Header.RectTransform.MinSize = new Point(0, Header.Rect.Height);
GUI.Style.Apply(Header, "", this);
if (!string.IsNullOrWhiteSpace(text))
if (height == 0)
{
Text = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform),
text, textAlignment: textAlignment, wrap: true);
GUI.Style.Apply(Text, "", this);
Text.RectTransform.NonScaledSize = Text.RectTransform.MinSize = Text.RectTransform.MaxSize =
new Point(Text.Rect.Width, Text.Rect.Height);
Text.RectTransform.IsFixedSize = true;
}
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), Content.RectTransform, Anchor.BottomCenter, maxSize: new Point(1000, 50)),
@@ -65,22 +76,7 @@ namespace Barotrauma
AbsoluteSpacing = 5,
IgnoreLayoutGroups = true
};
buttonContainer.RectTransform.NonScaledSize = buttonContainer.RectTransform.MinSize = buttonContainer.RectTransform.MaxSize =
new Point(buttonContainer.Rect.Width, (int)(30 * GUI.Scale));
buttonContainer.RectTransform.IsFixedSize = true;
if (height == 0)
{
height += Header.Rect.Height + Content.AbsoluteSpacing;
height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing;
height += buttonContainer.Rect.Height;
InnerFrame.RectTransform.NonScaledSize =
new Point(InnerFrame.Rect.Width, (int)Math.Max(height / Content.RectTransform.RelativeSize.Y, height + 50));
Content.RectTransform.NonScaledSize =
new Point(Content.Rect.Width, height);
}
Buttons = new List<GUIButton>(buttons.Length);
for (int i = 0; i < buttons.Length; i++)
{

View File

@@ -1,5 +1,4 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
@@ -10,12 +9,6 @@ namespace Barotrauma
{
private Dictionary<string, GUIComponentStyle> componentStyles;
private XElement configElement;
private GraphicsDevice graphicsDevice;
private ScalableFont defaultFont;
public ScalableFont Font { get; private set; }
public ScalableFont SmallFont { get; private set; }
public ScalableFont LargeFont { get; private set; }
@@ -52,6 +45,24 @@ namespace Barotrauma
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "font":
Font = new ScalableFont(subElement, graphicsDevice);
break;
case "smallfont":
SmallFont = new ScalableFont(subElement, graphicsDevice);
break;
case "largefont":
LargeFont = new ScalableFont(subElement, graphicsDevice);
break;
case "objectivetitle":
ObjectiveTitleFont = new ScalableFont(subElement, graphicsDevice);
break;
case "objectivename":
ObjectiveNameFont = new ScalableFont(subElement, graphicsDevice);
break;
case "videotitle":
VideoTitleFont = new ScalableFont(subElement, graphicsDevice);
break;
case "cursor":
CursorSprite = new Sprite(subElement);
break;
@@ -61,48 +72,12 @@ namespace Barotrauma
case "focusindicator":
FocusIndicator = new SpriteSheet(subElement);
break;
case "font":
Font = LoadFont(subElement, graphicsDevice);
break;
case "smallfont":
SmallFont = LoadFont(subElement, graphicsDevice);
break;
case "largefont":
LargeFont = LoadFont(subElement, graphicsDevice);
break;
case "objectivetitle":
ObjectiveTitleFont = LoadFont(subElement, graphicsDevice);
break;
case "objectivename":
ObjectiveNameFont = LoadFont(subElement, graphicsDevice);
break;
case "videotitle":
VideoTitleFont = LoadFont(subElement, graphicsDevice);
break;
default:
GUIComponentStyle componentStyle = new GUIComponentStyle(subElement);
componentStyles.Add(subElement.Name.ToString().ToLowerInvariant(), componentStyle);
break;
}
}
}
/// <summary>
/// Returns the default font of the currently selected language
/// </summary>
public ScalableFont LoadCurrentDefaultFont()
{
defaultFont?.Dispose();
defaultFont = null;
foreach (XElement subElement in configElement.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "font":
defaultFont = LoadFont(subElement, graphicsDevice);
break;
}
}
return defaultFont;
}
@@ -191,6 +166,12 @@ namespace Barotrauma
return style;
}
public GUIComponentStyle GetComponentStyle(string name)
{
componentStyles.TryGetValue(name.ToLowerInvariant(), out GUIComponentStyle style);
return style;
}
public void Apply(GUIComponent targetComponent, string styleName = "", GUIComponent parent = null)
{
GUIComponentStyle componentStyle = null;

View File

@@ -1,8 +1,6 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
@@ -249,7 +247,7 @@ namespace Barotrauma
return;
}
textPos = new Vector2(padding.X + (rect.Width - padding.Z - padding.X) / 2.0f, padding.Y + (rect.Height - padding.Y - padding.W) / 2.0f);
textPos = new Vector2(rect.Width / 2.0f, rect.Height / 2.0f);
origin = TextSize * 0.5f;
if (textAlignment.HasFlag(Alignment.Left) && !overflowClipActive)
@@ -335,7 +333,7 @@ namespace Barotrauma
{
spriteBatch.End();
spriteBatch.GraphicsDevice.ScissorRectangle = prevScissorRect;
spriteBatch.Begin(SpriteSortMode.Deferred, rasterizerState: GameMain.ScissorTestEnable);
spriteBatch.Begin(SpriteSortMode.Deferred);
}
if (OutlineColor.A * currColor.A > 0.0f) GUI.DrawRectangle(spriteBatch, rect, OutlineColor * (currColor.A / 255.0f), false);

View File

@@ -123,12 +123,6 @@ namespace Barotrauma
}
}
public bool OverflowClip
{
get { return textBlock.OverflowClip; }
set { textBlock.OverflowClip = value; }
}
public override bool Enabled
{
get { return enabled; }
@@ -324,7 +318,7 @@ namespace Barotrauma
for (int i = 0; i <= textBlock.Text.Length; i++)
{
Vector2 textSize = Font.MeasureString(textBlock.Text.Substring(0, i));
Vector2 indexPos = new Vector2(textSize.X + textBlock.Padding.X, textSize.Y + textBlock.Padding.Y) + textBlock.TextPos - textBlock.Origin;
Vector2 indexPos = new Vector2(textSize.X + textBlock.Padding.X, textSize.Y + textBlock.Padding.Y);
//DebugConsole.NewMessage($"index: {i}, pos: {indexPos}", Color.WhiteSmoke);
positions.Add(new Tuple<Vector2, int>(textBlock.Rect.Location.ToVector2() + indexPos, i));
}
@@ -365,9 +359,9 @@ namespace Barotrauma
OnDeselected?.Invoke(this, Keys.None);
}
public override void Flash(Color? color = null, float flashDuration = 1.5f, bool useRectangleFlash = false, Vector2? flashRectOffset = null)
public override void Flash(Color? color = null, float flashDuration = 1.5f)
{
textBlock.Flash(color, flashDuration, useRectangleFlash, flashRectOffset);
textBlock.Flash(color, flashDuration);
}
protected override void Update(float deltaTime)
@@ -411,7 +405,7 @@ namespace Barotrauma
{
isSelecting = PlayerInput.KeyDown(Keys.LeftShift) || PlayerInput.KeyDown(Keys.RightShift);
}
if (CaretEnabled)
{
if (textBlock.OverflowClipActive)
@@ -434,7 +428,7 @@ namespace Barotrauma
CalculateCaretPos();
}
}
if (GUI.KeyboardDispatcher.Subscriber == this)
{
state = ComponentState.Selected;
@@ -553,7 +547,15 @@ namespace Barotrauma
public void ReceiveTextInput(char inputChar)
{
ReceiveTextInput(inputChar.ToString());
if (selectedCharacters > 0)
{
RemoveSelectedText();
}
if (SetText(Text.Insert(CaretIndex, inputChar.ToString())))
{
CaretIndex = Math.Min(Text.Length, CaretIndex + 1);
OnTextChanged?.Invoke(this, Text);
}
}
public void ReceiveTextInput(string input)
@@ -562,16 +564,10 @@ namespace Barotrauma
{
RemoveSelectedText();
}
Vector2 textPos = textBlock.TextPos;
bool wasOverflowClipActive = textBlock.OverflowClipActive;
if (SetText(Text.Insert(CaretIndex, input)))
{
CaretIndex = Math.Min(Text.Length, CaretIndex + input.Length);
OnTextChanged?.Invoke(this, Text);
if (textBlock.OverflowClipActive && wasOverflowClipActive && !MathUtils.NearlyEqual(textBlock.TextPos, textPos))
{
textBlock.TextPos = textPos + Vector2.UnitX * Font.MeasureString(input).X;
}
}
}

View File

@@ -44,11 +44,10 @@ namespace Barotrauma
public Color TextColor
{
get { return text.TextColor; }
set { text.TextColor = value; }
get { return box; }
}
public override Rectangle MouseRect
public GUITextBlock TextBlock
{
get
{
@@ -57,17 +56,14 @@ namespace Barotrauma
}
}
public override ScalableFont Font
public override string ToolTip
{
get
{
return base.Font;
}
get { return base.ToolTip; }
set
{
base.Font = value;
if (text != null) text.Font = value;
base.ToolTip = value;
box.ToolTip = value;
text.ToolTip = value;
}
}
@@ -76,11 +72,6 @@ namespace Barotrauma
get { return box; }
}
public GUITextBlock TextBlock
{
get { return text; }
}
public override string ToolTip
{
get { return base.ToolTip; }
@@ -128,7 +119,6 @@ namespace Barotrauma
private void ResizeBox()
{
box.RectTransform.NonScaledSize = new Point(RectTransform.NonScaledSize.Y);
text.RectTransform.NonScaledSize = new Point(Rect.Width - box.Rect.Width, text.Rect.Height);
text.RectTransform.AbsoluteOffset = new Point(box.Rect.Width, 0);
}

View File

@@ -5,13 +5,12 @@ using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Barotrauma.Media;
using System.Linq;
namespace Barotrauma
{
class LoadingScreen
{
private Texture2D backgroundTexture;
private Texture2D backgroundTexture, monsterTexture, titleTexture;
private RenderTarget2D renderTarget;
@@ -44,7 +43,18 @@ namespace Barotrauma
private object loadMutex = new object();
private float? loadState;
public Vector2 TitleSize
{
get { return new Vector2(titleTexture.Width, titleTexture.Height); }
}
public float Scale
{
get;
private set;
}
public float? LoadState
{
get
@@ -93,7 +103,7 @@ namespace Barotrauma
try
{
DrawSplashScreen(spriteBatch);
if (SplashScreen != null && SplashScreen.IsPlaying) return;
if (SplashScreen!=null && SplashScreen.IsPlaying) return;
}
catch (Exception e)
{
@@ -101,27 +111,20 @@ namespace Barotrauma
GameMain.Config.EnableSplashScreen = false;
}
}
var titleStyle = GUI.Style?.GetComponentStyle("TitleText");
Sprite titleSprite = null;
if (titleStyle != null && titleStyle.Sprites.ContainsKey(GUIComponent.ComponentState.None))
{
titleSprite = titleStyle.Sprites[GUIComponent.ComponentState.None].First()?.Sprite;
}
drawn = true;
graphics.SetRenderTarget(renderTarget);
float backgroundScale = GameMain.GraphicsHeight / 1500.0f;
float titleScale = MathHelper.SmoothStep(0.8f, 1.0f, state / 10.0f) * GameMain.GraphicsHeight / 1000.0f;
Scale = GameMain.GraphicsHeight / 1500.0f;
state += deltaTime;
if (DrawLoadingText)
{
BackgroundPosition = new Vector2(GameMain.GraphicsWidth * 0.3f, GameMain.GraphicsHeight * 0.45f);
TitlePosition = new Vector2(GameMain.GraphicsWidth * 0.5f, GameMain.GraphicsHeight * 0.45f);
CenterPosition = new Vector2(GameMain.GraphicsWidth * 0.3f, GameMain.GraphicsHeight / 2.0f);
TitlePosition = CenterPosition + new Vector2(-0.0f + (float)Math.Sqrt(state) * 220.0f, 0.0f) * Scale;
TitlePosition.X = Math.Min(TitlePosition.X, (float)GameMain.GraphicsWidth / 2.0f);
}
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
@@ -129,10 +132,16 @@ namespace Barotrauma
spriteBatch.Draw(backgroundTexture, BackgroundPosition, null, Color.White * Math.Min(state / 5.0f, 1.0f), 0.0f,
new Vector2(backgroundTexture.Width / 2.0f, backgroundTexture.Height / 2.0f),
backgroundScale * 1.5f, SpriteEffects.None, 0.2f);
titleSprite?.Draw(spriteBatch, TitlePosition, Color.White * Math.Min((state - 1.0f) / 5.0f, 1.0f), scale: titleScale);
Scale * 1.5f, SpriteEffects.None, 0.2f);
spriteBatch.Draw(monsterTexture,
CenterPosition + new Vector2((state % 40) * 100.0f - 1800.0f, (state % 40) * 30.0f - 200.0f) * Scale, null,
Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.1f);
spriteBatch.Draw(titleTexture,
TitlePosition, null,
Color.White * Math.Min((state - 1.0f) / 5.0f, 1.0f), 0.0f, new Vector2(titleTexture.Width / 2.0f, titleTexture.Height / 2.0f), Scale, SpriteEffects.None, 0.0f);
spriteBatch.End();
graphics.SetRenderTarget(null);
@@ -145,7 +154,9 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
titleSprite?.Draw(spriteBatch, TitlePosition, Color.White * Math.Min((state - 1.0f) / 5.0f, 1.0f), scale: titleScale);
spriteBatch.Draw(titleTexture,
TitlePosition, null,
Color.White * Math.Min((state - 3.0f) / 5.0f, 1.0f), 0.0f, new Vector2(titleTexture.Width / 2.0f, titleTexture.Height / 2.0f), Scale, SpriteEffects.None, 0.0f);
if (DrawLoadingText)
{

View File

@@ -10,10 +10,9 @@ namespace Barotrauma
{
class VideoPlayer
{
public bool IsPlaying;
private Video currentVideo;
private string filePath;
private bool isPlaying;
private GUIFrame background, videoFrame, textFrame;
private GUITextBlock title, textContent, objectiveTitle, objectiveText;
@@ -25,14 +24,12 @@ namespace Barotrauma
private Point scaledVideoResolution;
private readonly int borderSize = 20;
private readonly Point buttonSize = new Point(120, 30);
private readonly Point buttonSize = new Point(160, 50);
private readonly int titleHeight = 30;
private readonly int objectiveFrameHeight = 60;
private readonly int textHeight = 25;
private bool useTextOnRightSide = false;
public class TextSettings
public struct TextSettings
{
public string Text;
public int Width;
@@ -44,7 +41,7 @@ namespace Barotrauma
}
}
public class VideoSettings
public struct VideoSettings
{
public string File;
@@ -65,14 +62,7 @@ namespace Barotrauma
background = new GUIFrame(new RectTransform(Point.Zero, GUI.Canvas, Anchor.Center), "InnerFrame", backgroundColor);
videoFrame = new GUIFrame(new RectTransform(Point.Zero, background.RectTransform, Anchor.Center, Pivot.Center), "SonarFrame");
if (useTextOnRightSide)
{
textFrame = new GUIFrame(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft), "TextFrame");
}
else
{
textFrame = new GUIFrame(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), "TextFrame");
}
textFrame = new GUIFrame(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.CenterLeft, Pivot.CenterLeft), "TextFrame");
videoView = new GUICustomComponent(new RectTransform(Point.Zero, videoFrame.RectTransform, Anchor.Center), (spriteBatch, guiCustomComponent) => { DrawVideo(spriteBatch, guiCustomComponent.Rect); });
title = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.VideoTitleFont, textColor: new Color(253, 174, 0), textAlignment: Alignment.Left);
@@ -80,7 +70,7 @@ namespace Barotrauma
textContent = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft), string.Empty, font: GUI.Font, textAlignment: Alignment.TopLeft);
objectiveTitle = new GUITextBlock(new RectTransform(new Vector2(1f, 0f), textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight, textColor: Color.White);
objectiveTitle.Text = TextManager.Get("Tutorial.NewObjective");
objectiveTitle.Text = TextManager.Get("NewObjective");
objectiveText = new GUITextBlock(new RectTransform(Point.Zero, textFrame.RectTransform, Anchor.TopCenter, Pivot.TopCenter), string.Empty, font: GUI.ObjectiveNameFont, textColor: new Color(4, 180, 108), textAlignment: Alignment.CenterRight);
objectiveTitle.Visible = objectiveText.Visible = false;
@@ -88,12 +78,12 @@ namespace Barotrauma
public void Play()
{
IsPlaying = true;
isPlaying = true;
}
public void Stop()
{
IsPlaying = false;
isPlaying = false;
if (currentVideo == null) return;
currentVideo.Dispose();
currentVideo = null;
@@ -109,6 +99,13 @@ namespace Barotrauma
public void Update()
{
if (currentVideo == null) return;
if (PlayerInput.KeyHit(Keys.Enter) || PlayerInput.KeyHit(Keys.Escape))
{
DisposeVideo(null, null);
return;
}
if (currentVideo.IsPlaying) return;
currentVideo.Dispose();
@@ -118,7 +115,7 @@ namespace Barotrauma
public void AddToGUIUpdateList(bool ignoreChildren = false, int order = 0)
{
if (!IsPlaying) return;
if (!isPlaying) return;
background.AddToGUIUpdateList(ignoreChildren, order);
}
@@ -141,8 +138,8 @@ namespace Barotrauma
}
currentVideo = CreateVideo(scaledVideoResolution);
title.Text = textSettings != null ? TextManager.Get(contentId) : string.Empty;
textContent.Text = textSettings != null ? textSettings.Text : string.Empty;
title.Text = TextManager.Get(contentId);
textContent.Text = textSettings.Text;
objectiveText.Text = objective;
AdjustFrames(videoSettings, textSettings);
@@ -168,8 +165,7 @@ namespace Barotrauma
title.TextScale = textContent.TextScale = objectiveText.TextScale = objectiveTitle.TextScale = GUI.Scale;
int scaledBorderSize = (int)(borderSize * GUI.Scale);
int scaledTextWidth = 0;
if (textSettings != null) scaledTextWidth = useTextOnRightSide ? (int)(textSettings.Width * GUI.Scale) : scaledVideoResolution.X / 2;
int scaledTextWidth = (int)(textSettings.Width * GUI.Scale);
int scaledTitleHeight = (int)(titleHeight * GUI.Scale);
int scaledTextHeight = (int)(textHeight * GUI.Scale);
int scaledObjectiveFrameHeight = (int)(objectiveFrameHeight * GUI.Scale);
@@ -184,21 +180,13 @@ namespace Barotrauma
title.RectTransform.NonScaledSize += new Point(scaledTextWidth, scaledTitleHeight);
title.RectTransform.AbsoluteOffset = new Point((int)(5 * GUI.Scale), (int)(10 * GUI.Scale));
if (textSettings != null && !string.IsNullOrEmpty(textSettings.Text))
if (!string.IsNullOrEmpty(textSettings.Text))
{
textSettings.Text = ToolBox.WrapText(textSettings.Text, scaledTextWidth, GUI.Font);
int wrappedHeight = textSettings.Text.Split('\n').Length * scaledTextHeight;
textFrame.RectTransform.NonScaledSize += new Point(scaledTextWidth + scaledBorderSize, wrappedHeight + scaledBorderSize + scaledButtonSize.Y + scaledTitleHeight);
if (useTextOnRightSide)
{
textFrame.RectTransform.AbsoluteOffset = new Point(scaledVideoResolution.X + scaledBorderSize * 2, 0);
}
else
{
textFrame.RectTransform.AbsoluteOffset = new Point(0, scaledVideoResolution.Y + scaledBorderSize * 2);
}
textFrame.RectTransform.AbsoluteOffset = new Point(scaledVideoResolution.X + scaledBorderSize * 2, 0);
textContent.RectTransform.NonScaledSize += new Point(scaledTextWidth, wrappedHeight);
textContent.RectTransform.AbsoluteOffset = new Point(0, scaledBorderSize + scaledTitleHeight);
@@ -221,41 +209,22 @@ namespace Barotrauma
objectiveTitle.Visible = objectiveText.Visible = false;
}
int totalFrameWidth = videoFrame.Rect.Width + textFrame.Rect.Width + scaledBorderSize * 2;
int xOffset = videoFrame.Rect.Width / 2 + scaledBorderSize - (videoFrame.Rect.Width / 2 - textFrame.Rect.Width / 2);
videoFrame.RectTransform.AbsoluteOffset = new Point(-xOffset, (int)(50 * GUI.Scale));
if (okButton != null)
{
textFrame.RemoveChild(okButton);
okButton = null;
}
if (textSettings != null)
okButton = new GUIButton(new RectTransform(scaledButtonSize, textFrame.RectTransform, Anchor.BottomRight, Pivot.BottomRight) { AbsoluteOffset = new Point(scaledBorderSize, scaledBorderSize) }, TextManager.Get("OK"))
{
if (useTextOnRightSide)
{
int totalFrameWidth = videoFrame.Rect.Width + textFrame.Rect.Width + scaledBorderSize * 2;
int xOffset = videoFrame.Rect.Width / 2 + scaledBorderSize - (videoFrame.Rect.Width / 2 - textFrame.Rect.Width / 2);
videoFrame.RectTransform.AbsoluteOffset = new Point(-xOffset, (int)(50 * GUI.Scale));
}
else
{
int totalFrameHeight = videoFrame.Rect.Height + textFrame.Rect.Height + scaledBorderSize * 2;
int yOffset = videoFrame.Rect.Height / 2 + scaledBorderSize - (videoFrame.Rect.Height / 2 - textFrame.Rect.Height / 2);
videoFrame.RectTransform.AbsoluteOffset = new Point(0, -yOffset);
}
okButton = new GUIButton(new RectTransform(scaledButtonSize, textFrame.RectTransform, Anchor.BottomRight, Pivot.BottomRight) { AbsoluteOffset = new Point(scaledBorderSize, scaledBorderSize) }, TextManager.Get("OK"))
{
OnClicked = DisposeVideo
};
}
else
{
videoFrame.RectTransform.AbsoluteOffset = new Point(0, (int)(100 * GUI.Scale));
okButton = new GUIButton(new RectTransform(scaledButtonSize, videoFrame.RectTransform, Anchor.TopLeft, Pivot.TopLeft) { AbsoluteOffset = new Point(scaledBorderSize, scaledBorderSize) }, TextManager.Get("Back"))
{
OnClicked = DisposeVideo
};
}
OnClicked = DisposeVideo
};
}
private Video CreateVideo(Point resolution)
@@ -276,7 +245,7 @@ namespace Barotrauma
private void DrawVideo(SpriteBatch spriteBatch, Rectangle rect)
{
if (!IsPlaying) return;
if (!isPlaying) return;
spriteBatch.Draw(currentVideo.GetTexture(), rect, Color.White);
}

View File

@@ -178,6 +178,10 @@ namespace Barotrauma
GUI.KeyboardDispatcher = new EventInput.KeyboardDispatcher(Window);
GUI.KeyboardDispatcher = new EventInput.KeyboardDispatcher(Window);
PerformanceCounter = new PerformanceCounter();
PerformanceCounter = new PerformanceCounter();
@@ -340,6 +344,7 @@ namespace Barotrauma
GUI.Init(Window, Config.SelectedContentPackages, GraphicsDevice);
DebugConsole.Init();
SteamManager.Initialize();
if (Config.AutoUpdateWorkshopItems)
{
if (SteamManager.AutoUpdateWorkshopItems())
@@ -525,20 +530,11 @@ namespace Barotrauma
}
/// <summary>
/// Returns the file paths of all files of the given type in the content packages.
/// Returns the file paths of all files of the given type in the currently selected content packages.
/// </summary>
/// <param name="type"></param>
/// <param name="searchAllContentPackages">If true, also returns files in content packages that are installed but not currently selected.</param>
public IEnumerable<string> GetFilesOfType(ContentType type, bool searchAllContentPackages = false)
public IEnumerable<string> GetFilesOfType(ContentType type)
{
if (searchAllContentPackages)
{
return ContentPackage.GetFilesOfType(ContentPackage.List, type);
}
else
{
return ContentPackage.GetFilesOfType(SelectedPackages, type);
}
return ContentPackage.GetFilesOfType(SelectedPackages, type);
}
/// <summary>
@@ -631,14 +627,6 @@ namespace Barotrauma
{
((GUIMessageBox)GUIMessageBox.VisibleBox).Close();
}
else if (Tutorial.Initialized && Tutorial.ContentRunning)
{
(GameSession.GameMode as TutorialMode).Tutorial.CloseActiveContentGUI();
}
else if (GUI.PauseMenuOpen)
{
GUI.TogglePauseMenu();
}
else if ((Character.Controlled?.SelectedConstruction == null || !Character.Controlled.SelectedConstruction.ActiveHUDs.Any(ic => ic.GuiFrame != null))
&& Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null)
{
@@ -648,17 +636,9 @@ namespace Barotrauma
}
GUI.ClearUpdateList();
paused = (DebugConsole.IsOpen || GUI.PauseMenuOpen || GUI.SettingsMenuOpen || Tutorial.ContentRunning) &&
paused = (DebugConsole.IsOpen || GUI.PauseMenuOpen || GUI.SettingsMenuOpen || ContextualTutorial.ContentRunning) &&
(NetworkMember == null || !NetworkMember.GameStarted);
#if !DEBUG
if (NetworkMember == null && !WindowActive && !paused && true && Screen.Selected != MainMenuScreen)
{
GUI.TogglePauseMenu();
paused = true;
}
#endif
Screen.Selected.AddToGUIUpdateList();
if (Client != null)
@@ -675,9 +655,9 @@ namespace Barotrauma
{
Screen.Selected.Update(Timing.Step);
}
else if (Tutorial.Initialized && Tutorial.ContentRunning)
else if (ContextualTutorial.Initialized && ContextualTutorial.ContentRunning && GameSession.GameMode is SinglePlayerCampaign)
{
(GameSession.GameMode as TutorialMode).Update((float)Timing.Step);
(GameSession.GameMode as SinglePlayerCampaign).ContextualTutorial.Update((float)Timing.Step);
}
if (NetworkMember != null)
@@ -742,85 +722,6 @@ namespace Barotrauma
PerformanceCounter.DrawTimeGraph.Update(sw.ElapsedTicks / (float)TimeSpan.TicksPerMillisecond);
}
public void ShowCampaignDisclaimer(Action onContinue = null)
{
var msgBox = new GUIMessageBox(TextManager.Get("CampaignDisclaimerTitle"), TextManager.Get("CampaignDisclaimerText"),
new string[] { TextManager.Get("CampaignRoadMapTitle"), TextManager.Get("OK") });
msgBox.Buttons[0].OnClicked = (btn, userdata) =>
{
var roadMap = new GUIMessageBox(TextManager.Get("CampaignRoadMapTitle"), TextManager.Get("CampaignRoadMapText"),
new string[] { TextManager.Get("Back"), TextManager.Get("OK") });
roadMap.Buttons[0].OnClicked += roadMap.Close;
roadMap.Buttons[0].OnClicked += (_, __) => { ShowCampaignDisclaimer(onContinue); return true; };
roadMap.Buttons[1].OnClicked += roadMap.Close;
roadMap.Buttons[1].OnClicked += (_, __) => { onContinue?.Invoke(); return true; };
return true;
};
msgBox.Buttons[0].OnClicked += msgBox.Close;
msgBox.Buttons[1].OnClicked += msgBox.Close;
msgBox.Buttons[1].OnClicked += (_, __) => { onContinue?.Invoke(); return true; };
Config.CampaignDisclaimerShown = true;
Config.SaveNewPlayerConfig();
}
public void ShowEditorDisclaimer()
{
var msgBox = new GUIMessageBox(TextManager.Get("EditorDisclaimerTitle"), TextManager.Get("EditorDisclaimerText"));
var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.25f), msgBox.Content.RectTransform)) { Stretch = true, RelativeSpacing = 0.025f };
linkHolder.RectTransform.MaxSize = new Point(int.MaxValue, linkHolder.Rect.Height);
List<Pair<string, string>> links = new List<Pair<string, string>>()
{
new Pair<string, string>(TextManager.Get("EditorDisclaimerWikiLink"),TextManager.Get("EditorDisclaimerWikiUrl")),
new Pair<string, string>(TextManager.Get("EditorDisclaimerDiscordLink"),TextManager.Get("EditorDisclaimerDiscordUrl")),
new Pair<string, string>(TextManager.Get("EditorDisclaimerForumLink"),TextManager.Get("EditorDisclaimerForumUrl")),
};
foreach (var link in links)
{
new GUIButton(new RectTransform(new Vector2(1.0f, 0.2f), linkHolder.RectTransform), link.First, style: "MainMenuGUIButton", textAlignment: Alignment.Left)
{
UserData = link.Second,
OnClicked = (btn, userdata) =>
{
Process.Start(userdata as string);
return true;
}
};
}
msgBox.InnerFrame.RectTransform.MinSize = new Point(0,
msgBox.InnerFrame.Rect.Height + linkHolder.Rect.Height + msgBox.Content.AbsoluteSpacing * 2 + 10);
Config.EditorDisclaimerShown = true;
Config.SaveNewPlayerConfig();
}
// ToDo: Move texts/links to localization, when possible.
public void ShowBugReporter()
{
var msgBox = new GUIMessageBox("", "");
var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), msgBox.Content.RectTransform)) { Stretch = true, RelativeSpacing = 0.05f };
List<Pair<string, string>> links = new List<Pair<string, string>>()
{
new Pair<string, string>("Barotrauma Feedback Form","https://barotraumagame.com/feedback"),
new Pair<string, string>("Github Issue Form (Needs account)","https://github.com/Regalis11/Barotrauma/issues/new?template=bug_report.md")
};
foreach (var link in links)
{
new GUIButton(new RectTransform(new Vector2(1.0f, 0.2f), linkHolder.RectTransform), link.First, style: "MainMenuGUIButton", textAlignment: Alignment.Left)
{
UserData = link.Second,
OnClicked = (btn, userdata) =>
{
Process.Start(userdata as string);
msgBox.Close();
return true;
}
};
}
}
static bool waitForKeyHit = true;
public CoroutineHandle ShowLoading(IEnumerable<object> loader, bool waitKeyHit = true)
{

View File

@@ -49,8 +49,6 @@ namespace Barotrauma
private GUIComponent orderTargetFrame, orderTargetFrameShadow;
public bool AllowCharacterSwitch = true;
public bool ToggleCrewAreaOpen
{
get { return toggleCrewAreaOpen; }
@@ -65,8 +63,6 @@ namespace Barotrauma
}
}
public List<GUIButton> OrderOptionButtons = new List<GUIButton>();
#endregion
#region Constructors
@@ -477,10 +473,7 @@ namespace Barotrauma
orderButtonFrame.RectTransform;
var btn = new GUIButton(new RectTransform(new Point(iconSize, iconSize), btnParent, Anchor.CenterLeft),
style: null)
{
UserData = order
};
style: null);
new GUIFrame(new RectTransform(new Vector2(1.5f), btn.RectTransform, Anchor.Center), "OuterGlow")
{
@@ -572,7 +565,6 @@ namespace Barotrauma
/// </summary>
public bool CharacterClicked(GUIComponent component, object selection)
{
if (!AllowCharacterSwitch) { return false; }
Character character = selection as Character;
if (character == null || character.IsDead || character.IsUnconscious) return false;
SelectCharacter(character);
@@ -614,7 +606,27 @@ namespace Barotrauma
characterListBox.BarScroll = roundedPos;
}
return false;
#endregion
#region Voice chat
public void SetPlayerVoiceIconState(Client client, bool muted, bool mutedLocally)
{
if (client?.Character == null) { return; }
var playerFrame = characterListBox.Content.FindChild(client.Character)?.FindChild(client.Character);
if (playerFrame == null) { return; }
var soundIcon = playerFrame.FindChild("soundicon");
var soundIconDisabled = playerFrame.FindChild("soundicondisabled");
if (!soundIcon.Visible)
{
soundIcon.Color = new Color(soundIcon.Color, 0.0f);
}
soundIcon.Visible = !muted && !mutedLocally;
soundIconDisabled.Visible = muted || mutedLocally;
soundIconDisabled.ToolTip = TextManager.Get(mutedLocally ? "MutedLocally" : "MutedGlobally");
}
private IEnumerable<object> KillCharacterAnim(GUIComponent component)
@@ -662,10 +674,6 @@ namespace Barotrauma
}
if (string.IsNullOrEmpty(text)) { return; }
if (sender != null)
{
GameMain.GameSession.CrewManager.SetCharacterSpeaking(sender);
}
ChatBox.AddMessage(ChatMessage.Create(senderName, text, messageType, sender));
}
@@ -717,19 +725,15 @@ namespace Barotrauma
soundIconDisabled.ToolTip = TextManager.Get(mutedLocally ? "MutedLocally" : "MutedGlobally");
}
public void SetClientSpeaking(Client client)
public void SetPlayerSpeaking(Client client)
{
if (client?.Character != null) { SetCharacterSpeaking(client.Character); }
}
if (client?.Character == null) { return; }
public void SetCharacterSpeaking(Character character)
{
var playerFrame = characterListBox.Content.FindChild(character)?.FindChild(character);
var playerFrame = characterListBox.Content.FindChild(client.Character)?.FindChild(client.Character);
if (playerFrame == null) { return; }
var soundIcon = playerFrame.FindChild("soundicon");
soundIcon.Color = new Color(soundIcon.Color, 1.0f);
}
#endregion
/// <summary>
@@ -746,7 +750,7 @@ namespace Barotrauma
if (IsSinglePlayer)
{
orderGiver.Speak(
order.GetChatMessage("", orderGiver.CurrentHull?.DisplayName, givingOrderToSelf: character == orderGiver), ChatMessageType.Order);
order.GetChatMessage("", orderGiver.CurrentHull?.RoomName, givingOrderToSelf: character == orderGiver), ChatMessageType.Order);
}
else
{
@@ -763,7 +767,7 @@ namespace Barotrauma
if (IsSinglePlayer)
{
orderGiver?.Speak(
order.GetChatMessage(character.Name, orderGiver.CurrentHull?.DisplayName, givingOrderToSelf: character == orderGiver, orderOption: option), null);
order.GetChatMessage(character.Name, orderGiver.CurrentHull?.RoomName, givingOrderToSelf: character == orderGiver, orderOption: option), null);
}
else if (orderGiver != null)
{
@@ -837,6 +841,12 @@ namespace Barotrauma
matchingItems.RemoveAll(it => it.Submarine != submarine && !submarine.DockedTo.Contains(it.Submarine));
matchingItems.RemoveAll(it => it.Submarine != null && it.Submarine.IsOutpost);
}
var characterElement = characterListBox.Content.FindChild(character);
GUIButton orderBtn = characterElement.FindChild(order, recursive: true) as GUIButton;
if (orderBtn.Frame.FlashTimer <= 0)
{
orderBtn.Flash(color, 1.5f, false, flashRectInflate);
}
//more than one target item -> create a minimap-like selection with a pic of the sub
if (matchingItems.Count > 1)
@@ -916,12 +926,9 @@ namespace Barotrauma
if (Character.Controlled == null) return false;
SetCharacterOrder(character, userData as Order, option, Character.Controlled);
orderTargetFrame = null;
OrderOptionButtons.Clear();
return true;
}
};
OrderOptionButtons.Add(optionButton);
}
}
@@ -954,13 +961,9 @@ namespace Barotrauma
if (Character.Controlled == null) return false;
SetCharacterOrder(character, userData as Order, option, Character.Controlled);
orderTargetFrame = null;
OrderOptionButtons.Clear();
return true;
}
};
OrderOptionButtons.Add(optionButton);
//lines between the order buttons
if (i < order.Options.Length - 1)
{
@@ -976,24 +979,6 @@ namespace Barotrauma
color: matchingItems.Count > 1 ? Color.Black * 0.9f : Color.Black * 0.7f);
}
public void HighlightOrderButton(Character character, string orderAiTag, Color color, Vector2? flashRectInflate = null)
{
var order = Order.PrefabList.Find(o => o.AITag == orderAiTag);
if (order == null)
{
DebugConsole.ThrowError("Could not find an order with the AI tag \"" + orderAiTag + "\".\n" + Environment.StackTrace);
return;
}
var characterElement = characterListBox.Content.FindChild(character);
GUIButton orderBtn = characterElement.FindChild(order, recursive: true) as GUIButton;
if (orderBtn.Frame.FlashTimer <= 0)
{
orderBtn.Flash(color, 1.5f, false, flashRectInflate);
}
//orderBtn.Pulsate(Vector2.One, Vector2.One * 2.0f, 1.5f);
}
#region Updating and drawing the UI
private void DrawMiniMapOverlay(SpriteBatch spriteBatch, GUICustomComponent container)
@@ -1051,7 +1036,6 @@ namespace Barotrauma
public void SelectNextCharacter()
{
if (!AllowCharacterSwitch) { return; }
if (GameMain.IsMultiplayer) { return; }
if (characters.None()) { return; }
SelectCharacter(characters[TryAdjustIndex(1)]);
@@ -1059,7 +1043,6 @@ namespace Barotrauma
public void SelectPreviousCharacter()
{
if (!AllowCharacterSwitch) { return; }
if (GameMain.IsMultiplayer) { return; }
if (characters.None()) { return; }
SelectCharacter(characters[TryAdjustIndex(-1)]);
@@ -1067,7 +1050,6 @@ namespace Barotrauma
private void SelectCharacter(Character character)
{
if (!AllowCharacterSwitch) { return; }
//make the previously selected character wait in place for some time
//(so they don't immediately start idling and walking away from their station)
if (Character.Controlled?.AIController?.ObjectiveManager != null)
@@ -1113,7 +1095,7 @@ namespace Barotrauma
ChatBox.Update(deltaTime);
ChatBox.InputBox.Visible = Character.Controlled != null;
if (!DebugConsole.IsOpen && ChatBox.InputBox.Visible && GUI.KeyboardDispatcher.Subscriber == null)
if (!DebugConsole.IsOpen && ChatBox.InputBox.Visible)
{
if (PlayerInput.KeyHit(InputType.Chat) && !ChatBox.InputBox.Selected)
{

View File

@@ -135,8 +135,6 @@ namespace Barotrauma
msg.Write(map.SelectedLocationIndex == -1 ? UInt16.MaxValue : (UInt16)map.SelectedLocationIndex);
msg.Write(map.SelectedMissionIndex == -1 ? byte.MaxValue : (byte)map.SelectedMissionIndex);
msg.Write(PurchasedHullRepairs);
msg.Write(PurchasedItemRepairs);
msg.Write((UInt16)CargoManager.PurchasedItems.Count);
foreach (PurchasedItem pi in CargoManager.PurchasedItems)

View File

@@ -9,6 +9,8 @@ namespace Barotrauma
{
class SinglePlayerCampaign : CampaignMode
{
public ContextualTutorial ContextualTutorial;
private GUIButton endRoundButton;
private bool crewDead;
@@ -39,6 +41,13 @@ namespace Barotrauma
CrewManager.AddCharacterInfo(new CharacterInfo(Character.HumanConfigFile, "", jobPrefab));
}
}
ContextualTutorial = Tutorial.Tutorials.Find(t => t is ContextualTutorial) as ContextualTutorial;
if (ContextualTutorial.Selected) // Selected when starting a new game -> initialize
{
ContextualTutorial.Initialize();
}
}
public override void Start()
@@ -56,6 +65,11 @@ namespace Barotrauma
endTimer = 5.0f;
isRunning = true;
CrewManager.InitSinglePlayerRound();
if (ContextualTutorial.Initialized)
{
ContextualTutorial.Start();
}
}
public bool TryHireCharacter(Location location, CharacterInfo characterInfo)
@@ -148,6 +162,11 @@ namespace Barotrauma
base.AddToGUIUpdateList();
CrewManager.AddToGUIUpdateList();
endRoundButton.AddToGUIUpdateList();
if (ContextualTutorial.Initialized)
{
ContextualTutorial.AddToGUIUpdateList();
}
}
public override void Update(float deltaTime)
@@ -156,6 +175,11 @@ namespace Barotrauma
base.Update(deltaTime);
if (ContextualTutorial.Initialized)
{
ContextualTutorial.Update(deltaTime);
}
if (!GUI.DisableHUD && !GUI.DisableUpperHUD)
{
endRoundButton.UpdateManually(deltaTime);
@@ -292,6 +316,7 @@ namespace Barotrauma
TextManager.Get("QuitButton"));
quitButton.OnClicked += GameMain.LobbyScreen.QuitToMainMenu;
quitButton.OnClicked += (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox); return true; };
quitButton.OnClicked += (GUIButton button, object obj) => { if (ContextualTutorial.Initialized) ContextualTutorial.Stop(); return true; };
}
}
@@ -376,6 +401,10 @@ namespace Barotrauma
case "map":
campaign.map = Map.LoadNew(subElement);
break;
case "contextualtutorial":
campaign.ContextualTutorial.Initialize(); // Initialize when saved element found
campaign.ContextualTutorial.LoadPartiallyComplete(subElement);
break;
}
}
@@ -384,7 +413,7 @@ namespace Barotrauma
if (campaign.CheatsEnabled)
{
DebugConsole.CheatsEnabled = true;
if (Steam.SteamManager.USE_STEAM && !SteamAchievementManager.CheatsEnabled)
if (GameMain.Config.UseSteam && !SteamAchievementManager.CheatsEnabled)
{
SteamAchievementManager.CheatsEnabled = true;
new GUIMessageBox("Cheats enabled", "Cheat commands have been enabled on the campaign. You will not receive Steam Achievements until you restart the game.");
@@ -411,6 +440,12 @@ namespace Barotrauma
new XAttribute("cheatsenabled", CheatsEnabled));
CrewManager.Save(modeElement);
Map.Save(modeElement);
if (ContextualTutorial.Initialized)
{
ContextualTutorial.SavePartiallyComplete(modeElement);
}
element.Add(modeElement);
}
}

View File

@@ -303,7 +303,7 @@ namespace Barotrauma.Tutorials
yield return new WaitForSeconds(1.0f);
infoBox = CreateInfoFrame("", "Uh-oh... Something enormous just appeared on the sonar.");
infoBox = CreateInfoFrame("Uh-oh... Something enormous just appeared on the sonar.");
List<Structure> windows = new List<Structure>();
foreach (Structure s in Structure.WallList)

View File

@@ -1,20 +1,25 @@
/*using System.Collections.Generic;
using System.Collections.Generic;
using System.Xml.Linq;
using System;
using Microsoft.Xna.Framework;
using Barotrauma.Items.Components;
using System.Linq;
using Microsoft.Xna.Framework.Input;
namespace Barotrauma.Tutorials
{
class ContextualTutorial : Tutorial
{
public ContextualTutorial(XElement element) : base(element)
{
//Name = "ContextualTutorial";
}
public static bool Selected = false;
public static bool ContentRunning = false;
public static bool Initialized = false;
private enum ContentTypes { None = 0, Video = 1, TextOnly = 2 };
private TutorialSegment activeSegment;
private List<TutorialSegment> segments;
private VideoPlayer videoPlayer;
private Steering navConsole;
private Reactor reactor;
@@ -28,24 +33,83 @@ namespace Barotrauma.Tutorials
private List<Pair<Character, float>> characterTimeOnSonar;
private float requiredTimeOnSonar = 5f;
private bool started = false;
private string playableContentPath;
private float tutorialTimer;
private bool disableTutorialOnDeficiencyFound = true;
private GUIFrame holderFrame, objectiveFrame;
private List<TutorialSegment> activeObjectives = new List<TutorialSegment>();
private string objectiveTranslated;
private float floodTutorialTimer = 0.0f;
private const float floodTutorialDelay = 2.0f;
private float medicalTutorialTimer = 0.0f;
private const float medicalTutorialDelay = 2.0f;
private Point screenResolution;
private float prevUIScale;
private class TutorialSegment
{
public string Id;
public string Objective;
public ContentTypes ContentType;
public XElement TextContent;
public XElement VideoContent;
public bool IsTriggered;
public GUIButton ReplayButton;
public GUITextBlock LinkedTitle, LinkedText;
public TutorialSegment(XElement config)
{
Id = config.GetAttributeString("id", "Missing ID");
Objective = TextManager.Get(config.GetAttributeString("objective", string.Empty), true);
Enum.TryParse(config.GetAttributeString("contenttype", "None"), true, out ContentType);
IsTriggered = config.GetAttributeBool("istriggered", false);
switch (ContentType)
{
case ContentTypes.None:
break;
case ContentTypes.Video:
VideoContent = config.Element("Video");
TextContent = config.Element("Text");
break;
case ContentTypes.TextOnly:
TextContent = config.Element("Text");
break;
}
}
}
public ContextualTutorial(XElement element) : base(element)
{
playableContentPath = element.GetAttributeString("playablecontentpath", "");
segments = new List<TutorialSegment>();
foreach (var segment in element.Elements("Segment"))
{
segments.Add(new TutorialSegment(segment));
}
Name = "ContextualTutorial";
}
public override void Initialize()
{
base.Initialize();
for (int i = 0; i < segments.Count; i++)
{
segments[i].IsTriggered = false;
}
if (Initialized) return;
Initialized = true;
base.Initialize();
videoPlayer = new VideoPlayer();
characterTimeOnSonar = new List<Pair<Character, float>>();
}
@@ -103,7 +167,10 @@ namespace Barotrauma.Tutorials
base.Start();
injuredMember = null;
activeContentSegment = null;
activeObjectives.Clear();
objectiveTranslated = TextManager.Get("Objective");
CreateObjectiveFrame();
activeSegment = null;
tutorialTimer = floodTutorialTimer = medicalTutorialTimer = 0.0f;
subStartingPosition = Vector2.Zero;
characterTimeOnSonar.Clear();
@@ -116,10 +183,10 @@ namespace Barotrauma.Tutorials
#if DEBUG
if (reactor == null || navConsole == null || sonar == null)
{
infoBox = CreateInfoFrame("Error", "Submarine not compatible with the tutorial:"
infoBox = CreateInfoFrame("Submarine not compatible with the tutorial:"
+ "\nReactor - " + (reactor != null ? "OK" : "Tag 'reactor' not found")
+ "\nNavigation Console - " + (navConsole != null ? "OK" : "Tag 'command' not found")
+ "\nSonar - " + (sonar != null ? "OK" : "Not found under Navigation Console"), hasButton: true);
+ "\nSonar - " + (sonar != null ? "OK" : "Not found under Navigation Console"), true);
CoroutineManager.StartCoroutine(WaitForErrorClosed());
return;
}
@@ -155,15 +222,62 @@ namespace Barotrauma.Tutorials
}
#endif
public override void Stop()
public void Stop()
{
base.Stop();
started = ContentRunning = Initialized = false;
videoPlayer.Remove();
videoPlayer = null;
characterTimeOnSonar = null;
}
private void CreateObjectiveFrame()
{
holderFrame = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center));
objectiveFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ObjectiveAnchor, holderFrame.RectTransform), style: null);
for (int i = 0; i < activeObjectives.Count; i++)
{
CreateObjectiveGUI(activeObjectives[i], i);
}
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
prevUIScale = GUI.Scale;
}
public override void AddToGUIUpdateList()
{
if (videoPlayer != null)
{
videoPlayer.AddToGUIUpdateList(order: 100);
}
if (GUI.DisableHUD) return;
if (GameMain.GraphicsWidth != screenResolution.X || GameMain.GraphicsHeight != screenResolution.Y || prevUIScale != GUI.Scale)
{
CreateObjectiveFrame();
}
if (objectiveFrame != null && activeObjectives.Count > 0)
{
objectiveFrame.AddToGUIUpdateList(order: -1);
}
base.AddToGUIUpdateList();
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
if (videoPlayer != null)
{
videoPlayer.Update();
}
if (infoBox != null)
{
if (PlayerInput.KeyHit(Keys.Enter) || PlayerInput.KeyHit(Keys.Escape))
{
CloseInfoFrame(null, null);
}
}
if (!started || ContentRunning) return;
@@ -171,12 +285,93 @@ namespace Barotrauma.Tutorials
for (int i = 0; i < segments.Count; i++)
{
if (segments[i].IsTriggered || HasObjective(segments[i])) continue;
if (segments[i].IsTriggered || activeObjectives.Contains(segments[i])) continue;
if (CheckContextualTutorials(i, deltaTime)) // Found a relevant tutorial, halt finding new ones
{
break;
}
}
for (int i = 0; i < activeObjectives.Count; i++)
{
CheckActiveObjectives(activeObjectives[i], deltaTime);
}
}
private void ClosePreTextAndTriggerVideoCallback()
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(activeSegment.VideoContent), new VideoPlayer.TextSettings(activeSegment.VideoContent), activeSegment.Id, true, activeSegment.Objective, CurrentSegmentStopCallback);
}
private void CurrentSegmentStopCallback()
{
if (!string.IsNullOrEmpty(activeSegment.Objective))
{
AddNewObjective(activeSegment);
}
activeSegment = null;
ContentRunning = false;
}
private void AddNewObjective(TutorialSegment segment)
{
activeObjectives.Add(segment);
CreateObjectiveGUI(segment, activeObjectives.Count - 1);
}
private void CreateObjectiveGUI(TutorialSegment segment, int index)
{
Point replayButtonSize = new Point((int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).X * GUI.Scale), (int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).Y * 1.45f * GUI.Scale));
segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopRight, Pivot.TopRight) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null);
segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) =>
{
ReplaySegmentVideo(segment);
return true;
};
int yOffset = (int)((GUI.ObjectiveNameFont.MeasureString(objectiveTranslated).Y / 2f + 5) * GUI.Scale);
segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.BottomCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }, objectiveTranslated, textColor: Color.White, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight);
segment.LinkedText = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.TopCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }, segment.Objective, textColor: new Color(4, 180, 108), font: GUI.ObjectiveNameFont, textAlignment: Alignment.CenterRight);
segment.LinkedTitle.TextScale = segment.LinkedText.TextScale = GUI.Scale;
segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent;
segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent;
segment.ReplayButton.Color = segment.ReplayButton.HoverColor = segment.ReplayButton.PressedColor = segment.ReplayButton.SelectedColor = Color.Transparent;
}
private void RemoveCompletedObjective(TutorialSegment objective)
{
objective.IsTriggered = true;
int checkMarkHeight = (int)(objective.ReplayButton.Rect.Height * 1.2f);
int checkMarkWidth = (int)(checkMarkHeight * 0.93f);
Color color = new Color(4, 180, 108);
RectTransform rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), objective.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5, 0);
GUIImage checkmark = new GUIImage(rectTA, "CheckMark");
checkmark.Color = color;
RectTransform rectTB = new RectTransform(new Vector2(1.1f, .8f), objective.LinkedText.RectTransform, Anchor.Center, Pivot.Center);
GUIImage stroke = new GUIImage(rectTB, "Stroke");
stroke.Color = color;
CoroutineManager.StartCoroutine(WaitForObjectiveEnd(objective));
}
private IEnumerable<object> WaitForObjectiveEnd(TutorialSegment objective)
{
yield return new WaitForSeconds(2.0f);
objectiveFrame.RemoveChild(objective.ReplayButton);
activeObjectives.Remove(objective);
for (int i = 0; i < activeObjectives.Count; i++)
{
activeObjectives[i].ReplayButton.RectTransform.AbsoluteOffset = new Point(0, (activeObjectives[i].ReplayButton.Rect.Height + 20) * i);
}
}
private bool CheckContextualTutorials(int index, float deltaTime)
@@ -331,7 +526,17 @@ namespace Barotrauma.Tutorials
return true;
}
protected override void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
private bool HasObjective(string objectiveName)
{
for (int i = 0; i < activeObjectives.Count; i++)
{
if (activeObjectives[i].Id == objectiveName) return true;
}
return false;
}
private void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
{
switch(objective.Id)
{
@@ -499,9 +704,50 @@ namespace Barotrauma.Tutorials
return characterTimeOnSonar.Find(ct => ct.Second >= requiredTimeOnSonar && !ct.First.IsDead) != null;
}
protected override void TriggerTutorialSegment(int index, params object[] args)
private void TriggerTutorialSegment(int index, params object[] args)
{
base.TriggerTutorialSegment(index, args);
Inventory.draggingItem = null;
ContentRunning = true;
activeSegment = segments[index];
string tutorialText = TextManager.GetFormatted(activeSegment.TextContent.GetAttributeString("tag", ""), true, args);
string objectiveText = string.Empty;
if (!string.IsNullOrEmpty(activeSegment.Objective))
{
if (args.Length == 0)
{
objectiveText = activeSegment.Objective;
}
else
{
objectiveText = string.Format(activeSegment.Objective, args);
}
activeSegment.Objective = objectiveText;
}
else
{
activeSegment.IsTriggered = true; // Complete at this stage only if no related objective
}
switch (activeSegment.ContentType)
{
case ContentTypes.None:
break;
case ContentTypes.Video:
infoBox = CreateInfoFrame(TextManager.Get(activeSegment.Id), tutorialText,
activeSegment.TextContent.GetAttributeInt("width", 300),
activeSegment.TextContent.GetAttributeInt("height", 80),
activeSegment.TextContent.GetAttributeString("anchor", "Center"), true, ClosePreTextAndTriggerVideoCallback);
break;
case ContentTypes.TextOnly:
infoBox = CreateInfoFrame(TextManager.Get(activeSegment.Id), tutorialText,
activeSegment.TextContent.GetAttributeInt("width", 300),
activeSegment.TextContent.GetAttributeInt("height", 80),
activeSegment.TextContent.GetAttributeString("anchor", "Center"), true, CurrentSegmentStopCallback);
break;
}
for (int i = 0; i < segments.Count; i++)
{
@@ -511,10 +757,17 @@ namespace Barotrauma.Tutorials
CoroutineManager.StartCoroutine(WaitToStop()); // Completed
}
private void ReplaySegmentVideo(TutorialSegment segment)
{
if (ContentRunning) return;
ContentRunning = true;
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, callback: () => ContentRunning = false);
}
private IEnumerable<object> WaitToStop()
{
while (ContentRunning) yield return null;
Stop();
}
}
}*/
}

View File

@@ -1,118 +1,44 @@
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Tutorials
{
class ScenarioTutorial : Tutorial
{
private CoroutineHandle tutorialCoroutine;
private Character character;
private string spawnSub;
private SpawnType spawnPointType;
private string submarinePath;
private string startOutpostPath;
private string endOutpostPath;
private string levelSeed;
private string levelParams;
private Submarine startOutpost = null;
private Submarine endOutpost = null;
private bool currentTutorialCompleted = false;
private float fadeOutTime = 3f;
protected float waitBeforeFade = 4f;
// Colors
protected Color highlightColor = Color.OrangeRed;
protected Color uiHighlightColor = new Color(150, 50, 0);
protected Color buttonHighlightColor = new Color(255, 100, 0);
protected Color inaccessibleColor = Color.Red;
protected Color accessibleColor = Color.Green;
public ScenarioTutorial(XElement element) : base(element)
{
submarinePath = element.GetAttributeString("submarinepath", "");
startOutpostPath = element.GetAttributeString("startoutpostpath", "");
endOutpostPath = element.GetAttributeString("endoutpostpath", "");
levelSeed = element.GetAttributeString("levelseed", "tuto");
levelParams = element.GetAttributeString("levelparams", "");
spawnSub = element.GetAttributeString("spawnsub", "");
Enum.TryParse(element.GetAttributeString("spawnpointtype", "Human"), true, out spawnPointType);
Enum.TryParse(element.GetAttributeString("spawnpointtype", "Human"), true, out spawnPointType);
}
public override void Initialize()
{
base.Initialize();
currentTutorialCompleted = false;
GameMain.Instance.ShowLoading(Loading());
}
private IEnumerable<object> Loading()
{
Submarine.MainSub = Submarine.Load(submarinePath, "", true);
LevelGenerationParams generationParams = LevelGenerationParams.LevelParams.Find(p => p.Name == levelParams);
yield return CoroutineStatus.Running;
GameMain.GameSession = new GameSession(Submarine.MainSub, "",
GameModePreset.List.Find(g => g.Identifier == "tutorial"));
(GameMain.GameSession.GameMode as TutorialMode).Tutorial = this;
if (generationParams != null)
{
Biome biome = LevelGenerationParams.GetBiomes().Find(b => generationParams.AllowedBiomes.Contains(b));
if (startOutpostPath != string.Empty)
{
startOutpost = Submarine.Load(startOutpostPath, "", false);
}
if (endOutpostPath != string.Empty)
{
endOutpost = Submarine.Load(endOutpostPath, "", false);
}
Level tutorialLevel = new Level(levelSeed, 0, 0, generationParams, biome, startOutpost, endOutpost);
GameMain.GameSession.StartRound(tutorialLevel);
}
else
{
GameMain.GameSession.StartRound(levelSeed);
}
GameMain.GameSession.EventManager.Events.Clear();
GameMain.GameSession.EventManager.Enabled = false;
GameMain.GameScreen.Select();
yield return CoroutineStatus.Success;
}
public override void Start()
{
base.Start();
Submarine.MainSub.GodMode = true;
CharacterInfo charInfo = configElement.Element("Character") == null ?
new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "engineer")) :
new CharacterInfo(configElement.Element("Character"));
WayPoint wayPoint = GetSpawnPoint(charInfo);
WayPoint wayPoint = WayPoint.GetRandom(spawnPointType, null);
if (wayPoint == null)
{
DebugConsole.ThrowError("A waypoint with the spawntype \"" + spawnPointType + "\" is required for the tutorial event");
return;
}
CharacterInfo charInfo = configElement.Element("Character") == null ?
new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "engineer")) :
new CharacterInfo(configElement.Element("Character"));
character = Character.Create(charInfo, wayPoint.WorldPosition, "", false, false);
Character.Controlled = character;
character.GiveJobItems(null);
@@ -126,82 +52,22 @@ namespace Barotrauma.Tutorials
idCard.AddTag("com");
idCard.AddTag("eng");
tutorialCoroutine = CoroutineManager.StartCoroutine(UpdateState());
CoroutineManager.StartCoroutine(UpdateState());
}
public override void AddToGUIUpdateList()
private IEnumerable<object> Loading()
{
if (!currentTutorialCompleted)
{
base.AddToGUIUpdateList();
}
}
Submarine.MainSub = Submarine.Load(submarinePath, "", true);
yield return CoroutineStatus.Running;
private WayPoint GetSpawnPoint(CharacterInfo charInfo)
{
Submarine spawnSub = null;
GameMain.GameSession = new GameSession(Submarine.MainSub, "",
GameModePreset.List.Find(g => g.Identifier == "tutorial"));
(GameMain.GameSession.GameMode as TutorialMode).tutorial = this;
GameMain.GameSession.StartRound(levelSeed);
GameMain.GameSession.EventManager.Events.Clear();
GameMain.GameScreen.Select();
if (this.spawnSub != string.Empty)
{
switch (this.spawnSub)
{
case "startoutpost":
spawnSub = startOutpost;
break;
case "endoutpost":
spawnSub = endOutpost;
break;
default:
spawnSub = Submarine.MainSub;
break;
}
}
return WayPoint.GetRandom(spawnPointType, charInfo.Job, spawnSub);
}
protected bool HasOrder(Character character, string aiTag, string option = null)
{
if (character.CurrentOrder?.AITag == aiTag)
{
if (option == null)
{
return true;
}
else
{
HumanAIController humanAI = character.AIController as HumanAIController;
return humanAI.CurrentOrderOption == option;
}
}
return false;
}
protected void SetHighlight(Item item, bool state)
{
if (item.ExternalHighlight == state) return;
item.SpriteColor = (state) ? highlightColor : Color.White;
item.ExternalHighlight = state;
}
protected void SetHighlight(Structure structure, bool state)
{
structure.SpriteColor = (state) ? highlightColor : Color.White;
structure.ExternalHighlight = state;
}
protected void SetHighlight(Character character, bool state)
{
character.ExternalHighlight = state;
}
protected void SetDoorAccess(Door door, LightComponent light, bool state)
{
if (state && door != null) door.requiredItems.Clear();
if (light != null) light.LightColor = (state) ? accessibleColor : inaccessibleColor;
yield return CoroutineStatus.Success;
}
public override void Update(float deltaTime)
@@ -209,47 +75,27 @@ namespace Barotrauma.Tutorials
base.Update(deltaTime);
if (character != null)
{
if (character.Oxygen < 1)
if (Character.Controlled == null)
{
character.Oxygen = 1;
}
if (character.IsDead)
{
CoroutineManager.StartCoroutine(Dead());
}
else if (Character.Controlled == null)
{
if (tutorialCoroutine != null)
{
CoroutineManager.StopCoroutines(tutorialCoroutine);
}
CoroutineManager.StopCoroutines("TutorialMode.UpdateState");
infoBox = null;
}
else if (Character.Controlled.IsDead)
{
Character.Controlled = null;
CoroutineManager.StopCoroutines("TutorialMode.UpdateState");
infoBox = null;
CoroutineManager.StartCoroutine(Dead());
}
}
}
public override void Stop()
{
if (tutorialCoroutine != null)
{
CoroutineManager.StopCoroutines(tutorialCoroutine);
}
base.Stop();
}
private IEnumerable<object> Dead()
{
GUI.PreventPauseMenuToggle = true;
Character.Controlled = character = null;
Stop();
yield return new WaitForSeconds(3.0f);
var messageBox = new GUIMessageBox(TextManager.Get("Tutorial.TryAgainHeader"), TextManager.Get("Tutorial.TryAgain"), new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
var messageBox = new GUIMessageBox("You have died", "Do you want to try again?", new string[] { "Yes", "No" });
messageBox.Buttons[0].OnClicked += Restart;
messageBox.Buttons[0].OnClicked += messageBox.Close;
@@ -260,29 +106,5 @@ namespace Barotrauma.Tutorials
yield return CoroutineStatus.Success;
}
protected IEnumerable<object> TutorialCompleted()
{
GUI.PreventPauseMenuToggle = true;
Character.Controlled.ClearInputs();
Character.Controlled = null;
yield return new WaitForSeconds(waitBeforeFade);
var endCinematic = new RoundEndCinematic(Submarine.MainSub, GameMain.GameScreen.Cam, fadeOutTime);
currentTutorialCompleted = Completed = true;
while (endCinematic.Running) yield return null;
Stop();
GameMain.MainMenuScreen.ReturnToMainMenu(null, null);
}
protected void Heal(Character character)
{
character.SetAllDamage(0.0f, 0.0f, 0.0f);
character.Oxygen = 100.0f;
character.Bloodloss = 0.0f;
character.SetStun(0.0f, true);
}
}
}

View File

@@ -1,82 +1,23 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Items.Components;
using Barotrauma.Extensions;
namespace Barotrauma.Tutorials
{
abstract class Tutorial
{
#region Tutorial variables
public static bool Initialized = false;
public static bool ContentRunning = false;
public static List<Tutorial> Tutorials;
protected bool started = false;
protected GUIComponent infoBox;
private Action infoBoxClosedCallback;
protected XElement configElement;
protected VideoPlayer videoPlayer;
protected enum TutorialContentTypes { None = 0, Video = 1, ManualVideo = 2, TextOnly = 3 };
protected string playableContentPath;
protected Point screenResolution;
protected float prevUIScale;
private enum TutorialType { None, Scenario, Contextual };
private TutorialType tutorialType = TutorialType.None;
private GUIFrame holderFrame, objectiveFrame;
private List<TutorialSegment> activeObjectives = new List<TutorialSegment>();
private string objectiveTranslated;
protected TutorialSegment activeContentSegment;
protected List<TutorialSegment> segments;
protected class TutorialSegment
{
public string Id;
public string Objective;
public TutorialContentTypes ContentType;
public XElement TextContent;
public XElement VideoContent;
public bool IsTriggered;
public GUIButton ReplayButton;
public GUITextBlock LinkedTitle, LinkedText;
public object[] Args;
public TutorialSegment(XElement config)
{
Id = config.GetAttributeString("id", "Missing ID");
Objective = TextManager.Get(config.GetAttributeString("objective", string.Empty), true);
Enum.TryParse(config.GetAttributeString("contenttype", "None"), true, out ContentType);
IsTriggered = config.GetAttributeBool("istriggered", false);
switch (ContentType)
{
case TutorialContentTypes.None:
break;
case TutorialContentTypes.Video:
case TutorialContentTypes.ManualVideo:
VideoContent = config.Element("Video");
TextContent = config.Element("Text");
break;
case TutorialContentTypes.TextOnly:
TextContent = config.Element("Text");
break;
}
}
}
public string Identifier
{
get;
protected set;
}
public string DisplayName
public string Name
{
get;
protected set;
@@ -93,9 +34,7 @@ namespace Barotrauma.Tutorials
GameMain.Config.SaveNewPlayerConfig();
}
}
#endregion
#region Tutorial Controls
public static void Init()
{
Tutorials = new List<Tutorial>();
@@ -165,88 +104,29 @@ namespace Barotrauma.Tutorials
public Tutorial(XElement element)
{
configElement = element;
Identifier = element.GetAttributeString("identifier", "unknown");
DisplayName = TextManager.Get(Identifier);
completed = GameMain.Config.CompletedTutorialNames.Contains(Identifier);
playableContentPath = element.GetAttributeString("playablecontentpath", "");
segments = new List<TutorialSegment>();
foreach (var segment in element.Elements("Segment"))
{
segments.Add(new TutorialSegment(segment));
}
Name = element.GetAttributeString("name", "Unnamed");
completed = GameMain.Config.CompletedTutorialNames.Contains(Name);
Enum.TryParse(element.GetAttributeString("tutorialtype", "Scenario"), true, out tutorialType);
}
public virtual void Initialize()
{
if (Initialized) return;
Initialized = true;
videoPlayer = new VideoPlayer();
}
public virtual void Start()
{
activeObjectives.Clear();
objectiveTranslated = TextManager.Get("Tutorial.Objective");
CreateObjectiveFrame();
// Setup doors: Clear all requirements, unless the door is setup as locked.
foreach (var item in Item.ItemList)
{
var door = item.GetComponent<Door>();
if (door != null)
{
if (door.requiredItems.Values.None(ris => ris.None(ri => ri.Identifiers.None(i => i == "locked"))))
{
door.requiredItems.Clear();
}
}
}
}
public virtual void AddToGUIUpdateList()
{
if (GameMain.GraphicsWidth != screenResolution.X || GameMain.GraphicsHeight != screenResolution.Y || prevUIScale != GUI.Scale)
{
CreateObjectiveFrame();
}
if (objectiveFrame != null && activeObjectives.Count > 0)
{
objectiveFrame.AddToGUIUpdateList(order: -1);
}
if (infoBox != null) infoBox.AddToGUIUpdateList(order: 100);
if (videoPlayer != null) videoPlayer.AddToGUIUpdateList(order: 100);
}
public virtual void Update(float deltaTime)
{
if (videoPlayer != null)
{
videoPlayer.Update();
}
if (activeObjectives != null)
{
for (int i = 0; i < activeObjectives.Count; i++)
{
CheckActiveObjectives(activeObjectives[i], deltaTime);
}
}
}
public void CloseActiveContentGUI()
{
if (videoPlayer.IsPlaying)
{
videoPlayer.Stop();
}
else if (infoBox != null)
{
CloseInfoFrame(null, null);
}
}
public virtual IEnumerable<object> UpdateState()
@@ -254,232 +134,6 @@ namespace Barotrauma.Tutorials
yield return CoroutineStatus.Success;
}
protected bool Restart(GUIButton button, object obj)
{
GUI.PreventPauseMenuToggle = false;
TutorialMode.StartTutorial(this);
return true;
}
protected virtual void TriggerTutorialSegment(int index, params object[] args)
{
Inventory.draggingItem = null;
ContentRunning = true;
activeContentSegment = segments[index];
segments[index].Args = args;
string tutorialText = TextManager.GetFormatted(activeContentSegment.TextContent.GetAttributeString("tag", ""), true, args);
tutorialText = TextManager.ParseInputTypes(tutorialText);
string objectiveText = string.Empty;
if (!string.IsNullOrEmpty(activeContentSegment.Objective))
{
if (args.Length == 0)
{
objectiveText = activeContentSegment.Objective;
}
else
{
objectiveText = string.Format(activeContentSegment.Objective, args);
}
objectiveText = TextManager.ParseInputTypes(objectiveText);
activeContentSegment.Objective = objectiveText;
}
else
{
activeContentSegment.IsTriggered = true; // Complete at this stage only if no related objective
}
switch (activeContentSegment.ContentType)
{
case TutorialContentTypes.None:
break;
case TutorialContentTypes.Video:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, () => LoadVideo(activeContentSegment));
break;
case TutorialContentTypes.ManualVideo:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, StopCurrentContentSegment, () => LoadVideo(activeContentSegment));
break;
case TutorialContentTypes.TextOnly:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, StopCurrentContentSegment);
break;
}
}
public virtual void Stop()
{
started = ContentRunning = Initialized = false;
infoBox = null;
if (videoPlayer != null)
{
videoPlayer.Remove();
videoPlayer = null;
}
}
#endregion
#region Objectives
private void CreateObjectiveFrame()
{
holderFrame = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center));
objectiveFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ObjectiveAnchor, holderFrame.RectTransform), style: null);
for (int i = 0; i < activeObjectives.Count; i++)
{
CreateObjectiveGUI(activeObjectives[i], i, activeObjectives[i].ContentType);
}
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
prevUIScale = GUI.Scale;
}
protected void StopCurrentContentSegment()
{
if (!string.IsNullOrEmpty(activeContentSegment.Objective))
{
AddNewObjective(activeContentSegment, activeContentSegment.ContentType);
}
activeContentSegment = null;
ContentRunning = false;
}
protected virtual void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
{
}
protected bool HasObjective(TutorialSegment segment)
{
return activeObjectives.Contains(segment);
}
protected void AddNewObjective(TutorialSegment segment, TutorialContentTypes type)
{
activeObjectives.Add(segment);
CreateObjectiveGUI(segment, activeObjectives.Count - 1, type);
}
private void CreateObjectiveGUI(TutorialSegment segment, int index, TutorialContentTypes type)
{
Point replayButtonSize = new Point((int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).X * GUI.Scale), (int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).Y * 1.45f * GUI.Scale));
segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopRight, Pivot.TopRight) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null);
segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) =>
{
if (type == TutorialContentTypes.Video)
{
ReplaySegmentVideo(segment);
}
else
{
ShowSegmentText(segment);
}
return true;
};
string objectiveText = TextManager.ParseInputTypes(objectiveTranslated);
int yOffset = (int)((GUI.ObjectiveNameFont.MeasureString(objectiveText).Y / 2f + 5));
segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point((int)GUI.ObjectiveNameFont.MeasureString(objectiveText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterRight, Pivot.BottomRight) { AbsoluteOffset = new Point((int)(-10 * GUI.Scale), 0) },
objectiveText, textColor: Color.White, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight);
segment.LinkedText = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.TopCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) },
TextManager.ParseInputTypes(segment.Objective), textColor: new Color(4, 180, 108), font: GUI.ObjectiveNameFont, textAlignment: Alignment.CenterRight);
segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent;
segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent;
segment.ReplayButton.Color = segment.ReplayButton.HoverColor = segment.ReplayButton.PressedColor = segment.ReplayButton.SelectedColor = Color.Transparent;
}
private void ReplaySegmentVideo(TutorialSegment segment)
{
if (ContentRunning) return;
ContentRunning = true;
LoadVideo(segment);
//videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, callback: () => ContentRunning = false);
}
private void ShowSegmentText(TutorialSegment segment)
{
if (ContentRunning) return;
Inventory.draggingItem = null;
ContentRunning = true;
string tutorialText = TextManager.GetFormatted(segment.TextContent.GetAttributeString("tag", ""), true, segment.Args);
Action videoAction = null;
if (segment.ContentType != TutorialContentTypes.TextOnly)
{
videoAction = () => LoadVideo(segment);
}
infoBox = CreateInfoFrame(TextManager.Get(segment.Id), tutorialText,
segment.TextContent.GetAttributeInt("width", 300),
segment.TextContent.GetAttributeInt("height", 80),
segment.TextContent.GetAttributeString("anchor", "Center"), true, () => ContentRunning = false, videoAction);
}
protected void RemoveCompletedObjective(TutorialSegment segment)
{
if (!HasObjective(segment)) return;
segment.IsTriggered = true;
segment.ReplayButton.OnClicked = null;
int checkMarkHeight = (int)(segment.ReplayButton.Rect.Height * 1.2f);
int checkMarkWidth = (int)(checkMarkHeight * 0.93f);
Color color = new Color(4, 180, 108);
int objectiveTextWidth = segment.LinkedText.Rect.Width;
int objectiveTitleWidth = segment.LinkedTitle.Rect.Width;
RectTransform rectTA;
if (objectiveTextWidth > objectiveTitleWidth)
{
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5, 0);
}
else
{
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5 - (objectiveTitleWidth), 0);
}
GUIImage checkmark = new GUIImage(rectTA, "CheckMark");
checkmark.Color = checkmark.SelectedColor = checkmark.HoverColor = checkmark.PressedColor = color;
RectTransform rectTB = new RectTransform(new Vector2(1.1f, .8f), segment.LinkedText.RectTransform, Anchor.Center, Pivot.Center);
GUIImage stroke = new GUIImage(rectTB, "Stroke");
stroke.Color = stroke.SelectedColor = stroke.HoverColor = stroke.PressedColor = color;
CoroutineManager.StartCoroutine(WaitForObjectiveEnd(segment));
}
private IEnumerable<object> WaitForObjectiveEnd(TutorialSegment objective)
{
yield return new WaitForSeconds(2.0f);
objectiveFrame.RemoveChild(objective.ReplayButton);
activeObjectives.Remove(objective);
for (int i = 0; i < activeObjectives.Count; i++)
{
activeObjectives[i].ReplayButton.RectTransform.AbsoluteOffset = new Point(0, (activeObjectives[i].ReplayButton.Rect.Height + 20) * i);
}
}
#endregion
#region InfoFrame
protected bool CloseInfoFrame(GUIButton button, object userData)
{
infoBox = null;
@@ -487,130 +141,87 @@ namespace Barotrauma.Tutorials
return true;
}
protected GUIComponent CreateInfoFrame(string title, string text, int width = 300, int height = 80, string anchorStr = "", bool hasButton = false, Action callback = null, Action showVideo = null)
protected GUIComponent CreateInfoFrame(string text, bool hasButton = false, Action callback = null)
{
if (hasButton) height += 60;
int width = 300;
int height = hasButton ? 110 : 80;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
height += wrappedText.Split('\n').Length * 25;
var infoBlock = new GUIFrame(new RectTransform(new Point(width, height), GUI.Canvas, Anchor.TopRight) { AbsoluteOffset = new Point(20) });
infoBlock.Flash(Color.Green);
var textBlock = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.7f), infoBlock.RectTransform, Anchor.Center),
text, wrap: true);
infoBoxClosedCallback = callback;
if (hasButton)
{
var okButton = new GUIButton(new RectTransform(new Point(160, 50), infoBlock.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { AbsoluteOffset = new Point(0, -10) },
TextManager.Get("OK"))
{
OnClicked = CloseInfoFrame
};
}
GUI.PlayUISound(GUISoundType.UIMessage);
return infoBlock;
}
protected GUIComponent CreateInfoFrame(string title, string text, int width, int height, string anchorStr, bool hasButton = false, Action callback = null)
{
if (hasButton) height += 30;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
height += (int)(GUI.Font.MeasureString(wrappedText).Y + 50);
height += wrappedText.Split('\n').Length * 25;
if (title.Length > 0)
{
height += 35;
}
Anchor anchor = Anchor.TopRight;
Enum.TryParse(anchorStr, out anchor);
if (anchorStr != string.Empty)
{
Enum.TryParse(anchorStr, out anchor);
}
var background = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center), "InnerFrame", new Color(0, 0, 0, 1f));
var infoBlock = new GUIFrame(new RectTransform(new Point((int)(width * GUI.Scale), (int)(height * GUI.Scale)), background.RectTransform, anchor) { AbsoluteOffset = new Point(20) });
var infoBlock = new GUIFrame(new RectTransform(new Point((int)(width * GUI.Scale), (int)(height * GUI.Scale)), GUI.Canvas, anchor) { AbsoluteOffset = new Point(20) });
infoBlock.Flash(Color.Green);
var infoContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), infoBlock.RectTransform, Anchor.Center))
{
Stretch = true,
AbsoluteSpacing = 5
};
if (title.Length > 0)
{
var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform),
title, font: GUI.VideoTitleFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
titleBlock.RectTransform.IsFixedSize = true;
var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1f, .35f), infoBlock.RectTransform, Anchor.TopCenter,
Pivot.TopCenter), title, font: GUI.VideoTitleFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
titleBlock.TextScale = GUI.Scale;
}
var textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoContent.RectTransform), text, wrap: true);
textBlock.RectTransform.IsFixedSize = true;
var textBlock = new GUITextBlock(new RectTransform(new Vector2(0.9f, 1f), infoBlock.RectTransform, Anchor.BottomCenter),
text, wrap: true);
textBlock.TextScale = GUI.Scale;
infoBoxClosedCallback = callback;
if (hasButton)
{
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.3f), infoContent.RectTransform) { MinSize = new Point(0, 30), MaxSize = new Point((int) infoContent.Rect.X, 60) }, isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.1f
};
buttonContainer.RectTransform.IsFixedSize = true;
if (showVideo != null)
{
var videoButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("Video"), style: "GUIButtonLarge")
{
OnClicked = (GUIButton button, object obj) =>
{
showVideo();
return true;
}
};
}
var okButton = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("OK"), style: "GUIButtonLarge")
var okButton = new GUIButton(new RectTransform(new Point(160, 50), infoBlock.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { AbsoluteOffset = new Point(0, -10) },
TextManager.Get("OK"))
{
OnClicked = CloseInfoFrame
};
}
infoBlock.RectTransform.NonScaledSize = new Point(infoBlock.Rect.Width, (int)(infoContent.Children.Sum(c => c.Rect.Height + infoContent.AbsoluteSpacing) / infoContent.RectTransform.RelativeSize.Y));
GUI.PlayUISound(GUISoundType.UIMessage);
return background;
}
#endregion
#region Video
protected void LoadVideo(TutorialSegment segment)
{
if (videoPlayer == null) videoPlayer = new VideoPlayer();
if (segment.ContentType != TutorialContentTypes.ManualVideo)
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, segment.Objective, StopCurrentContentSegment);
}
else
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), null, segment.Id, true, string.Empty, null);
}
}
#endregion
#region Highlights
protected void HighlightInventorySlot(Inventory inventory, string identifier, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
{
if (inventory.slots == null) { return; }
for (int i = 0; i < inventory.Items.Length; i++)
{
if (inventory.Items[i] != null && inventory.Items[i].Prefab.Identifier == identifier)
{
HighlightInventorySlot(inventory, i, color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
}
return infoBlock;
}
protected void HighlightInventorySlotWithTag(Inventory inventory, string tag, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
protected bool Restart(GUIButton button, object obj)
{
if (inventory.slots == null) { return; }
for (int i = 0; i < inventory.Items.Length; i++)
{
if (inventory.Items[i] != null && inventory.Items[i].HasTag(tag))
{
HighlightInventorySlot(inventory, i, color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
}
TutorialMode.StartTutorial(this);
return true;
}
protected void HighlightInventorySlot(Inventory inventory, int index, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
{
if (inventory.slots == null || index < 0 || inventory.slots[index].HighlightTimer > 0) return;
inventory.slots[index].ShowBorderHighlight(color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
#endregion
}
}

View File

@@ -4,7 +4,7 @@ namespace Barotrauma
{
class TutorialMode : GameMode
{
public Tutorial Tutorial;
public Tutorial tutorial;
public static void StartTutorial(Tutorial tutorial)
{
@@ -19,20 +19,18 @@ namespace Barotrauma
public override void Start()
{
base.Start();
GameMain.GameSession.CrewManager = new CrewManager(true);
Tutorial.Start();
tutorial.Start();
}
public override void AddToGUIUpdateList()
{
base.AddToGUIUpdateList();
Tutorial.AddToGUIUpdateList();
tutorial.AddToGUIUpdateList();
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
Tutorial.Update(deltaTime);
tutorial.Update(deltaTime);
}
}
}

View File

@@ -81,17 +81,10 @@ namespace Barotrauma
var leftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.25f, 1.0f), settingsFramePadding.RectTransform, Anchor.TopLeft));
var settingsTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform),
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), leftPanel.RectTransform),
TextManager.Get("Settings"), textAlignment: Alignment.TopLeft, font: GUI.LargeFont)
{ ForceUpperCase = true };
//TODO: enable when new texts can be added
/*new GUIButton(new RectTransform(new Vector2(1.0f, 0.75f), settingsTitle.RectTransform, Anchor.CenterRight), style: "GUIBugButton")
{
ToolTip = "Bug Reporter",
OnClicked = (btn, userdata) => { GameMain.Instance.ShowBugReporter(); return true; }
};*/
var generalLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), leftPanel.RectTransform, Anchor.TopLeft));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), generalLayoutGroup.RectTransform), TextManager.Get("ContentPackages"));
@@ -132,23 +125,18 @@ namespace Barotrauma
var languageDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.045f), generalLayoutGroup.RectTransform));
foreach (string language in TextManager.AvailableLanguages)
{
languageDD.AddItem(TextManager.Get("Language." + language, returnNull: true) ?? language, language);
languageDD.AddItem(TextManager.Get("Language." + language), language);
}
languageDD.SelectItem(TextManager.Language);
languageDD.OnSelected = (guiComponent, obj) =>
{
string newLanguage = obj as string;
if (newLanguage == Language) return true;
Language = newLanguage;
ApplySettings();
var msgBox = new GUIMessageBox(TextManager.Get("RestartRequiredLabel"), TextManager.Get("RestartRequiredLanguage"));
//change fonts to the default font of the new language to make sure
//they can be displayed when for example changing from English to Chinese
var defaultFont = GUI.Style.LoadCurrentDefaultFont();
msgBox.Header.Font = defaultFont;
msgBox.Text.Font = defaultFont;
UnsavedSettings = true;
Language = newLanguage;
new GUIMessageBox(TextManager.Get("RestartRequiredLabel"), TextManager.Get("RestartRequiredLanguage"));
return true;
};
@@ -169,7 +157,7 @@ namespace Barotrauma
{
UserData = tab
};
tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform),
tabButtons[(int)tab] = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonHolder.RectTransform),
TextManager.Get("SettingsTab." + tab.ToString()), style: "GUITabButton")
{
UserData = tab,
@@ -207,7 +195,7 @@ namespace Barotrauma
var resolutionDD = new GUIDropDown(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), elementCount: supportedDisplayModes.Count)
{
OnSelected = SelectResolution,
#if !LINUX
#if OSX
ButtonEnabled = GameMain.Config.WindowMode == WindowMode.Windowed
#endif
};
@@ -247,7 +235,7 @@ namespace Barotrauma
{
UnsavedSettings = true;
GameMain.Config.WindowMode = (WindowMode)guiComponent.UserData;
#if !LINUX
#if OSX
resolutionDD.ButtonEnabled = GameMain.Config.WindowMode == WindowMode.Windowed;
#endif
return true;
@@ -268,18 +256,6 @@ namespace Barotrauma
Selected = VSyncEnabled
};
//TODO: remove hardcoded texts after the texts have been added to localization
GUITickBox pauseOnFocusLostBox = new GUITickBox(new RectTransform(new Point(32, 32), leftColumn.RectTransform),
TextManager.Get("PauseOnFocusLost", returnNull: true) ?? "Pause on focus lost");
pauseOnFocusLostBox.Selected = PauseOnFocusLost;
pauseOnFocusLostBox.ToolTip = TextManager.Get("PauseOnFocusLostToolTip", returnNull: true) ?? "Pauses the game when its window is not in focus. Note that the game won't be paused when a multiplayer session is active.";
pauseOnFocusLostBox.OnSelected = (tickBox) =>
{
PauseOnFocusLost = tickBox.Selected;
UnsavedSettings = true;
return true;
};
GUITextBlock particleLimitText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform), TextManager.Get("ParticleLimit"));
GUIScrollBar particleScrollBar = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), rightColumn.RectTransform),
barSize: 0.1f)
@@ -455,7 +431,7 @@ namespace Barotrauma
UnsavedSettings = true;
return true;
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), audioSliders.RectTransform), TextManager.Get("VoiceChat"));
IList<string> deviceNames = Alc.GetString((IntPtr)null, AlcGetStringList.CaptureDeviceSpecifier);
@@ -664,7 +640,7 @@ namespace Barotrauma
return true;
}
};
var inputFrame = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.75f), controlsLayoutGroup.RectTransform), isHorizontal: true)
{ Stretch = true, RelativeSpacing = 0.03f };
@@ -674,15 +650,13 @@ namespace Barotrauma
{ Stretch = true, RelativeSpacing = 0.02f };
var inputNames = Enum.GetValues(typeof(InputType));
var inputNameBlocks = new List<GUITextBlock>();
for (int i = 0; i < inputNames.Length; i++)
{
var inputContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.06f),(i <= (inputNames.Length / 2.2f) ? inputColumnLeft : inputColumnRight).RectTransform))
{ Stretch = true, IsHorizontal = true, RelativeSpacing = 0.05f, Color = new Color(12, 14, 15, 215) };
var inputName = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), inputContainer.RectTransform, Anchor.TopLeft) { MinSize = new Point(150, 0) },
new GUITextBlock(new RectTransform(new Vector2(0.3f, 1.0f), inputContainer.RectTransform, Anchor.TopLeft) { MinSize = new Point(150, 0) },
TextManager.Get("InputType." + ((InputType)i)) + ": ", font: GUI.SmallFont) { ForceUpperCase = true };
inputNameBlocks.Add(inputName);
var keyBox = new GUITextBox(new RectTransform(new Vector2(0.3f, 1.0f), inputContainer.RectTransform),
var keyBox = new GUITextBox(new RectTransform(new Vector2(0.7f, 1.0f), inputContainer.RectTransform),
text: keyMapping[i].ToString(), font: GUI.SmallFont)
{
UserData = i
@@ -691,14 +665,12 @@ namespace Barotrauma
keyBox.SelectedColor = Color.Gold * 0.3f;
}
GUITextBlock.AutoScaleAndNormalize(inputNameBlocks);
var resetControlsHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.07f), controlsLayoutGroup.RectTransform), isHorizontal: true)
{
RelativeSpacing = 0.02f
};
var defaultBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetDefaultBindings"))
new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetDefaultBindings"))
{
ToolTip = TextManager.Get("SetDefaultBindingsToolTip"),
OnClicked = (button, data) =>
@@ -708,7 +680,7 @@ namespace Barotrauma
}
};
var legacyBindingsButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetLegacyBindings"))
new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), resetControlsHolder.RectTransform), TextManager.Get("SetLegacyBindings"))
{
ToolTip = TextManager.Get("SetLegacyBindingsToolTip"),
OnClicked = (button, data) =>
@@ -718,11 +690,6 @@ namespace Barotrauma
}
};
legacyBindingsButton.TextBlock.RectTransform.SizeChanged += () =>
{
GUITextBlock.AutoScaleAndNormalize(defaultBindingsButton.TextBlock, legacyBindingsButton.TextBlock);
};
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.02f), generalLayoutGroup.RectTransform), style: null);

View File

@@ -19,7 +19,7 @@ namespace Barotrauma
Right,
Center
}
private enum QuickUseAction
{
None,
@@ -34,8 +34,6 @@ namespace Barotrauma
}
private static Dictionary<InvSlotType, Sprite> limbSlotIcons;
const InvSlotType PersonalSlots = InvSlotType.Card | InvSlotType.Headset | InvSlotType.InnerClothes | InvSlotType.OuterClothes | InvSlotType.Head;
private Point screenResolution;
@@ -53,42 +51,11 @@ namespace Barotrauma
}
}
public bool Hidden { get; set; }
private bool hidePersonalSlots;
private float hidePersonalSlotsState;
private GUIButton hideButton;
private Rectangle personalSlotArea;
public bool HidePersonalSlots
{
get { return hidePersonalSlots; }
}
public Rectangle PersonalSlotArea
{
get { return personalSlotArea; }
}
partial void InitProjSpecific(XElement element)
{
Hidden = true;
hideButton = new GUIButton(new RectTransform(new Point((int)(30 * GUI.Scale), (int)(60 * GUI.Scale)), GUI.Canvas)
{ AbsoluteOffset = HUDLayoutSettings.CrewArea.Location },
"", style: "UIToggleButton");
hideButton.Children.ForEach(c => c.SpriteEffects = SpriteEffects.FlipHorizontally);
hideButton.OnClicked += (GUIButton btn, object userdata) =>
{
hidePersonalSlots = !hidePersonalSlots;
foreach (GUIComponent child in btn.Children)
{
child.SpriteEffects = hidePersonalSlots ? SpriteEffects.None : SpriteEffects.FlipHorizontally;
}
return true;
};
hidePersonalSlots = false;
if (limbSlotIcons == null)
{
limbSlotIcons = new Dictionary<InvSlotType, Sprite>();
@@ -100,13 +67,13 @@ namespace Barotrauma
limbSlotIcons.Add(InvSlotType.Head, new Sprite("Content/UI/IconAtlas.png", new Rectangle(896 + margin, 128 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.LeftHand, new Sprite("Content/UI/IconAtlas.png", new Rectangle(640 + margin, 383 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.RightHand, new Sprite("Content/UI/IconAtlas.png", new Rectangle(768 + margin, 383 + margin, 128 - margin * 2, 128 - margin * 2)));
limbSlotIcons.Add(InvSlotType.OuterClothes, new Sprite("Content/UI/IconAtlas.png", new Rectangle(768 + margin, 896 + margin, 128 - margin * 2, 128 - margin * 2)));
}
SlotPositions = new Vector2[SlotTypes.Length];
CurrentLayout = Layout.Default;
SetSlotPositions(layout);
}
protected override void PutItem(Item item, int i, Character user, bool removeItem = true, bool createNetworkEvent = true)
{
base.PutItem(item, i, user, removeItem, createNetworkEvent);
@@ -192,11 +159,6 @@ namespace Barotrauma
{
if (slots[i].Disabled || (hideEmptySlot[i] && Items[i] == null)) return true;
if (layout == Layout.Default)
{
if (PersonalSlots.HasFlag(SlotTypes[i]) && !personalSlotArea.Contains(slots[i].Rect.Center + slots[i].DrawOffset.ToPoint())) return true;
}
//no need to draw the right hand slot if the item is in both hands
if (Items[i] != null && SlotTypes[i] == InvSlotType.RightHand && IsInLimbSlot(Items[i], InvSlotType.LeftHand))
{
@@ -214,6 +176,7 @@ namespace Barotrauma
return false;
}
private void SetSlotPositions(Layout layout)
{
int spacing = (int)(10 * UIScale);
@@ -222,32 +185,27 @@ namespace Barotrauma
if (slots == null) CreateSlots();
hideButton.Visible = false;
var upperSlots = InvSlotType.Card | InvSlotType.Headset | InvSlotType.InnerClothes | InvSlotType.Head | InvSlotType.OuterClothes;
switch (layout)
{
case Layout.Default:
{
int personalSlotCount = SlotTypes.Count(s => PersonalSlots.HasFlag(s));
int normalSlotCount = SlotTypes.Count(s => !PersonalSlots.HasFlag(s));
int personalSlotCount = SlotTypes.Count(s => upperSlots.HasFlag(s));
int normalSlotCount = SlotTypes.Count(s => !upperSlots.HasFlag(s));
int x = GameMain.GraphicsWidth / 2 - normalSlotCount * (slotSize.X + spacing) / 2;
int upperX = HUDLayoutSettings.PortraitArea.X - slotSize.X * 2;
int upperX = HUDLayoutSettings.PortraitArea.X - slotSize.X;
//make sure the rightmost normal slot doesn't overlap with the personal slots
x -= Math.Max((x + normalSlotCount * (slotSize.X + spacing)) - (upperX - personalSlotCount * (slotSize.X + spacing)), 0);
int hideButtonSlotIndex = -1;
for (int i = 0; i < SlotPositions.Length; i++)
{
if (PersonalSlots.HasFlag(SlotTypes[i]))
if (upperSlots.HasFlag(SlotTypes[i]))
{
SlotPositions[i] = new Vector2(upperX, GameMain.GraphicsHeight - bottomOffset);
upperX -= slotSize.X + spacing;
personalSlotArea = (hideButtonSlotIndex == -1) ?
new Rectangle(SlotPositions[i].ToPoint(), slotSize) :
Rectangle.Union(personalSlotArea, new Rectangle(SlotPositions[i].ToPoint(), slotSize));
hideButtonSlotIndex = i;
}
else
{
@@ -255,29 +213,19 @@ namespace Barotrauma
x += slotSize.X + spacing;
}
}
if (hideButtonSlotIndex > -1)
{
hideButton.RectTransform.SetPosition(Anchor.TopLeft, Pivot.TopLeft);
hideButton.RectTransform.NonScaledSize = new Point(slotSize.X / 2, slotSize.Y + slots[hideButtonSlotIndex].EquipButtonRect.Height);
hideButton.RectTransform.AbsoluteOffset = new Point(
personalSlotArea.Right + spacing,
personalSlotArea.Y - slots[hideButtonSlotIndex].EquipButtonRect.Height);
hideButton.Visible = true;
}
}
break;
case Layout.Right:
{
int extraOffset = 0;
int x = HUDLayoutSettings.InventoryAreaLower.Right;
int personalSlotX = HUDLayoutSettings.InventoryAreaLower.Right - slotSize.X - spacing;
int upperX = HUDLayoutSettings.InventoryAreaLower.Right;
for (int i = 0; i < slots.Length; i++)
{
if (HideSlot(i)) continue;
if (PersonalSlots.HasFlag(SlotTypes[i]))
if (upperSlots.HasFlag(SlotTypes[i]))
{
//upperX -= slotSize.X + spacing;
upperX -= slotSize.X + spacing;
}
else
{
@@ -289,10 +237,10 @@ namespace Barotrauma
for (int i = 0; i < SlotPositions.Length; i++)
{
if (HideSlot(i)) continue;
if (PersonalSlots.HasFlag(SlotTypes[i]))
if (upperSlots.HasFlag(SlotTypes[i]))
{
SlotPositions[i] = new Vector2(personalSlotX, GameMain.GraphicsHeight - bottomOffset * 2 - extraOffset - spacing * 2);
personalSlotX -= slots[i].Rect.Width + spacing;
SlotPositions[i] = new Vector2(upperX, GameMain.GraphicsHeight - bottomOffset * 2 - extraOffset - spacing * 2);
upperX += slots[i].Rect.Width + spacing;
}
else
{
@@ -313,14 +261,14 @@ namespace Barotrauma
case Layout.Left:
{
int x = HUDLayoutSettings.InventoryAreaLower.X;
int personalSlotX = x;
int upperX = x;
for (int i = 0; i < SlotPositions.Length; i++)
{
if (HideSlot(i)) continue;
if (PersonalSlots.HasFlag(SlotTypes[i]))
if (upperSlots.HasFlag(SlotTypes[i]))
{
SlotPositions[i] = new Vector2(personalSlotX, GameMain.GraphicsHeight - bottomOffset * 2 - spacing * 2);
personalSlotX += slots[i].Rect.Width + spacing;
SlotPositions[i] = new Vector2(upperX, GameMain.GraphicsHeight - bottomOffset * 2 - spacing * 2);
upperX += slots[i].Rect.Width + spacing;
}
else
{
@@ -406,27 +354,6 @@ namespace Barotrauma
((selectedSlot != null && selectedSlot.IsSubSlot) || (draggingItem != null && (draggingSlot == null || !draggingSlot.MouseOn())));
if (CharacterHealth.OpenHealthWindow != null) hoverOnInventory = true;
if (layout == Layout.Default && hideButton.Visible)
{
hideButton.AddToGUIUpdateList();
hideButton.UpdateManually(deltaTime, alsoChildren: true);
hidePersonalSlotsState = hidePersonalSlots ?
Math.Min(hidePersonalSlotsState + deltaTime * 5.0f, 1.0f) :
Math.Max(hidePersonalSlotsState - deltaTime * 5.0f, 0.0f);
for (int i = 0; i < slots.Length; i++)
{
if (!PersonalSlots.HasFlag(SlotTypes[i])) { continue; }
if (HidePersonalSlots)
{
if (selectedSlot?.Slot == slots[i]) { selectedSlot = null; }
highlightedSubInventorySlots.RemoveWhere(s => s.Slot == slots[i]);
}
slots[i].DrawOffset = Vector2.Lerp(Vector2.Zero, new Vector2(personalSlotArea.Width, 0.0f), hidePersonalSlotsState);
}
}
if (hoverOnInventory) HideTimer = 0.5f;
if (HideTimer > 0.0f) HideTimer -= deltaTime;
@@ -439,23 +366,7 @@ namespace Barotrauma
QuickUseItem(Items[i], true, false, true);
}
}
//force personal slots open if an item is running out of battery/fuel/oxygen/etc
if (hidePersonalSlots)
{
for (int i = 0; i < slots.Length; i++)
{
if (Items[i]?.OwnInventory != null && Items[i].OwnInventory.Capacity == 1 && PersonalSlots.HasFlag(SlotTypes[i]))
{
if (Items[i].OwnInventory.Items[0].Condition > 0.0f &&
Items[i].OwnInventory.Items[0].Condition / Items[i].OwnInventory.Items[0].MaxCondition < 0.15f)
{
hidePersonalSlots = false;
}
}
}
}
List<SlotReference> hideSubInventories = new List<SlotReference>();
foreach (var highlightedSubInventorySlot in highlightedSubInventorySlots)
{
@@ -792,12 +703,7 @@ namespace Barotrauma
}
base.Draw(spriteBatch);
if (hideButton != null && hideButton.Visible && !Locked)
{
hideButton.DrawManually(spriteBatch, alsoChildren: true);
}
InventorySlot highlightedQuickUseSlot = null;
for (int i = 0; i < capacity; i++)
{
@@ -811,7 +717,7 @@ namespace Barotrauma
if (limbSlotIcons.ContainsKey(SlotTypes[i]))
{
var icon = limbSlotIcons[SlotTypes[i]];
icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2() + slots[i].DrawOffset, Color.White * 0.3f, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X);
icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2(), Color.White * 0.3f, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X);
}
continue;
}
@@ -821,12 +727,12 @@ namespace Barotrauma
if (IsInLimbSlot(Items[i], InvSlotType.LeftHand))
{
var icon = limbSlotIcons[InvSlotType.LeftHand];
icon.Draw(spriteBatch, new Vector2(slots[i].Rect.X, slots[i].Rect.Bottom) + slots[i].DrawOffset, Color.White * 0.6f, origin: new Vector2(icon.size.X * 0.35f, icon.size.Y * 0.75f), scale: slots[i].Rect.Width / icon.size.X * 0.7f);
icon.Draw(spriteBatch, new Vector2(slots[i].Rect.X, slots[i].Rect.Bottom), Color.White * 0.6f, origin: new Vector2(icon.size.X * 0.35f, icon.size.Y * 0.75f), scale: slots[i].Rect.Width / icon.size.X * 0.7f);
}
if (IsInLimbSlot(Items[i], InvSlotType.RightHand))
{
var icon = limbSlotIcons[InvSlotType.RightHand];
icon.Draw(spriteBatch, new Vector2(slots[i].Rect.Right, slots[i].Rect.Bottom) + slots[i].DrawOffset, Color.White * 0.6f, origin: new Vector2(icon.size.X * 0.65f, icon.size.Y * 0.75f), scale: slots[i].Rect.Width / icon.size.X * 0.7f);
icon.Draw(spriteBatch, new Vector2(slots[i].Rect.Right, slots[i].Rect.Bottom), Color.White * 0.6f, origin: new Vector2(icon.size.X * 0.65f, icon.size.Y * 0.75f), scale: slots[i].Rect.Width / icon.size.X * 0.7f);
}
Color color = slots[i].EquipButtonState == GUIComponent.ComponentState.Pressed ? Color.Gray : Color.White * 0.8f;
@@ -835,7 +741,6 @@ namespace Barotrauma
color = Color.White;
highlightedQuickUseSlot = slots[i];
}
if (Locked) { color *= 0.3f; }
var quickUseIndicator = Items[i].AllowedSlots.Any(a => a == InvSlotType.Any) ?
EquipIndicator : DropIndicator;

View File

@@ -227,9 +227,10 @@ namespace Barotrauma.Items.Components
}
return;
}
if (!sounds.TryGetValue(type, out List<ItemSound> matchingSounds)) return;
ItemSound itemSound = null;
var matchingSounds = sounds[type];
if (loopingSoundChannel == null || !loopingSoundChannel.IsPlaying)
{
SoundSelectionMode soundSelectionMode = soundSelectionModes[type];
@@ -264,7 +265,7 @@ namespace Barotrauma.Items.Components
private void PlaySound(ItemSound itemSound, Vector2 position, Character user = null)
{
if (Vector2.DistanceSquared(new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y), position) > itemSound.Range * itemSound.Range)
if (Vector3.DistanceSquared(GameMain.SoundManager.ListenerPosition, new Vector3(position.X, position.Y, 0.0f)) > itemSound.Range * itemSound.Range)
{
return;
}
@@ -292,7 +293,7 @@ namespace Barotrauma.Items.Components
{
float volume = GetSoundVolume(itemSound);
if (volume <= 0.0f) return;
SoundPlayer.PlaySound(itemSound.RoundSound.Sound, position, volume, itemSound.Range, item.CurrentHull);
SoundPlayer.PlaySound(itemSound.RoundSound.Sound, volume, itemSound.Range, position, item.CurrentHull);
}
}
@@ -379,13 +380,9 @@ namespace Barotrauma.Items.Components
public virtual void UpdateHUD(Character character, float deltaTime, Camera cam) { }
public virtual void CreateEditingHUD(SerializableEntityEditor editor)
public ItemComponent GetLinkUIToComponent()
{
}
private bool LoadElemProjSpecific(XElement subElement)
{
switch (subElement.Name.ToString().ToLowerInvariant())
if (string.IsNullOrEmpty(LinkUIToComponent))
{
case "guiframe":
if (subElement.Attribute("rect") != null)

View File

@@ -28,7 +28,7 @@ namespace Barotrauma.Items.Components
}
private string text;
[Serialize("", true, translationTextTag: "Label."), Editable(100)]
[Serialize("", true), Editable(100)]
public string Text
{
get { return text; }
@@ -40,10 +40,9 @@ namespace Barotrauma.Items.Components
{
textBlock = null;
}
text = value;
DisplayText = TextManager.Get(text, returnNull: true) ?? value;
TextBlock.Text = DisplayText;
TextBlock.Text = value;
SetScrollingText();
}
}
@@ -122,7 +121,7 @@ namespace Barotrauma.Items.Components
{
if (!scrollable) return;
float totalWidth = textBlock.Font.MeasureString(DisplayText).X;
float totalWidth = textBlock.Font.MeasureString(text).X;
float textAreaWidth = Math.Max(textBlock.Rect.Width - textBlock.Padding.X - textBlock.Padding.Z, 0);
if (totalWidth >= textAreaWidth)
{
@@ -130,13 +129,13 @@ namespace Barotrauma.Items.Components
//(so the text can scroll entirely out of view before we reset it back to start)
needsScrolling = true;
float spaceWidth = textBlock.Font.MeasureChar(' ').X;
scrollingText = new string(' ', (int)Math.Ceiling(textAreaWidth / spaceWidth)) + DisplayText;
scrollingText = new string(' ', (int)Math.Ceiling(textAreaWidth / spaceWidth)) + text;
}
else
{
//whole text can fit in the textblock, no need to scroll
needsScrolling = false;
scrollingText = DisplayText;
scrollingText = text;
scrollAmount = 0.0f;
scrollIndex = 0;
return;
@@ -152,7 +151,7 @@ namespace Barotrauma.Items.Components
charWidths[i] = charWidth;
}
scrollIndex = MathHelper.Clamp(scrollIndex, 0, DisplayText.Length);
scrollIndex = MathHelper.Clamp(scrollIndex, 0, text.Length);
}
public override void Update(float deltaTime, Camera cam)

View File

@@ -23,7 +23,7 @@ namespace Barotrauma.Items.Components
{
if (light.LightSprite != null && (item.body == null || item.body.Enabled) && lightBrightness > 0.0f)
{
light.LightSprite.Draw(spriteBatch, new Vector2(item.DrawPosition.X, -item.DrawPosition.Y), lightColor * lightBrightness, 0.0f, item.Scale, SpriteEffects.None, item.SpriteDepth - 0.0001f);
light.LightSprite.Draw(spriteBatch, new Vector2(item.DrawPosition.X, -item.DrawPosition.Y), lightColor * lightBrightness, 0.0f, 1.0f, Microsoft.Xna.Framework.Graphics.SpriteEffects.None, item.SpriteDepth - 0.0001f);
}
}

View File

@@ -9,10 +9,6 @@ namespace Barotrauma.Items.Components
{
partial class Deconstructor : Powered, IServerSerializable, IClientSerializable
{
public GUIButton ActivateButton
{
get { return activateButton; }
}
private GUIButton activateButton;
private GUIComponent inputInventoryHolder, outputInventoryHolder;
private GUICustomComponent inputInventoryOverlay;
@@ -48,6 +44,7 @@ namespace Barotrauma.Items.Components
Visible = false,
CanBeFocused = false
};
outputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.3f), paddedFrame.RectTransform), style: null);
}
@@ -74,7 +71,7 @@ namespace Barotrauma.Items.Components
public override void UpdateHUD(Character character, float deltaTime, Camera cam)
{
inSufficientPowerWarning.Visible = powerConsumption > 0 && voltage < minVoltage;
//activateButton.Enabled = !inSufficientPowerWarning.Visible;
activateButton.Enabled = !inSufficientPowerWarning.Visible;
}
private bool ToggleActive(GUIButton button, object obj)

View File

@@ -30,25 +30,25 @@ namespace Barotrauma.Items.Components
partial void InitProjSpecific(XElement element)
{
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center))
{
Stretch = true,
RelativeSpacing = 0.05f
};
powerIndicator = new GUITickBox(new RectTransform(new Point(30, 30), content.RectTransform),
powerIndicator = new GUITickBox(new RectTransform(new Point(30, 30), GuiFrame.RectTransform) { RelativeOffset = new Vector2(0.05f, 0.15f) },
TextManager.Get("EnginePowered"), style: "IndicatorLightGreen")
{
CanBeFocused = false
};
string powerLabel = TextManager.Get("EngineForce");
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform), "", textAlignment: Alignment.Center)
new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.3f), GuiFrame.RectTransform, Anchor.BottomCenter)
{ RelativeOffset = new Vector2(0.0f, 0.4f) }, "", textAlignment: Alignment.Center)
{
TextGetter = () => { return powerLabel + ": " + (int)(targetForce) + " %"; }
};
forceSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform), barSize: 0.2f, style: "GUISlider")
var sliderArea = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.25f), GuiFrame.RectTransform, Anchor.BottomCenter)
{ RelativeOffset = new Vector2(0.0f, 0.2f) }, isHorizontal: true);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), sliderArea.RectTransform), TextManager.Get("EngineBackwards"),
font: GUI.SmallFont, textAlignment: Alignment.Center);
forceSlider = new GUIScrollBar(new RectTransform(new Vector2(0.6f, 1.0f), sliderArea.RectTransform), barSize: 0.25f, style: "GUISlider")
{
Step = 0.05f,
OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -66,16 +66,8 @@ namespace Barotrauma.Items.Components
return true;
}
};
var textArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), content.RectTransform), isHorizontal: true)
{
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textArea.RectTransform), TextManager.Get("EngineBackwards"),
font: GUI.SmallFont, textAlignment: Alignment.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), textArea.RectTransform), TextManager.Get("EngineForwards"),
font: GUI.SmallFont, textAlignment: Alignment.CenterRight);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), sliderArea.RectTransform), TextManager.Get("EngineForwards"),
font: GUI.SmallFont, textAlignment: Alignment.Center);
foreach (XElement subElement in element.Elements())
{

View File

@@ -15,10 +15,6 @@ namespace Barotrauma.Items.Components
private GUIFrame selectedItemFrame;
public GUIButton ActivateButton
{
get { return activateButton; }
}
private GUIButton activateButton;
private GUITextBox itemFilterBox;
@@ -26,10 +22,6 @@ namespace Barotrauma.Items.Components
private GUIComponent inputInventoryHolder, outputInventoryHolder;
private GUICustomComponent inputInventoryOverlay, outputInventoryOverlay;
public FabricationRecipe SelectedItem
{
get { return selectedItem; }
}
private FabricationRecipe selectedItem;
private GUIComponent inSufficientPowerWarning;
@@ -81,31 +73,7 @@ namespace Barotrauma.Items.Components
{
CanBeFocused = false
};
CreateRecipes();
activateButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.07f), paddedFrame.RectTransform),
TextManager.Get("FabricatorCreate"), style: "GUIButtonLarge")
{
OnClicked = StartButtonClicked,
UserData = selectedItem,
Enabled = false
};
inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("FabricatorNoPower"),
textColor: Color.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow")
{
HoverColor = Color.Black,
IgnoreLayoutGroups = true,
Visible = false,
CanBeFocused = false
};
}
partial void CreateRecipes()
{
itemList.Content.RectTransform.ClearChildren();
foreach (FabricationRecipe fi in fabricationRecipes)
{
GUIFrame frame = new GUIFrame(new RectTransform(new Point(itemList.Rect.Width, 30), itemList.Content.RectTransform), style: null)
@@ -133,6 +101,23 @@ namespace Barotrauma.Items.Components
};
}
}
activateButton = new GUIButton(new RectTransform(new Vector2(0.8f, 0.07f), paddedFrame.RectTransform),
TextManager.Get("FabricatorCreate"), style: "GUIButtonLarge")
{
OnClicked = StartButtonClicked,
UserData = selectedItem,
Enabled = false
};
inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), TextManager.Get("FabricatorNoPower"),
textColor: Color.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow")
{
HoverColor = Color.Black,
IgnoreLayoutGroups = true,
Visible = false,
CanBeFocused = false
};
}
partial void OnItemLoadedProjSpecific()
@@ -164,15 +149,13 @@ namespace Barotrauma.Items.Components
return string.Compare(item1.DisplayName, item2.DisplayName);
});
var sufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform),
TextManager.Get("fabricatorsufficientskills", returnNull: true) ?? "Sufficient skills to fabricate", textColor: Color.LightGreen)
var sufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform), "Sufficient skills to fabricate:", textColor: Color.LightGreen)
{
CanBeFocused = false
};
sufficientSkillsText.RectTransform.SetAsFirstChild();
var insufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform),
TextManager.Get("fabricatorinsufficientskills", returnNull: true) ?? "Insufficient skills to fabricate", textColor: Color.Orange)
var insufficientSkillsText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), itemList.Content.RectTransform), "Insufficient skills to fabricate:", textColor: Color.Orange)
{
CanBeFocused = false
};
@@ -258,7 +241,6 @@ namespace Barotrauma.Items.Components
}
}
}
private void DrawOutputOverLay(SpriteBatch spriteBatch, GUICustomComponent overlayComponent)
{
overlayComponent.RectTransform.SetAsLastChild();
@@ -381,29 +363,6 @@ namespace Barotrauma.Items.Components
return true;
}
public void HighlightRecipe(string identifier, Color color)
{
foreach (GUIComponent child in itemList.Content.Children)
{
FabricationRecipe recipe = child.UserData as FabricationRecipe;
if (recipe?.DisplayName == null) { continue; }
if (recipe.TargetItem.Identifier == identifier)
{
if (child.FlashTimer > 0.0f) return;
child.Flash(color, 1.5f, false);
for (int i = 0; i < child.CountChildren; i++)
{
var grandChild = child.GetChild(i);
if (grandChild is GUITextBlock) continue;
grandChild.Flash(color, 1.5f, false);
}
return;
}
}
}
private bool StartButtonClicked(GUIButton button, object obj)
{
if (selectedItem == null) { return false; }

View File

@@ -221,7 +221,7 @@ namespace Barotrauma.Items.Components
{
hullInfoFrame.RectTransform.ScreenSpaceOffset = hullFrame.Rect.Center;
hullInfoFrame.Visible = true;
hullNameText.Text = hull.DisplayName;
hullNameText.Text = hull.RoomName;
foreach (Hull linkedHull in hullData.LinkedHulls)
{

View File

@@ -10,10 +10,6 @@ namespace Barotrauma.Items.Components
{
partial class Pump : Powered, IServerSerializable, IClientSerializable
{
public GUIScrollBar IsActiveSlider
{
get { return isActiveSlider; }
}
private GUIScrollBar isActiveSlider;
private GUIScrollBar pumpSpeedSlider;
private GUITickBox powerIndicator;
@@ -53,6 +49,7 @@ namespace Barotrauma.Items.Components
};
var sliderHandle = isActiveSlider.GetChild<GUIButton>();
sliderHandle.RectTransform.NonScaledSize = new Point(84, sliderHandle.Rect.Height);
isActiveSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
bool active = scrollBar.BarScroll < 0.5f;
@@ -78,8 +75,8 @@ namespace Barotrauma.Items.Components
CanBeFocused = false
};
var pumpSpeedText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), rightArea.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.0f) },
"", textAlignment: Alignment.BottomLeft, wrap: true);
var pumpSpeedText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), rightArea.RectTransform) { RelativeOffset = new Vector2(0.25f, 0.0f) },
"", textAlignment: Alignment.BottomLeft);
string pumpSpeedStr = TextManager.Get("PumpSpeed");
pumpSpeedText.TextGetter = () => { return pumpSpeedStr + ": " + (int)flowPercentage + " %"; };
@@ -90,7 +87,7 @@ namespace Barotrauma.Items.Components
};
new GUITextBlock(new RectTransform(new Vector2(0.15f, 1.0f), sliderArea.RectTransform),
TextManager.Get("PumpOut"), textAlignment: Alignment.Center, wrap: true);
TextManager.Get("PumpOut"), textAlignment: Alignment.Center);
pumpSpeedSlider = new GUIScrollBar(new RectTransform(new Vector2(0.8f, 1.0f), sliderArea.RectTransform), barSize: 0.25f, style: "GUISlider")
{
Step = 0.05f,
@@ -111,7 +108,7 @@ namespace Barotrauma.Items.Components
};
new GUITextBlock(new RectTransform(new Vector2(0.15f, 1.0f), sliderArea.RectTransform),
TextManager.Get("PumpIn"), textAlignment: Alignment.Center, wrap: true);
TextManager.Get("PumpIn"), textAlignment: Alignment.Center);
}
public override void OnItemLoaded()

View File

@@ -11,16 +11,7 @@ namespace Barotrauma.Items.Components
{
partial class Reactor : Powered, IServerSerializable, IClientSerializable
{
public GUIScrollBar AutoTempSlider
{
get { return autoTempSlider; }
}
private GUIScrollBar autoTempSlider;
public GUIScrollBar OnOffSwitch
{
get { return onOffSwitch; }
}
private GUIScrollBar onOffSwitch;
private const int GraphSize = 25;
@@ -36,16 +27,7 @@ namespace Barotrauma.Items.Components
private Sprite graphLine;
public GUIScrollBar FissionRateScrollBar
{
get { return fissionRateScrollBar; }
}
private GUIScrollBar fissionRateScrollBar;
public GUIScrollBar TurbineOutputScrollBar
{
get { return turbineOutputScrollBar; }
}
private GUIScrollBar turbineOutputScrollBar;
private float[] outputGraph = new float[GraphSize];
@@ -110,8 +92,8 @@ namespace Barotrauma.Items.Components
GUIFrame columnLeft = new GUIFrame(new RectTransform(new Vector2(0.2f, 1.0f), paddedFrame.RectTransform), style: null);
leftHUDColumn = columnLeft;
GUIFrame columnMid = new GUIFrame(new RectTransform(new Vector2(0.5f, 1.0f), paddedFrame.RectTransform), style: null);
GUIFrame columnRight = new GUIFrame(new RectTransform(new Vector2(0.3f, 1.0f), paddedFrame.RectTransform), style: null);
GUIFrame columnMid = new GUIFrame(new RectTransform(new Vector2(0.45f, 1.0f), paddedFrame.RectTransform), style: null);
GUIFrame columnRight = new GUIFrame(new RectTransform(new Vector2(0.35f, 1.0f), paddedFrame.RectTransform), style: null);
//----------------------------------------------------------
//left column
@@ -136,7 +118,6 @@ namespace Barotrauma.Items.Components
btnText.SetTextPos();
warningButtons.Add(warningTexts[i], warningBtn);
}
GUITextBlock.AutoScaleAndNormalize(warningButtons.Values.Select(b => b.TextBlock));
inventoryContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.45f), columnLeft.RectTransform, Anchor.BottomLeft), style: null);
@@ -144,37 +125,33 @@ namespace Barotrauma.Items.Components
//mid column
//----------------------------------------------------------
criticalHeatWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, 30), columnMid.RectTransform),
criticalHeatWarning = new GUITickBox(new RectTransform(new Point(30, 30), columnMid.RectTransform),
TextManager.Get("ReactorWarningCriticalTemp"), font: GUI.SmallFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
lowTemperatureWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, 30), columnMid.RectTransform) { RelativeOffset = new Vector2(0.27f, 0.0f) },
lowTemperatureWarning = new GUITickBox(new RectTransform(new Point(30, 30), columnMid.RectTransform) { RelativeOffset = new Vector2(0.3f, 0.0f) },
TextManager.Get("ReactorWarningCriticalLowTemp"), font: GUI.SmallFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
criticalOutputWarning = new GUITickBox(new RectTransform(new Point(columnMid.Rect.Width / 3, 30), columnMid.RectTransform) { RelativeOffset = new Vector2(0.66f, 0.0f) },
criticalOutputWarning = new GUITickBox(new RectTransform(new Point(30, 30), columnMid.RectTransform) { RelativeOffset = new Vector2(0.75f, 0.0f) },
TextManager.Get("ReactorWarningCriticalOutput"), font: GUI.SmallFont, style: "IndicatorLightRed")
{
CanBeFocused = false
};
GUITextBlock.AutoScaleAndNormalize(criticalHeatWarning.TextBlock, lowTemperatureWarning.TextBlock, criticalOutputWarning.TextBlock);
float gaugeOffset = criticalHeatWarning.Rect.Height / (float)columnMid.Rect.Height + 0.05f;
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, gaugeOffset) },
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.25f) },
TextManager.Get("ReactorFissionRate"));
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, gaugeOffset + 0.05f) },
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.3f) },
DrawFissionRateMeter, null)
{
ToolTip = TextManager.Get("ReactorTipFissionRate")
};
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, gaugeOffset) },
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.05f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, 0.25f) },
TextManager.Get("ReactorTurbineOutput"));
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, gaugeOffset + 0.05f) },
new GUICustomComponent(new RectTransform(new Vector2(0.5f, 0.5f), columnMid.RectTransform, Anchor.TopRight) { RelativeOffset = new Vector2(0.0f, 0.3f) },
DrawTurbineOutputMeter, null)
{
ToolTip = TextManager.Get("ReactorTipTurbineOutput")
@@ -214,13 +191,12 @@ namespace Barotrauma.Items.Components
//right column
//----------------------------------------------------------
new GUITextBlock(new RectTransform(new Vector2(0.7f, 0.1f), columnRight.RectTransform), TextManager.Get("ReactorAutoTemp"))
new GUITextBlock(new RectTransform(new Point(100, 20), columnRight.RectTransform), TextManager.Get("ReactorAutoTemp"))
{
ToolTip = TextManager.Get("ReactorTipAutoTemp"),
AutoScale = true
ToolTip = TextManager.Get("ReactorTipAutoTemp")
};
autoTempSlider = new GUIScrollBar(new RectTransform(new Vector2(0.6f, 0.15f), columnRight.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.1f) },
barSize: 0.55f, style: "OnOffSlider", isHorizontal: true)
autoTempSlider = new GUIScrollBar(new RectTransform(new Point(100, 30), columnRight.RectTransform) { AbsoluteOffset = new Point(0, 30) },
barSize: 0.5f, style: "OnOffSlider")
{
ToolTip = TextManager.Get("ReactorTipAutoTemp"),
IsBooleanSwitch = true,
@@ -232,11 +208,9 @@ namespace Barotrauma.Items.Components
return true;
}
};
var sliderSprite = autoTempSlider.Frame.Style.Sprites[GUIComponent.ComponentState.None].First();
autoTempSlider.RectTransform.MaxSize = sliderSprite.Sprite.SourceRect.Size;
onOffSwitch = new GUIScrollBar(new RectTransform(new Vector2(0.4f, 0.3f), columnRight.RectTransform, Anchor.TopRight),
barSize: 0.2f, style: "OnOffLever", isHorizontal: false)
onOffSwitch = new GUIScrollBar(new RectTransform(new Point(50, 80), columnRight.RectTransform, Anchor.TopRight),
barSize: 0.2f, style: "OnOffLever")
{
IsBooleanSwitch = true,
MinValue = 0.25f,
@@ -248,8 +222,6 @@ namespace Barotrauma.Items.Components
return true;
}
};
var switchSprite = onOffSwitch.Frame.Style.Sprites[GUIComponent.ComponentState.None].First();
onOffSwitch.RectTransform.MaxSize = switchSprite.Sprite.SourceRect.Size;
var lever = onOffSwitch.GetChild<GUIButton>();
lever.RectTransform.NonScaledSize = new Point(lever.Rect.Width + 30, lever.Rect.Height);
@@ -582,8 +554,6 @@ namespace Barotrauma.Items.Components
fissionRateScrollBar.BarScroll = targetFissionRate / 100.0f;
turbineOutputScrollBar.BarScroll = targetTurbineOutput / 100.0f;
onOffSwitch.BarScroll = shutDown ? Math.Max(onOffSwitch.BarScroll, 0.55f) : Math.Min(onOffSwitch.BarScroll, 0.45f);
IsActive = true;
}
}
}

View File

@@ -17,15 +17,9 @@ namespace Barotrauma.Items.Components
Passive
};
private bool dynamicDockingIndicator = true;
private bool unsentChanges;
private float networkUpdateTimer;
public GUITickBox ActiveTickBox
{
get { return activeTickBox; }
}
private GUITickBox activeTickBox, passiveTickBox;
private GUITextBlock signalWarningText;
@@ -66,8 +60,6 @@ namespace Barotrauma.Items.Components
new Color(255, 255, 255)
};
private float prevDockingDist;
public Vector2 DisplayOffset { get; private set; }
public float DisplayRadius { get; private set; }
@@ -175,31 +167,6 @@ namespace Barotrauma.Items.Components
sonarMode.Selected = Mode.Passive;
GuiFrame.CanBeFocused = false;
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "pingcircle":
pingCircle = new Sprite(subElement);
break;
case "directionalpingcircle":
directionalPingCircle = new Sprite(subElement);
break;
case "screenoverlay":
screenOverlay = new Sprite(subElement);
break;
case "screenbackground":
screenBackground = new Sprite(subElement);
break;
case "blip":
sonarBlip = new Sprite(subElement);
break;
case "linesprite":
lineSprite = new Sprite(subElement);
break;
}
}
}
public override void OnItemLoaded()
@@ -264,7 +231,8 @@ namespace Barotrauma.Items.Components
return;
}
Vector2 transducerCenter = GetTransducerPos() + DisplayOffset;
Vector2 transducerCenter = UseTransducers ? GetTransducerCenter() : item.WorldPosition;
transducerCenter += DisplayOffset;
if (Level.Loaded != null)
{
@@ -313,31 +281,8 @@ namespace Barotrauma.Items.Components
sonarBlips.Add(flowBlip);
}
}
}
Steering steering = item.GetComponent<Steering>();
if (steering != null && steering.DockingModeEnabled)
{
float dockingDist = Vector2.Distance(steering.DockingSource.Item.WorldPosition, steering.DockingTarget.Item.WorldPosition);
if (prevDockingDist > steering.DockingAssistThreshold && dockingDist <= steering.DockingAssistThreshold)
{
zoom = Math.Max(zoom, MathHelper.Lerp(MinZoom, MaxZoom, 0.25f));
}
else if (prevDockingDist > steering.DockingAssistThreshold * 0.75f && dockingDist <= steering.DockingAssistThreshold * 0.75f)
{
zoom = Math.Max(zoom, MathHelper.Lerp(MinZoom, MaxZoom, 0.5f));
}
else if (prevDockingDist > steering.DockingAssistThreshold * 0.5f && dockingDist <= steering.DockingAssistThreshold * 0.5f)
{
zoom = Math.Max(zoom, MathHelper.Lerp(MinZoom, MaxZoom, 0.25f));
}
prevDockingDist = Math.Min(dockingDist, prevDockingDist);
}
else
{
prevDockingDist = float.MaxValue;
}
}
if (IsActive)
{
float pingRadius = DisplayRadius * pingState / zoom;
@@ -408,7 +353,7 @@ namespace Barotrauma.Items.Components
}
}
Vector2 transducerCenter = GetTransducerPos();
Vector2 transducerCenter = UseTransducers && connectedTransducers.Count > 0 ? GetTransducerCenter() : item.WorldPosition;
if (item.Submarine != null && !DetectSubmarineWalls)
{
@@ -421,6 +366,7 @@ namespace Barotrauma.Items.Components
DisplayOffset = Vector2.Zero;
}
if (sonarBlips.Count > 0)
{
zoomSqrt = (float)Math.Sqrt(zoom);
@@ -441,8 +387,8 @@ namespace Barotrauma.Items.Components
{
Vector2 sector1 = MathUtils.RotatePointAroundTarget(pingDirection * DisplayRadius, Vector2.Zero, DirectionalPingSector * 0.5f);
Vector2 sector2 = MathUtils.RotatePointAroundTarget(pingDirection * DisplayRadius, Vector2.Zero, -DirectionalPingSector * 0.5f);
DrawLine(spriteBatch, center, center + sector1, Color.LightCyan * 0.2f * directionalPingVisibility, width: 3);
DrawLine(spriteBatch, center, center + sector2, Color.LightCyan * 0.2f * directionalPingVisibility, width: 3);
GUI.DrawLine(spriteBatch, center, center + sector1, Color.LightCyan * 0.2f * directionalPingVisibility, width: 3);
GUI.DrawLine(spriteBatch, center, center + sector2, Color.LightCyan * 0.2f * directionalPingVisibility, width: 3);
}
if (GameMain.DebugDraw)
@@ -493,14 +439,11 @@ namespace Barotrauma.Items.Components
{
var mission = GameMain.GameSession.Mission;
if (!string.IsNullOrWhiteSpace(mission.SonarLabel))
if (!string.IsNullOrWhiteSpace(mission.SonarLabel) && mission.SonarPosition != Vector2.Zero)
{
foreach (Vector2 sonarPosition in mission.SonarPositions)
{
DrawMarker(spriteBatch,
mission.SonarLabel,
sonarPosition - transducerCenter, displayScale, center, (rect.Width * 0.47f));
}
DrawMarker(spriteBatch,
mission.SonarLabel,
mission.SonarPosition - transducerCenter, displayScale, center, (rect.Width * 0.47f));
}
}
@@ -545,7 +488,7 @@ namespace Barotrauma.Items.Components
Vector2 end = (submarine.HullVertices[(i + 1) % submarine.HullVertices.Count] + offset) * simScale;
end.Y = -end.Y;
DrawLine(spriteBatch, start, end, Color.LightBlue * signalStrength * 0.5f, width: 4);
DrawLine(spriteBatch, start, end, Color.LightBlue * signalStrength * 0.5f, width: 3);
}
}
}
@@ -562,38 +505,22 @@ namespace Barotrauma.Items.Components
{
if (MathUtils.GetLineCircleIntersections(Vector2.Zero, DisplayRadius, end, start, true, out Vector2? intersection1, out Vector2? intersection2) == 1)
{
DrawLineSprite(spriteBatch, center + intersection1.Value, center + end, color, width: width);
GUI.DrawLine(spriteBatch, center + intersection1.Value, center + end, color, width: width);
}
}
else if (endOutside)
{
if (MathUtils.GetLineCircleIntersections(Vector2.Zero, DisplayRadius, start, end, true, out Vector2? intersection1, out Vector2? intersection2) == 1)
{
DrawLineSprite(spriteBatch, center + start, center + intersection1.Value, color, width: width);
GUI.DrawLine(spriteBatch, center + start, center + intersection1.Value, color, width: width);
}
}
else
{
DrawLineSprite(spriteBatch, center + start, center + end, color, width: width);
GUI.DrawLine(spriteBatch, center + start, center + end, color, width: width);
}
}
private void DrawLineSprite(SpriteBatch spriteBatch, Vector2 start, Vector2 end, Color color, int width)
{
if (lineSprite == null)
{
GUI.DrawLine(spriteBatch, start, end, color, width: width);
}
else
{
Vector2 dir = end - start;
float angle = (float)Math.Atan2(dir.Y, dir.X);
lineSprite.Draw(spriteBatch, start, color, origin: lineSprite.Origin, rotate: angle,
scale: new Vector2(dir.Length() / lineSprite.size.X, 1.0f));
}
}
private void DrawDockingPorts(SpriteBatch spriteBatch, Vector2 transducerCenter, float signalStrength)
{
float scale = displayScale * zoom;
@@ -601,12 +528,61 @@ namespace Barotrauma.Items.Components
Steering steering = item.GetComponent<Steering>();
if (steering != null && steering.DockingModeEnabled)
{
DrawDockingIndicator(spriteBatch, steering, ref transducerCenter);
DisplayOffset =
Vector2.Lerp(DisplayOffset,
(steering.DockingSource.Item.WorldPosition + steering.DockingTarget.Item.WorldPosition) / 2.0f - transducerCenter,
0.1f);
transducerCenter += DisplayOffset;
Vector2 sourcePortDiff = (steering.DockingSource.Item.WorldPosition - transducerCenter) * scale;
Vector2 sourcePortPos = new Vector2(sourcePortDiff.X, -sourcePortDiff.Y);
Vector2 targetPortDiff = (steering.DockingTarget.Item.WorldPosition - transducerCenter) * scale;
Vector2 targetPortPos = new Vector2(targetPortDiff.X, -targetPortDiff.Y);
Vector2 midPos = (sourcePortPos + targetPortPos) / 2.0f;
System.Diagnostics.Debug.Assert(steering.DockingSource.IsHorizontal == steering.DockingTarget.IsHorizontal);
float xDist = Math.Abs(steering.DockingSource.Item.WorldPosition.X - steering.DockingTarget.Item.WorldPosition.X);
float normalizedXDist = xDist / steering.DockingSource.DistanceTolerance.X;
float yDist = Math.Abs(steering.DockingSource.Item.WorldPosition.Y - steering.DockingTarget.Item.WorldPosition.Y);
float normalizedYDist = yDist / steering.DockingSource.DistanceTolerance.Y;
Color xColor = normalizedXDist <= 1.0f ? Color.Lime : Color.Lerp(Color.Orange, Color.Red, normalizedXDist - 1.0f);
Color yColor = normalizedYDist <= 1.0f ? Color.Lime : Color.Lerp(Color.Orange, Color.Red, normalizedYDist - 1.0f);
if (steering.DockingSource.IsHorizontal)
{
if (yDist < steering.DockingSource.DistanceTolerance.Y)
{
DrawLine(spriteBatch, sourcePortPos, new Vector2(targetPortPos.X, sourcePortPos.Y), xColor, width: 3);
}
else
{
DrawLine(spriteBatch, sourcePortPos, new Vector2(midPos.X, sourcePortPos.Y), xColor, width: 3);
DrawLine(spriteBatch, targetPortPos, new Vector2(midPos.X, targetPortPos.Y), xColor, width: 3);
DrawLine(spriteBatch, new Vector2(midPos.X, sourcePortPos.Y), new Vector2(midPos.X, targetPortPos.Y), yColor, width: 3);
}
}
else
{
if (xDist < steering.DockingSource.DistanceTolerance.X)
{
DrawLine(spriteBatch, sourcePortPos, new Vector2(sourcePortPos.X, targetPortPos.Y), yColor, width: 3);
}
else
{
DrawLine(spriteBatch, sourcePortPos, new Vector2(sourcePortPos.X, midPos.Y), yColor, width: 3);
DrawLine(spriteBatch, targetPortPos, new Vector2(targetPortPos.X, midPos.Y), yColor, width: 3);
DrawLine(spriteBatch, new Vector2(sourcePortPos.X, midPos.Y), new Vector2(targetPortPos.X, midPos.Y), xColor, width: 3);
}
}
}
else
{
DisplayOffset = Vector2.Lerp(DisplayOffset, Vector2.Zero, 0.1f);
}
}
foreach (DockingPort dockingPort in DockingPort.List)
{
@@ -625,102 +601,9 @@ namespace Barotrauma.Items.Components
{
size.Y = 0.0f;
}
GUI.DrawLine(spriteBatch, center + offset - size, center + offset + size, Color.LightGreen, width: (int)(zoom * 2.5f));
}
}
private void DrawDockingIndicator(SpriteBatch spriteBatch, Steering steering, ref Vector2 transducerCenter)
{
float scale = displayScale * zoom;
Vector2 worldFocusPos = (steering.DockingSource.Item.WorldPosition + steering.DockingTarget.Item.WorldPosition) / 2.0f;
worldFocusPos.X = steering.DockingTarget.Item.WorldPosition.X;
DisplayOffset = Vector2.Lerp(DisplayOffset, worldFocusPos - transducerCenter, 0.1f);
transducerCenter += DisplayOffset;
Vector2 sourcePortDiff = (steering.DockingSource.Item.WorldPosition - transducerCenter) * scale;
Vector2 sourcePortPos = new Vector2(sourcePortDiff.X, -sourcePortDiff.Y);
Vector2 targetPortDiff = (steering.DockingTarget.Item.WorldPosition - transducerCenter) * scale;
Vector2 targetPortPos = new Vector2(targetPortDiff.X, -targetPortDiff.Y);
Vector2 midPos = (sourcePortPos + targetPortPos) / 2.0f;
System.Diagnostics.Debug.Assert(steering.DockingSource.IsHorizontal == steering.DockingTarget.IsHorizontal);
Vector2 diff = steering.DockingTarget.Item.WorldPosition - steering.DockingSource.Item.WorldPosition;
float dist = diff.Length();
bool readyToDock =
Math.Abs(diff.X) < steering.DockingTarget.DistanceTolerance.X &&
Math.Abs(diff.Y) < steering.DockingTarget.DistanceTolerance.Y;
Vector2 dockingDir = sourcePortPos - targetPortPos;
Vector2 normalizedDockingDir = Vector2.Normalize(dockingDir);
if (!dynamicDockingIndicator)
{
if (steering.DockingSource.IsHorizontal)
{
normalizedDockingDir = new Vector2(Math.Sign(normalizedDockingDir.X), 0.0f);
}
else
{
normalizedDockingDir = new Vector2(0.0f, Math.Sign(normalizedDockingDir.Y));
}
GUI.DrawLine(spriteBatch, center + offset - size / 2, center + offset + size / 2, Color.LightGreen, width: (int)(zoom));
}
Color staticLineColor = Color.White * 0.2f;
float sector = MathHelper.ToRadians(MathHelper.Lerp(10.0f, 45.0f, MathHelper.Clamp(dist / steering.DockingAssistThreshold, 0.0f, 1.0f)));
float sectorLength = DisplayRadius;
//use law of cosines to calculate the length of the center line
float midLength = (float)(Math.Cos(sector) * sectorLength);
Vector2 midNormal = new Vector2(-normalizedDockingDir.Y, normalizedDockingDir.X);
DrawLine(spriteBatch, targetPortPos, targetPortPos + normalizedDockingDir * midLength, readyToDock ? Color.LightGreen : staticLineColor, width: 2);
DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir, sector) * sectorLength, staticLineColor, width: 2);
DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir, -sector) * sectorLength, staticLineColor, width: 2);
for (float z = 0; z < 1.0f; z += 0.1f * zoom)
{
Vector2 linePos = targetPortPos + normalizedDockingDir * midLength * z;
DrawLine(spriteBatch, linePos + midNormal * 3.0f, linePos - midNormal * 3.0f, staticLineColor, width: 3);
}
if (readyToDock)
{
Color indicatorColor = Color.LightGreen * 0.8f;
float indicatorSize = (float)Math.Sin((float)Timing.TotalTime * 5.0f) * DisplayRadius * 0.75f;
Vector2 midPoint = (sourcePortPos + targetPortPos) / 2.0f;
DrawLine(spriteBatch,
midPoint + Vector2.UnitY * indicatorSize,
midPoint - Vector2.UnitY * indicatorSize,
indicatorColor, width: 3);
DrawLine(spriteBatch,
midPoint + Vector2.UnitX * indicatorSize,
midPoint - Vector2.UnitX * indicatorSize,
indicatorColor, width: 3);
}
else
{
float indicatorSector = sector * 0.75f;
float indicatorSectorLength = (float)(midLength / Math.Cos(indicatorSector));
bool withinSector =
(Math.Abs(diff.X) < steering.DockingSource.DistanceTolerance.X && Math.Abs(diff.Y) < steering.DockingSource.DistanceTolerance.Y) ||
Vector2.Dot(normalizedDockingDir, MathUtils.RotatePoint(normalizedDockingDir, indicatorSector)) <
Vector2.Dot(normalizedDockingDir, Vector2.Normalize(dockingDir));
Color indicatorColor = withinSector ? Color.LightGreen * 0.8f : Color.Red * 0.8f;
DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir,indicatorSector) * indicatorSectorLength, indicatorColor, width: 3);
DrawLine(spriteBatch, targetPortPos,
targetPortPos + MathUtils.RotatePoint(normalizedDockingDir, -indicatorSector) * indicatorSectorLength, indicatorColor, width: 3);
}
}
private void UpdateDisruptions(Vector2 pingSource, float worldPingRadius, float worldPrevPingRadius)

View File

@@ -4,9 +4,7 @@ using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
@@ -27,11 +25,6 @@ namespace Barotrauma.Items.Components
};
private GUITickBox maintainPosTickBox, levelEndTickBox, levelStartTickBox;
private GUIComponent statusContainer, dockingContainer;
private GUIButton dockingButton;
private string dockText, undockText;
private GUIFrame autoPilotControlsDisabler;
private GUIComponent steerArea;
@@ -42,14 +35,9 @@ namespace Barotrauma.Items.Components
private string noPowerTip, autoPilotMaintainPosTip, autoPilotLevelStartTip, autoPilotLevelEndTip;
private Sprite maintainPosIndicator, maintainPosOriginIndicator;
private Sprite steeringIndicator;
private Vector2 keyboardInput = Vector2.Zero;
private float inputCumulation;
private bool? swapDestinationOrder;
private bool levelStartSelected;
public bool LevelStartSelected
{
@@ -76,12 +64,10 @@ namespace Barotrauma.Items.Components
get;
set;
}
public DockingPort DockingSource, DockingTarget;
private bool searchedConnectedDockingPort;
partial void InitProjSpecific(XElement element)
partial void InitProjSpecific()
{
int viewSize = (int)Math.Min(GuiFrame.Rect.Width - 150, GuiFrame.Rect.Height * 0.9f);
var controlContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.35f), GuiFrame.RectTransform, Anchor.CenterLeft)
@@ -92,7 +78,7 @@ namespace Barotrauma.Items.Components
Stretch = true
};
statusContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft)
var statusContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft)
{ MinSize = new Point(150, 0), AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0) }, "SonarFrame");
var paddedStatusContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), statusContainer.RectTransform, Anchor.Center))
{
@@ -121,9 +107,7 @@ namespace Barotrauma.Items.Components
AutoPilot = box.Selected;
if (AutoPilot && MaintainPos)
{
posToMaintain = controlledSub != null ?
controlledSub.WorldPosition :
item.Submarine == null ? item.WorldPosition : item.Submarine.WorldPosition;
posToMaintain = controlledSub == null ? item.WorldPosition : controlledSub.WorldPosition;
}
unsentChanges = true;
user = Character.Controlled;
@@ -294,80 +278,6 @@ namespace Barotrauma.Items.Components
steerArea = new GUICustomComponent(new RectTransform(new Point(viewSize), GuiFrame.RectTransform, Anchor.CenterLeft),
(spriteBatch, guiCustomComponent) => { DrawHUD(spriteBatch, guiCustomComponent.Rect); }, null);
//docking interface ----------------------------------------------------
dockingContainer = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GuiFrame.RectTransform, Anchor.BottomLeft)
{ MinSize = new Point(150, 0), AbsoluteOffset = new Point((int)(viewSize * 0.9f), 0) }, style: null);
var paddedDockingContainer = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), dockingContainer.RectTransform, Anchor.Center), style: null);
//TODO: add new texts for these ("Dock" & "Undock")
dockText = TextManager.Get("captain.dock");
undockText = TextManager.Get("captain.undock");
dockingButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.5f), paddedDockingContainer.RectTransform, Anchor.Center), dockText, style: "GUIButtonLarge")
{
OnClicked = (btn, userdata) =>
{
item.SendSignal(0, "1", "toggle_docking", sender: Character.Controlled);
return true;
}
};
dockingButton.Font = GUI.SmallFont;
var leftButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterLeft), "")
{
OnClicked = NudgeButtonClicked,
UserData = -Vector2.UnitX
};
new GUIImage(new RectTransform(new Vector2(0.7f), leftButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow").SpriteEffects = SpriteEffects.FlipHorizontally;
var rightButton = new GUIButton(new RectTransform(new Vector2(0.2f, 0.5f), paddedDockingContainer.RectTransform, Anchor.CenterRight), "")
{
OnClicked = NudgeButtonClicked,
UserData = Vector2.UnitX
};
new GUIImage(new RectTransform(new Vector2(0.7f), rightButton.RectTransform, Anchor.Center), "GUIButtonHorizontalArrow");
var upButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.TopCenter), "")
{
OnClicked = NudgeButtonClicked,
UserData = Vector2.UnitY
};
new GUIImage(new RectTransform(new Vector2(0.7f), upButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow");
var downButton = new GUIButton(new RectTransform(new Vector2(0.5f, 0.2f), paddedDockingContainer.RectTransform, Anchor.BottomCenter), "")
{
OnClicked = NudgeButtonClicked,
UserData = -Vector2.UnitY
};
new GUIImage(new RectTransform(new Vector2(0.7f), downButton.RectTransform, Anchor.Center), "GUIButtonVerticalArrow").SpriteEffects = SpriteEffects.FlipVertically;
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "steeringindicator":
steeringIndicator = new Sprite(subElement);
break;
case "maintainposindicator":
maintainPosIndicator = new Sprite(subElement);
break;
case "maintainposoriginindicator":
maintainPosOriginIndicator = new Sprite(subElement);
break;
}
}
}
private void FindConnectedDockingPort()
{
DockingSource =
(item.linkedTo.FirstOrDefault(l => l is Item item && item.GetComponent<DockingPort>() != null) as Item)?.GetComponent<DockingPort>();
if (DockingSource == null)
{
var dockingConnection = item.Connections.FirstOrDefault(c => c.Name == "toggle_docking");
if (dockingConnection != null)
{
var connectedPorts = item.GetConnectedComponentsRecursive<DockingPort>(dockingConnection);
DockingSource = connectedPorts.Find(p => p.Item.Submarine == item.Submarine);
}
}
}
/// <summary>
@@ -384,15 +294,15 @@ namespace Barotrauma.Items.Components
int width = rect.Width, height = rect.Height;
int x = rect.X;
int y = rect.Y;
if (voltage < minVoltage && currPowerConsumption > 0.0f) return;
Rectangle velRect = new Rectangle(x + 20, y + 20, width - 40, height - 40);
Vector2 displaySubPos = (-sonar.DisplayOffset * sonar.Zoom) / sonar.Range * sonar.DisplayRadius * sonar.Zoom;
displaySubPos.Y = -displaySubPos.Y;
displaySubPos = displaySubPos.ClampLength(velRect.Width / 2);
displaySubPos = steerArea.Rect.Center.ToVector2() + displaySubPos;
Rectangle velRect = new Rectangle(x + 20, y + 20, width - 40, height - 40);
GUI.DrawLine(spriteBatch,
new Vector2(velRect.Center.X, velRect.Center.Y),
new Vector2(velRect.Center.X + currVelocity.X, velRect.Center.Y - currVelocity.Y),
Color.Gray);
if (!AutoPilot)
{
Vector2 unitSteeringInput = steeringInput / 100.0f;
@@ -400,24 +310,20 @@ namespace Barotrauma.Items.Components
Vector2 steeringInputPos = new Vector2(
steeringInput.X * (float)Math.Sqrt(1.0f - 0.5f * unitSteeringInput.Y * unitSteeringInput.Y),
-steeringInput.Y * (float)Math.Sqrt(1.0f - 0.5f * unitSteeringInput.X * unitSteeringInput.X));
steeringInputPos += displaySubPos;
steeringInputPos.X += velRect.Center.X;
steeringInputPos.Y += velRect.Center.Y;
if (steeringIndicator != null)
{
Vector2 dir = steeringInputPos - displaySubPos;
float angle = (float)Math.Atan2(dir.Y, dir.X);
steeringIndicator.Draw(spriteBatch, displaySubPos, Color.White, origin: steeringIndicator.Origin, rotate: angle,
scale: new Vector2(dir.Length() / steeringIndicator.size.X, 1.0f));
}
else
{
GUI.DrawLine(spriteBatch, displaySubPos, steeringInputPos, Color.LightGray);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 5, (int)steeringInputPos.Y - 5, 10, 10), Color.White);
}
GUI.DrawLine(spriteBatch,
new Vector2(velRect.Center.X, velRect.Center.Y),
steeringInputPos,
Color.LightGray);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 5, (int)steeringInputPos.Y - 5, 10, 10), Color.White);
//if (keyboardInput.Length() > 0 || Vector2.Distance(PlayerInput.MousePosition, new Vector2(velRect.Center.X, velRect.Center.Y)) < 200.0f)
if (velRect.Contains(PlayerInput.MousePosition))
{
GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 4, (int)steeringInputPos.Y - 4, 8, 8), Color.Red, thickness: 2);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)steeringInputPos.X - 10, (int)steeringInputPos.Y - 10, 20, 20), Color.Red);
}
}
else if (posToMaintain.HasValue && !LevelStartSelected && !LevelEndSelected)
@@ -428,53 +334,35 @@ namespace Barotrauma.Items.Components
Vector2 displayPosToMaintain = ((posToMaintain.Value - sonar.DisplayOffset * sonar.Zoom - controlledSub.WorldPosition)) / sonar.Range * sonar.DisplayRadius * sonar.Zoom;
displayPosToMaintain.Y = -displayPosToMaintain.Y;
displayPosToMaintain = displayPosToMaintain.ClampLength(velRect.Width / 2);
displayPosToMaintain = steerArea.Rect.Center.ToVector2() + displayPosToMaintain;
displayPosToMaintain = velRect.Center.ToVector2() + displayPosToMaintain;
float crossHairSize = 8.0f;
Color crosshairColor = Color.Orange * (0.5f + ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) / 4.0f);
if (maintainPosIndicator != null)
{
maintainPosIndicator.Draw(spriteBatch, displayPosToMaintain, crosshairColor, scale: 0.5f * sonar.Zoom);
}
else
{
float crossHairSize = 8.0f;
GUI.DrawLine(spriteBatch, displayPosToMaintain + Vector2.UnitY * crossHairSize, displayPosToMaintain - Vector2.UnitY * crossHairSize, crosshairColor, width: 3);
GUI.DrawLine(spriteBatch, displayPosToMaintain + Vector2.UnitX * crossHairSize, displayPosToMaintain - Vector2.UnitX * crossHairSize, crosshairColor, width: 3);
}
if (maintainPosOriginIndicator != null)
{
maintainPosOriginIndicator.Draw(spriteBatch, displaySubPos, Color.Orange, scale: 0.5f * sonar.Zoom);
}
else
{
GUI.DrawRectangle(spriteBatch, new Rectangle((int)displaySubPos.X - 5, (int)displaySubPos.Y - 5, 10, 10), Color.Orange);
}
GUI.DrawLine(spriteBatch, displayPosToMaintain + Vector2.UnitY * crossHairSize, displayPosToMaintain - Vector2.UnitY * crossHairSize, crosshairColor, width: 3);
GUI.DrawLine(spriteBatch, displayPosToMaintain + Vector2.UnitX * crossHairSize, displayPosToMaintain - Vector2.UnitX * crossHairSize, crosshairColor, width: 3);
Vector2 neutralPos = ((controlledSub.WorldPosition - sonar.DisplayOffset * sonar.Zoom - controlledSub.WorldPosition)) / sonar.Range * sonar.DisplayRadius * sonar.Zoom;
neutralPos.Y = -neutralPos.Y;
neutralPos = neutralPos.ClampLength(velRect.Width / 2);
neutralPos = velRect.Center.ToVector2() + neutralPos;
GUI.DrawRectangle(spriteBatch, new Rectangle((int)neutralPos.X - 5, (int)neutralPos.Y - 5, 10, 10), Color.Orange);
}
}
//map velocity from rectangle to circle
Vector2 unitTargetVel = targetVelocity / 100.0f;
Vector2 steeringPos = new Vector2(
targetVelocity.X * 0.9f * (float)Math.Sqrt(1.0f - 0.5f * unitTargetVel.Y * unitTargetVel.Y),
-targetVelocity.Y * 0.9f * (float)Math.Sqrt(1.0f - 0.5f * unitTargetVel.X * unitTargetVel.X));
steeringPos += displaySubPos;
steeringPos.X += velRect.Center.X;
steeringPos.Y += velRect.Center.Y;
if (steeringIndicator != null)
{
Vector2 dir = steeringPos - displaySubPos;
float angle = (float)Math.Atan2(dir.Y, dir.X);
steeringIndicator.Draw(spriteBatch, displaySubPos, Color.Gray, origin: steeringIndicator.Origin, rotate: angle,
scale: new Vector2(dir.Length() / steeringIndicator.size.X, 0.7f));
}
else
{
GUI.DrawLine(spriteBatch,
displaySubPos,
steeringPos,
Color.CadetBlue, 0, 2);
}
GUI.DrawLine(spriteBatch,
new Vector2(velRect.Center.X, velRect.Center.Y),
steeringPos,
Color.CadetBlue, 0, 2);
}
public void DebugDrawHUD(SpriteBatch spriteBatch, Vector2 transducerCenter, float displayScale, float displayRadius, Vector2 center)
@@ -535,21 +423,6 @@ namespace Barotrauma.Items.Components
public override void UpdateHUD(Character character, float deltaTime, Camera cam)
{
if (swapDestinationOrder == null)
{
swapDestinationOrder = item.Submarine != null && item.Submarine.FlippedX;
if (swapDestinationOrder.Value)
{
levelStartTickBox.RectTransform.SetAsLastChild();
}
}
if (!searchedConnectedDockingPort)
{
FindConnectedDockingPort();
searchedConnectedDockingPort = true;
}
if (steerArea.Rect.Contains(PlayerInput.MousePosition))
{
if (!PlayerInput.KeyDown(InputType.Deselect) && !PlayerInput.KeyHit(InputType.Deselect))
@@ -558,38 +431,6 @@ namespace Barotrauma.Items.Components
}
}
dockingContainer.Visible = DockingModeEnabled;
statusContainer.Visible = !DockingModeEnabled;
if (DockingModeEnabled)
{
if (Math.Abs(DockingSource.Item.WorldPosition.X - DockingTarget.Item.WorldPosition.X) < DockingSource.DistanceTolerance.X &&
Math.Abs(DockingSource.Item.WorldPosition.Y - DockingTarget.Item.WorldPosition.Y) < DockingSource.DistanceTolerance.Y)
{
dockingButton.Text = dockText;
if (dockingButton.FlashTimer <= 0.0f)
{
dockingButton.Flash(Color.LightGreen, 0.5f);
dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer);
}
}
}
else if (DockingSource != null && DockingSource.Docked)
{
dockingButton.Text = undockText;
dockingContainer.Visible = true;
statusContainer.Visible = false;
if (dockingButton.FlashTimer <= 0.0f)
{
dockingButton.Flash(Color.OrangeRed);
dockingButton.Pulsate(Vector2.One, Vector2.One * 1.2f, dockingButton.FlashTimer);
}
}
else
{
dockingButton.Text = dockText;
}
autoPilotControlsDisabler.Visible = !AutoPilot;
if (voltage < minVoltage && currPowerConsumption > 0.0f)
@@ -627,17 +468,13 @@ namespace Barotrauma.Items.Components
{
if (PlayerInput.LeftButtonHeld())
{
Vector2 displaySubPos = (-sonar.DisplayOffset * sonar.Zoom) / sonar.Range * sonar.DisplayRadius * sonar.Zoom;
displaySubPos.Y = -displaySubPos.Y;
displaySubPos = steerArea.Rect.Center.ToVector2() + displaySubPos;
Vector2 inputPos = PlayerInput.MousePosition - displaySubPos;
Vector2 inputPos = PlayerInput.MousePosition - steerArea.Rect.Center.ToVector2();
inputPos.Y = -inputPos.Y;
if (AutoPilot && !LevelStartSelected && !LevelEndSelected)
{
posToMaintain = controlledSub != null ?
controlledSub.WorldPosition + inputPos / sonar.DisplayRadius * sonar.Range / sonar.Zoom :
item.Submarine == null ? item.WorldPosition : item.Submarine.WorldPosition;
posToMaintain = controlledSub == null ?
item.WorldPosition :
controlledSub.WorldPosition + (sonar.DisplayOffset * sonar.Zoom) + inputPos / sonar.DisplayRadius * sonar.Range / sonar.Zoom;
}
else
{
@@ -703,6 +540,16 @@ namespace Barotrauma.Items.Components
if (sourcePort.Docked || sourcePort.Item.Submarine == null) { continue; }
if (sourcePort.Item.Submarine != controlledSub) { continue; }
float closestDist = DockingAssistThreshold * DockingAssistThreshold;
DockingModeEnabled = false;
DockingSource = null;
DockingTarget = null;
foreach (DockingPort sourcePort in DockingPort.List)
{
if (sourcePort.Docked || sourcePort.Item.Submarine == null) { continue; }
if (sourcePort.Item.Submarine != controlledSub) { continue; }
int sourceDir = sourcePort.IsHorizontal ?
Math.Sign(sourcePort.Item.WorldPosition.X - sourcePort.Item.Submarine.WorldPosition.X) :
Math.Sign(sourcePort.Item.WorldPosition.Y - sourcePort.Item.Submarine.WorldPosition.Y);
@@ -730,27 +577,6 @@ namespace Barotrauma.Items.Components
}
}
private bool NudgeButtonClicked(GUIButton btn, object userdata)
{
if (!MaintainPos || !AutoPilot)
{
AutoPilot = true;
posToMaintain = item.Submarine.WorldPosition;
}
MaintainPos = true;
if (userdata is Vector2)
{
Sonar sonar = item.GetComponent<Sonar>();
Vector2 nudgeAmount = (Vector2)userdata;
if (sonar != null)
{
nudgeAmount *= sonar == null ? 500.0f : 500.0f / sonar.Zoom;
}
PosToMaintain += nudgeAmount;
}
return true;
}
protected override void RemoveComponentSpecific()
{
maintainPosIndicator?.Remove();

View File

@@ -10,10 +10,6 @@ namespace Barotrauma.Items.Components
{
partial class Repairable : ItemComponent, IDrawableComponent
{
public GUIButton RepairButton
{
get { return repairButton; }
}
private GUIButton repairButton;
private GUIProgressBar progressBar;

View File

@@ -18,14 +18,6 @@ namespace Barotrauma.Items.Components
private static Wire draggingConnected;
private Color flashColor;
private float flashDuration = 1.5f;
public float FlashTimer
{
get { return flashTimer; }
}
private float flashTimer;
public static void DrawConnections(SpriteBatch spriteBatch, ConnectionPanel panel, Character character)
{
Rectangle panelRect = panel.GuiFrame.Rect;
@@ -182,38 +174,14 @@ namespace Barotrauma.Items.Components
}
}
}
if (flashTimer > 0.0f)
{
//the number of flashes depends on the duration, 1 flash per 1 full second
int flashCycleCount = (int)Math.Max(flashDuration, 1);
float flashCycleDuration = flashDuration / flashCycleCount;
//MathHelper.Pi * 0.8f -> the curve goes from 144 deg to 0,
//i.e. quickly bumps up from almost full brightness to full and then fades out
connectionSpriteHighlight.Draw(spriteBatch, position, flashColor * (float)Math.Sin(flashTimer % flashCycleDuration / flashCycleDuration * MathHelper.Pi * 0.8f));
}
if (Wires.Any(w => w != null && w != draggingConnected))
{
int screwIndex = (int)Math.Floor(position.Y / 30.0f) % screwSprites.Count;
screwSprites[screwIndex].Draw(spriteBatch, position);
}
}
public void Flash(Color? color = null, float flashDuration = 1.5f)
{
flashTimer = flashDuration;
this.flashDuration = flashDuration;
flashColor = (color == null) ? Color.Red : (Color)color;
}
public void UpdateFlashTimer(float deltaTime)
{
if (flashTimer <= 0) return;
flashTimer -= deltaTime;
}
private static void DrawWire(SpriteBatch spriteBatch, Wire wire, Item item, Vector2 end, Vector2 start, bool mouseIn, Wire equippedWire, ConnectionPanel panel, string label)
{
if (draggingConnected == wire)

View File

@@ -3,7 +3,6 @@ using Lidgren.Network;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
@@ -17,22 +16,16 @@ namespace Barotrauma.Items.Components
{
uiElements.Clear();
var visibleElements = customInterfaceElementList.Where(ciElement => !string.IsNullOrEmpty(ciElement.Label));
GUILayoutGroup paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), GuiFrame.RectTransform, Anchor.Center),
childAnchor: customInterfaceElementList.Count > 1 ? Anchor.TopCenter : Anchor.Center)
{
RelativeSpacing = 0.05f,
Stretch = visibleElements.Count() > 2
};
{ RelativeSpacing = 0.05f };
float elementSize = Math.Min(1.0f / visibleElements.Count(), 0.5f);
foreach (CustomInterfaceElement ciElement in visibleElements)
float elementSize = Math.Min(1.0f / customInterfaceElementList.Count, 0.5f);
foreach (CustomInterfaceElement ciElement in customInterfaceElementList)
{
if (ciElement.ContinuousSignal)
{
var tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, elementSize), paddedFrame.RectTransform),
TextManager.Get(ciElement.Label, returnNull: true) ?? ciElement.Label)
var tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, elementSize), paddedFrame.RectTransform), ciElement.Label)
{
UserData = ciElement
};
@@ -52,8 +45,7 @@ namespace Barotrauma.Items.Components
}
else
{
var btn = new GUIButton(new RectTransform(new Vector2(1.0f, elementSize), paddedFrame.RectTransform),
TextManager.Get(ciElement.Label, returnNull: true) ?? ciElement.Label, style: "GUIButtonLarge")
var btn = new GUIButton(new RectTransform(new Vector2(1.0f, elementSize), paddedFrame.RectTransform), ciElement.Label, style: "GUIButtonLarge")
{
UserData = ciElement
};
@@ -74,54 +66,17 @@ namespace Barotrauma.Items.Components
}
}
public override void CreateEditingHUD(SerializableEntityEditor editor)
{
base.CreateEditingHUD(editor);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(customInterfaceElementList[0]);
PropertyDescriptor labelProperty = properties.Find("Label", false);
PropertyDescriptor signalProperty = properties.Find("Signal", false);
for (int i = 0; i< customInterfaceElementList.Count; i++)
{
editor.CreateStringField(customInterfaceElementList[i],
new SerializableProperty(labelProperty, customInterfaceElementList[i]),
customInterfaceElementList[i].Label, "Label #" + (i + 1), "");
editor.CreateStringField(customInterfaceElementList[i],
new SerializableProperty(signalProperty, customInterfaceElementList[i]),
customInterfaceElementList[i].Signal, "Signal #" + (i + 1), "");
}
}
public void HighlightElement(int index, Color color, float duration, float pulsateAmount = 0.0f)
{
if (index < 0 || index >= uiElements.Count) { return; }
uiElements[index].Flash(color, duration);
if (pulsateAmount > 0.0f)
{
if (uiElements[index] is GUIButton button)
{
button.Frame.Pulsate(Vector2.One, Vector2.One * (1.0f + pulsateAmount), duration);
button.Frame.RectTransform.SetPosition(Anchor.Center);
}
else
{
uiElements[index].Pulsate(Vector2.One, Vector2.One * (1.0f + pulsateAmount), duration);
}
}
}
partial void UpdateLabelsProjSpecific()
{
for (int i = 0; i < labels.Length && i < uiElements.Count; i++)
{
if (uiElements[i] is GUIButton button)
{
button.Text = customInterfaceElementList[i].Label;
button.Text = labels[i];
}
else if (uiElements[i] is GUITickBox tickBox)
{
tickBox.Text = customInterfaceElementList[i].Label;
tickBox.Text = labels[i];
}
}
}

View File

@@ -271,11 +271,19 @@ namespace Barotrauma.Items.Components
}
}
}
}
}
if (highlighted != null)
{
highlighted.item.IsHighlighted = true;
if (Character.Controlled != null)
{
Character.Controlled.FocusedItem = null;
Character.Controlled.ResetInteract = true;
Character.Controlled.ClearInputs();
}
if (PlayerInput.LeftButtonClicked())
{
MapEntity.DisableSelect = true;

View File

@@ -150,14 +150,14 @@ namespace Barotrauma.Items.Components
{
if (moveSoundChannel == null && startMoveSound != null)
{
moveSoundChannel = SoundPlayer.PlaySound(startMoveSound.Sound, item.WorldPosition, startMoveSound.Volume, startMoveSound.Range);
moveSoundChannel = SoundPlayer.PlaySound(startMoveSound.Sound, startMoveSound.Volume, startMoveSound.Range, item.WorldPosition);
}
else if (moveSoundChannel == null || !moveSoundChannel.IsPlaying)
{
if (moveSound != null)
{
moveSoundChannel.FadeOutAndDispose();
moveSoundChannel = SoundPlayer.PlaySound(moveSound.Sound, item.WorldPosition, moveSound.Volume, moveSound.Range);
moveSoundChannel = SoundPlayer.PlaySound(moveSound.Sound, moveSound.Volume, moveSound.Range, item.WorldPosition);
if (moveSoundChannel != null) moveSoundChannel.Looping = true;
}
}
@@ -169,7 +169,7 @@ namespace Barotrauma.Items.Components
if (endMoveSound != null && moveSoundChannel.Sound != endMoveSound.Sound)
{
moveSoundChannel.FadeOutAndDispose();
moveSoundChannel = SoundPlayer.PlaySound(endMoveSound.Sound, item.WorldPosition, endMoveSound.Volume, endMoveSound.Range);
moveSoundChannel = SoundPlayer.PlaySound(endMoveSound.Sound, endMoveSound.Volume, endMoveSound.Range, item.WorldPosition);
if (moveSoundChannel != null) moveSoundChannel.Looping = false;
}
else if (!moveSoundChannel.IsPlaying)

View File

@@ -26,7 +26,6 @@ namespace Barotrauma
public Color Color;
public Color HighlightColor;
public float HighlightScaleUpAmount;
private CoroutineHandle highlightCoroutine;
public float HighlightTimer;
@@ -81,7 +80,7 @@ namespace Barotrauma
return rect.Contains(PlayerInput.MousePosition);
}
public void ShowBorderHighlight(Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount = 0.5f)
public void ShowBorderHighlight(Color color, float fadeInDuration, float fadeOutDuration)
{
if (highlightCoroutine != null)
{
@@ -89,7 +88,6 @@ namespace Barotrauma
highlightCoroutine = null;
}
HighlightScaleUpAmount = scaleUpAmount;
highlightCoroutine = CoroutineManager.StartCoroutine(UpdateBorderHighlight(color, fadeInDuration, fadeOutDuration));
}
@@ -156,6 +154,8 @@ namespace Barotrauma
public SlotReference(Inventory parentInventory, InventorySlot slot, int slotIndex, bool isSubSlot, Inventory subInventory = null)
{
ParentInventory = parentInventory;
Slot = slot;
SlotIndex = slotIndex;
@@ -714,15 +714,12 @@ namespace Barotrauma
float scale = Math.Min(Math.Min(iconSize / sprite.size.X, iconSize / sprite.size.Y), 1.5f);
Vector2 itemPos = PlayerInput.MousePosition;
bool mouseOnHealthInterface = CharacterHealth.OpenHealthWindow != null && CharacterHealth.OpenHealthWindow.MouseOnElement;
if ((GUI.MouseOn == null || mouseOnHealthInterface) && selectedSlot == null)
if (GUI.MouseOn == null && selectedSlot == null)
{
var shadowSprite = GUI.Style.GetComponentStyle("OuterGlow").Sprites[GUIComponent.ComponentState.None][0];
string toolTip = mouseOnHealthInterface ? TextManager.Get("QuickUseAction.UseTreatment") :
Character.Controlled.FocusedItem != null ?
TextManager.Get("PutItemIn").Replace("[itemname]", Character.Controlled.FocusedItem.Name) :
TextManager.Get("DropItem");
string toolTip = Character.Controlled.FocusedItem != null ?
TextManager.Get("PutItemIn").Replace("[itemname]", Character.Controlled.FocusedItem.Name) :
TextManager.Get("DropItem");
int textWidth = (int)Math.Max(GUI.Font.MeasureString(draggingItem.Name).X, GUI.SmallFont.MeasureString(toolTip).X);
int textSpacing = (int)(15 * GUI.Scale);
Point shadowBorders = (new Point(40, 10)).Multiply(GUI.Scale);
@@ -730,7 +727,7 @@ namespace Barotrauma
new Rectangle(itemPos.ToPoint() - new Point(iconSize / 2) - shadowBorders, new Point(iconSize + textWidth + textSpacing, iconSize) + shadowBorders.Multiply(2)), Color.Black * 0.8f);
GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y - iconSize / 2), draggingItem.Name, Color.White);
GUI.DrawString(spriteBatch, new Vector2(itemPos.X + iconSize / 2 + textSpacing, itemPos.Y), toolTip,
color: Character.Controlled.FocusedItem == null && !mouseOnHealthInterface ? Color.Red : Color.LightGreen,
color: Character.Controlled.FocusedItem == null ? Color.Red : Color.LightGreen,
font: GUI.SmallFont);
}
sprite.Draw(spriteBatch, itemPos + Vector2.One * 2, Color.Black, scale: scale);
@@ -802,7 +799,8 @@ namespace Barotrauma
if (slot.HighlightColor.A > 0)
{
float inflateAmount = (slot.HighlightColor.A / 255.0f) * slot.HighlightScaleUpAmount * 0.5f;
float scaleUpAmount = 0.5f;
float inflateAmount = (slot.HighlightColor.A / 255.0f) * scaleUpAmount * 0.5f;
rect.Inflate(rect.Width * inflateAmount, rect.Height * inflateAmount);
}
@@ -820,9 +818,8 @@ namespace Barotrauma
else
{
Sprite slotSprite = slot.SlotSprite ?? slotSpriteSmall;
Color slotColor = slot.IsHighlighted ? Color.White : Color.White * 0.8f;
if (inventory != null && inventory.Locked) { slotColor = Color.Gray * 0.5f; }
spriteBatch.Draw(slotSprite.Texture, rect, slotSprite.SourceRect, slotColor);
spriteBatch.Draw(slotSprite.Texture, rect, slotSprite.SourceRect, slot.IsHighlighted ? Color.White : Color.White * 0.8f);
if (item != null && drawItem)
{
@@ -856,7 +853,7 @@ namespace Barotrauma
if (itemContainer.ContainedStateIndicator?.Texture == null)
{
containedIndicatorArea.Inflate(0, -2);
GUI.DrawRectangle(spriteBatch, containedIndicatorArea, Color.DarkGray * 0.9f, true);
GUI.DrawRectangle(spriteBatch, containedIndicatorArea, Color.DarkGray * 0.8f, true);
GUI.DrawRectangle(spriteBatch,
new Rectangle(containedIndicatorArea.X, containedIndicatorArea.Y, (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Height),
Color.Lerp(Color.Red, Color.Green, containedState) * 0.8f, true);
@@ -870,21 +867,18 @@ namespace Barotrauma
if (containedState > 0.0f && containedState < 0.25f)
{
indicatorScale += ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) * 0.25f;
indicatorScale += ((float)Math.Sin(Timing.TotalTime * 5.0f) + 1.0f) * 0.1f;
}
indicatorSprite.Draw(spriteBatch, containedIndicatorArea.Center.ToVector2(),
(inventory != null && inventory.Locked) ? Color.DarkGray * 0.5f : Color.DarkGray * 0.9f,
Color.DarkGray * 0.6f,
origin: indicatorSprite.size / 2,
rotate: 0.0f,
scale: indicatorScale);
Color indicatorColor = ToolBox.GradientLerp(containedState, Color.Red, Color.Orange, Color.Green);
if (inventory != null && inventory.Locked) { indicatorColor *= 0.5f; }
spriteBatch.Draw(indicatorSprite.Texture, containedIndicatorArea.Center.ToVector2(),
sourceRectangle: new Rectangle(indicatorSprite.SourceRect.Location, new Point((int)(indicatorSprite.SourceRect.Width * containedState), indicatorSprite.SourceRect.Height)),
color: indicatorColor,
color: ToolBox.GradientLerp(containedState, Color.Red, Color.Orange, Color.Green),
rotation: 0.0f,
origin: indicatorSprite.size / 2,
scale: indicatorScale,
@@ -924,7 +918,6 @@ namespace Barotrauma
}
Color spriteColor = sprite == item.Sprite ? item.GetSpriteColor() : item.GetInventoryIconColor();
if (inventory != null && inventory.Locked) { spriteColor *= 0.5f; }
if (CharacterHealth.OpenHealthWindow != null && !item.UseInHealthInterface)
{
spriteColor = Color.Lerp(spriteColor, Color.TransparentBlack, 0.5f);
@@ -936,10 +929,7 @@ namespace Barotrauma
sprite.Draw(spriteBatch, itemPos, spriteColor, rotation, scale);
}
if (inventory != null &&
!inventory.Locked &&
Character.Controlled?.Inventory == inventory &&
slot.QuickUseKey != Keys.None)
if (inventory != null && Character.Controlled?.Inventory == inventory && slot.QuickUseKey != Keys.None)
{
GUI.DrawString(spriteBatch, rect.Location.ToVector2(),
slot.QuickUseKey.ToString().Substring(1, 1),

View File

@@ -41,6 +41,8 @@ namespace Barotrauma
{
get { return activeSprite; }
}
public float SpriteRotation;
private GUITextBlock itemInUseWarning;
private GUITextBlock ItemInUseWarning
@@ -184,7 +186,7 @@ namespace Barotrauma
if (!Visible || (!editing && hiddenInGame)) return;
if (editing && !ShowItems) return;
Color color = IsHighlighted && !GUI.DisableItemHighlights && Screen.Selected != GameMain.GameScreen ? Color.Orange : GetSpriteColor();
Color color = isHighlighted && !GUI.DisableItemHighlights && Screen.Selected != GameMain.GameScreen ? Color.Orange : GetSpriteColor();
//if (IsSelected && editing) color = Color.Lerp(color, Color.Gold, 0.5f);
BrokenItemSprite fadeInBrokenSprite = null;
@@ -384,7 +386,7 @@ namespace Barotrauma
Timing.TotalTime > LastImpactSoundTime + ImpactSoundInterval)
{
LastImpactSoundTime = (float)Timing.TotalTime;
SoundPlayer.PlaySound(Prefab.ImpactSoundTag, WorldPosition, hullGuess: CurrentHull);
SoundPlayer.PlaySound(Prefab.ImpactSoundTag, 1.0f, 500.0f, WorldPosition, CurrentHull);
}
}
@@ -562,7 +564,6 @@ namespace Barotrauma
}
};
itemEditor.AddCustomContent(buttonContainer, itemEditor.ContentCount);
GUITextBlock.AutoScaleAndNormalize(buttonContainer.Children.Select(b => ((GUIButton)b).TextBlock));
}
foreach (ItemComponent ic in components)
@@ -578,13 +579,8 @@ namespace Barotrauma
}
var componentEditor = new SerializableEntityEditor(listBox.Content.RectTransform, ic, inGame, showName: !inGame);
if (inGame)
{
ic.CreateEditingHUD(componentEditor);
componentEditor.Recalculate();
continue;
}
if (inGame) continue;
foreach (var kvp in ic.requiredItems)
{
@@ -618,10 +614,6 @@ namespace Barotrauma
}
}
ic.CreateEditingHUD(componentEditor);
componentEditor.Recalculate();
}
PositionEditingHUD();
SetHUDLayout();
@@ -838,28 +830,14 @@ namespace Barotrauma
case NetEntityEvent.Type.ComponentState:
{
int componentIndex = msg.ReadRangedInteger(0, components.Count - 1);
if (components[componentIndex] is IServerSerializable serverSerializable)
{
serverSerializable.ClientRead(type, msg, sendingTime);
}
else
{
throw new Exception("Failed to read component state - " + components[componentIndex].GetType() + " is not IServerSerializable.");
}
(components[componentIndex] as IServerSerializable).ClientRead(type, msg, sendingTime);
}
break;
case NetEntityEvent.Type.InventoryState:
{
{
int containerIndex = msg.ReadRangedInteger(0, components.Count - 1);
if (components[containerIndex] is ItemContainer container)
{
container.Inventory.ClientRead(type, msg, sendingTime);
}
else
{
throw new Exception("Failed to read inventory state - " + components[containerIndex].GetType() + " is not an ItemContainer.");
}
(components[containerIndex] as ItemContainer).Inventory.ClientRead(type, msg, sendingTime);
}
break;
case NetEntityEvent.Type.Status:

View File

@@ -233,11 +233,11 @@ namespace Barotrauma
}
}
public override void DrawPlacing(SpriteBatch spriteBatch, Rectangle placeRect, float scale = 1.0f, SpriteEffects spriteEffects = SpriteEffects.None)
public override void DrawPlacing(SpriteBatch spriteBatch, Rectangle placeRect, float scale = 1.0f)
{
if (!ResizeHorizontal && !ResizeVertical)
{
sprite.Draw(spriteBatch, new Vector2(placeRect.Center.X, -(placeRect.Y - placeRect.Height / 2)), SpriteColor * 0.8f, scale: scale);
sprite.Draw(spriteBatch, new Vector2(placeRect.Center.X, -(placeRect.Y - placeRect.Height / 2)), SpriteColor * 0.8f, scale: Scale * scale);
}
else
{

View File

@@ -326,6 +326,33 @@ namespace Barotrauma
Color.Green, width: 2);
}
}
foreach (MapEntity e in linkedTo)
{
if (e is Hull)
{
Hull linkedHull = (Hull)e;
Rectangle connectedHullRect = e.Submarine == null ?
linkedHull.rect :
new Rectangle(
(int)(Submarine.DrawPosition.X + linkedHull.WorldPosition.X),
(int)(Submarine.DrawPosition.Y + linkedHull.WorldPosition.Y),
linkedHull.WorldRect.Width, linkedHull.WorldRect.Height);
//center of the hull
Rectangle currentHullRect = Submarine == null ?
WorldRect :
new Rectangle(
(int)(Submarine.DrawPosition.X + WorldPosition.X),
(int)(Submarine.DrawPosition.Y + WorldPosition.Y),
WorldRect.Width, WorldRect.Height);
GUI.DrawLine(spriteBatch,
new Vector2(currentHullRect.X, -currentHullRect.Y),
new Vector2(connectedHullRect.X, -connectedHullRect.Y),
Color.Green, width: 2);
}
}
}
public static void UpdateVertices(GraphicsDevice graphicsDevice, Camera cam, WaterRenderer renderer)

View File

@@ -22,7 +22,7 @@ namespace Barotrauma
drawRect = new Rectangle(
(int)(drawRect.X * scale) + drawArea.Center.X, -((int)((drawRect.Y - drawRect.Height) * scale) + drawArea.Center.Y),
(int)(drawRect.Width * scale), (int)(drawRect.Height * scale));
entity.First.DrawPlacing(spriteBatch, drawRect, entity.First.Scale * scale);
entity.First.DrawPlacing(spriteBatch, drawRect, scale);
}
}
@@ -34,7 +34,7 @@ namespace Barotrauma
{
Rectangle drawRect = entity.Second;
drawRect.Location += Submarine.MouseToWorldGrid(cam, Submarine.MainSub).ToPoint();
entity.First.DrawPlacing(spriteBatch, drawRect, entity.First.Scale);
entity.First.DrawPlacing(spriteBatch, drawRect);
}
}

View File

@@ -105,7 +105,7 @@ namespace Barotrauma
if (Vector2.DistanceSquared(bodyPos, levelWall.Body.Position) > 0.5f)
{
levelWall.Body.SetTransformIgnoreContacts(ref bodyPos, levelWall.Body.Rotation);
levelWall.Body.SetTransform(bodyPos, levelWall.Body.Rotation);
}
}
}

View File

@@ -255,9 +255,9 @@ namespace Barotrauma
Duration = CurrentLocation == location ? 1.0f : 2.0f,
StartDelay = 1.0f
};
if (change.Messages != null && change.Messages.Count > 0)
if (change.Messages.Count > 0)
{
mapAnim.EndMessage = change.Messages[Rand.Range(0, change.Messages.Count)]
mapAnim.EndMessage = change.Messages[Rand.Range(0,change.Messages.Count)]
.Replace("[previousname]", prevName)
.Replace("[name]", location.Name);
}
@@ -380,10 +380,7 @@ namespace Barotrauma
zoom += PlayerInput.ScrollWheelSpeed / 1000.0f;
zoom = MathHelper.Clamp(zoom, 1.0f, 4.0f);
if (PlayerInput.MidButtonHeld() || (highlightedLocation == null && PlayerInput.LeftButtonHeld()))
{
drawOffset += PlayerInput.MouseSpeed / zoom;
}
if (PlayerInput.MidButtonHeld()) { drawOffset += PlayerInput.MouseSpeed / zoom; }
#if DEBUG
if (PlayerInput.DoubleClicked() && highlightedLocation != null)
{
@@ -624,9 +621,7 @@ namespace Barotrauma
if (mouseOn && PlayerInput.LeftButtonClicked() && !messageBoxOpen)
{
//TODO: translate or replace
var messageBox = new GUIMessageBox("Mysteries lie ahead...", "This area is unreachable in this version of Barotrauma. Please wait for future updates!");
messageBoxOpen = true;
CoroutineManager.StartCoroutine(WaitForMessageBoxClosed(messageBox));
}
}

View File

@@ -504,19 +504,8 @@ namespace Barotrauma
{
foreach (MapEntity e in selectedList)
{
SpriteEffects spriteEffects = SpriteEffects.None;
if (e is Item item)
{
if (item.FlippedX && item.Prefab.CanSpriteFlipX) spriteEffects ^= SpriteEffects.FlipHorizontally;
if (item.flippedY && item.Prefab.CanSpriteFlipY) spriteEffects ^= SpriteEffects.FlipVertically;
}
else if (e is Structure structure)
{
if (structure.FlippedX && structure.Prefab.CanSpriteFlipX) spriteEffects ^= SpriteEffects.FlipHorizontally;
if (structure.flippedY && structure.Prefab.CanSpriteFlipY) spriteEffects ^= SpriteEffects.FlipVertically;
}
e.prefab?.DrawPlacing(spriteBatch,
new Rectangle(e.WorldRect.Location + new Point((int)moveAmount.X, (int)-moveAmount.Y), e.WorldRect.Size), e.Scale, spriteEffects);
new Rectangle(e.WorldRect.Location + new Point((int)moveAmount.X, (int)-moveAmount.Y), e.WorldRect.Size));
GUI.DrawRectangle(spriteBatch,
new Vector2(e.WorldRect.X, -e.WorldRect.Y) + moveAmount,
new Vector2(e.rect.Width, e.rect.Height),

View File

@@ -37,7 +37,7 @@ namespace Barotrauma
}
}
public virtual void DrawPlacing(SpriteBatch spriteBatch, Rectangle drawRect, float scale = 1.0f, SpriteEffects spriteEffects = SpriteEffects.None)
public virtual void DrawPlacing(SpriteBatch spriteBatch, Rectangle drawRect, float scale = 1.0f)
{
if (Submarine.MainSub != null)
{

View File

@@ -1,9 +1,6 @@
using Barotrauma.Extensions;
using Barotrauma.Lights;
using Barotrauma.Networking;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
@@ -46,14 +43,6 @@ namespace Barotrauma
}
}
private string specialTag;
[Editable, Serialize("", true)]
public string SpecialTag
{
get { return specialTag; }
set { specialTag = value; }
}
// Only for testing in the debug build. Not saved.
#if DEBUG
[Editable, Serialize(true, false)]
@@ -113,7 +102,7 @@ namespace Barotrauma
editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this };
GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null);
var editor = new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, elementHeight: 20);
var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, 20)), isHorizontal: true)
{
Stretch = true,
@@ -168,20 +157,6 @@ namespace Barotrauma
{
Vector2 pos = ConvertUnits.ToDisplayUnits(f2.Body.Position);
int section = FindSectionIndex(pos);
if (section > -1)
{
Vector2 normal = contact.Manifold.LocalNormal;
float impact = Vector2.Dot(f2.Body.LinearVelocity, -normal) * f2.Body.Mass * 0.1f;
if (impact > 10.0f)
{
SoundPlayer.PlayDamageSound("StructureBlunt", impact, SectionPosition(section, true), tags: Tags);
}
}
}
}
public override bool IsVisible(Rectangle worldView)
{
Rectangle worldRect = WorldRect;
@@ -218,7 +193,7 @@ namespace Barotrauma
if (HasBody && !ShowWalls) return;
}
Color color = IsHighlighted ? Color.Orange : spriteColor;
Color color = isHighlighted ? Color.Orange : spriteColor;
if (IsSelected && editing)
{
//color = Color.Lerp(color, Color.Gold, 0.5f);
@@ -266,35 +241,62 @@ namespace Barotrauma
}
dropShadowOffset.Y = -dropShadowOffset.Y;
}
SpriteEffects oldEffects = Prefab.BackgroundSprite.effects;
Prefab.BackgroundSprite.effects ^= SpriteEffects;
Point backGroundOffset = new Point(
MathUtils.PositiveModulo((int)-textureOffset.X, Prefab.BackgroundSprite.SourceRect.Width),
MathUtils.PositiveModulo((int)-textureOffset.Y, Prefab.BackgroundSprite.SourceRect.Height));
Prefab.BackgroundSprite.DrawTiled(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)),
new Vector2(rect.Width, rect.Height),
color: color,
textureScale: TextureScale * Scale,
startOffset: backGroundOffset);
if (UseDropShadow)
if (DrawTiled)
{
SpriteEffects oldEffects = Prefab.BackgroundSprite.effects;
Prefab.BackgroundSprite.effects ^= SpriteEffects;
Point backGroundOffset = new Point(
MathUtils.PositiveModulo((int)-textureOffset.X, Prefab.BackgroundSprite.SourceRect.Width),
MathUtils.PositiveModulo((int)-textureOffset.Y, Prefab.BackgroundSprite.SourceRect.Height));
Prefab.BackgroundSprite.DrawTiled(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)) + dropShadowOffset,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)),
new Vector2(rect.Width, rect.Height),
color: Color.Black * 0.5f,
color: color,
textureScale: TextureScale * Scale,
startOffset: backGroundOffset,
depth: (depth + Prefab.BackgroundSprite.Depth) / 2.0f);
}
startOffset: backGroundOffset);
Prefab.BackgroundSprite.effects = oldEffects;
if (UseDropShadow)
{
Prefab.BackgroundSprite.DrawTiled(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)) + dropShadowOffset,
new Vector2(rect.Width, rect.Height),
color: Color.Black * 0.5f,
textureScale: TextureScale * Scale,
startOffset: backGroundOffset,
depth: (depth + Prefab.BackgroundSprite.Depth) / 2.0f);
}
Prefab.BackgroundSprite.effects = oldEffects;
}
else
{
Prefab.BackgroundSprite.Draw(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)),
color,
Vector2.Zero,
scale: Scale,
rotate: 0,
spriteEffect: SpriteEffects);
if (UseDropShadow)
{
Prefab.BackgroundSprite.Draw(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)) + dropShadowOffset,
Color.Black * 0.5f,
Vector2.Zero,
scale: Scale,
rotate: 0,
spriteEffect: SpriteEffects,
depth: (depth + Prefab.BackgroundSprite.Depth) / 2.0f);
}
}
}
}
@@ -321,25 +323,39 @@ namespace Barotrauma
Submarine.DamageEffectColor = color;
}
}
Point sectionOffset = new Point(
Math.Abs(rect.Location.X - Sections[i].rect.Location.X),
Math.Abs(rect.Location.Y - Sections[i].rect.Location.Y));
if (FlippedX && IsHorizontal) sectionOffset.X = Sections[i].rect.Right - rect.Right;
if (FlippedY && !IsHorizontal) sectionOffset.Y = (rect.Y - rect.Height) - (Sections[i].rect.Y - Sections[i].rect.Height);
if (DrawTiled)
{
Point sectionOffset = new Point(
Math.Abs(rect.Location.X - Sections[i].rect.Location.X),
Math.Abs(rect.Location.Y - Sections[i].rect.Location.Y));
sectionOffset.X += MathUtils.PositiveModulo((int)-textureOffset.X, prefab.sprite.SourceRect.Width);
sectionOffset.Y += MathUtils.PositiveModulo((int)-textureOffset.Y, prefab.sprite.SourceRect.Height);
if (FlippedX && IsHorizontal) sectionOffset.X = Sections[i].rect.Right - rect.Right;
if (FlippedY && !IsHorizontal) sectionOffset.Y = (rect.Y - rect.Height) - (Sections[i].rect.Y - Sections[i].rect.Height);
prefab.sprite.DrawTiled(
spriteBatch,
new Vector2(Sections[i].rect.X + drawOffset.X, -(Sections[i].rect.Y + drawOffset.Y)),
new Vector2(Sections[i].rect.Width, Sections[i].rect.Height),
color: color,
startOffset: sectionOffset,
depth: depth,
textureScale: TextureScale * Scale);
sectionOffset.X += MathUtils.PositiveModulo((int)-textureOffset.X, prefab.sprite.SourceRect.Width);
sectionOffset.Y += MathUtils.PositiveModulo((int)-textureOffset.Y, prefab.sprite.SourceRect.Height);
prefab.sprite.DrawTiled(
spriteBatch,
new Vector2(Sections[i].rect.X + drawOffset.X, -(Sections[i].rect.Y + drawOffset.Y)),
new Vector2(Sections[i].rect.Width, Sections[i].rect.Height),
color: color,
startOffset: sectionOffset,
depth: depth,
textureScale: TextureScale * Scale);
}
else
{
prefab.sprite.Draw(
spriteBatch,
new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)),
color,
Vector2.Zero,
scale: Scale,
rotate: 0,
spriteEffect: SpriteEffects);
}
}
prefab.sprite.effects = oldEffects;
}
@@ -360,20 +376,6 @@ namespace Barotrauma
-Bodies[i].Rotation, Color.White);
}
}
if (SectionCount > 0 && HasBody)
{
for (int i = 0; i < SectionCount; i++)
{
if (GetSection(i).damage > 0)
{
var textPos = SectionPosition(i, true);
textPos.Y = -textPos.Y;
GUI.DrawString(spriteBatch, textPos, "Damage: " + (int)((GetSection(i).damage / Health) * 100f) + "%", Color.Yellow);
}
}
}
AiTarget?.Draw(spriteBatch);
}
}

View File

@@ -32,19 +32,10 @@ namespace Barotrauma
GUI.DrawRectangle(spriteBatch, new Rectangle(newRect.X, -newRect.Y - GameMain.GraphicsHeight, newRect.Width, newRect.Height + GameMain.GraphicsHeight * 2), Color.White);
}
public override void DrawPlacing(SpriteBatch spriteBatch, Rectangle placeRect, float scale = 1.0f, SpriteEffects spriteEffects = SpriteEffects.None)
public override void DrawPlacing(SpriteBatch spriteBatch, Rectangle placeRect, float scale = 1.0f)
{
SpriteEffects oldEffects = sprite.effects;
sprite.effects ^= spriteEffects;
sprite.DrawTiled(
spriteBatch,
new Vector2(placeRect.X, -placeRect.Y),
new Vector2(placeRect.Width, placeRect.Height),
color: Color.White * 0.8f,
textureScale: TextureScale * scale);
sprite.effects = oldEffects;
// TODO: the scale property is not used
sprite.DrawTiled(spriteBatch, new Vector2(placeRect.X, -placeRect.Y), new Vector2(placeRect.Width, placeRect.Height), color: Color.White * 0.8f, textureScale: TextureScale * Scale);
}
}
}

View File

@@ -315,7 +315,7 @@ namespace Barotrauma
var dimensionsText = new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("Dimensions"), textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(0.45f, 0.0f), dimensionsText.RectTransform, Anchor.TopRight),
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), dimensionsText.RectTransform, Anchor.TopRight),
dimensionsStr, textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
dimensionsText.RectTransform.MinSize = new Point(0, dimensionsText.Children.First().Rect.Height);
@@ -326,7 +326,7 @@ namespace Barotrauma
var crewSizeText = new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("RecommendedCrewSize"), textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(0.45f, 0.0f), crewSizeText.RectTransform, Anchor.TopRight),
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), crewSizeText.RectTransform, Anchor.TopRight),
RecommendedCrewSizeMin + " - " + RecommendedCrewSizeMax, textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
crewSizeText.RectTransform.MinSize = new Point(0, crewSizeText.Children.First().Rect.Height);
@@ -337,7 +337,7 @@ namespace Barotrauma
var crewExperienceText = new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("RecommendedCrewExperience"), textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(0.45f, 0.0f), crewExperienceText.RectTransform, Anchor.TopRight),
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), crewExperienceText.RectTransform, Anchor.TopRight),
TextManager.Get(RecommendedCrewExperience), textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
crewExperienceText.RectTransform.MinSize = new Point(0, crewExperienceText.Children.First().Rect.Height);
@@ -348,21 +348,18 @@ namespace Barotrauma
var contentPackagesText = new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("RequiredContentPackages"), textAlignment: Alignment.TopLeft, font: GUI.Font)
{ CanBeFocused = false };
new GUITextBlock(new RectTransform(new Vector2(0.45f, 0.0f), contentPackagesText.RectTransform, Anchor.TopRight),
new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), contentPackagesText.RectTransform, Anchor.TopRight),
string.Join(", ", RequiredContentPackages), textAlignment: Alignment.TopLeft, font: GUI.Font, wrap: true)
{ CanBeFocused = false };
contentPackagesText.RectTransform.MinSize = new Point(0, contentPackagesText.Children.First().Rect.Height);
}
GUITextBlock.AutoScaleAndNormalize(descriptionBox.Content.Children.Where(c => c is GUITextBlock).Cast<GUITextBlock>());
//space
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), descriptionBox.Content.RectTransform), style: null);
if (Description.Length != 0)
{
new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform),
TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true) { CanBeFocused = false, ForceUpperCase = true };
new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), TextManager.Get("SaveSubDialogDescription") + ":", font: GUI.Font, wrap: true) { CanBeFocused = false, ForceUpperCase = true };
}
new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Description, font: GUI.Font, wrap: true)

View File

@@ -42,17 +42,10 @@ namespace Barotrauma
bool displace = moveAmount.LengthSquared() > 100.0f * 100.0f;
foreach (Submarine sub in subsToMove)
{
sub.PhysicsBody.SetTransform(sub.PhysicsBody.SimPosition + ConvertUnits.ToSimUnits(moveAmount), 0.0f);
sub.PhysicsBody.LinearVelocity = newVelocity;
if (displace)
{
sub.PhysicsBody.SetTransform(sub.PhysicsBody.SimPosition + ConvertUnits.ToSimUnits(moveAmount), 0.0f);
sub.SubBody.DisplaceCharacters(moveAmount);
}
else
{
sub.PhysicsBody.SetTransformIgnoreContacts(sub.PhysicsBody.SimPosition + ConvertUnits.ToSimUnits(moveAmount), 0.0f);
}
if (displace) sub.SubBody.DisplaceCharacters(moveAmount);
}
if (closestSub != null && subsToMove.Contains(closestSub))
@@ -62,6 +55,7 @@ namespace Barotrauma
if (Character.Controlled != null) Character.Controlled.CursorPosition += moveAmount;
}
}
}
}

View File

@@ -61,7 +61,7 @@ namespace Barotrauma.Networking
{
orderOption = order.Options[optionIndex];
}
txt = order.GetChatMessage(targetCharacter?.Name, senderCharacter?.CurrentHull?.DisplayName, givingOrderToSelf: targetCharacter == senderCharacter, orderOption: orderOption);
txt = order.GetChatMessage(targetCharacter?.Name, senderCharacter?.CurrentHull?.RoomName, givingOrderToSelf: targetCharacter == senderCharacter, orderOption: orderOption);
if (order.TargetAllCharacters)
{

View File

@@ -26,7 +26,6 @@ namespace Barotrauma.Networking
//TODO: move these to NetLobbyScreen
public GUIButton EndRoundButton;
public GUITickBox EndVoteTickBox;
private GUIComponent buttonContainer;
private NetStats netStats;
@@ -130,7 +129,7 @@ namespace Barotrauma.Networking
chatBox.OnEnterMessage += EnterChatMessage;
chatBox.InputBox.OnTextChanged += TypingChatMessage;
buttonContainer = new GUILayoutGroup(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ButtonAreaTop, inGameHUD.RectTransform),
var buttonContainer = new GUILayoutGroup(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ButtonAreaTop, inGameHUD.RectTransform),
isHorizontal: true, childAnchor: Anchor.CenterRight)
{
AbsoluteSpacing = 5,
@@ -631,11 +630,13 @@ namespace Barotrauma.Networking
}
else
{
GameMain.GameSession?.CrewManager?.SetClientSpeaking(myClient);
GameMain.GameSession?.CrewManager?.SetPlayerSpeaking(myClient);
}
}
}
if (gameStarted) SetRadioButtonColor();
if (ShowNetStats && client?.ServerConnection != null)
{
netStats.AddValue(NetStats.NetStatType.ReceivedBytes, client.ServerConnection.Statistics.ReceivedBytes);
@@ -1079,8 +1080,6 @@ namespace Barotrauma.Networking
bool isTraitor = inc.ReadBoolean();
string traitorTargetName = isTraitor ? inc.ReadString() : null;
bool allowRagdollButton = inc.ReadBoolean();
serverSettings.ReadMonsterEnabled(inc);
GameModePreset gameMode = GameModePreset.List.Find(gm => gm.Identifier == modeIdentifier);
@@ -1097,7 +1096,6 @@ namespace Barotrauma.Networking
GameMain.LightManager.LosMode = (LosMode)losMode;
serverSettings.AllowDisguises = disguisesAllowed;
serverSettings.AllowRagdollButton = allowRagdollButton;
if (campaign == null)
{
@@ -2126,7 +2124,9 @@ namespace Barotrauma.Networking
protected GUIFrame inGameHUD;
protected ChatBox chatBox;
public GUIButton ShowLogButton; //TODO: move to NetLobbyScreen
private float myCharacterFrameOpenState;
public GUIFrame InGameHUD
{
get { return inGameHUD; }
@@ -2136,7 +2136,22 @@ namespace Barotrauma.Networking
{
get { return chatBox; }
}
protected void SetRadioButtonColor()
{
if (Character.Controlled == null || Character.Controlled.SpeechImpediment >= 100.0f)
{
chatBox.RadioButton.GetChild<GUIImage>().Color = new Color(60, 60, 60, 255);
}
else
{
var radioItem = Character.Controlled?.Inventory?.Items.FirstOrDefault(i => i?.GetComponent<WifiComponent>() != null);
chatBox.RadioButton.GetChild<GUIImage>().Color =
(radioItem != null && Character.Controlled.HasEquippedItem(radioItem) && radioItem.GetComponent<WifiComponent>().CanTransmit()) ?
Color.White : new Color(60, 60, 60, 255);
}
}
public bool TypingChatMessage(GUITextBox textBox, string text)
{
return chatBox.TypingChatMessage(textBox, text);
@@ -2168,6 +2183,11 @@ namespace Barotrauma.Networking
Screen.Selected == GameMain.GameScreen)
{
inGameHUD.AddToGUIUpdateList();
if (Character.Controlled == null)
{
GameMain.NetLobbyScreen.MyCharacterFrame.AddToGUIUpdateList();
}
}
}
@@ -2186,17 +2206,24 @@ namespace Barotrauma.Networking
if (gameStarted && Screen.Selected == GameMain.GameScreen)
{
bool disableButtons =
Character.Controlled != null &&
Character.Controlled.SelectedConstruction?.GetComponent<Controller>() != null;
buttonContainer.Visible = !disableButtons;
if (!GUI.DisableHUD && !GUI.DisableUpperHUD)
{
inGameHUD.UpdateManually(deltaTime);
chatBox.Update(deltaTime);
cameraFollowsSub.Visible = Character.Controlled == null;
if (Character.Controlled == null)
{
myCharacterFrameOpenState = GameMain.NetLobbyScreen.MyCharacterFrameOpen ? myCharacterFrameOpenState + deltaTime * 5 : myCharacterFrameOpenState - deltaTime * 5;
myCharacterFrameOpenState = MathHelper.Clamp(myCharacterFrameOpenState, 0.0f, 1.0f);
var myCharFrame = GameMain.NetLobbyScreen.MyCharacterFrame;
int padding = GameMain.GraphicsWidth - myCharFrame.Parent.Rect.Right;
myCharFrame.RectTransform.AbsoluteOffset =
Vector2.SmoothStep(new Vector2(-myCharFrame.Rect.Width - padding, 0.0f), new Vector2(-padding, 0), myCharacterFrameOpenState).ToPoint();
}
}
if (Character.Controlled == null || Character.Controlled.IsDead)
{

View File

@@ -25,7 +25,6 @@ namespace Barotrauma.Networking
public SelectionMode? ModeSelectionMode;
public SelectionMode? SubSelectionMode;
public bool? AllowSpectating;
public bool? VoipEnabled;
public bool? AllowRespawn;
public YesNoMaybe? TraitorsEnabled;
public string GameMode;
@@ -151,14 +150,11 @@ namespace Barotrauma.Networking
else
allowRespawn.Selected = AllowRespawn.Value;
var voipEnabledTickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("serversettingsvoicechatenabled"))
/*new GUITickBox(new RectTransform(new Vector2(1.0f, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListHasPassword"))
{
Selected = HasPassword,
CanBeFocused = false
};
if (!VoipEnabled.HasValue)
new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), voipEnabledTickBox.Box.RectTransform, Anchor.Center), "?", textAlignment: Alignment.Center);
else
voipEnabledTickBox.Selected = VoipEnabled.Value;
};*/
var usingWhiteList = new GUITickBox(new RectTransform(new Vector2(1, elementHeight), columnRight.RectTransform), TextManager.Get("ServerListUsingWhitelist"))
{

View File

@@ -24,8 +24,8 @@ namespace Barotrauma.Networking
return true;
};
GUIFrame innerFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.5f), LogFrame.RectTransform, Anchor.Center) { MinSize = new Point(700, 500) });
GUIFrame paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.95f, 0.85f), innerFrame.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.0f, -0.03f) }, style: null);
GUIFrame innerFrame = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.4f), LogFrame.RectTransform, Anchor.Center) { MinSize = new Point(600, 420) });
GUIFrame paddedFrame = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.85f), innerFrame.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.0f, -0.03f) }, style: null);
new GUITextBlock(new RectTransform(new Vector2(0.75f, 0.05f), paddedFrame.RectTransform, Anchor.TopRight), TextManager.Get("ServerLog.Filter"), font: GUI.SmallFont);
GUITextBox searchBox = new GUITextBox(new RectTransform(new Vector2(0.6f, 0.05f), paddedFrame.RectTransform, Anchor.TopRight), font: GUI.SmallFont);
@@ -45,12 +45,20 @@ namespace Barotrauma.Networking
listBox = new GUIListBox(new RectTransform(new Vector2(0.75f, 0.95f), paddedFrame.RectTransform, Anchor.BottomRight));
var tickBoxContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.2f, 0.95f), paddedFrame.RectTransform, Anchor.BottomLeft));
var tickBoxContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.25f, 0.95f), paddedFrame.RectTransform, Anchor.BottomLeft));
int y = 30;
List<GUITickBox> tickBoxes = new List<GUITickBox>();
foreach (MessageType msgType in Enum.GetValues(typeof(MessageType)))
{
var tickBox = new GUITickBox(new RectTransform(new Point(tickBoxContainer.Rect.Width, 30), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[(int)msgType]), font: GUI.SmallFont)
var tickBox = new GUITickBox(new RectTransform(new Point(20, 20), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[(int)msgType]), font: GUI.SmallFont)
{
Selected = true,
TextColor = messageColor[(int)msgType]
};
tickBox.OnSelected += (GUITickBox tb) =>
{
Selected = true,
TextColor = messageColor[(int)msgType],

View File

@@ -295,7 +295,7 @@ namespace Barotrauma.Networking
OnClicked = SelectSettingsTab
};
}
GUITextBlock.AutoScaleAndNormalize(tabButtons.Select(b => b.TextBlock));
SelectSettingsTab(tabButtons[0], 0);
//"Close"
@@ -388,7 +388,7 @@ namespace Barotrauma.Networking
ToolTip = TextManager.Get("ServerSettingsMinRespawnToolTip")
};
string minRespawnLabel = TextManager.Get("ServerSettingsMinRespawn") + " ";
string minRespawnLabel = TextManager.Get("ServerSettingsMinRespawn");
CreateLabeledSlider(roundsTab, "", out slider, out sliderLabel);
slider.ToolTip = minRespawnText.ToolTip;
slider.UserData = minRespawnText;
@@ -407,7 +407,7 @@ namespace Barotrauma.Networking
ToolTip = TextManager.Get("ServerSettingsRespawnDurationToolTip")
};
string respawnDurationLabel = TextManager.Get("ServerSettingsRespawnDuration") + " ";
string respawnDurationLabel = TextManager.Get("ServerSettingsRespawnDuration");
CreateLabeledSlider(roundsTab, "", out slider, out sliderLabel);
slider.ToolTip = respawnDurationText.ToolTip;
slider.UserData = respawnDurationText;
@@ -471,7 +471,7 @@ namespace Barotrauma.Networking
{
string translatedLabel = TextManager.Get($"Character.{s}", true);
var monsterEnabledBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), monsterFrame.Content.RectTransform) { MinSize = new Point(0, 25) },
label: translatedLabel ?? s)
label: translatedLabel != null ? translatedLabel : s)
{
Selected = tempMonsterEnabled[s],
OnSelected = (GUITickBox tb) =>
@@ -504,8 +504,6 @@ namespace Barotrauma.Networking
return true;
};
GUITextBlock.AutoScaleAndNormalize(buttonHolder.Children.Select(c => ((GUIButton)c).TextBlock));
foreach (ItemPrefab ip in MapEntityPrefab.List.Where(p => p is ItemPrefab).Select(p => p as ItemPrefab))
{
if (!ip.CanBeBought && !ip.Tags.Contains("smallitem")) continue;
@@ -575,7 +573,7 @@ namespace Barotrauma.Networking
//***********************************************
string autoRestartDelayLabel = TextManager.Get("ServerSettingsAutoRestartDelay") + " ";
string autoRestartDelayLabel = TextManager.Get("ServerSettingsAutoRestartDelay");
var startIntervalText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), serverTab.RectTransform), autoRestartDelayLabel);
var startIntervalSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), serverTab.RectTransform), barSize: 0.1f)
{
@@ -619,7 +617,7 @@ namespace Barotrauma.Networking
GetPropertyData("AllowVoteKick").AssignGUIComponent(voteKickBox);
CreateLabeledSlider(serverTab, "ServerSettingsKickVotesRequired", out slider, out sliderLabel);
string votesRequiredLabel = sliderLabel.Text + " ";
string votesRequiredLabel = sliderLabel.Text;
slider.Step = 0.2f;
slider.Range = new Vector2(0.5f, 1.0f);
slider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -631,7 +629,7 @@ namespace Barotrauma.Networking
slider.OnMoved(slider, slider.BarScroll);
CreateLabeledSlider(serverTab, "ServerSettingsAutobanTime", out slider, out sliderLabel);
string autobanLabel = sliderLabel.Text + " ";
string autobanLabel = sliderLabel.Text;
slider.Step = 0.05f;
slider.Range = new Vector2(0.0f, MaxAutoBanTime);
slider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -683,8 +681,8 @@ namespace Barotrauma.Networking
traitorRatioSlider.Range = new Vector2(1.0f, maxPlayers);
}
string traitorRatioLabel = TextManager.Get("ServerSettingsTraitorRatio") + " ";
string traitorCountLabel = TextManager.Get("ServerSettingsTraitorCount") + " ";
string traitorRatioLabel = TextManager.Get("ServerSettingsTraitorRatio");
string traitorCountLabel = TextManager.Get("ServerSettingsTraitorCount");
traitorRatioSlider.Range = new Vector2(0.1f, 1.0f);
traitorRatioSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>

View File

@@ -11,12 +11,6 @@ namespace Barotrauma.Steam
{
partial class SteamManager
{
private static List<string> initializationErrors = new List<string>();
public static IEnumerable<string> InitializationErrors
{
get { return initializationErrors; }
}
private SteamManager()
{
try
@@ -32,12 +26,12 @@ namespace Barotrauma.Steam
catch (DllNotFoundException)
{
isInitialized = false;
initializationErrors.Add("SteamDllNotFound");
new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("SteamDllNotFound"));
}
catch (Exception)
{
isInitialized = false;
initializationErrors.Add("SteamClientInitFailed");
new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("SteamClientInitFailed"));
}
if (!isInitialized)
@@ -220,7 +214,6 @@ namespace Barotrauma.Steam
}
if (s.Rules.ContainsKey("allowspectating")) serverInfo.AllowSpectating = s.Rules["allowspectating"] == "True";
if (s.Rules.ContainsKey("allowrespawn")) serverInfo.AllowRespawn = s.Rules["allowrespawn"] == "True";
if (s.Rules.ContainsKey("voicechatenabled")) serverInfo.VoipEnabled = s.Rules["voicechatenabled"] == "True";
if (s.Rules.ContainsKey("traitors"))
{
if (Enum.TryParse(s.Rules["traitors"], out YesNoMaybe traitorsEnabled)) serverInfo.TraitorsEnabled = traitorsEnabled;
@@ -589,23 +582,6 @@ namespace Barotrauma.Steam
ContentPackage contentPackage = new ContentPackage(metaDataFilePath);
string newContentPackagePath = GetWorkshopItemContentPackagePath(contentPackage);
if (!contentPackage.IsCompatible())
{
errorMsg = TextManager.Get(contentPackage.GameVersion <= new Version(0, 0, 0, 0) ? "IncompatibleContentPackageUnknownVersion" : "IncompatibleContentPackage")
.Replace("[packagename]", contentPackage.Name)
.Replace("[packageversion]", contentPackage.GameVersion.ToString())
.Replace("[gameversion]", GameMain.Version.ToString());
return false;
}
if (contentPackage.CorePackage && !contentPackage.ContainsRequiredCorePackageFiles(out List<ContentType> missingContentTypes))
{
errorMsg = TextManager.Get("ContentPackageMissingCoreFiles")
.Replace("[packagename]", contentPackage.Name)
.Replace("[missingfiletypes]", string.Join(", ", missingContentTypes));
return false;
}
var allPackageFiles = Directory.GetFiles(item.Directory.FullName, "*", SearchOption.AllDirectories);
List<string> nonContentFiles = new List<string>();
foreach (string file in allPackageFiles)
@@ -622,7 +598,7 @@ namespace Barotrauma.Steam
if (!allowFileOverwrite)
{
if (File.Exists(newContentPackagePath) && !CheckFileEquality(newContentPackagePath, metaDataFilePath))
if (File.Exists(newContentPackagePath))
{
errorMsg = TextManager.Get("WorkshopErrorOverwriteOnEnable")
.Replace("[itemname]", item.Title)
@@ -634,7 +610,7 @@ namespace Barotrauma.Steam
foreach (ContentFile contentFile in contentPackage.Files)
{
string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path);
if (File.Exists(sourceFile) && File.Exists(contentFile.Path) && !CheckFileEquality(sourceFile, contentFile.Path))
if (File.Exists(sourceFile) && File.Exists(contentFile.Path))
{
errorMsg = TextManager.Get("WorkshopErrorOverwriteOnEnable")
.Replace("[itemname]", item.Title)
@@ -650,41 +626,12 @@ namespace Barotrauma.Steam
foreach (ContentFile contentFile in contentPackage.Files)
{
string sourceFile = Path.Combine(item.Directory.FullName, contentFile.Path);
//path not allowed -> the content file must be a reference to an external file (such as some vanilla file outside the Mods folder)
if (!File.Exists(sourceFile)) { continue; }
if (!ContentPackage.IsModFilePathAllowed(contentFile))
{
//the content package is trying to copy a file to a prohibited path, which is not allowed
if (File.Exists(sourceFile))
{
errorMsg = TextManager.Get("WorkshopErrorIllegalPathOnEnable").Replace("[filename]", contentFile.Path);
return false;
}
//not trying to copy anything, so this is a reference to an external file
//if the external file doesn't exist, we cannot enable the package
else if (!File.Exists(contentFile.Path))
{
//TODO: add the error message to localization
errorMsg = TextManager.Get("WorkshopErrorEnableFailed").Replace("[itemname]", item.Title) + " {File \"" + contentFile.Path + "\" not found.}";
return false;
}
DebugConsole.ThrowError(TextManager.Get("WorkshopErrorIllegalPathOnEnable").Replace("[filename]", contentFile.Path));
continue;
}
else if (!File.Exists(sourceFile))
{
if (File.Exists(contentFile.Path))
{
//the file is already present in the game folder, all good
continue;
}
else
{
//file not present in either the mod or the game folder -> cannot enable the package
//TODO: add the error message to localization
errorMsg = TextManager.Get("WorkshopErrorEnableFailed").Replace("[itemname]", item.Title) + " {File \"" + contentFile.Path + "\" not found.}";
return false;
}
}
//make sure the destination directory exists
Directory.CreateDirectory(Path.GetDirectoryName(contentFile.Path));
@@ -706,7 +653,7 @@ namespace Barotrauma.Steam
}
catch (Exception e)
{
errorMsg = TextManager.Get("WorkshopErrorEnableFailed").Replace("[itemname]", item.Title) + " {" + e.Message + "}";
errorMsg = TextManager.Get("WorkshopErrorEnableFailed").Replace("[itemname]", item.Title) + " " + e.Message;
DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red);
return false;
}
@@ -735,22 +682,6 @@ namespace Barotrauma.Steam
return true;
}
private static bool CheckFileEquality(string filePath1, string filePath2)
{
if (filePath1 == filePath2)
{
return true;
}
using (FileStream fs1 = File.OpenRead(filePath1))
using (FileStream fs2 = File.OpenRead(filePath2))
{
Md5Hash hash1 = new Md5Hash(fs1);
Md5Hash hash2 = new Md5Hash(fs2);
return hash1.Hash == hash2.Hash;
}
}
/// <summary>
/// Disables a workshop item by removing the files from the game folder.
/// </summary>
@@ -877,7 +808,7 @@ namespace Barotrauma.Steam
{
foreach (ContentFile contentFile in contentPackage.Files)
{
if (!File.Exists(contentFile.Path)) { return false; }
if (!File.Exists(contentFile.Path)) return false;
}
}

View File

@@ -76,8 +76,7 @@ namespace Barotrauma.Networking
if (!GUIMessageBox.MessageBoxes.Any(mb => mb.UserData as string == "capturedevicenotfound"))
{
GUI.SettingsMenuOpen = false;
new GUIMessageBox(TextManager.Get("Error"),
TextManager.Get("VoipCaptureDeviceNotFound", returnNull: true) ?? "Could not start voice capture, suitable capture device not found.")
new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("VoipCaptureDeviceNotFound"))
{
UserData = "capturedevicenotfound"
};

View File

@@ -115,7 +115,7 @@ namespace Barotrauma.Networking
}
}
GameMain.NetLobbyScreen.SetPlayerSpeaking(client);
GameMain.GameSession?.CrewManager?.SetClientSpeaking(client);
GameMain.GameSession?.CrewManager?.SetPlayerSpeaking(client);
}
}

View File

@@ -30,7 +30,6 @@ namespace Barotrauma
[STAThread]
static void Main()
{
SteamManager.Initialize();
GameMain game = null;
#if !DEBUG
try
@@ -214,10 +213,6 @@ namespace Barotrauma
sb.AppendLine("Level seed: " + ((Level.Loaded == null) ? "no level loaded" : Level.Loaded.Seed));
sb.AppendLine("Loaded submarine: " + ((Submarine.MainSub == null) ? "None" : Submarine.MainSub.Name + " (" + Submarine.MainSub.MD5Hash + ")"));
sb.AppendLine("Selected screen: " + (Screen.Selected == null ? "None" : Screen.Selected.ToString()));
if (SteamManager.IsInitialized)
{
sb.AppendLine("SteamManager initialized");
}
if (GameMain.Client != null)
{

View File

@@ -16,6 +16,9 @@ namespace Barotrauma
private GUIListBox saveList;
private GUITextBox saveNameBox, seedBox;
private GUITickBox contextualTutorialBox;
private GUILayoutGroup subPreviewContainer;
private GUILayoutGroup subPreviewContainer;
@@ -23,6 +26,14 @@ namespace Barotrauma
public Action<Submarine, string, string> StartNewGame;
public Action<string> LoadGame;
public bool TutorialSelected
{
get
{
if (contextualTutorialBox == null) return false;
return contextualTutorialBox.Selected;
}
}
private readonly bool isMultiplayer;
@@ -54,31 +65,19 @@ namespace Barotrauma
// New game left side
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SaveName") + ":");
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); }
};
saveNameBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, string.Empty);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("MapSeed") + ":");
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") + ":");
var filterContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), leftColumn.RectTransform), isHorizontal: true)
if (!isMultiplayer)
{
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("FilterMapEntities"), 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);
searchBox.OnSelected += (sender, userdata) => { searchTitle.Visible = false; };
searchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
contextualTutorialBox = new GUITickBox(new RectTransform(new Point(32, 32), leftColumn.RectTransform), TextManager.Get("TutorialActive"));
UpdateTutorialSelection();
}
searchBox.OnTextChanged += (textBox, text) => { FilterSubs(subList, text); return true; };
var clearButton = new GUIButton(new RectTransform(new Vector2(0.075f, 1.0f), filterContainer.RectTransform), "x")
{
OnClicked = (btn, userdata) => { searchBox.Text = ""; FilterSubs(subList, ""); searchBox.Flash(Color.White); return true; }
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.02f), leftColumn.RectTransform) { MinSize = new Point(0, 20) }, TextManager.Get("SelectedSub") + ":");
subList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.65f), leftColumn.RectTransform)) { ScrollBarVisible = true };
if (!isMultiplayer) { subList.OnSelected = OnSubSelected; }
@@ -176,20 +175,10 @@ namespace Barotrauma
}
};
if (!isMultiplayer)
{
var disclaimerBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.8f), rightColumn.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(5) }, style: "GUINotificationButton")
{
IgnoreLayoutGroups = true,
OnClicked = (btn, userdata) => { GameMain.Instance.ShowCampaignDisclaimer(); return true; }
};
disclaimerBtn.RectTransform.MaxSize = new Point((int)(30 * GUI.Scale));
}
leftColumn.Recalculate();
rightColumn.Recalculate();
UpdateSubList(submarines);
UpdateLoadMenu(saveFiles);
}
@@ -199,16 +188,6 @@ namespace Barotrauma
seedBox.Text = ToolBox.RandomSeed(8);
}
private void FilterSubs(GUIListBox subList, string filter)
{
foreach (GUIComponent child in subList.Content.Children)
{
var sub = child.UserData as Submarine;
if (sub == null) { return; }
child.Visible = string.IsNullOrEmpty(filter) ? true : sub.Name.ToLower().Contains(filter.ToLower());
}
}
private bool OnSubSelected(GUIComponent component, object obj)
{
if (subPreviewContainer == null) { return false; }
@@ -280,7 +259,7 @@ namespace Barotrauma
{
IsFixedSize = false
},
TextManager.Get("Shuttle", fallBackTag: "RespawnShuttle"), textAlignment: Alignment.Right, font: GUI.SmallFont)
TextManager.Get("Shuttle"), textAlignment: Alignment.Right, font: GUI.SmallFont)
{
TextColor = textBlock.TextColor * 0.8f,
ToolTip = textBlock.ToolTip
@@ -398,7 +377,14 @@ namespace Barotrauma
},
Enabled = false
};
}
}
public void UpdateTutorialSelection()
{
if (isMultiplayer) return;
Tutorial contextualTutorial = Tutorial.Tutorials.Find(t => t is ContextualTutorial);
contextualTutorialBox.Selected = (contextualTutorial != null) ? !GameMain.Config.CompletedTutorialNames.Contains(contextualTutorial.Name) : true;
}
private bool SelectSaveFile(GUIComponent component, object obj)
{

View File

@@ -9,14 +9,16 @@ namespace Barotrauma
{
class CampaignUI
{
public enum Tab { Map, Crew, Store, Repair }
public enum Tab { Map, Crew, Store }
private Tab selectedTab;
private GUIFrame[] tabs;
private GUIFrame topPanel;
private GUIListBox characterList;
private GUIButton startButton;
private GUIFrame topPanel;
private MapEntityCategory selectedItemCategory = MapEntityCategory.Equipment;
private GUIListBox characterList;
private GUIListBox myItemList;
private GUIListBox storeItemList;
@@ -26,8 +28,6 @@ namespace Barotrauma
private GUIComponent selectedLocationInfo;
private GUIListBox selectedMissionInfo;
private GUIButton repairHullsButton, repairItemsButton;
private GUIFrame characterPreviewFrame;
private List<GUIButton> tabButtons = new List<GUIButton>();
@@ -41,7 +41,10 @@ namespace Barotrauma
public GUIComponent MapContainer { get; private set; }
public GUIButton StartButton { get; private set; }
public GUIButton StartButton
{
get { return startButton; }
}
public CampaignMode Campaign { get; }
@@ -69,7 +72,7 @@ namespace Barotrauma
var outpostBtn = new GUIButton(new RectTransform(new Vector2(0.15f, 0.55f), topPanelContent.RectTransform),
TextManager.Get("Outpost"), textAlignment: Alignment.Center, style: "GUISlopedHeader")
{
OnClicked = (btn, userdata) => { SelectTab(Tab.Map); return true; }
OnClicked = (btn, userdata) => { SelectTab(Tab.Map); return true; }
};
outpostBtn.TextBlock.Font = GUI.LargeFont;
outpostBtn.TextBlock.AutoScale = true;
@@ -78,6 +81,7 @@ namespace Barotrauma
int i = 0;
var tabValues = Enum.GetValues(typeof(Tab));
float minTextScale = 1.0f;
foreach (Tab tab in tabValues)
{
var tabButton = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tabButtonContainer.RectTransform),
@@ -92,12 +96,17 @@ namespace Barotrauma
var buttonSprite = tabButton.Style.Sprites[GUIComponent.ComponentState.None][0];
tabButton.RectTransform.MaxSize = new Point(
(int)(tabButton.Rect.Height * (buttonSprite.Sprite.size.X / buttonSprite.Sprite.size.Y)), int.MaxValue);
tabButtons.Add(tabButton);
tabButton.Font = GUI.LargeFont;
tabButton.TextBlock.AutoScale = true;
minTextScale = Math.Min(tabButton.TextBlock.TextScale, minTextScale);
i++;
}
GUITextBlock.AutoScaleAndNormalize(tabButtons.Select(t => t.TextBlock));
foreach (GUIButton tabButton in tabButtons)
{
tabButton.TextBlock.TextScale = minTextScale;
}
// crew tab -------------------------------------------------------------------------
@@ -105,7 +114,7 @@ namespace Barotrauma
tabs[(int)Tab.Crew] = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.7f), container.RectTransform, Anchor.TopLeft)
{
RelativeOffset = new Vector2(0.0f, topPanel.RectTransform.RelativeSize.Y)
}, color: Color.Black * 0.9f);
}, color: Color.Black * 0.7f);
new GUIFrame(new RectTransform(new Vector2(1.25f, 1.25f), tabs[(int)Tab.Crew].RectTransform, Anchor.Center), style: "OuterGlow", color: Color.Black * 0.7f)
{
CanBeFocused = false
@@ -150,7 +159,7 @@ namespace Barotrauma
tabs[(int)Tab.Store] = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.7f), container.RectTransform, Anchor.TopLeft)
{
RelativeOffset = new Vector2(0.1f, topPanel.RectTransform.RelativeSize.Y)
}, color: Color.Black * 0.9f);
}, color: Color.Black * 0.7f);
new GUIFrame(new RectTransform(new Vector2(1.25f, 1.25f), tabs[(int)Tab.Store].RectTransform, Anchor.Center), style: "OuterGlow", color: Color.Black * 0.7f)
{
CanBeFocused = false
@@ -167,33 +176,15 @@ namespace Barotrauma
RelativeSpacing = 0.02f
};
var storeContentTop = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), storeContent.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft)
{
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), storeContentTop.RectTransform), "", font: GUI.LargeFont)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.1f), storeContent.RectTransform), "", font: GUI.LargeFont)
{
TextGetter = GetMoney
};
var filterContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.5f, 0.4f), storeContentTop.RectTransform), isHorizontal: true)
{
Stretch = true
};
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("FilterMapEntities"), textAlignment: Alignment.CenterLeft, font: GUI.Font);
searchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform), font: GUI.Font);
searchBox.OnSelected += (sender, userdata) => { searchTitle.Visible = false; };
searchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
searchBox.OnTextChanged += (textBox, text) => { FilterStoreItems(null, text); return true; };
var clearButton = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), filterContainer.RectTransform), "x")
{
OnClicked = (btn, userdata) => { searchBox.Text = ""; FilterStoreItems(selectedItemCategory, ""); searchBox.Flash(Color.White); return true; }
};
var storeItemLists = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.8f), storeContent.RectTransform), isHorizontal: true)
{
Stretch = true
Stretch = true,
RelativeSpacing = 0.02f
};
myItemList = new GUIListBox(new RectTransform(new Vector2(0.5f, 1.0f), storeItemLists.RectTransform));
storeItemList = new GUIListBox(new RectTransform(new Vector2(0.5f, 1.0f), storeItemLists.RectTransform))
@@ -211,7 +202,7 @@ namespace Barotrauma
"", style: "ItemCategory" + category.ToString())
{
UserData = category,
OnClicked = (btn, userdata) => { FilterStoreItems((MapEntityCategory)userdata, searchBox.Text); return true; }
OnClicked = (btn, userdata) => { SelectItemCategory((MapEntityCategory)userdata); return true; }
};
itemCategoryButtons.Add(categoryButton);
@@ -227,115 +218,7 @@ namespace Barotrauma
CanBeFocused = false
};
}
FillStoreItemList();
FilterStoreItems(MapEntityCategory.Equipment, "");
// repair tab -------------------------------------------------------------------------
tabs[(int)Tab.Repair] = new GUIFrame(new RectTransform(new Vector2(0.35f, 0.5f), container.RectTransform, Anchor.TopLeft)
{
RelativeOffset = new Vector2(0.02f, topPanel.RectTransform.RelativeSize.Y)
}, color: Color.Black * 0.9f);
new GUIFrame(new RectTransform(new Vector2(1.25f, 1.25f), tabs[(int)Tab.Repair].RectTransform, Anchor.Center), style: "OuterGlow", color: Color.Black * 0.7f)
{
CanBeFocused = false
};
var repairContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), tabs[(int)Tab.Repair].RectTransform, Anchor.Center))
{
RelativeSpacing = 0.05f,
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), repairContent.RectTransform), "", font: GUI.LargeFont)
{
TextGetter = GetMoney
};
var repairHullsHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), repairContent.RectTransform), childAnchor: Anchor.TopRight)
{
RelativeSpacing = 0.05f,
Stretch = true
};
new GUIImage(new RectTransform(new Vector2(0.3f, 1.0f), repairHullsHolder.RectTransform, Anchor.CenterLeft), "RepairHullButton")
{
IgnoreLayoutGroups = true,
CanBeFocused = false
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairHullsHolder.RectTransform), TextManager.Get("RepairAllWalls"), textAlignment: Alignment.Right, font: GUI.LargeFont)
{
ForceUpperCase = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairHullsHolder.RectTransform), "500", textAlignment: Alignment.Right, font: GUI.LargeFont);
repairHullsButton = new GUIButton(new RectTransform(new Vector2(0.4f, 0.3f), repairHullsHolder.RectTransform), TextManager.Get("Repair"), style: "GUIButtonLarge")
{
OnClicked = (btn, userdata) =>
{
if (campaign.PurchasedHullRepairs)
{
campaign.Money += CampaignMode.HullRepairCost;
campaign.PurchasedHullRepairs = false;
}
else
{
if (campaign.Money >= CampaignMode.HullRepairCost)
{
campaign.Money -= CampaignMode.HullRepairCost;
campaign.PurchasedHullRepairs = true;
}
}
GameMain.Client?.SendCampaignState();
btn.GetChild<GUITickBox>().Selected = campaign.PurchasedHullRepairs;
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.65f), repairHullsButton.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point(10, 0) }, "")
{
CanBeFocused = false
};
var repairItemsHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), repairContent.RectTransform), childAnchor: Anchor.TopRight)
{
RelativeSpacing = 0.05f,
Stretch = true
};
new GUIImage(new RectTransform(new Vector2(0.3f, 1.0f), repairItemsHolder.RectTransform, Anchor.CenterLeft), "RepairItemsButton")
{
IgnoreLayoutGroups = true,
CanBeFocused = false
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairItemsHolder.RectTransform), TextManager.Get("RepairAllItems"), textAlignment: Alignment.Right, font: GUI.LargeFont)
{
ForceUpperCase = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), repairItemsHolder.RectTransform), "500", textAlignment: Alignment.Right, font: GUI.LargeFont);
repairItemsButton = new GUIButton(new RectTransform(new Vector2(0.4f, 0.3f), repairItemsHolder.RectTransform), TextManager.Get("Repair"), style: "GUIButtonLarge")
{
OnClicked = (btn, userdata) =>
{
if (campaign.PurchasedItemRepairs)
{
campaign.Money += CampaignMode.ItemRepairCost;
campaign.PurchasedItemRepairs = false;
}
else
{
if (campaign.Money >= CampaignMode.ItemRepairCost)
{
campaign.Money -= CampaignMode.ItemRepairCost;
campaign.PurchasedItemRepairs = true;
}
}
GameMain.Client?.SendCampaignState();
btn.GetChild<GUITickBox>().Selected = campaign.PurchasedItemRepairs;
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.65f), repairItemsButton.RectTransform, Anchor.CenterLeft) { AbsoluteOffset = new Point(10, 0) }, "")
{
CanBeFocused = false
};
SelectItemCategory(MapEntityCategory.Equipment);
// mission info -------------------------------------------------------------------------
@@ -449,7 +332,8 @@ namespace Barotrauma
bool purchaseableItemsFound = false;
foreach (MapEntityPrefab mapEntityPrefab in MapEntityPrefab.List)
{
if (!(mapEntityPrefab is ItemPrefab itemPrefab)) { continue; }
var itemPrefab = mapEntityPrefab as ItemPrefab;
if (itemPrefab == null) { continue; }
PriceInfo priceInfo = itemPrefab.GetPrice(Campaign.Map.CurrentLocation);
if (priceInfo != null) { purchaseableItemsFound = true; break; }
@@ -466,9 +350,9 @@ namespace Barotrauma
else
{
//refresh store view
FillStoreItemList();
FilterStoreItems(MapEntityCategory.Equipment, searchBox.Text);
}
SelectItemCategory(MapEntityCategory.Equipment);
}
}
private void DrawMap(SpriteBatch spriteBatch, GUICustomComponent mapContainer)
@@ -570,7 +454,7 @@ namespace Barotrauma
RefreshMissionTab(selectedMission);
StartButton = new GUIButton(new RectTransform(new Vector2(0.3f, 0.7f), missionContent.RectTransform, Anchor.CenterRight),
startButton = new GUIButton(new RectTransform(new Vector2(0.3f, 0.7f), missionContent.RectTransform, Anchor.CenterRight),
TextManager.Get("StartCampaignButton"), style: "GUIButtonLarge")
{
IgnoreLayoutGroups = true,
@@ -579,7 +463,7 @@ namespace Barotrauma
};
if (GameMain.Client != null)
{
StartButton.Visible = !GameMain.Client.GameStarted &&
startButton.Visible = !GameMain.Client.GameStarted &&
(GameMain.Client.HasPermission(Networking.ClientPermissions.ManageRound) ||
GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign));
}
@@ -626,10 +510,10 @@ namespace Barotrauma
CanBeFocused = false
};
if (StartButton != null)
if (startButton != null)
{
StartButton.Enabled = true;
StartButton.Visible = GameMain.Client == null ||
startButton.Enabled = true;
startButton.Visible = GameMain.Client == null ||
GameMain.Client.HasPermission(Networking.ClientPermissions.ManageRound) ||
GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign);
}
@@ -715,7 +599,8 @@ namespace Barotrauma
private bool BuyItem(GUIComponent component, object obj)
{
if (!(obj is PurchasedItem pi) || pi.ItemPrefab == null) return false;
PurchasedItem pi = obj as PurchasedItem;
if (pi == null || pi.ItemPrefab == null) return false;
if (GameMain.Client != null && !GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign))
{
@@ -733,7 +618,8 @@ namespace Barotrauma
private bool SellItem(GUIComponent component, object obj)
{
if (!(obj is PurchasedItem pi) || pi.ItemPrefab == null) return false;
PurchasedItem pi = obj as PurchasedItem;
if (pi == null || pi.ItemPrefab == null) return false;
if (GameMain.Client != null && !GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign))
{
@@ -775,59 +661,35 @@ namespace Barotrauma
{
button.Selected = (Tab)button.UserData == tab;
}
switch (selectedTab)
{
case Tab.Repair:
repairHullsButton.Enabled =
(Campaign.PurchasedHullRepairs || Campaign.Money >= CampaignMode.HullRepairCost) &&
(GameMain.Client == null || GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign));
repairHullsButton.GetChild<GUITickBox>().Selected = Campaign.PurchasedHullRepairs;
repairItemsButton.Enabled =
(Campaign.PurchasedItemRepairs || Campaign.Money >= CampaignMode.ItemRepairCost) &&
(GameMain.Client == null || GameMain.Client.HasPermission(Networking.ClientPermissions.ManageCampaign));
repairItemsButton.GetChild<GUITickBox>().Selected = Campaign.PurchasedItemRepairs;
break;
}
}
private void FillStoreItemList()
private bool SelectItemCategory(MapEntityCategory category)
{
storeItemList.ClearChildren();
int width = storeItemList.Rect.Width;
foreach (MapEntityPrefab mapEntityPrefab in MapEntityPrefab.List)
{
if (!(mapEntityPrefab is ItemPrefab itemPrefab)) { continue; }
var itemPrefab = mapEntityPrefab as ItemPrefab;
if (itemPrefab == null || !itemPrefab.Category.HasFlag(category)) continue;
PriceInfo priceInfo = itemPrefab.GetPrice(Campaign.Map.CurrentLocation);
if (priceInfo == null) continue;
CreateItemFrame(new PurchasedItem(itemPrefab, 0), priceInfo, storeItemList, width);
}
storeItemList.Content.RectTransform.SortChildren(
(x, y) => (x.GUIComponent.UserData as PurchasedItem).ItemPrefab.Name.CompareTo((y.GUIComponent.UserData as PurchasedItem).ItemPrefab.Name));
}
private void FilterStoreItems(MapEntityCategory? category, string filter)
{
if (category.HasValue)
{
selectedItemCategory = category.Value;
}
foreach (GUIComponent child in storeItemList.Content.Children)
{
var item = child.UserData as PurchasedItem;
if (item?.ItemPrefab?.Name == null) { continue; }
child.Visible =
(!category.HasValue || item.ItemPrefab.Category.HasFlag(category.Value)) &&
(string.IsNullOrEmpty(filter) || item.ItemPrefab.Name.ToLower().Contains(searchBox.Text.ToLower()));
}
foreach (GUIButton btn in itemCategoryButtons)
{
btn.Selected = (MapEntityCategory)btn.UserData == selectedItemCategory;
btn.Selected = (MapEntityCategory)btn.UserData == category;
}
storeItemList.UpdateScrollBarSize();
storeItemList.BarScroll = 0.0f;
return true;
}
public string GetMoney()
@@ -847,8 +709,9 @@ namespace Barotrauma
}
if (prevInfoFrame != null) { tabs[(int)selectedTab].RemoveChild(prevInfoFrame); }
if (!(selection is CharacterInfo characterInfo)) { return false; }
CharacterInfo characterInfo = selection as CharacterInfo;
if (characterInfo == null) { return false; }
if (Character.Controlled != null && characterInfo == Character.Controlled.Info) { return false; }
if (characterPreviewFrame == null || characterPreviewFrame.UserData != characterInfo)
@@ -900,9 +763,11 @@ namespace Barotrauma
private bool HireCharacter(GUIButton button, object selection)
{
if (!(selection is CharacterInfo characterInfo)) { return false; }
CharacterInfo characterInfo = selection as CharacterInfo;
if (characterInfo == null) { return false; }
if (!(Campaign is SinglePlayerCampaign spCampaign))
SinglePlayerCampaign spCampaign = Campaign as SinglePlayerCampaign;
if (spCampaign == null)
{
DebugConsole.ThrowError("Characters can only be hired in the single player campaign.\n" + Environment.StackTrace);
return false;
@@ -921,9 +786,11 @@ namespace Barotrauma
private bool FireCharacter(GUIButton button, object selection)
{
if (!(selection is CharacterInfo characterInfo)) return false;
CharacterInfo characterInfo = selection as CharacterInfo;
if (characterInfo == null) return false;
if (!(Campaign is SinglePlayerCampaign spCampaign))
SinglePlayerCampaign spCampaign = Campaign as SinglePlayerCampaign;
if (spCampaign == null)
{
DebugConsole.ThrowError("Characters can only be fired in the single player campaign.\n" + Environment.StackTrace);
return false;

View File

@@ -42,16 +42,16 @@ namespace Barotrauma
private bool showParamsEditor;
private bool showSpritesheet;
private bool isFreezed;
private bool autoFreeze;
private bool limbPairEditing;
private bool uniformScaling;
private bool lockSpriteOrigin;
private bool autoFreeze = true;
private bool limbPairEditing = true;
private bool uniformScaling = true;
private bool lockSpriteOrigin = true;
private bool lockSpritePosition;
private bool lockSpriteSize;
private bool recalculateCollider;
private bool copyJointSettings;
private bool displayColliders;
private bool displayWearables;
private bool displayWearables = true;
private bool displayBackgroundColor;
private bool ragdollResetRequiresForceLoading;
private bool animationResetRequiresForceLoading;
@@ -89,16 +89,10 @@ namespace Barotrauma
public override void Select()
{
base.Select();
SoundPlayer.OverrideMusicType = "none";
SoundPlayer.OverrideMusicDuration = null;
GameMain.SoundManager.SetCategoryGainMultiplier("waterambience", 0.0f);
GUI.ForceMouseOn(null);
CalculateSpritesheetPosition();
if (Submarine.MainSub == null)
{
ResetVariables();
Submarine.MainSub = new Submarine("Content/AnimEditor.sub");
Submarine.MainSub.Load(unloadPrevious: false, showWarningMessages: false);
originalWall = new WallGroup(new List<Structure>(Structure.WallList));
@@ -107,10 +101,6 @@ namespace Barotrauma
isEndlessRunner = true;
GameMain.LightManager.LightingEnabled = false;
}
else if (instance == null)
{
ResetVariables();
}
Submarine.MainSub.GodMode = true;
if (Character.Controlled == null)
{
@@ -126,71 +116,33 @@ namespace Barotrauma
OpenDoors();
GameMain.Instance.OnResolutionChanged += OnResolutionChanged;
instance = this;
if (!GameMain.Config.EditorDisclaimerShown)
{
GameMain.Instance.ShowEditorDisclaimer();
}
}
private void ResetVariables()
{
editAnimations = false;
editLimbs = false;
editJoints = false;
editIK = false;
showRagdoll = false;
showParamsEditor = false;
showSpritesheet = false;
isFreezed = false;
autoFreeze = true;
limbPairEditing = true;
uniformScaling = true;
lockSpriteOrigin = false;
lockSpritePosition = false;
lockSpriteSize = false;
recalculateCollider = false;
copyJointSettings = false;
displayColliders = false;
displayWearables = true;
displayBackgroundColor = false;
ragdollResetRequiresForceLoading = false;
animationResetRequiresForceLoading = false;
isExtrudingJoint = false;
isDrawingJoint = false;
Wizard.instance = null;
}
private void Reset()
{
ResetVariables();
if (character != null)
AnimParams.ForEach(a => a.Reset(true));
RagdollParams.Reset(true);
RagdollParams.ClearHistory();
CurrentAnimation.ClearHistory();
if (!character.Removed)
{
AnimParams.ForEach(a => a.Reset(true));
RagdollParams.Reset(true);
RagdollParams.ClearHistory();
CurrentAnimation.ClearHistory();
if (!character.Removed)
{
character.Remove();
}
character = null;
character.Remove();
}
character = null;
}
public override void Deselect()
{
base.Deselect();
SoundPlayer.OverrideMusicType = null;
GameMain.SoundManager.SetCategoryGainMultiplier("waterambience", GameMain.Config.SoundVolume);
GUI.ForceMouseOn(null);
if (isEndlessRunner)
{
Submarine.MainSub.Remove();
isEndlessRunner = false;
Reset();
if (character != null)
{
Reset();
}
GameMain.World.ProcessChanges();
}
else
@@ -223,7 +175,7 @@ namespace Barotrauma
{
//base.AddToGUIUpdateList();
rightPanel.AddToGUIUpdateList();
Wizard.instance?.AddToGUIUpdateList();
Wizard.Instance.AddToGUIUpdateList();
if (displayBackgroundColor)
{
backgroundColorPanel.AddToGUIUpdateList();
@@ -255,7 +207,7 @@ namespace Barotrauma
base.Update(deltaTime);
spriteSheetRect = CalculateSpritesheetRectangle();
// Handle shortcut keys
if (GUI.KeyboardDispatcher.Subscriber == null && Wizard.instance == null)
if (GUI.KeyboardDispatcher.Subscriber == null)
{
if (PlayerInput.KeyDown(Keys.LeftControl))
{
@@ -444,7 +396,7 @@ namespace Barotrauma
}
}
}
if (!isFreezed && Wizard.instance == null)
if (!isFreezed)
{
if (character.AnimController.Invalid)
{
@@ -1179,22 +1131,7 @@ namespace Barotrauma
character = Character.Create(configFile, spawnPosition, ToolBox.RandomSeed(8), hasAi: false, ragdoll: ragdoll);
selectedJob = null;
}
if (character != null)
{
character.dontFollowCursor = dontFollowCursor;
}
if (character == null)
{
if (currentCharacterConfig == configFile)
{
return null;
}
else
{
// Respawn the current character;
SpawnCharacter(currentCharacterConfig);
}
}
character.dontFollowCursor = dontFollowCursor;
OnPostSpawn();
return character;
}
@@ -1310,33 +1247,27 @@ namespace Barotrauma
string speciesName = name;
// Config file
string configFilePath = Path.Combine(mainFolder, $"{speciesName}.xml").Replace(@"\", @"/");
if (ContentPackage.GetFilesOfType(GameMain.SelectedPackages, ContentType.Character).Any(path => path.Contains(speciesName)))
if (ContentPackage.GetFilesOfType(GameMain.SelectedPackages, ContentType.Character).None(path => path.Contains(speciesName)))
{
GUI.AddMessage(GetCharacterEditorTranslation("ExistingCharacterFound"), Color.Red, font: GUI.LargeFont);
// TODO: add a prompt: "Do you want to replace it?" + functionality
return false;
// Create the config file
XElement mainElement = new XElement("Character",
new XAttribute("name", speciesName),
new XAttribute("humanoid", isHumanoid),
new XElement("ragdolls", new XAttribute("folder", Path.Combine(mainFolder, $"Ragdolls/").Replace(@"\", @"/"))),
new XElement("animations", new XAttribute("folder", Path.Combine(mainFolder, $"Animations/").Replace(@"\", @"/"))),
new XElement("health"),
new XElement("ai"));
XDocument doc = new XDocument(mainElement);
if (!Directory.Exists(mainFolder))
{
Directory.CreateDirectory(mainFolder);
}
doc.Save(configFilePath);
// Add to the selected content package
contentPackage.AddFile(configFilePath, ContentType.Character);
contentPackage.Save(contentPackage.Path);
DebugConsole.NewMessage(GetCharacterEditorTranslation("ContentPackageSaved").Replace("[path]", contentPackage.Path));
}
// Create the config file
XElement mainElement = new XElement("Character",
new XAttribute("name", speciesName),
new XAttribute("humanoid", isHumanoid),
new XElement("ragdolls", new XAttribute("folder", Path.Combine(mainFolder, $"Ragdolls/").Replace(@"\", @"/"))),
new XElement("animations", new XAttribute("folder", Path.Combine(mainFolder, $"Animations/").Replace(@"\", @"/"))),
new XElement("health"),
new XElement("ai"));
XDocument doc = new XDocument(mainElement);
if (!Directory.Exists(mainFolder))
{
Directory.CreateDirectory(mainFolder);
}
doc.Save(configFilePath);
// Add to the selected content package
contentPackage.AddFile(configFilePath, ContentType.Character);
contentPackage.Save(contentPackage.Path);
DebugConsole.NewMessage(GetCharacterEditorTranslation("ContentPackageSaved").Replace("[path]", contentPackage.Path));
// Ragdoll
string ragdollFolder = RagdollParams.GetFolder(speciesName);
string ragdollPath = RagdollParams.GetDefaultFile(speciesName);
@@ -1347,20 +1278,12 @@ namespace Barotrauma
string animFolder = AnimationParams.GetFolder(speciesName);
foreach (AnimationType animType in Enum.GetValues(typeof(AnimationType)))
{
switch (animType)
if (animType != AnimationType.NotDefined)
{
case AnimationType.Walk:
case AnimationType.Run:
if (!ragdollParams.CanEnterSubmarine) { continue; }
break;
case AnimationType.SwimSlow:
case AnimationType.SwimFast:
break;
default: continue;
Type type = AnimationParams.GetParamTypeFromAnimType(animType, isHumanoid);
string fullPath = AnimationParams.GetDefaultFile(speciesName, animType);
AnimationParams.Create(fullPath, speciesName, animType, type);
}
Type type = AnimationParams.GetParamTypeFromAnimType(animType, isHumanoid);
string fullPath = AnimationParams.GetDefaultFile(speciesName, animType);
AnimationParams.Create(fullPath, speciesName, animType, type);
}
if (!AllFiles.Contains(configFilePath))
{
@@ -1779,20 +1702,8 @@ namespace Barotrauma
Vector2 buttonSize = new Vector2(1, 0.04f);
Vector2 toggleSize = new Vector2(0.03f, 0.03f);
Point margin = new Point(40, 60);
rightPanel = new GUIFrame(new RectTransform(new Vector2(0.15f, 1.0f), parent: Frame.RectTransform, anchor: Anchor.CenterRight), style: "GUIFrameRight");
var layoutGroup = new GUILayoutGroup(new RectTransform(new Point(rightPanel.Rect.Width - margin.X, rightPanel.Rect.Height - margin.Y), rightPanel.RectTransform, Anchor.Center))
{
Stretch = true
};
var disclaimerBtnHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.04f), layoutGroup.RectTransform), style: null);
var disclaimerBtn = new GUIButton(new RectTransform(new Vector2(1.0f, 0.8f), disclaimerBtnHolder.RectTransform, Anchor.TopRight), style: "GUINotificationButton")
{
OnClicked = (btn, userdata) => { GameMain.Instance.ShowEditorDisclaimer(); return true; }
};
disclaimerBtn.RectTransform.MaxSize = new Point(disclaimerBtn.Rect.Height);
rightPanel = new GUIFrame(new RectTransform(new Vector2(0.15f, 0.95f), parent: Frame.RectTransform, anchor: Anchor.CenterRight) { RelativeOffset = new Vector2(0.01f, 0) });
var layoutGroup = new GUILayoutGroup(new RectTransform(new Point(rightPanel.Rect.Width - margin.X, rightPanel.Rect.Height - margin.Y), rightPanel.RectTransform, Anchor.Center));
var characterDropDown = new GUIDropDown(new RectTransform(new Vector2(1, 0.04f), layoutGroup.RectTransform), elementCount: 10, style: null);
characterDropDown.ListBox.Color = new Color(characterDropDown.ListBox.Color.R, characterDropDown.ListBox.Color.G, characterDropDown.ListBox.Color.B, byte.MaxValue);
foreach (var file in AllFiles)
@@ -1823,16 +1734,14 @@ namespace Barotrauma
return true;
};
}
var charButtons = new GUIFrame(new RectTransform(new Vector2(buttonSize.X, buttonSize.Y * 1.5f), parent: layoutGroup.RectTransform), style: null);
var prevCharacterButton = new GUIButton(new RectTransform(new Vector2(0.5f, 1.0f), charButtons.RectTransform, Anchor.TopLeft), GetCharacterEditorTranslation("PreviousCharacter"));
prevCharacterButton.TextBlock.AutoScale = true;
var charButtons = new GUIFrame(new RectTransform(buttonSize, parent: layoutGroup.RectTransform), style: null);
var prevCharacterButton = new GUIButton(new RectTransform(new Vector2(0.5f, 1), charButtons.RectTransform, Anchor.TopLeft), GetCharacterEditorTranslation("PreviousCharacter"));
prevCharacterButton.OnClicked += (b, obj) =>
{
SpawnCharacter(GetPreviousConfigFile());
return true;
};
var nextCharacterButton = new GUIButton(new RectTransform(new Vector2(0.5f, 1.0f), charButtons.RectTransform, Anchor.TopRight), GetCharacterEditorTranslation("NextCharacter"));
prevCharacterButton.TextBlock.AutoScale = true;
var nextCharacterButton = new GUIButton(new RectTransform(new Vector2(0.5f, 1), charButtons.RectTransform, Anchor.TopRight), GetCharacterEditorTranslation("NextCharacter"));
nextCharacterButton.OnClicked += (b, obj) =>
{
SpawnCharacter(GetNextConfigFile());
@@ -3855,7 +3764,7 @@ namespace Barotrauma
void RecalculateCollider(Limb l)
{
// 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;
float multiplier = 0.75f;
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));
@@ -4374,7 +4283,7 @@ namespace Barotrauma
private List<XElement> jointXElements = new List<XElement>();
private List<GUIComponent> jointGUIElements = new List<GUIComponent>();
public static Wizard instance;
private static Wizard instance;
public static Wizard Instance
{
get
@@ -4405,6 +4314,7 @@ namespace Barotrauma
break;
case Tab.None:
default:
//activeView = null;
instance = null;
break;
}
@@ -4433,7 +4343,7 @@ namespace Barotrauma
GUITextBox xmlPathElement = null;
void UpdatePaths()
{
string pathBase = $"Mods/Characters/{Name}/{Name}";
string pathBase = $"Content/Characters/{Name}/{Name}";
XMLPath = $"{pathBase}.xml";
TexturePath = $"{pathBase}.png";
texturePathElement.Text = TexturePath;
@@ -4512,7 +4422,7 @@ namespace Barotrauma
// Cancel
box.Buttons[0].OnClicked += (b, d) =>
{
Wizard.Instance.SelectTab(Tab.None);
Instance.SelectTab(Tab.None);
return true;
};
// Next
@@ -4524,7 +4434,7 @@ namespace Barotrauma
texturePathElement.Flash(Color.Red);
return false;
}
Wizard.Instance.SelectTab(Tab.Ragdoll);
Instance.SelectTab(Tab.Ragdoll);
return true;
};
return box;
@@ -4665,7 +4575,7 @@ namespace Barotrauma
// Previous
box.Buttons[0].OnClicked += (b, d) =>
{
Wizard.Instance.SelectTab(Tab.Character);
Instance.SelectTab(Tab.Character);
return true;
};
// Parse and create
@@ -4756,7 +4666,7 @@ namespace Barotrauma
{
GUI.AddMessage(GetCharacterEditorTranslation("CharacterCreated").Replace("[name]", Name), Color.Green, font: GUI.Font);
}
Wizard.Instance.SelectTab(Tab.None);
Instance.SelectTab(Tab.None);
return true;
};
return box;
@@ -4936,27 +4846,23 @@ namespace Barotrauma
int width = rectInputs[2].IntValue;
int height = rectInputs[3].IntValue;
var colliderAttributes = new List<XAttribute>();
// Capsules/Circles
//if (width == height)
//{
// colliderAttributes.Add(new XAttribute("radius", (int)(width / 2 * 0.85f)));
//}
//else
//{
// if (height > width)
// {
// colliderAttributes.Add(new XAttribute("radius", (int)(width / 2 * 0.85f)));
// colliderAttributes.Add(new XAttribute("height",(int) (height - width * 0.85f)));
// }
// else
// {
// colliderAttributes.Add(new XAttribute("radius", (int)(height / 2 * 0.85f)));
// colliderAttributes.Add(new XAttribute("width", (int)(width - height * 0.85f)));
// }
//}
// Rectangles
colliderAttributes.Add(new XAttribute("height", (int)(height * 0.85f)));
colliderAttributes.Add(new XAttribute("width", (int)(width * 0.85f)));
if (width == height)
{
colliderAttributes.Add(new XAttribute("radius", width / 2));
}
else
{
if (height > width)
{
colliderAttributes.Add(new XAttribute("radius", width / 2));
colliderAttributes.Add(new XAttribute("height", height - width));
}
else
{
colliderAttributes.Add(new XAttribute("radius", height / 2));
colliderAttributes.Add(new XAttribute("width", width - height));
}
}
idToCodeName.TryGetValue(id, out string notes);
LimbXElements.Add(id.ToString(), new XElement("limb",
new XAttribute("id", id),

View File

@@ -149,8 +149,8 @@ namespace Barotrauma
//These will be visible through the LOS effect.
//Could be drawn with one Submarine.DrawBack call, but we can avoid sorting by depth by doing it like this.
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, DepthStencilState.None, null, null, cam.Transform);
Submarine.DrawBack(spriteBatch, false, e => e is Structure s && (s.ResizeVertical || s.ResizeHorizontal) && !s.DrawDamageEffect);
Submarine.DrawBack(spriteBatch, false, e => e is Structure s && !(s.ResizeVertical && s.ResizeHorizontal) && s.Prefab.BackgroundSprite != null);
Submarine.DrawBack(spriteBatch, false, s => s is Structure && s.ResizeVertical && s.ResizeHorizontal);
Submarine.DrawBack(spriteBatch, false, s => s is Structure && !(s.ResizeVertical && s.ResizeHorizontal) && ((Structure)s).Prefab.BackgroundSprite != null);
spriteBatch.End();
graphics.SetRenderTarget(null);

View File

@@ -4,7 +4,9 @@ using Barotrauma.Tutorials;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -14,7 +16,7 @@ namespace Barotrauma
{
class MainMenuScreen : Screen
{
public enum Tab { NewGame = 1, LoadGame = 2, HostServer = 3, Settings = 4, Tutorials = 5, JoinServer = 6, CharacterEditor = 7, SubmarineEditor = 8, QuickStartDev = 9, SteamWorkshop = 10, Credits = 11 }
public enum Tab { NewGame = 1, LoadGame = 2, HostServer = 3, Settings = 4, Tutorials = 5, JoinServer = 6, CharacterEditor = 7, SubmarineEditor = 8, QuickStartDev = 9, SteamWorkshop = 10 }
private GUIComponent buttonsParent;
@@ -34,27 +36,22 @@ namespace Barotrauma
private Sprite backgroundSprite;
private Sprite backgroundVignette;
private GUIComponent titleText;
private CreditsPlayer creditsPlayer;
#region Creation
public MainMenuScreen(GameMain game)
{
backgroundVignette = new Sprite("Content/UI/MainMenuVignette.png", Vector2.Zero);
new GUIImage(new RectTransform(new Vector2(0.35f, 0.2f), Frame.RectTransform, Anchor.BottomRight)
{ RelativeOffset = new Vector2(0.05f, 0.1f), AbsoluteOffset = new Point(-8, -8) },
{ RelativeOffset = new Vector2(0.05f, 0.05f), AbsoluteOffset = new Point(-5, -5) },
style: "TitleText")
{
Color = Color.Black * 0.5f,
CanBeFocused = false
};
titleText = new GUIImage(new RectTransform(new Vector2(0.35f, 0.2f), Frame.RectTransform, Anchor.BottomRight)
{ RelativeOffset = new Vector2(0.05f, 0.1f) },
new GUIImage(new RectTransform(new Vector2(0.35f, 0.2f), Frame.RectTransform, Anchor.BottomRight) { RelativeOffset = new Vector2(0.05f, 0.05f) },
style: "TitleText");
buttonsParent = new GUILayoutGroup(new RectTransform(new Vector2(0.3f, 0.85f), parent: Frame.RectTransform, anchor: Anchor.CenterLeft)
buttonsParent = new GUILayoutGroup(new RectTransform(new Vector2(0.3f, 0.85f), parent: Frame.RectTransform, anchor: Anchor.BottomLeft, pivot: Pivot.BottomLeft)
{
AbsoluteOffset = new Point(50, 0)
})
@@ -62,10 +59,10 @@ namespace Barotrauma
Stretch = true,
RelativeSpacing = 0.02f
};
// === CAMPAIGN
var campaignHolder = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 1.0f), parent: buttonsParent.RectTransform) { RelativeOffset = new Vector2(0.1f, 0.0f) }, isHorizontal: true);
new GUIImage(new RectTransform(new Vector2(0.2f, 0.7f), campaignHolder.RectTransform), "MainMenuCampaignIcon")
{
CanBeFocused = false
@@ -87,17 +84,6 @@ namespace Barotrauma
RelativeSpacing = 0.035f
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), campaignList.RectTransform), TextManager.Get("TutorialButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
UserData = Tab.Tutorials,
OnClicked = (tb, userdata) =>
{
SelectTab(tb, userdata);
return true;
}
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), campaignList.RectTransform), TextManager.Get("LoadGameButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
@@ -198,10 +184,6 @@ namespace Barotrauma
UserData = Tab.SteamWorkshop,
OnClicked = SelectTab
};
#if OSX && !DEBUG
steamWorkshopButton.Text += " (Not yet available on MacOS)";
#endif
}
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("SubEditorButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
@@ -227,7 +209,7 @@ namespace Barotrauma
};
// === OPTION
var optionHolder = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), parent: buttonsParent.RectTransform), isHorizontal: true);
var optionHolder = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.5f), parent: buttonsParent.RectTransform), isHorizontal: true);
new GUIImage(new RectTransform(new Vector2(0.15f, 0.6f), optionHolder.RectTransform), "MainMenuOptionIcon")
{
@@ -237,9 +219,9 @@ namespace Barotrauma
//spacing
new GUIFrame(new RectTransform(new Vector2(0.01f, 0.0f), optionHolder.RectTransform), style: null);
var optionButtons = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 1.0f), parent: optionHolder.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.0f) });
var optionButtons = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 1.0f), parent: optionHolder.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.05f) });
var optionList = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.25f), parent: optionButtons.RectTransform))
var optionList = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.3f), parent: optionButtons.RectTransform))
{
Stretch = false,
RelativeSpacing = 0.035f
@@ -251,13 +233,6 @@ namespace Barotrauma
UserData = Tab.Settings,
OnClicked = SelectTab
};
//TODO: translate
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), optionList.RectTransform), TextManager.Get("CreditsButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = true,
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,
@@ -266,9 +241,9 @@ namespace Barotrauma
//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, 40) },
new GUIButton(new RectTransform(new Vector2(0.8f, 0.1f), buttonsParent.RectTransform, Anchor.TopLeft, Pivot.BottomLeft) { AbsoluteOffset = new Point(0, -40) },
"Quickstart (dev)", style: "GUIButtonLarge", color: Color.Red)
{
{
IgnoreLayoutGroups = true,
UserData = Tab.QuickStartDev,
OnClicked = (tb, userdata) =>
@@ -334,7 +309,7 @@ namespace Barotrauma
false, null, "");
foreach (Tutorial tutorial in Tutorial.Tutorials)
{
var tutorialText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), tutorialList.Content.RectTransform), tutorial.DisplayName, textAlignment: Alignment.Center, font: GUI.LargeFont)
var tutorialText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.15f), tutorialList.Content.RectTransform), tutorial.Name, textAlignment: Alignment.Center, font: GUI.LargeFont)
{
UserData = tutorial
};
@@ -345,6 +320,8 @@ namespace Barotrauma
return true;
};
UpdateTutorialList();
this.game = game;
menuTabs[(int)Tab.Credits] = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), style: null, color: Color.Black * 0.5f)
@@ -354,9 +331,9 @@ namespace Barotrauma
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);
creditsPlayer = new CreditsPlayer(new RectTransform(Vector2.One, creditsContainer.RectTransform), "Content/Texts/Credits.xml");
}
#endregion
#endregion
#region Selection
#region Selection
public override void Select()
{
base.Select();
@@ -371,6 +348,10 @@ namespace Barotrauma
ResetButtonStates(null);
UpdateTutorialList();
ResetButtonStates(null);
GameAnalyticsManager.SetCustomDimension01("");
}
@@ -384,8 +365,6 @@ namespace Barotrauma
{
if (obj is Tab)
{
titleText.Visible = true;
if (GameMain.Config.UnsavedSettings)
{
var applyBox = new GUIMessageBox(
@@ -416,14 +395,9 @@ namespace Barotrauma
switch (selectedTab)
{
case Tab.NewGame:
if (!GameMain.Config.CampaignDisclaimerShown)
{
selectedTab = 0;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.NewGame); });
return true;
}
campaignSetupUI.CreateDefaultSaveName();
campaignSetupUI.RandomizeSeed();
campaignSetupUI.UpdateTutorialSelection();
campaignSetupUI.UpdateSubList(Submarine.SavedSubmarines);
break;
case Tab.LoadGame:
@@ -440,13 +414,6 @@ namespace Barotrauma
case Tab.HostServer:
break;
case Tab.Tutorials:
if (!GameMain.Config.CampaignDisclaimerShown)
{
selectedTab = 0;
GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.Tutorials); });
return true;
}
UpdateTutorialList();
break;
case Tab.CharacterEditor:
Submarine.MainSub = null;
@@ -462,9 +429,6 @@ namespace Barotrauma
if (!Steam.SteamManager.IsInitialized) return false;
GameMain.SteamWorkshopScreen.Select();
break;
case Tab.Credits:
titleText.Visible = false;
break;
}
}
else
@@ -480,8 +444,6 @@ namespace Barotrauma
public bool ReturnToMainMenu(GUIButton button, object obj)
{
GUI.PreventPauseMenuToggle = false;
if (Selected != this)
{
Select();
@@ -506,7 +468,7 @@ namespace Barotrauma
otherButton.Selected = false;
}
}
#endregion
#endregion
private void QuickStart()
{
@@ -673,22 +635,21 @@ namespace Barotrauma
" -ownerkey " + ownerKey.ToString();
string filename = "DedicatedServer.exe";
#if LINUX
filename = "./DedicatedServer";
#elif OSX
#if LINUX || OSX
filename = "mono";
arguments = "./DedicatedServer.exe " + arguments;
#endif
var processInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = arguments
Arguments = arguments,
#if !DEBUG
,
WindowStyle = ProcessWindowStyle.Hidden
#endif
};
GameMain.ServerChildProcess = Process.Start(processInfo);
Thread.Sleep(1000); //wait until the server is ready before connecting
GameMain.Client = new GameClient(name, "127.0.0.1:" + port.ToString(),ownerKey);
@@ -718,8 +679,12 @@ namespace Barotrauma
public override void Update(double deltaTime)
{
GameMain.TitleScreen.TitlePosition =
Vector2.Lerp(GameMain.TitleScreen.TitlePosition, new Vector2(
GameMain.TitleScreen.TitleSize.X / 2.0f * GameMain.TitleScreen.Scale + 30.0f,
GameMain.TitleScreen.TitleSize.Y / 2.0f * GameMain.TitleScreen.Scale + 30.0f),
0.1f);
#if !DEBUG
#if !OSX
if (Steam.SteamManager.USE_STEAM)
{
if (GameMain.Config.UseSteamMatchmaking)
@@ -729,16 +694,6 @@ namespace Barotrauma
}
steamWorkshopButton.Enabled = Steam.SteamManager.IsInitialized;
}
#else
if (Steam.SteamManager.USE_STEAM)
{
if (GameMain.Config.UseSteamMatchmaking)
{
joinServerButton.Enabled = Steam.SteamManager.IsInitialized;
hostServerButton.Enabled = Steam.SteamManager.IsInitialized;
}
}
#endif
#else
joinServerButton.Enabled = true;
hostServerButton.Enabled = true;
@@ -768,13 +723,6 @@ namespace Barotrauma
spriteBatch.End();
}
readonly string[] legalCrap = new string[]
{
"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."
};
public override void Draw(double deltaTime, GraphicsDevice graphics, SpriteBatch spriteBatch)
{
DrawBackground(graphics, spriteBatch);
@@ -782,7 +730,7 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, GameMain.ScissorTestEnable);
GUI.Draw(Cam, spriteBatch);
#if DEBUG
GUI.Font.DrawString(spriteBatch, "Barotrauma v" + GameMain.Version + " (debug build)", new Vector2(10, GameMain.GraphicsHeight - 20), Color.White);
#else
@@ -856,11 +804,13 @@ namespace Barotrauma
}
selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");
ContextualTutorial.Selected = campaignSetupUI.TutorialSelected;
GameMain.GameSession = new GameSession(selectedSub, saveName,
GameModePreset.List.Find(g => g.Identifier == "singleplayercampaign"));
(GameMain.GameSession.GameMode as CampaignMode).GenerateMap(mapSeed);
GameMain.LobbyScreen.Select();
}
@@ -882,7 +832,7 @@ namespace Barotrauma
GameMain.LobbyScreen.Select();
}
#region UI Methods
#region UI Methods
private void CreateHostServerFields()
{
Vector2 textLabelSize = new Vector2(1.0f, 0.1f);
@@ -963,7 +913,7 @@ namespace Barotrauma
OnClicked = HostServerClicked
};
}
#endregion
#endregion
}
}

View File

@@ -158,7 +158,14 @@ namespace Barotrauma
get;
private set;
}
public GUIFrame MyCharacterFrame
{
get { return myCharacterFrame; }
}
public bool MyCharacterFrameOpen;
public GUIFrame InfoFrame
{
get { return infoFrame; }
@@ -286,6 +293,25 @@ namespace Barotrauma
myCharacterFrame = new GUIFrame(new RectTransform(new Vector2(0.3f - panelSpacing, 0.65f), defaultModeContainer.RectTransform, Anchor.TopRight));
playerInfoContainer = new GUIFrame(new RectTransform(new Vector2(0.9f, 0.9f), myCharacterFrame.RectTransform, Anchor.Center), style: null);
playYourself = new GUITickBox(new RectTransform(new Vector2(0.06f, 0.06f), myCharacterFrame.RectTransform) { RelativeOffset = new Vector2(0.05f,0.05f) },
TextManager.Get("PlayYourself"))
{
Selected = true,
OnSelected = TogglePlayYourself,
UserData = "playyourself"
};
var toggleMyPlayerFrame = new GUIButton(new RectTransform(new Point(25, 70), myCharacterFrame.RectTransform, Anchor.TopLeft, Pivot.TopRight), "", style: "GUIButtonHorizontalArrow");
toggleMyPlayerFrame.OnClicked += (GUIButton btn, object userdata) =>
{
MyCharacterFrameOpen = !MyCharacterFrameOpen;
foreach (GUIComponent child in btn.Children)
{
child.SpriteEffects = MyCharacterFrameOpen ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
}
return true;
};
playYourself = new GUITickBox(new RectTransform(new Vector2(0.06f, 0.06f), myCharacterFrame.RectTransform) { RelativeOffset = new Vector2(0.05f,0.05f) },
TextManager.Get("PlayYourself"))
{
@@ -437,13 +463,9 @@ namespace Barotrauma
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), modeList.Content.RectTransform),
mode.Name, style: "ListBoxElement", textAlignment: Alignment.CenterLeft)
{
ToolTip = mode.Description,
UserData = mode
};
//TODO: translate mission descriptions
if (TextManager.Language == "English")
{
textBlock.ToolTip = mode.Description;
}
}
//mission type ------------------------------------------------------------------
@@ -684,6 +706,7 @@ namespace Barotrauma
public override void Deselect()
{
textBox.Deselect();
myCharacterFrame.GetChild<GUIButton>().Visible = true;
CampaignCharacterDiscarded = false;
}
@@ -698,7 +721,10 @@ namespace Barotrauma
textBox.Select();
textBox.OnEnterPressed = GameMain.Client.EnterChatMessage;
textBox.OnTextChanged += GameMain.Client.TypingChatMessage;
myCharacterFrame.RectTransform.AbsoluteOffset = new Point(0, 0);
myCharacterFrame.GetChild<GUIButton>().Visible = false;
subList.Enabled = AllowSubSelection;// || GameMain.Server != null;
shuttleList.Enabled = AllowSubSelection;// || GameMain.Server != null;
@@ -719,15 +745,11 @@ namespace Barotrauma
spectateButton.Visible = GameMain.Client.GameStarted;
ReadyToStartBox.Visible = !GameMain.Client.GameStarted;
ReadyToStartBox.Selected = false;
if (campaignUI != null)
if (campaignUI?.StartButton != null)
{
//SelectTab(Tab.Map);
if (campaignUI.StartButton != null)
{
campaignUI.StartButton.Visible = !GameMain.Client.GameStarted &&
(GameMain.Client.HasPermission(ClientPermissions.ManageRound) ||
GameMain.Client.HasPermission(ClientPermissions.ManageCampaign));
}
campaignUI.StartButton.Visible = !GameMain.Client.GameStarted &&
(GameMain.Client.HasPermission(ClientPermissions.ManageRound) ||
GameMain.Client.HasPermission(ClientPermissions.ManageCampaign));
}
GameMain.Client.SetReadyToStart(ReadyToStartBox);
}
@@ -1220,7 +1242,7 @@ namespace Barotrauma
if (sub.HasTag(SubmarineTag.Shuttle))
{
new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), frame.RectTransform, Anchor.CenterRight) { RelativeOffset = new Vector2(0.1f, 0.0f) },
TextManager.Get("Shuttle", fallBackTag: "RespawnShuttle"), textAlignment: Alignment.CenterRight, font: GUI.SmallFont)
TextManager.Get("Shuttle"), textAlignment: Alignment.CenterRight, font: GUI.SmallFont)
{
TextColor = subTextBlock.TextColor * 0.8f,
ToolTip = subTextBlock.ToolTip,

View File

@@ -60,10 +60,7 @@ namespace Barotrauma
var infoHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), leftColumn.RectTransform)) { RelativeSpacing = 0.05f };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), infoHolder.RectTransform, Anchor.Center), TextManager.Get("JoinServer"), font: GUI.LargeFont)
{
ForceUpperCase = true,
AutoScale = true
};
{ ForceUpperCase = true };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoHolder.RectTransform), TextManager.Get("YourName"));
clientNameBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.13f), infoHolder.RectTransform), "")

View File

@@ -329,8 +329,6 @@ namespace Barotrauma
{
element.Elements("sprite").ForEach(s => CreateSprite(s));
element.Elements("Sprite").ForEach(s => CreateSprite(s));
element.Elements("backgroundsprite").ForEach(s => CreateSprite(s));
element.Elements("BackgroundSprite").ForEach(s => CreateSprite(s));
element.Elements("brokensprite").ForEach(s => CreateSprite(s));
element.Elements("BrokenSprite").ForEach(s => CreateSprite(s));
element.Elements("containedsprite").ForEach(s => CreateSprite(s));

View File

@@ -6,7 +6,6 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace Barotrauma
@@ -44,6 +43,7 @@ namespace Barotrauma
private ContentPackage itemContentPackage;
private Facepunch.Steamworks.Workshop.Editor itemEditor;
//private Facepunch.Steamworks.Overlay overlay;
public SteamWorkshopScreen()
{
@@ -131,7 +131,7 @@ namespace Barotrauma
OutlineColor = new Color(72, 124, 77, 255),
OnClicked = (btn, userdata) =>
{
SteamManager.OverlayCustomURL("steam://url/SteamWorkshopPage/" + SteamManager.AppID);
System.Diagnostics.Process.Start("steam://url/SteamWorkshopPage/" + SteamManager.AppID);
return true;
}
};
@@ -309,23 +309,14 @@ namespace Barotrauma
return;
}
int prevIndex = -1;
var existingFrame = listBox.Content.FindChild(item);
if (existingFrame != null)
{
prevIndex = listBox.Content.GetChildIndex(existingFrame);
listBox.Content.RemoveChild(existingFrame);
}
if (existingFrame != null) { listBox.Content.RemoveChild(existingFrame); }
var itemFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), listBox.Content.RectTransform, minSize: new Point(0, 80)),
style: "ListBoxElement")
{
UserData = item
};
if (prevIndex > -1)
{
itemFrame.RectTransform.RepositionChildInHierarchy(prevIndex);
}
var innerFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), itemFrame.RectTransform, Anchor.Center), isHorizontal: true)
{
@@ -338,7 +329,6 @@ namespace Barotrauma
{
new GUIImage(new RectTransform(new Point(iconSize), innerFrame.RectTransform), itemPreviewSprites[item.PreviewImageUrl], scaleToFit: true)
{
UserData = "previewimage",
CanBeFocused = false
};
}
@@ -346,7 +336,6 @@ namespace Barotrauma
{
new GUIImage(new RectTransform(new Point(iconSize), innerFrame.RectTransform), SteamManager.Instance.DefaultPreviewImage, scaleToFit: true)
{
UserData = "previewimage",
CanBeFocused = false
};
try
@@ -381,7 +370,7 @@ namespace Barotrauma
catch (Exception e)
{
pendingPreviewImageDownloads.Remove(item.PreviewImageUrl);
DebugConsole.ThrowError("Downloading the preview image of the Workshop item \"" + EnsureUTF8(item.Title) + "\" failed.", e);
DebugConsole.ThrowError("Downloading the preview image of the Workshop item \"" + item.Title + "\" failed.", e);
}
}
@@ -392,9 +381,8 @@ namespace Barotrauma
CanBeFocused = false
};
var titleText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), rightColumn.RectTransform), EnsureUTF8(item.Title), textAlignment: Alignment.CenterLeft, wrap: true)
var titleText = new GUITextBlock(new RectTransform(new Vector2(0.5f, 0.0f), rightColumn.RectTransform), item.Title, textAlignment: Alignment.CenterLeft, wrap: true)
{
UserData = "titletext",
CanBeFocused = false
};
@@ -410,14 +398,14 @@ namespace Barotrauma
{
if (SteamManager.UpdateWorkshopItem(item, out string errorMsg))
{
new GUIMessageBox("", TextManager.Get("WorkshopItemUpdated").Replace("[itemname]", EnsureUTF8(item.Title)));
new GUIMessageBox("", TextManager.Get("WorkshopItemUpdated").Replace("[itemname]", item.Title));
}
else
{
DebugConsole.ThrowError(errorMsg);
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.Get("WorkshopItemUpdateFailed").Replace("[itemname]", EnsureUTF8(item.Title)).Replace("[errormessage]", errorMsg));
TextManager.Get("WorkshopItemUpdateFailed").Replace("[itemname]", item.Title).Replace("[errormessage]", errorMsg));
}
btn.Enabled = false;
btn.Visible = false;
@@ -559,17 +547,7 @@ namespace Barotrauma
itemPreviewSprites.Add(item.PreviewImageUrl, newSprite);
}
var previewImage = listBox.Content.FindChild(item)?.GetChildByUserData("previewimage") as GUIImage;
if (previewImage != null)
{
previewImage.Sprite = newSprite;
}
else
{
CreateWorkshopItemFrame(item, listBox);
}
CreateWorkshopItemFrame(item, listBox);
if (modsPreviewFrame.FindChild(item) != null)
{
ShowItemPreview(item, modsPreviewFrame);
@@ -597,7 +575,8 @@ namespace Barotrauma
private bool ToggleItemEnabled(GUITickBox tickBox)
{
if (!(tickBox.UserData is Facepunch.Steamworks.Workshop.Item item)) { return false; }
Facepunch.Steamworks.Workshop.Item item = tickBox.UserData as Facepunch.Steamworks.Workshop.Item;
if (item == null) { return false; }
var updateButton = tickBox.Parent.FindChild("updatebutton");
@@ -606,9 +585,7 @@ namespace Barotrauma
{
if (!SteamManager.EnableWorkShopItem(item, false, out errorMsg))
{
tickBox.Visible = false;
tickBox.Selected = false;
if (tickBox.Parent.GetChildByUserData("titletext") is GUITextBlock titleText) { titleText.TextColor = Color.Red; }
tickBox.Enabled = false;
}
}
else
@@ -617,7 +594,6 @@ namespace Barotrauma
{
tickBox.Enabled = false;
}
GameMain.Config.EnsureCoreContentPackageSelected();
}
if (updateButton != null)
{
@@ -648,11 +624,11 @@ namespace Barotrauma
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.005f), content.RectTransform), style: null);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), EnsureUTF8(item.Title), textAlignment: Alignment.TopLeft, font: GUI.LargeFont, wrap: true);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), item.Title, textAlignment: Alignment.TopLeft, font: GUI.LargeFont, wrap: true);
var creatorHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), content.RectTransform)) { IsHorizontal = true, Stretch = true };
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), creatorHolder.RectTransform), TextManager.Get("WorkshopItemCreator") + ": " + EnsureUTF8(item.OwnerName), textAlignment: Alignment.BottomLeft, wrap: true);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), creatorHolder.RectTransform), TextManager.Get("WorkshopItemCreator") + ": " + item.OwnerName, textAlignment: Alignment.BottomLeft, wrap: true);
new GUIButton(new RectTransform(new Vector2(0.5f, 1.0f), creatorHolder.RectTransform, Anchor.BottomRight), TextManager.Get("WorkshopShowItemInSteam"), style: null)
{
@@ -662,7 +638,13 @@ namespace Barotrauma
OutlineColor = new Color(72, 124, 77, 255),
OnClicked = (btn, userdata) =>
{
SteamManager.OverlayCustomURL("steam://url/CommunityFilePage/" + item.Id);
// Failed attempt, might have to be activated before accessing because as of now it just throws a null for overlay
/*if (overlay.Enabled)
{
overlay.OpenUrl("steam://url/CommunityFilePage/" + item.Id);
}*/
System.Diagnostics.Process.Start("steam://url/CommunityFilePage/" + item.Id);
return true;
}
};
@@ -685,7 +667,7 @@ namespace Barotrauma
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), descriptionContainer.Content.RectTransform) { MinSize = new Point(0, 5) }, style: null);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), descriptionContainer.Content.RectTransform), EnsureUTF8(item.Description), wrap: true)
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), descriptionContainer.Content.RectTransform), item.Description, wrap: true)
{
CanBeFocused = false
};
@@ -763,28 +745,25 @@ namespace Barotrauma
itemEditor.Tags.Add("Submarine");
itemEditor.Description = sub.Description;
if (sub.PreviewImage != null)
string previewImagePath = Path.GetFullPath(Path.Combine(SteamManager.WorkshopItemStagingFolder, SteamManager.PreviewImageName));
try
{
string previewImagePath = Path.GetFullPath(Path.Combine(SteamManager.WorkshopItemStagingFolder, SteamManager.PreviewImageName));
try
using (Stream s = File.Create(previewImagePath))
{
using (Stream s = File.Create(previewImagePath))
{
sub.PreviewImage.Texture.SaveAsPng(s, (int)sub.PreviewImage.size.X, (int)sub.PreviewImage.size.Y);
itemEditor.PreviewImage = previewImagePath;
}
if (new FileInfo(previewImagePath).Length > 1024 * 1024)
{
new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("WorkshopItemPreviewImageTooLarge"));
itemEditor.PreviewImage = SteamManager.DefaultPreviewImagePath;
}
sub.PreviewImage.Texture.SaveAsPng(s, (int)sub.PreviewImage.size.X, (int)sub.PreviewImage.size.Y);
itemEditor.PreviewImage = previewImagePath;
}
catch (Exception e)
if (new FileInfo(previewImagePath).Length > 1024 * 1024)
{
DebugConsole.ThrowError("Saving submarine preview image failed.", e);
itemEditor.PreviewImage = null;
new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("WorkshopItemPreviewImageTooLarge"));
itemEditor.PreviewImage = SteamManager.DefaultPreviewImagePath;
}
}
catch (Exception e)
{
DebugConsole.ThrowError("Saving submarine preview image failed.", e);
itemEditor.PreviewImage = null;
}
}
private void CreateWorkshopItem(ContentPackage contentPackage)
{
@@ -821,7 +800,7 @@ namespace Barotrauma
if (!item.Installed)
{
new GUIMessageBox(TextManager.Get("Error"),
TextManager.Get("WorkshopErrorInstallRequiredToEdit").Replace("[itemname]", EnsureUTF8(item.Title)));
TextManager.Get("WorkshopErrorInstallRequiredToEdit").Replace("[itemname]", item.Title));
return;
}
SteamManager.CreateWorkshopItemStaging(item, out itemEditor, out itemContentPackage);
@@ -1256,7 +1235,7 @@ namespace Barotrauma
string pleaseWaitText = TextManager.Get("WorkshopPublishPleaseWait");
var msgBox = new GUIMessageBox(
pleaseWaitText,
TextManager.Get("WorkshopPublishInProgress").Replace("[itemname]", EnsureUTF8(item.Title)),
TextManager.Get("WorkshopPublishInProgress").Replace("[itemname]", item.Title),
new string[] { TextManager.Get("Cancel") });
msgBox.Buttons[0].OnClicked = (btn, userdata) =>
@@ -1278,13 +1257,13 @@ namespace Barotrauma
if (string.IsNullOrEmpty(item.Error))
{
new GUIMessageBox("", TextManager.Get("WorkshopItemPublished").Replace("[itemname]", EnsureUTF8(item.Title)));
new GUIMessageBox("", TextManager.Get("WorkshopItemPublished").Replace("[itemname]", item.Title));
}
else
{
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.Get("WorkshopItemPublishFailed").Replace("[itemname]", EnsureUTF8(item.Title)) + item.Error);
TextManager.Get("WorkshopItemPublishFailed").Replace("[itemname]", item.Title) + item.Error);
}
createItemFrame.ClearChildren();
@@ -1313,12 +1292,6 @@ namespace Barotrauma
{
}
private string EnsureUTF8(string text)
{
byte[] bytes = Encoding.Default.GetBytes(text);
return Encoding.UTF8.GetString(bytes);
}
#endregion
}
}

View File

@@ -183,12 +183,6 @@ namespace Barotrauma
TextGetter = GetSubName
};
var disclaimerBtn = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), paddedTopPanel.RectTransform, Anchor.CenterRight), style: "GUINotificationButton")
{
OnClicked = (btn, userdata) => { GameMain.Instance.ShowEditorDisclaimer(); return true; }
};
disclaimerBtn.RectTransform.MaxSize = new Point(disclaimerBtn.Rect.Height);
linkedSubBox = new GUIDropDown(new RectTransform(new Vector2(0.15f, 0.9f), paddedTopPanel.RectTransform) { RelativeOffset = new Vector2(0.385f, 0.0f) },
TextManager.Get("AddSubButton"), elementCount: 20)
{
@@ -257,12 +251,12 @@ namespace Barotrauma
saveAssemblyFrame = new GUIFrame(new RectTransform(new Vector2(0.08f, 0.5f), TopPanel.RectTransform, Anchor.BottomLeft, Pivot.TopLeft)
{ MinSize = new Point(200, 40), AbsoluteOffset = new Point(LeftPanel.Rect.Width + hullVolumeFrame.Rect.Width, 0) }, "InnerFrame")
{ MinSize = new Point(180, 40), AbsoluteOffset = new Point(LeftPanel.Rect.Width + hullVolumeFrame.Rect.Width, 0) }, "InnerFrame")
{
Visible = false
};
var saveAssemblyButton = new GUIButton(new RectTransform(new Vector2(0.9f, 0.8f), saveAssemblyFrame.RectTransform, Anchor.Center), TextManager.Get("SaveItemAssembly"));
saveAssemblyButton.TextBlock.AutoScale = true;
saveAssemblyFrame.Font = GUI.SmallFont;
saveAssemblyButton.OnClicked += (btn, userdata) =>
{
CreateSaveAssemblyScreen();
@@ -317,11 +311,10 @@ namespace Barotrauma
Stretch = true
};
entityCategoryButtons.Add(
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), tabButtonHolder.RectTransform), TextManager.Get("MapEntityCategory.All"), style: "GUITabButton")
{
OnClicked = (btn, userdata) => { entityCategoryButtons.ForEach(b => b.Selected = b == btn); ClearFilter(); return true; }
});
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), tabButtonHolder.RectTransform), TextManager.Get("MapEntityCategory.All"), style: "GUITabButton")
{
OnClicked = (btn, userdata) => { ClearFilter(); return true; }
};
foreach (MapEntityCategory category in Enum.GetValues(typeof(MapEntityCategory)))
{
@@ -338,8 +331,6 @@ namespace Barotrauma
});
}
GUITextBlock.AutoScaleAndNormalize(entityCategoryButtons.Select(b => b.TextBlock));
entityList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.9f), entityListHolder.RectTransform, Anchor.BottomCenter))
{
OnSelected = SelectPrefab,
@@ -354,7 +345,7 @@ namespace Barotrauma
var characterModeTickBoxHolder = new GUILayoutGroup(new RectTransform(new Vector2(paddedLeftPanel.RectTransform.RelativeSize.X, 0.01f), paddedLeftPanel.RectTransform) { MinSize = new Point(0, 32) })
{ Color = secondaryColor };
characterModeTickBox = new GUITickBox(new RectTransform(Vector2.One, characterModeTickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("CharacterModeButton"))
characterModeTickBox = new GUITickBox(new RectTransform(new Point(32, 32), characterModeTickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("CharacterModeButton"))
{
ToolTip = TextManager.Get("CharacterModeToolTip"),
OnSelected = (GUITickBox tBox) =>
@@ -367,7 +358,7 @@ namespace Barotrauma
var wiringModeTickBoxHolder = new GUILayoutGroup(new RectTransform(new Vector2(paddedLeftPanel.RectTransform.RelativeSize.X, 0.01f), paddedLeftPanel.RectTransform) { MinSize = new Point(0, 32) })
{ Color = secondaryColor };
wiringModeTickBox = new GUITickBox(new RectTransform(Vector2.One, wiringModeTickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("WiringModeButton"))
wiringModeTickBox = new GUITickBox(new RectTransform(new Point(32, 32), wiringModeTickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("WiringModeButton"))
{
ToolTip = TextManager.Get("WiringModeToolTip"),
OnSelected = (GUITickBox tBox) =>
@@ -376,9 +367,7 @@ namespace Barotrauma
return true;
}
};
GUITextBlock.AutoScaleAndNormalize(characterModeTickBox.TextBlock, wiringModeTickBox.TextBlock);
button = new GUIButton(new RectTransform(new Vector2(1.0f, 0.025f), paddedLeftPanel.RectTransform), TextManager.Get("GenerateWaypointsButton"), style: null, color: new Color(70, 100, 122, 255))
{
ForceUpperCase = true,
@@ -387,18 +376,17 @@ namespace Barotrauma
ToolTip = TextManager.Get("GenerateWaypointsToolTip"),
OnClicked = GenerateWaypoints
};
button.TextBlock.AutoScale = true;
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), paddedLeftPanel.RectTransform), style: null);
var tickBoxHolder = new GUILayoutGroup(new RectTransform(new Vector2(paddedLeftPanel.RectTransform.RelativeSize.X, 0.3f), paddedLeftPanel.RectTransform))
{ Color = secondaryColor, Stretch = true, RelativeSpacing = 0.05f };
var showEntitiesHolder = new GUILayoutGroup(new RectTransform(new Vector2(paddedLeftPanel.RectTransform.RelativeSize.X, 0.3f), paddedLeftPanel.RectTransform))
{ Color = secondaryColor, Stretch = true, RelativeSpacing = 0.05f };
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), tickBoxHolder.RectTransform) { MinSize = new Point(0, 3) }, style: null);
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), showEntitiesHolder.RectTransform) { MinSize = new Point(0, 3) }, style: null);
var tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowLighting"))
var tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowLighting"))
{
Selected = lightingEnabled,
OnSelected = (GUITickBox obj) =>
@@ -420,64 +408,53 @@ namespace Barotrauma
return true;
}
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowWalls"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowWalls"))
{
Selected = Structure.ShowWalls,
OnSelected = (GUITickBox obj) => { Structure.ShowWalls = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowStructures"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowStructures"))
{
Selected = Structure.ShowStructures,
OnSelected = (GUITickBox obj) => { Structure.ShowStructures = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowItems"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowItems"))
{
Selected = Item.ShowItems,
OnSelected = (GUITickBox obj) => { Item.ShowItems = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowWaypoints"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowWaypoints"))
{
Selected = WayPoint.ShowWayPoints,
OnSelected = (GUITickBox obj) => { WayPoint.ShowWayPoints = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowSpawnpoints"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowSpawnpoints"))
{
Selected = WayPoint.ShowSpawnPoints,
OnSelected = (GUITickBox obj) => { WayPoint.ShowSpawnPoints = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowLinks"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowLinks"))
{
Selected = Item.ShowLinks,
OnSelected = (GUITickBox obj) => { Item.ShowLinks = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowHulls"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowHulls"))
{
Selected = Hull.ShowHulls,
OnSelected = (GUITickBox obj) => { Hull.ShowHulls = obj.Selected; return true; }
};
tickBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), tickBoxHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowGaps"))
tickBox = new GUITickBox(new RectTransform(new Point(32, 32), showEntitiesHolder.RectTransform) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("ShowGaps"))
{
Selected = Gap.ShowGaps,
OnSelected = (GUITickBox obj) => { Gap.ShowGaps = obj.Selected; return true; },
};
tickBoxHolder.Children.ForEach(c =>
{
if (c is GUITickBox tb) { tb.RectTransform.MinSize = new Point(0, 32); }
});
GUITextBlock.AutoScaleAndNormalize(tickBoxHolder.Children.Where(c => c is GUITickBox).Select(c => ((GUITickBox)c).TextBlock));
//spacing
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), tickBoxHolder.RectTransform) { MinSize = new Point(0, 3) }, style: null);
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), showEntitiesHolder.RectTransform) { MinSize = new Point(0, 3) }, style: null);
new GUITextBlock(new RectTransform(new Vector2(0.95f, 0.025f), paddedLeftPanel.RectTransform, Anchor.BottomCenter) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("PreviouslyUsedLabel"))
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.025f), paddedLeftPanel.RectTransform, Anchor.BottomCenter) { AbsoluteOffset = new Point(10, 0) }, TextManager.Get("PreviouslyUsedLabel"));
previouslyUsedList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), paddedLeftPanel.RectTransform, Anchor.BottomCenter) { AbsoluteOffset = new Point(10, 0) })
{
AutoScale = true
};
previouslyUsedList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), paddedLeftPanel.RectTransform, Anchor.BottomCenter))
{
ScrollBarVisible = true,
OnSelected = SelectPrefab
};
@@ -830,7 +807,7 @@ namespace Barotrauma
{
if (dummyCharacter != null) RemoveDummyCharacter();
dummyCharacter = Character.Create(Character.HumanConfigFile, Vector2.Zero, "", hasAi: false);
dummyCharacter = Character.Create(Character.HumanConfigFile, Vector2.Zero, "");
//make space for the entity menu
for (int i = 0; i < dummyCharacter.Inventory.SlotPositions.Length; i++)
@@ -909,10 +886,6 @@ namespace Barotrauma
GUI.AddMessage(TextManager.Get("SubSavedNotification").Replace("[filepath]", Submarine.MainSub.FilePath), Color.Green);
Submarine.RefreshSavedSub(savePath);
if (prevSavePath != null && prevSavePath != savePath)
{
Submarine.RefreshSavedSub(prevSavePath);
}
linkedSubBox.ClearChildren();
foreach (Submarine sub in Submarine.SavedSubmarines)
@@ -1052,7 +1025,7 @@ namespace Barotrauma
var previewImageButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), rightColumn.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f };
new GUIButton(new RectTransform(new Vector2(0.5f, 1.0f), previewImageButtonHolder.RectTransform), TextManager.Get("SubPreviewImageCreate"))
new GUIButton(new RectTransform(new Vector2(0.5f, 1.0f), previewImageButtonHolder.RectTransform), TextManager.Get("SubPreviewImageGenerate"))
{
OnClicked = (btn, userdata) =>
{
@@ -1204,6 +1177,7 @@ namespace Barotrauma
AbsoluteSpacing = 5,
Stretch = true
};
#endif
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedSaveFrame.RectTransform),
TextManager.Get("SaveItemAssemblyDialogHeader"), font: GUI.LargeFont);
@@ -1304,8 +1278,9 @@ namespace Barotrauma
{
if (CharacterMode) SetCharacterMode(false);
if (WiringMode) SetWiringMode(false);
var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.2f, 0.36f), loadFrame.RectTransform, Anchor.Center) { MinSize = new Point(350, 500) });
loadFrame = new GUIButton(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker")
{
OnClicked = (btn, userdata) => { if (GUI.MouseOn == btn || GUI.MouseOn == btn.TextBlock) loadFrame = null; return true; },
@@ -1313,15 +1288,10 @@ namespace Barotrauma
var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.2f, 0.36f), loadFrame.RectTransform, Anchor.Center) { MinSize = new Point(350, 500) });
var paddedLoadFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), innerFrame.RectTransform, Anchor.Center)) { Stretch = true, RelativeSpacing = 0.02f };
var paddedLoadFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), innerFrame.RectTransform, Anchor.Center)) { Stretch = true, RelativeSpacing = 0.05f };
var deleteButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), paddedLoadFrame.RectTransform, Anchor.Center));
var filterContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), paddedLoadFrame.RectTransform), isHorizontal: true)
{
Stretch = true
};
var subList = new GUIListBox(new RectTransform(new Vector2(1.0f, 1.0f), paddedLoadFrame.RectTransform))
{
ScrollBarVisible = true,
@@ -1332,17 +1302,6 @@ namespace Barotrauma
}
};
var searchTitle = new GUITextBlock(new RectTransform(new Vector2(0.001f, 1.0f), filterContainer.RectTransform), TextManager.Get("FilterMapEntities"), textAlignment: Alignment.CenterLeft, font: GUI.Font);
var searchBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 1.0f), filterContainer.RectTransform), font: GUI.Font);
searchBox.OnSelected += (sender, userdata) => { searchTitle.Visible = false; };
searchBox.OnDeselected += (sender, userdata) => { searchTitle.Visible = true; };
searchBox.OnTextChanged += (textBox, text) => { FilterSubs(subList, text); return true; };
var clearButton = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), filterContainer.RectTransform), "x")
{
OnClicked = (btn, userdata) => { searchBox.Text = ""; FilterSubs(subList, ""); searchBox.Flash(Color.White); return true; }
};
foreach (Submarine sub in Submarine.SavedSubmarines)
{
GUITextBlock textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.1f), subList.Content.RectTransform) { MinSize = new Point(0, 30) },
@@ -1355,7 +1314,7 @@ namespace Barotrauma
if (sub.HasTag(SubmarineTag.Shuttle))
{
var shuttleText = new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), textBlock.RectTransform, Anchor.CenterRight),
TextManager.Get("Shuttle", fallBackTag: "RespawnShuttle"), font: GUI.SmallFont)
TextManager.Get("Shuttle"), font: GUI.SmallFont)
{
TextColor = textBlock.TextColor * 0.8f,
ToolTip = textBlock.ToolTip
@@ -1404,16 +1363,6 @@ namespace Barotrauma
}
private void FilterSubs(GUIListBox subList, string filter)
{
foreach (GUIComponent child in subList.Content.Children)
{
var sub = child.UserData as Submarine;
if (sub == null) { return; }
child.Visible = string.IsNullOrEmpty(filter) ? true : sub.Name.ToLower().Contains(filter.ToLower());
}
}
private bool LoadSub(GUIButton button, object obj)
{
if (loadFrame == null)
{
@@ -1509,9 +1458,7 @@ namespace Barotrauma
ClearFilter();
foreach (GUIButton button in entityCategoryButtons)
{
button.Selected =
button.UserData != null &&
(MapEntityCategory)button.UserData == selectedCategory;
button.Selected = (MapEntityCategory)button.UserData == selectedCategory;
}
foreach (GUIComponent child in toggleEntityMenuButton.Children)
@@ -2293,11 +2240,6 @@ namespace Barotrauma
GameMain.LightManager.UpdateLightMap(graphics, spriteBatch, cam);
}
foreach (Submarine sub in Submarine.Loaded)
{
sub.UpdateTransform();
}
spriteBatch.Begin(SpriteSortMode.BackToFront,
BlendState.AlphaBlend,
null, null, null, null,

View File

@@ -277,17 +277,13 @@ namespace Barotrauma
{
component.RectTransform.Parent = layoutGroup.RectTransform;
component.RectTransform.RepositionChildInHierarchy(childIndex);
Recalculate();
}
public void Recalculate()
{
int contentHeight = ContentHeight;
RectTransform.NonScaledSize = new Point(RectTransform.NonScaledSize.X, contentHeight);
layoutGroup.RectTransform.NonScaledSize = new Point(layoutGroup.RectTransform.NonScaledSize.X, contentHeight);
}
public GUIComponent CreateNewField(SerializableProperty property, ISerializableEntity entity)
private GUIComponent CreateNewField(SerializableProperty property, ISerializableEntity entity)
{
object value = property.GetValue(entity);
if (property.PropertyType == typeof(string) && value == null)
@@ -355,7 +351,7 @@ namespace Barotrauma
return propertyField;
}
public GUIComponent CreateBoolField(ISerializableEntity entity, SerializableProperty property, bool value, string displayName, string toolTip)
private GUIComponent CreateBoolField(ISerializableEntity entity, SerializableProperty property, bool value, string displayName, string toolTip)
{
GUITickBox propertyTickBox = new GUITickBox(new RectTransform(new Point(Rect.Width, elementHeight), layoutGroup.RectTransform), displayName)
{
@@ -371,11 +367,11 @@ namespace Barotrauma
return true;
}
};
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { propertyTickBox }); }
Fields.Add(property.Name, new GUIComponent[] { propertyTickBox });
return propertyTickBox;
}
public GUIComponent CreateIntField(ISerializableEntity entity, SerializableProperty property, int value, string displayName, string toolTip)
private GUIComponent CreateIntField(ISerializableEntity entity, SerializableProperty property, int value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -399,11 +395,11 @@ namespace Barotrauma
TrySendNetworkUpdate(entity, property);
}
};
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { numberInput }); }
Fields.Add(property.Name, new GUIComponent[] { numberInput });
return frame;
}
public GUIComponent CreateFloatField(ISerializableEntity entity, SerializableProperty property, float value, string displayName, string toolTip)
private GUIComponent CreateFloatField(ISerializableEntity entity, SerializableProperty property, float value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -429,11 +425,11 @@ namespace Barotrauma
TrySendNetworkUpdate(entity, property);
}
};
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { numberInput }); }
Fields.Add(property.Name, new GUIComponent[] { numberInput });
return frame;
}
public GUIComponent CreateEnumField(ISerializableEntity entity, SerializableProperty property, object value, string displayName, string toolTip)
private GUIComponent CreateEnumField(ISerializableEntity entity, SerializableProperty property, object value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, elementHeight), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -458,11 +454,11 @@ namespace Barotrauma
return true;
};
enumDropDown.SelectItem(value);
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { enumDropDown }); }
Fields.Add(property.Name, new GUIComponent[] { enumDropDown });
return frame;
}
public GUIComponent CreateEnumFlagField(ISerializableEntity entity, SerializableProperty property, object value, string displayName, string toolTip)
private GUIComponent CreateEnumFlagField(ISerializableEntity entity, SerializableProperty property, object value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, elementHeight), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -491,26 +487,22 @@ namespace Barotrauma
return true;
};
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { enumDropDown }); }
Fields.Add(property.Name, new GUIComponent[] { enumDropDown });
return frame;
}
public GUIComponent CreateStringField(ISerializableEntity entity, SerializableProperty property, string value, string displayName, string toolTip)
private GUIComponent CreateStringField(ISerializableEntity entity, SerializableProperty property, string value, string displayName, string toolTip)
{
var frame = new GUILayoutGroup(new RectTransform(new Point(Rect.Width, elementHeight), layoutGroup.RectTransform), isHorizontal: true)
{
Stretch = true
};
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, elementHeight), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1), frame.RectTransform), displayName, font: GUI.SmallFont, textAlignment: Alignment.Left)
{
ToolTip = toolTip
};
GUITextBox propertyBox = new GUITextBox(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform))
GUITextBox propertyBox = new GUITextBox(new RectTransform(new Vector2(0.6f, 1), frame.RectTransform, Anchor.TopRight))
{
ToolTip = toolTip,
Font = GUI.SmallFont,
Text = value,
OverflowClip = true,
OnEnterPressed = (textBox, text) =>
{
if (property.TrySetValue(entity, text))
@@ -522,36 +514,11 @@ namespace Barotrauma
return true;
}
};
string translationTextTag = property.GetAttribute<Serialize>()?.translationTextTag;
if (translationTextTag != null)
{
new GUIButton(new RectTransform(new Vector2(0.1f, 1), frame.RectTransform, Anchor.TopRight), "...")
{
OnClicked = (bt, userData) => { CreateTextPicker(translationTextTag, entity, property, propertyBox); return true; }
};
propertyBox.OnTextChanged += (tb, text) =>
{
string translatedText = TextManager.Get(text, returnNull: true);
if (translatedText == null)
{
propertyBox.TextColor = Color.Gray;
propertyBox.ToolTip = TextManager.Get("StringPropertyCannotTranslate").Replace("[tag]", text ?? "");
}
else
{
propertyBox.TextColor = Color.LightGreen;
propertyBox.ToolTip = TextManager.Get("StringPropertyTranslate").Replace("[translation]", translatedText);
}
return true;
};
propertyBox.Text = value;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, new GUIComponent[] { propertyBox }); }
Fields.Add(property.Name, new GUIComponent[] { propertyBox });
return frame;
}
public GUIComponent CreatePointField(ISerializableEntity entity, SerializableProperty property, Point value, string displayName, string toolTip)
private GUIComponent CreatePointField(ISerializableEntity entity, SerializableProperty property, Point value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -599,11 +566,11 @@ namespace Barotrauma
};
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public GUIComponent CreateVector2Field(ISerializableEntity entity, SerializableProperty property, Vector2 value, string displayName, string toolTip)
private GUIComponent CreateVector2Field(ISerializableEntity entity, SerializableProperty property, Vector2 value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.4f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -653,11 +620,11 @@ namespace Barotrauma
};
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public GUIComponent CreateVector3Field(ISerializableEntity entity, SerializableProperty property, Vector3 value, string displayName, string toolTip)
private GUIComponent CreateVector3Field(ISerializableEntity entity, SerializableProperty property, Vector3 value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.3f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -711,11 +678,11 @@ namespace Barotrauma
};
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public GUIComponent CreateVector4Field(ISerializableEntity entity, SerializableProperty property, Vector4 value, string displayName, string toolTip)
private GUIComponent CreateVector4Field(ISerializableEntity entity, SerializableProperty property, Vector4 value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -773,14 +740,14 @@ namespace Barotrauma
};
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public GUIComponent CreateColorField(ISerializableEntity entity, SerializableProperty property, Color value, string displayName, string toolTip)
private GUIComponent CreateColorField(ISerializableEntity entity, SerializableProperty property, Color value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), frame.RectTransform) { MinSize = new Point(80, 26) }, displayName, font: GUI.SmallFont)
var label = new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), frame.RectTransform) { MinSize = new Point(80, 26)}, displayName, font: GUI.SmallFont)
{
ToolTip = toolTip
};
@@ -840,11 +807,11 @@ namespace Barotrauma
colorBox.Color = (Color)property.GetValue(entity);
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public GUIComponent CreateRectangleField(ISerializableEntity entity, SerializableProperty property, Rectangle value, string displayName, string toolTip)
private GUIComponent CreateRectangleField(ISerializableEntity entity, SerializableProperty property, Rectangle value, string displayName, string toolTip)
{
var frame = new GUIFrame(new RectTransform(new Point(Rect.Width, Math.Max(elementHeight, 26)), layoutGroup.RectTransform), color: Color.Transparent);
var label = new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), frame.RectTransform), displayName, font: GUI.SmallFont)
@@ -900,44 +867,9 @@ namespace Barotrauma
};
fields[i] = numberInput;
}
if (!Fields.ContainsKey(property.Name)) { Fields.Add(property.Name, fields); }
Fields.Add(property.Name, fields);
return frame;
}
public void CreateTextPicker(string textTag, ISerializableEntity entity, SerializableProperty property, GUITextBox textBox)
{
var msgBox = new GUIMessageBox("", "", new string[] { TextManager.Get("Cancel") }, width: 300, height: 400);
msgBox.Buttons[0].OnClicked = msgBox.Close;
var textList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.8f), msgBox.Content.RectTransform, Anchor.TopCenter))
{
OnSelected = (component, userData) =>
{
string text = userData as string ?? "";
if (property.TrySetValue(entity, text))
{
TrySendNetworkUpdate(entity, property);
textBox.Text = (string)property.GetValue(entity);
textBox.Deselect();
}
return true;
}
};
textTag = textTag.ToLowerInvariant();
var tagTextPairs = TextManager.GetAllTagTextPairs();
tagTextPairs.Sort((t1, t2) => { return t1.Value.CompareTo(t2.Value); });
foreach (KeyValuePair<string, string> tagTextPair in tagTextPairs)
{
if (!tagTextPair.Key.StartsWith(textTag)) { continue; }
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), textList.Content.RectTransform) { MinSize = new Point(0, 20) },
ToolBox.LimitString(tagTextPair.Value, GUI.Font, textList.Content.Rect.Width))
{
UserData = tagTextPair.Key
};
}
}
private void TrySendNetworkUpdate(ISerializableEntity entity, SerializableProperty property)
{

View File

@@ -35,7 +35,6 @@ namespace Barotrauma
{
public readonly string File;
public readonly string Type;
public readonly bool DuckVolume;
public readonly Vector2 IntensityRange;
@@ -44,7 +43,6 @@ namespace Barotrauma
this.File = Path.GetFullPath(element.GetAttributeString("file", ""));
this.Type = element.GetAttributeString("type", "").ToLowerInvariant();
this.IntensityRange = element.GetAttributeVector2("intensityrange", new Vector2(0.0f, 100.0f));
this.DuckVolume = element.GetAttributeBool("duckvolume", false);
}
}
@@ -238,7 +236,7 @@ namespace Barotrauma
}
float ambienceVolume = 0.8f;
if (Character.Controlled != null && !Character.Controlled.Removed)
if (Character.Controlled != null)
{
AnimController animController = Character.Controlled.AnimController;
if (animController.HeadInWater)
@@ -374,6 +372,167 @@ namespace Barotrauma
}
}
private static void UpdateFireSounds(float deltaTime)
{
for (int i = 0; i < fireVolumeLeft.Length; i++)
{
fireVolumeLeft[i] = 0.0f;
fireVolumeRight[i] = 0.0f;
}
Vector2 listenerPos = new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y);
foreach (Hull hull in Hull.hullList)
{
foreach (FireSource fs in hull.FireSources)
{
Vector2 diff = fs.WorldPosition + fs.Size / 2 - listenerPos;
if (Math.Abs(diff.X) < FireSoundRange && Math.Abs(diff.Y) < FireSoundRange)
{
Vector2 diffLeft = (fs.WorldPosition + new Vector2(fs.Size.X, fs.Size.Y / 2)) - listenerPos;
if (diff.X < fs.Size.X / 2.0f) diff.X = 0.0f;
if (diffLeft.X <= 0)
{
float distFallOffLeft = diffLeft.Length() / FireSoundRange;
if (distFallOffLeft < 0.99f)
{
fireVolumeLeft[0] += (1.0f - distFallOffLeft) * (fs.Size.X / FireSoundLargeLimit);
if (fs.Size.X > FireSoundLargeLimit) fireVolumeLeft[1] += (1.0f - distFallOffLeft) * ((fs.Size.X - FireSoundLargeLimit) / FireSoundLargeLimit);
}
}
Vector2 diffRight = (fs.WorldPosition + new Vector2(0.0f, fs.Size.Y / 2)) - listenerPos;
if (diff.X < fs.Size.X / 2.0f) diff.X = 0.0f;
if (diffRight.X >= 0)
{
float distFallOffRight = diffRight.Length() / FireSoundRange;
if (distFallOffRight < 0.99f)
{
fireVolumeRight[0] += 1.0f - distFallOffRight;
if (fs.Size.X > FireSoundLargeLimit) fireVolumeRight[1] += (1.0f - distFallOffRight) * ((fs.Size.X - FireSoundLargeLimit) / FireSoundLargeLimit);
}
}
}
}
}
for (int i = 0; i < fireVolumeLeft.Length; i++)
{
if (fireVolumeLeft[i] < 0.05f && fireVolumeRight[i] < 0.05f)
{
if (fireSoundChannels[i] != null)
{
fireSoundChannels[i].FadeOutAndDispose();
fireSoundChannels[i] = null;
}
}
else
{
Vector2 soundPos = new Vector2(GameMain.SoundManager.ListenerPosition.X + (fireVolumeRight[i] - fireVolumeLeft[i]) * 100, GameMain.SoundManager.ListenerPosition.Y);
if (fireSoundChannels[i] == null || !fireSoundChannels[i].IsPlaying)
{
fireSoundChannels[i] = GetSound(i == 0 ? "fire" : "firelarge").Play(1.0f, FlowSoundRange, soundPos);
fireSoundChannels[i].Looping = true;
}
fireSoundChannels[i].Gain = Math.Max(fireVolumeRight[i], fireVolumeLeft[i]);
fireSoundChannels[i].Position = new Vector3(soundPos, 0.0f);
}
}
}
if (waterAmbiences.Count > 1)
{
if (waterAmbienceChannels[0] == null || !waterAmbienceChannels[0].IsPlaying)
{
waterAmbienceChannels[0] = waterAmbiences[0].Play(ambienceVolume * (1.0f - movementSoundVolume),"waterambience");
//waterAmbiences[0].Loop(waterAmbienceIndexes[0], ambienceVolume * (1.0f - movementSoundVolume));
waterAmbienceChannels[0].Looping = true;
}
else
{
waterAmbienceChannels[0].Gain = ambienceVolume * (1.0f - movementSoundVolume);
}
if (waterAmbienceChannels[1] == null || !waterAmbienceChannels[1].IsPlaying)
{
waterAmbienceChannels[1] = waterAmbiences[1].Play(ambienceVolume * movementSoundVolume, "waterambience");
//waterAmbienceIndexes[1] = waterAmbiences[1].Loop(waterAmbienceIndexes[1], ambienceVolume * movementSoundVolume);
waterAmbienceChannels[1].Looping = true;
}
else
{
waterAmbienceChannels[1].Gain = ambienceVolume * movementSoundVolume;
}
}
}
private static void UpdateWaterFlowSounds(float deltaTime)
{
if (FlowSounds.Count == 0) { return; }
float[] targetFlowLeft = new float[FlowSounds.Count];
float[] targetFlowRight = new float[FlowSounds.Count];
Vector2 listenerPos = new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y);
foreach (Gap gap in Gap.GapList)
{
if (gap.Open < 0.01f) continue;
float gapFlow = Math.Abs(gap.LerpedFlowForce.X) + Math.Abs(gap.LerpedFlowForce.Y) * 2.5f;
if (gapFlow < 10.0f) continue;
int flowSoundIndex = (int)Math.Floor(MathHelper.Clamp(gapFlow / MaxFlowStrength, 0, FlowSounds.Count));
flowSoundIndex = Math.Min(flowSoundIndex, FlowSounds.Count - 1);
Vector2 diff = gap.WorldPosition - listenerPos;
if (Math.Abs(diff.X) < FlowSoundRange && Math.Abs(diff.Y) < FlowSoundRange)
{
float dist = diff.Length();
float distFallOff = dist / FlowSoundRange;
if (distFallOff >= 0.99f) continue;
//flow at the left side
if (diff.X < 0)
{
targetFlowLeft[flowSoundIndex] = 1.0f - distFallOff;
}
else
{
targetFlowRight[flowSoundIndex] = 1.0f - distFallOff;
}
}
}
for (int i = 0; i < FlowSounds.Count; i++)
{
flowVolumeLeft[i] = (targetFlowLeft[i] < flowVolumeLeft[i]) ?
Math.Max(targetFlowLeft[i], flowVolumeLeft[i] - deltaTime) :
Math.Min(targetFlowLeft[i], flowVolumeLeft[i] + deltaTime);
flowVolumeRight[i] = (targetFlowRight[i] < flowVolumeRight[i]) ?
Math.Max(targetFlowRight[i], flowVolumeRight[i] - deltaTime) :
Math.Min(targetFlowRight[i], flowVolumeRight[i] + deltaTime);
if (flowVolumeLeft[i] < 0.05f && flowVolumeRight[i] < 0.05f)
{
if (flowSoundChannels[i] != null)
{
flowSoundChannels[i].Dispose();
flowSoundChannels[i] = null;
}
}
else
{
Vector2 soundPos = new Vector2(GameMain.SoundManager.ListenerPosition.X + (flowVolumeRight[i] - flowVolumeLeft[i]) * 100, GameMain.SoundManager.ListenerPosition.Y);
if (flowSoundChannels[i] == null || !flowSoundChannels[i].IsPlaying)
{
flowSoundChannels[i] = FlowSounds[i].Play(1.0f, FlowSoundRange, soundPos);
flowSoundChannels[i].Looping = true;
}
flowSoundChannels[i].Gain = Math.Max(flowVolumeRight[i], flowVolumeLeft[i]);
flowSoundChannels[i].Position = new Vector3(soundPos, 0.0f);
}
}
}
private static void UpdateFireSounds(float deltaTime)
{
for (int i = 0; i < fireVolumeLeft.Length; i++)
@@ -453,7 +612,8 @@ namespace Barotrauma
"ambient",
new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y) + Rand.Vector(100.0f),
Rand.Range(0.5f, 1.0f),
1000.0f);
1000.0f,
new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y) + Rand.Vector(100.0f));
ambientSoundTimer = Rand.Range(ambientSoundInterval.X, ambientSoundInterval.Y);
}
@@ -467,31 +627,23 @@ namespace Barotrauma
return matchingSounds[Rand.Int(matchingSounds.Count)];
}
/// <summary>
/// Play a sound defined in a sound xml file without any positional effects.
/// </summary>
public static SoundChannel PlaySound(string soundTag, float volume = 1.0f)
{
var sound = GetSound(soundTag);
return sound?.Play(volume);
}
/// <summary>
/// Play a sound defined in a sound xml file. If the volume or range parameters are omitted, the volume and range defined in the sound xml are used.
/// </summary>
public static SoundChannel PlaySound(string soundTag, Vector2 position, float? volume = null, float? range = null, Hull hullGuess = null)
public static SoundChannel PlaySound(string soundTag, float volume, float range, Vector2 position, Hull hullGuess = null)
{
var sound = GetSound(soundTag);
if (sound == null) return null;
return PlaySound(sound, position, volume ?? sound.BaseGain, range ?? sound.BaseFar, hullGuess);
return PlaySound(sound, sound.BaseGain * volume, range, position, hullGuess);
}
public static SoundChannel PlaySound(Sound sound, Vector2 position, float? volume = null, float? range = null, Hull hullGuess = null)
public static SoundChannel PlaySound(Sound sound, float volume, float range, Vector2 position, Hull hullGuess = null)
{
float far = range ?? sound.BaseFar;
if (Vector2.DistanceSquared(new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y), position) > far * far) return null;
return sound.Play(volume ?? sound.BaseGain, far, position, muffle: ShouldMuffleSound(Character.Controlled, position, far, hullGuess));
if (Vector2.DistanceSquared(new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y), position) > range * range) return null;
return sound.Play(sound.BaseGain * volume, range, position, muffle: ShouldMuffleSound(Character.Controlled, position, range, hullGuess));
}
private static void UpdateMusic(float deltaTime)
@@ -525,7 +677,7 @@ namespace Barotrauma
//switch the music if nothing playing atm or the currently playing clip is not suitable anymore
else if (targetMusic[0] == null || currentMusic[0] == null || !suitableMusic.Any(m => m.File == currentMusic[0].Filename))
{
targetMusic[0] = suitableMusic.GetRandom();
targetMusic[0] = suitableMusic.GetRandom();
}
//get the appropriate intensity layers for current situation
@@ -560,7 +712,6 @@ namespace Barotrauma
updateMusicTimer = UpdateMusicInterval;
}
int activeTrackCount = targetMusic.Count(m => m != null);
for (int i = 0; i < MaxMusicChannels; i++)
{
//nothing should be playing on this channel
@@ -600,12 +751,7 @@ namespace Barotrauma
musicChannel[i] = currentMusic[i].Play(0.0f, "music");
musicChannel[i].Looping = true;
}
float targetGain = 1.0f;
if (targetMusic[i].DuckVolume)
{
targetGain = (float)Math.Sqrt(1.0f / activeTrackCount);
}
musicChannel[i].Gain = MathHelper.Lerp(musicChannel[i].Gain, targetGain, MusicLerpSpeed * deltaTime);
musicChannel[i].Gain = MathHelper.Lerp(musicChannel[i].Gain, 1.0f, MusicLerpSpeed * deltaTime);
}
}
}
@@ -673,7 +819,8 @@ namespace Barotrauma
foreach (Character character in Character.CharacterList)
{
if (character.IsDead || !character.Enabled) continue;
if (!(character.AIController is EnemyAIController enemyAI) || (!enemyAI.AttackHumans && !enemyAI.AttackRooms)) continue;
EnemyAIController enemyAI = character.AIController as EnemyAIController;
if (enemyAI == null || (!enemyAI.AttackHumans && !enemyAI.AttackRooms)) continue;
if (targetSubmarine != null)
{
@@ -691,16 +838,9 @@ namespace Barotrauma
}
}
if (GameMain.GameSession != null)
if (GameMain.GameSession != null && Timing.TotalTime < GameMain.GameSession.RoundStartTime + 120.0)
{
if (Submarine.Loaded != null && Level.Loaded != null && Submarine.MainSub.AtEndPosition)
{
return "levelend";
}
if (Timing.TotalTime < GameMain.GameSession.RoundStartTime + 120.0)
{
return "start";
}
return "start";
}
return "default";

View File

@@ -104,7 +104,14 @@ namespace Barotrauma.SpriteDeformations
public Point Resolution
{
get { return deformationParams.Resolution; }
get
{
if (deformationParams.Resolution.X != Deformation.GetLength(0) || deformationParams.Resolution.Y != Deformation.GetLength(1))
{
Deformation = new Vector2[deformationParams.Resolution.X, deformationParams.Resolution.Y];
}
return deformationParams.Resolution;
}
set { SetResolution(value); }
}
@@ -195,15 +202,6 @@ namespace Barotrauma.SpriteDeformations
public static Vector2[,] GetDeformation(IEnumerable<SpriteDeformation> animations, Vector2 scale)
{
foreach (SpriteDeformation animation in animations)
{
if (animation.deformationParams.Resolution.X != animation.Deformation.GetLength(0) ||
animation.deformationParams.Resolution.Y != animation.Deformation.GetLength(1))
{
animation.Deformation = new Vector2[animation.deformationParams.Resolution.X, animation.deformationParams.Resolution.Y];
}
}
Point resolution = animations.First().Resolution;
if (animations.Any(a => a.Resolution != resolution))
{
@@ -213,6 +211,7 @@ namespace Barotrauma.SpriteDeformations
}
Vector2[,] deformation = new Vector2[resolution.X, resolution.Y];
foreach (SpriteDeformation animation in animations)
{
animation.GetDeformation(out Vector2[,] animDeformation, out float multiplier);

View File

@@ -62,7 +62,7 @@ namespace Barotrauma
{
foreach (RoundSound sound in sounds)
{
soundChannel = SoundPlayer.PlaySound(sound.Sound, entity.WorldPosition, sound.Volume, sound.Range, hull);
soundChannel = SoundPlayer.PlaySound(sound.Sound, sound.Volume, sound.Range, entity.WorldPosition, hull);
if (soundChannel != null) soundChannel.Looping = loopSound;
}
}
@@ -82,7 +82,7 @@ namespace Barotrauma
selectedSoundIndex = Rand.Int(sounds.Count);
}
var selectedSound = sounds[selectedSoundIndex];
soundChannel = SoundPlayer.PlaySound(selectedSound.Sound, entity.WorldPosition, selectedSound.Volume, selectedSound.Range, hull);
soundChannel = SoundPlayer.PlaySound(selectedSound.Sound, selectedSound.Volume, selectedSound.Range, entity.WorldPosition, hull);
if (soundChannel != null) soundChannel.Looping = loopSound;
}
}

View File

@@ -11,7 +11,7 @@ namespace Barotrauma
{
private static Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"])*\"|[^,]*)", RegexOptions.Compiled); // Handling commas inside data fields surrounded by ""
private static List<int> conversationClosingIndent = new List<int>();
private static char[] separator = new char[1] { '|' };
private static char[] separator = new char[1] { ',' };
private const string conversationsPath = "Content/NPCConversations";
private const string infoTextPath = "Content/Texts";
@@ -48,7 +48,7 @@ namespace Barotrauma
DebugConsole.ThrowError("NPCConversation Localization .csv to .xml conversion failed for: " + conversationFiles[i]);
continue;
}
string xmlFileFullPath = $"{conversationsPath}/NpcConversations_{language}_NEW.xml";
string xmlFileFullPath = $"{conversationsPath}/NPCConversations_{language}_NEW.xml";
File.WriteAllLines(xmlFileFullPath, xmlContent);
DebugConsole.NewMessage("Conversation localization .xml file successfully created at: " + xmlFileFullPath);
}
@@ -141,8 +141,7 @@ namespace Barotrauma
for (int i = 0; i < NPCPersonalityTrait.List.Count; i++) // Traits
{
//string[] split = SplitCSV(csvContent[traitStart + i].Trim(separator));
string[] split = csvContent[traitStart + i].Split(separator);
string[] split = SplitCSV(csvContent[traitStart + i].Trim(separator));
xmlContent.Add(
$"<PersonalityTrait " +
$"{GetVariable("name", split[1])}" +
@@ -152,10 +151,7 @@ namespace Barotrauma
for (int i = traitStart + NPCPersonalityTrait.List.Count; i < csvContent.Length; i++) // Conversations
{
//string[] presplit = csvContent[i].Split(separator); // Handling speaker index fetching, somehow doesn't work with the regex
//string[] split = SplitCSV(csvContent[i]);
string[] split = csvContent[i].Split(separator);
string[] split = SplitCSV(csvContent[i]);
int emptyFields = 0;
@@ -179,17 +175,17 @@ namespace Barotrauma
string speaker = split[1];
int depthIndex = int.Parse(split[2]);
// 3 = original line
string line = split[3].Replace("\"", "");
string flags = split[4].Replace("\"", "");
string allowedJobs = split[5].Replace("\"", "");
string speakerTags = split[6].Replace("\"", "");
string minIntensity = split[7].Replace("\"", "").Replace(",", ".");
string maxIntensity = split[8].Replace("\"", "").Replace(",", ".");
string line = split[4].Replace("\"", "");
string flags = split[5].Replace("\"", "");
string allowedJobs = split[6].Replace("\"", "");
string speakerTags = split[7].Replace("\"", "");
string minIntensity = split[8].Replace("\"", "");
string maxIntensity = split[9].Replace("\"", "");
string element =
$"{GetIndenting(depthIndex)}" +
$"<Conversation line=\"{line}\" " +
$"{GetVariable("speaker", speaker)}" +
$"{GetVariable("speaker" ,speaker)}" +
$"{GetVariable("flags", flags)}" +
$"{GetVariable("allowedjobs", allowedJobs)}" +
$"{GetVariable("speakertags", speakerTags)}" +
@@ -260,7 +256,7 @@ namespace Barotrauma
list.Add("");
}
list.Add(curr.TrimStart(separator));
list.Add(curr.TrimStart(','));
}
return list.ToArray();

View File

@@ -1,7 +1,6 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
@@ -142,7 +141,7 @@ namespace Barotrauma
StringBuilder wrappedText = new StringBuilder();
float linePos = 0f;
Vector2 spaceSize = font.MeasureString(" ") * textScale;
for (int i = 0; i < words.Count; ++i)
for (int i = 0; i < words.Length; ++i)
{
if (words[i].Length == 0)
{

View File

@@ -31,7 +31,6 @@
<BootstrapperEnabled>true</BootstrapperEnabled>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<AllowedReferenceRelatedFileExtensions>.pdb</AllowedReferenceRelatedFileExtensions>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>..\BarotraumaShared\Icon.ico</ApplicationIcon>
@@ -54,32 +53,14 @@
<PlatformTarget>x64</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseWindows|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\ReleaseWindows\</OutputPath>
<DefineConstants>TRACE;WINDOWS;CLIENT</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugWindows|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\bin\x86\DebugWindows\</OutputPath>
<DefineConstants>TRACE;WINDOWS;CLIENT;DEBUG</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Concentus, Version=1.1.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\Concentus.1.1.7\lib\portable-net45+win+wpa81+wp80\Concentus.dll</HintPath>
</Reference>
<Reference Include="GameAnalytics.Mono, Version=1.0.6710.29255, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\Libraries\NuGet\GameAnalytics.Mono.SDK.1.1.12\lib\net45\GameAnalytics.Mono.dll</HintPath>
</Reference>
@@ -145,30 +126,10 @@
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<Choose>
<When Condition="'$(Configuration)|$(Platform)' == 'DebugWindows|x86' Or '$(Configuration)|$(Platform)' == 'ReleaseWindows|x86'">
<ItemGroup>
<ContentWithTargetPath Include="lib86/freetype6.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<TargetPath>freetype6.dll</TargetPath>
</ContentWithTargetPath>
<Content Include="steam_api.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<Content Include="freetype6.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="steam_api64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Otherwise>
</Choose>
<ItemGroup>
<Content Include="freetype6.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="libvlc.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -215,6 +176,9 @@
<Content Include="Shaders\losshader.fx" />
<Content Include="Shaders\postprocess.fx" />
<Content Include="Shaders\watershader.fx" />
<Content Include="steam_api64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="wrap_oal.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
@@ -251,10 +215,6 @@
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Libraries\Concentus\CSharp\Concentus\Concentus.csproj">
<Project>{0e7fee6a-15e5-4a4e-943c-80276003478c}</Project>
<Name>Concentus</Name>
</ProjectReference>
<ProjectReference Include="..\..\Libraries\Facepunch.Steamworks\Facepunch.Steamworks.csproj">
<Project>{3af0347c-5a9b-4421-868c-8ee3dbfaebc6}</Project>
<Name>Facepunch.Steamworks</Name>
@@ -320,13 +280,7 @@
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
-->
<Target Name="AfterBuild">
<!-- Write version number to a "Version.txt" file in the output folder -->
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
<Output TaskParameter="Assemblies" ItemName="CurrentAssembly" />
</GetAssemblyIdentity>
<Exec Command="echo v%(CurrentAssembly.Version) &gt; $(TargetDir)Version.txt">
</Exec>
</Target>
-->
</Project>

View File

@@ -1,35 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="SharpDX" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.MediaFoundation" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.XAudio2" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.DXGI" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.Direct3D11" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.Direct2D1" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.XInput" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="SharpDX" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.MediaFoundation" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.XAudio2" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.DXGI" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.Direct3D11" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.Direct2D1" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SharpDX.XInput" publicKeyToken="b4dcf0f35e5521f1" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Concentus" version="1.1.7" targetFramework="net45" />
<package id="GameAnalytics.Mono.SDK" version="1.1.12" targetFramework="net45" />
<package id="Microsoft.NETCore.Platforms" version="3.0.0-preview.19073.11" targetFramework="net45" />
<package id="MonoGame.Framework.DesktopGL" version="3.7.1.189" targetFramework="net45" />

View File

@@ -31,5 +31,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.10.0")]
[assembly: AssemblyFileVersion("0.8.10.0")]
[assembly: AssemblyVersion("0.8.9.10")]
[assembly: AssemblyFileVersion("0.8.9.10")]

View File

@@ -91,63 +91,6 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseLinux|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\ReleaseLinux\</OutputPath>
<DefineConstants>TRACE;SERVER</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugLinux|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\DebugLinux\</OutputPath>
<DefineConstants>TRACE;SERVER;DEBUG</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseMac|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\ReleaseMac\</OutputPath>
<DefineConstants>TRACE;SERVER</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugMac|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\DebugMac\</OutputPath>
<DefineConstants>TRACE;SERVER;DEBUG</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseWindows|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\ReleaseWindows\</OutputPath>
<DefineConstants>TRACE;SERVER</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugWindows|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\DebugWindows\</OutputPath>
<DefineConstants>TRACE;SERVER;DEBUG</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
@@ -272,23 +215,11 @@
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup Condition="$(Configuration.EndsWith('Linux'))">
</ItemGroup>
<ItemGroup Condition="'$(DefineConstants)' == 'LINUX' ">
<None Include="Launch_BarotraumaServer">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="DedicatedServer">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="DedicatedServer.bin.x86">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="DedicatedServer.bin.x86_64">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="DedicatedServer.bin.osx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="..\BarotraumaShared\SharedCode.projitems" Label="Shared" />
<Import Project="..\BarotraumaShared\SharedContent.projitems" Label="Shared" />

Some files were not shown because too many files have changed in this diff Show More