Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix antag selection being evil #28197

Merged
merged 15 commits into from
May 26, 2024
28 changes: 28 additions & 0 deletions Content.IntegrationTests/Pair/TestPair.Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Server.Preferences.Managers;
using Content.Shared.Preferences;
using Content.Shared.Roles;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
Expand Down Expand Up @@ -128,4 +131,29 @@ public async Task WaitClientCommand(string cmd, int numTicks = 10)

return list;
}

/// <summary>
/// Helper method for enabling or disabling a antag role
/// </summary>
public async Task SetAntagPref(ProtoId<AntagPrototype> id, bool value)
{
var prefMan = Server.ResolveDependency<IServerPreferencesManager>();

var prefs = prefMan.GetPreferences(Client.User!.Value);
// what even is the point of ICharacterProfile if we always cast it to HumanoidCharacterProfile to make it usable?
var profile = (HumanoidCharacterProfile) prefs.SelectedCharacter;

Assert.That(profile.AntagPreferences.Contains(id), Is.EqualTo(!value));
var newProfile = profile.WithAntagPreference(id, value);

await Server.WaitPost(() =>
{
prefMan.SetProfile(Client.User.Value, prefs.SelectedCharacterIndex, newProfile).Wait();
});

// And why the fuck does it always create a new preference and profile object instead of just reusing them?
var newPrefs = prefMan.GetPreferences(Client.User.Value);
var newProf = (HumanoidCharacterProfile) newPrefs.SelectedCharacter;
Assert.That(newProf.AntagPreferences.Contains(id), Is.EqualTo(value));
}
}
4 changes: 2 additions & 2 deletions Content.IntegrationTests/PoolManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ public static partial class PoolManager

options.BeforeStart += () =>
{
// Server-only systems (i.e., systems that subscribe to events with server-only components)
var entSysMan = IoCManager.Resolve<IEntitySystemManager>();
entSysMan.LoadExtraSystemType<ResettingEntitySystemTests.TestRoundRestartCleanupEvent>();
entSysMan.LoadExtraSystemType<InteractionSystemTests.TestInteractionSystem>();
entSysMan.LoadExtraSystemType<DeviceNetworkTestSystem>();
entSysMan.LoadExtraSystemType<TestDestructibleListenerSystem>();

IoCManager.Resolve<ILogManager>().GetSawmill("loc").Level = LogLevel.Error;
IoCManager.Resolve<IConfigurationManager>()
.OnValueChanged(RTCVars.FailureLogLevel, value => logHandler.FailureLevel = value, true);
Expand Down
78 changes: 78 additions & 0 deletions Content.IntegrationTests/Tests/GameRules/AntagPreferenceTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using Content.Server.Antag;
using Content.Server.Antag.Components;
using Content.Server.GameTicking;
using Content.Shared.GameTicking;
using Robust.Shared.GameObjects;
using Robust.Shared.Player;
using Robust.Shared.Random;

namespace Content.IntegrationTests.Tests.GameRules;

// Once upon a time, players in the lobby weren't ever considered eligible for antag roles.
// Lets not let that happen again.
[TestFixture]
public sealed class AntagPreferenceTest
{
/// <summary>
/// Check that a nuke ops game mode can start without issue. I.e., that the nuke station and such all get loaded.
ElectroJr marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
[Test]
public async Task TestLobbyPlayersValid()
{
await using var pair = await PoolManager.GetServerClient(new PoolSettings
{
DummyTicker = false,
Connected = true,
InLobby = true
});

var server = pair.Server;
var client = pair.Client;
var ticker = server.System<GameTicker>();
var sys = server.System<AntagSelectionSystem>();

// Initially in the lobby
Assert.That(ticker.RunLevel, Is.EqualTo(GameRunLevel.PreRoundLobby));
Assert.That(client.AttachedEntity, Is.Null);
Assert.That(ticker.PlayerGameStatuses[client.User!.Value], Is.EqualTo(PlayerGameStatus.NotReadyToPlay));

EntityUid uid = default;
await server.WaitPost(() => uid = server.EntMan.Spawn("Traitor"));
var rule = new Entity<AntagSelectionComponent>(uid, server.EntMan.GetComponent<AntagSelectionComponent>(uid));
var def = rule.Comp.Definitions.Single();

// IsSessionValid & IsEntityValid are preference agnostic and should always be true for players in the lobby.
// Though maybe that will change in the future, but then GetPlayerPool() needs to be updated to reflect that.
Assert.That(sys.IsSessionValid(rule, pair.Player, def), Is.True);
Assert.That(sys.IsEntityValid(client.AttachedEntity, def), Is.True);

// By default, traitor/antag preferences are disabled, so the pool should be empty.
var sessions = new List<ICommonSession>{pair.Player!};
var pool = sys.GetPlayerPool(rule, sessions, def);
Assert.That(pool.Count, Is.EqualTo(0));

// Opt into the traitor role.
await pair.SetAntagPref("Traitor", true);

Assert.That(sys.IsSessionValid(rule, pair.Player, def), Is.True);
Assert.That(sys.IsEntityValid(client.AttachedEntity, def), Is.True);
pool = sys.GetPlayerPool(rule, sessions, def);
Assert.That(pool.Count, Is.EqualTo(1));
pool.TryPickAndTake(pair.Server.ResolveDependency<IRobustRandom>(), out var picked);
Assert.That(picked, Is.EqualTo(pair.Player));
Assert.That(sessions.Count, Is.EqualTo(1));

// opt back out
await pair.SetAntagPref("Traitor", false);

Assert.That(sys.IsSessionValid(rule, pair.Player, def), Is.True);
Assert.That(sys.IsEntityValid(client.AttachedEntity, def), Is.True);
pool = sys.GetPlayerPool(rule, sessions, def);
Assert.That(pool.Count, Is.EqualTo(0));

await pair.CleanReturnAsync();
}
}
4 changes: 4 additions & 0 deletions Content.IntegrationTests/Tests/GameRules/NukeOpsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ public async Task TryStopNukeOpsFromConstantlyFailing()
Assert.That(client.AttachedEntity, Is.Null);
Assert.That(ticker.PlayerGameStatuses[client.User!.Value], Is.EqualTo(PlayerGameStatus.NotReadyToPlay));

// Opt into the nukies role.
await pair.SetAntagPref("NukeopsCommander", true);

// There are no grids or maps
Assert.That(entMan.Count<MapComponent>(), Is.Zero);
Assert.That(entMan.Count<MapGridComponent>(), Is.Zero);
Expand Down Expand Up @@ -198,6 +201,7 @@ public async Task TryStopNukeOpsFromConstantlyFailing()

ticker.SetGamePreset((GamePresetPrototype?)null);
server.CfgMan.SetCVar(CCVars.GridFill, false);
await pair.SetAntagPref("NukeopsCommander", false);
await pair.CleanReturnAsync();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,6 @@ public async Task InsideContainerInteractionBlockTest()
await pair.CleanReturnAsync();
}

[Reflect(false)]
public sealed class TestInteractionSystem : EntitySystem
{
public EntityEventHandler<InteractUsingEvent>? InteractUsingEvent;
Expand Down
3 changes: 0 additions & 3 deletions Content.IntegrationTests/Tests/ResettingEntitySystemTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace Content.IntegrationTests.Tests
[TestOf(typeof(RoundRestartCleanupEvent))]
public sealed class ResettingEntitySystemTests
{
[Reflect(false)]
public sealed class TestRoundRestartCleanupEvent : EntitySystem
{
public bool HasBeenReset { get; set; }
Expand Down Expand Up @@ -49,8 +48,6 @@ public async Task ResettingEntitySystemResetTest()

system.HasBeenReset = false;

Assert.That(system.HasBeenReset, Is.False);

gameTicker.RestartRound();

Assert.That(system.HasBeenReset);
Expand Down
24 changes: 10 additions & 14 deletions Content.Server/Antag/AntagSelectionSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,11 @@ public AntagSelectionPlayerPool GetPlayerPool(Entity<AntagSelectionComponent> en
{
var preferredList = new List<ICommonSession>();
var fallbackList = new List<ICommonSession>();
var unwantedList = new List<ICommonSession>();
var invalidList = new List<ICommonSession>();
foreach (var session in sessions)
{
if (!IsSessionValid(ent, session, def) ||
!IsEntityValid(session.AttachedEntity, def))
{
invalidList.Add(session);
continue;
}

var pref = (HumanoidCharacterProfile) _pref.GetPreferences(session.UserId).SelectedCharacter;
if (def.PrefRoles.Count != 0 && pref.AntagPreferences.Any(p => def.PrefRoles.Contains(p)))
Expand All @@ -345,13 +340,9 @@ public AntagSelectionPlayerPool GetPlayerPool(Entity<AntagSelectionComponent> en
{
fallbackList.Add(session);
}
else
{
unwantedList.Add(session);
}
}

return new AntagSelectionPlayerPool(new() { preferredList, fallbackList, unwantedList, invalidList });
return new AntagSelectionPlayerPool(new() { preferredList, fallbackList });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When i was trying to fix this myself i basically did the same thing. My only consairn and why i never made a pr was cause. What happens if we got no one in the prefferedlist or fallbacklist? Are we starting the gamemode without any antags. This resulting in a broken gamerule/greenshift.

Yes i agree this should be intended behavior (#24292). But i don't think we currently have a solution to prevent broken gamerules.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok this doesnt cancel it, but nukies should be changed to make spawners if theres not enough players like in my issue
traitors zombies etc doesnt really matter as theres no unused map lying around doing nothing

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Afaik it also picks people at random in game not just in the lobby (look at sleeper agents. There are reports that players get sleeper agent given to them when they never opted in)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes this fixes that since it wont pick anyone that didnt opt in

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

keep the unwanted list but not the invalid one at least until we have ways of setting up ghost roles and other rules properly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the majority of the issue is people that arent opted in getting picked, invalid is only really picked in a dev environment. nukies making ghost roles for missing players wyci

}

/// <summary>
Expand All @@ -362,14 +353,18 @@ public bool IsSessionValid(Entity<AntagSelectionComponent> ent, ICommonSession?
if (session == null)
return true;

mind ??= session.GetMind();

if (session.Status is SessionStatus.Disconnected or SessionStatus.Zombie)
return false;

if (ent.Comp.SelectedSessions.Contains(session))
return false;

mind ??= session.GetMind();

// If the player has not spawned in as any entity (e.g., in the lobby), they can be given an antag role/entity.
if (mind == null)
return true;

//todo: we need some way to check that we're not getting the same role twice. (double picking thieves or zombies through midrounds)

switch (def.MultiAntagSetting)
Expand Down Expand Up @@ -398,10 +393,11 @@ public bool IsSessionValid(Entity<AntagSelectionComponent> ent, ICommonSession?
/// <summary>
/// Checks if a given entity (mind/session not included) is valid for a given antagonist.
/// </summary>
private bool IsEntityValid(EntityUid? entity, AntagSelectionDefinition def)
public bool IsEntityValid(EntityUid? entity, AntagSelectionDefinition def)
{
// If the player has not spawned in as any entity (e.g., in the lobby), they can be given an antag role/entity.
if (entity == null)
return false;
return true;

if (HasComp<PendingClockInComponent>(entity))
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ public interface IServerPreferencesManager
PlayerPreferences? GetPreferencesOrNull(NetUserId? userId);
IEnumerable<KeyValuePair<NetUserId, ICharacterProfile>> GetSelectedProfilesForPlayers(List<NetUserId> userIds);
bool HavePreferencesLoaded(ICommonSession session);

Task SetProfile(NetUserId userId, int slot, ICharacterProfile profile);
}
}
30 changes: 15 additions & 15 deletions Content.Server/Preferences/Managers/ServerPreferencesManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ public sealed class ServerPreferencesManager : IServerPreferencesManager
[Dependency] private readonly IServerDbManager _db = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IDependencyCollection _dependencies = default!;
[Dependency] private readonly ILogManager _log = default!;

// Cache player prefs on the server so we don't need as much async hell related to them.
private readonly Dictionary<NetUserId, PlayerPrefData> _cachedPlayerPrefs =
new();

private ISawmill _sawmill = default!;

private int MaxCharacterSlots => _cfg.GetCVar(CCVars.GameMaxCharacterSlots);

public void Init()
Expand All @@ -42,6 +45,7 @@ public void Init()
_netManager.RegisterNetMessage<MsgSelectCharacter>(HandleSelectCharacterMessage);
_netManager.RegisterNetMessage<MsgUpdateCharacter>(HandleUpdateCharacterMessage);
_netManager.RegisterNetMessage<MsgDeleteCharacter>(HandleDeleteCharacterMessage);
_sawmill = _log.GetSawmill("prefs");
}

private async void HandleSelectCharacterMessage(MsgSelectCharacter message)
Expand Down Expand Up @@ -78,27 +82,25 @@ private async void HandleSelectCharacterMessage(MsgSelectCharacter message)

private async void HandleUpdateCharacterMessage(MsgUpdateCharacter message)
{
var slot = message.Slot;
var profile = message.Profile;
var userId = message.MsgChannel.UserId;

if (profile == null)
{
Logger.WarningS("prefs",
$"User {userId} sent a {nameof(MsgUpdateCharacter)} with a null profile in slot {slot}.");
return;
}
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (message.Profile == null)
_sawmill.Error($"User {userId} sent a {nameof(MsgUpdateCharacter)} with a null profile in slot {message.Slot}.");
else
await SetProfile(userId, message.Slot, message.Profile);
}

public async Task SetProfile(NetUserId userId, int slot, ICharacterProfile profile)
{
if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded)
{
Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
_sawmill.Error($"Tried to modify user {userId} preferences before they loaded.");
return;
}

if (slot < 0 || slot >= MaxCharacterSlots)
{
return;
}

var curPrefs = prefsData.Prefs!;
var session = _playerManager.GetSessionById(userId);
Expand All @@ -112,10 +114,8 @@ private async void HandleUpdateCharacterMessage(MsgUpdateCharacter message)

prefsData.Prefs = new PlayerPreferences(profiles, slot, curPrefs.AdminOOCColor);

if (ShouldStorePrefs(message.MsgChannel.AuthType))
{
await _db.SaveCharacterSlotAsync(message.MsgChannel.UserId, message.Profile, message.Slot);
}
if (ShouldStorePrefs(session.Channel.AuthType))
await _db.SaveCharacterSlotAsync(userId, profile, slot);
}

private async void HandleDeleteCharacterMessage(MsgDeleteCharacter message)
Expand Down
4 changes: 3 additions & 1 deletion Content.Shared/Roles/Jobs/SharedJobSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,10 @@ public string MindTryGetJobName([NotNullWhen(true)] EntityUid? mindId)

public bool CanBeAntag(ICommonSession player)
{
// If the player does not have any mind associated with them (e.g., has not spawned in or is in the lobby), then
// they are eligible to be given an antag role/entity.
if (_playerSystem.ContentData(player) is not { Mind: { } mindId })
return false;
return true;

if (!MindTryGetJob(mindId, out _, out var prototype))
return true;
Expand Down