Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
- Reworked dynamic AI to be more efficient
- Bots will no longer spawn without a brain due to a hidden exception
  • Loading branch information
Lacyway committed May 20, 2024
1 parent 208ee49 commit 69d2b70
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 24 deletions.
53 changes: 44 additions & 9 deletions Fika.Core/Coop/Custom/FikaDynamicAI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using EFT;
using Fika.Core.Coop.Components;
using Fika.Core.Coop.Players;
using System;
using System.Collections.Generic;
using UnityEngine;

Expand All @@ -16,8 +17,9 @@ public class FikaDynamicAI : MonoBehaviour
private CoopHandler coopHandler;
private int frameCounter;
private int resetCounter;
private List<CoopPlayer> humanPlayers = [];
private List<CoopBot> bots = [];
private readonly List<CoopPlayer> humanPlayers = [];
private readonly List<CoopBot> bots = [];
private readonly HashSet<CoopBot> disabledBots = [];
private BotSpawner spawner;

protected void Awake()
Expand Down Expand Up @@ -65,11 +67,21 @@ private void Spawner_OnBotRemoved(BotOwner botOwner)

private void Spawner_OnBotCreated(BotOwner botOwner)
{
if (botOwner.IsYourPlayer || !botOwner.IsAI)
{
return;
}

bots.Add((CoopBot)botOwner.GetPlayer);
}

protected void Update()
{
if (!FikaPlugin.DynamicAI.Value)
{
return;
}

frameCounter++;

if (frameCounter % resetCounter == 0)
Expand All @@ -93,7 +105,7 @@ public void AddHumans()
}
}

private void DeactivateBot(CoopPlayer bot)
private void DeactivateBot(CoopBot bot)
{
#if DEBUG
logger.LogWarning($"Disabling {bot.gameObject.name}");
Expand All @@ -102,26 +114,33 @@ private void DeactivateBot(CoopPlayer bot)
bot.AIData.BotOwner.Memory.GoalEnemy = null;
bot.AIData.BotOwner.PatrollingData.Pause();
bot.gameObject.SetActive(false);

if (!disabledBots.Contains(bot))
{
disabledBots.Add(bot);
}
else
{
logger.LogError($"{bot.gameObject.name} was already in the disabled bots list when adding!");
}
}

private void ActivateBot(CoopPlayer bot)
private void ActivateBot(CoopBot bot)
{
#if DEBUG
logger.LogWarning($"Enabling {bot.gameObject.name}");
#endif
bot.gameObject.SetActive(true);
bot.AIData.BotOwner.PatrollingData.Unpause();
bot.AIData.BotOwner.PostActivate();
disabledBots.Remove(bot);
}

private void CheckForPlayers(CoopBot bot)
{
if (!FikaPlugin.DynamicAI.Value)
// Do not run on bots that have no initialized yet
if (bot.AIData.BotOwner.BotState is EBotState.NonActive or EBotState.PreActive)
{
if (!bot.gameObject.activeSelf)
{
ActivateBot(bot);
}
return;
}

Expand All @@ -139,13 +158,16 @@ private void CheckForPlayers(CoopBot bot)
notInRange++;
continue;
}

if (!humanPlayer.HealthController.IsAlive)
{
notInRange++;
continue;
}

float distance = Vector3.SqrMagnitude(bot.Position - humanPlayer.Position);
float range = FikaPlugin.DynamicAIRange.Value;

if (distance > range * range)
{
notInRange++;
Expand All @@ -161,5 +183,18 @@ private void CheckForPlayers(CoopBot bot)
ActivateBot(bot);
}
}

public void SettingChanged(bool value)
{
if (!value)
{
foreach (CoopBot bot in disabledBots)
{
bot.gameObject.SetActive(true);
}

disabledBots.Clear();
}
}
}
}
38 changes: 23 additions & 15 deletions Fika.Core/Coop/GameMode/CoopGame.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Aki.Custom.Airdrops;
using Aki.Reflection.Utils;
using BepInEx.Configuration;
using BepInEx.Logging;
using Comfort.Common;
using CommonAssets.Scripts.Game;
Expand Down Expand Up @@ -58,7 +59,8 @@ internal sealed class CoopGame : BaseLocalGame<GamePlayerOwner>, IBotGame, IFika
public bool forceStart = false;
private CoopExfilManager exfilManager;
private GameObject fikaStartButton;
private Dictionary<int, int> botQueue = [];
private readonly Dictionary<int, int> botQueue = [];
private FikaDynamicAI dynamicAI;

public RaidSettings RaidSettings { get; private set; }

Expand Down Expand Up @@ -114,10 +116,10 @@ internal static CoopGame Create(InputTree inputTree, Profile profile, GameDateTi
coopGame.nonWavesSpawnScenario_0.ImplementWaveSettings(wavesSettings);

// Waves Scenario setup
WildSpawnWave[] waves = EFT.LocalGame.smethod_7(wavesSettings, location.waves);
WildSpawnWave[] waves = LocalGame.smethod_7(wavesSettings, location.waves);
coopGame.wavesSpawnScenario_0 = WavesSpawnScenario.smethod_0(coopGame.gameObject, waves, new Action<BotWaveDataClass>(coopGame.botsController_0.ActivateBotsByWave), location);

BossLocationSpawn[] bossSpawns = EFT.LocalGame.smethod_8(wavesSettings, location.BossLocationSpawn);
BossLocationSpawn[] bossSpawns = LocalGame.smethod_8(wavesSettings, location.BossLocationSpawn);
coopGame.GClass579 = GClass579.smethod_0(bossSpawns, new Action<BossLocationSpawn>(coopGame.botsController_0.ActivateBotsByWave));

if (useCustomWeather && MatchmakerAcceptPatches.IsServer)
Expand Down Expand Up @@ -361,7 +363,7 @@ private async Task<LocalPlayer> CreateBot(Profile profile, Vector3 position)
}
else
{
int num = 999 + Bots.Count;
int num = method_12();
profile.SetSpawnedInSession(profile.Info.Side == EPlayerSide.Savage);

FikaServer server = Singleton<FikaServer>.Instance;
Expand Down Expand Up @@ -390,7 +392,7 @@ private async Task<LocalPlayer> CreateBot(Profile profile, Vector3 position)
else
{
#if DEBUG
Logger.LogInfo($"Bot {profile.Info.Settings.Role.ToString()} created at {position} SUCCESSFULLY!");
Logger.LogInfo($"Bot {profile.Info.Settings.Role} created at {position} SUCCESSFULLY!");
#endif
Bots.Add(localPlayer.ProfileId, localPlayer);
}
Expand Down Expand Up @@ -546,8 +548,7 @@ private async void DeployScreen(float timeBeforeDeploy)
Destroy(fikaStartButton);
}

FikaDynamicAI newDynamicAI = gameObject.GetComponent<FikaDynamicAI>();
newDynamicAI?.AddHumans();
dynamicAI?.AddHumans();

SetStatusModel status = new(coopHandler.MyPlayer.ProfileId, LobbyEntry.ELobbyStatus.IN_GAME);
await FikaRequestHandler.UpdateSetStatus(status);
Expand Down Expand Up @@ -597,8 +598,7 @@ private async void DeployScreen(float timeBeforeDeploy)
Singleton<FikaServer>.Instance.SendDataToAll(writer, ref syncPacket, LiteNetLib.DeliveryMethod.ReliableUnordered);
}

FikaDynamicAI newDynamicAI = gameObject.GetComponent<FikaDynamicAI>();
newDynamicAI?.AddHumans();
dynamicAI?.AddHumans();
}
else if (MatchmakerAcceptPatches.IsClient)
{
Expand Down Expand Up @@ -919,8 +919,7 @@ public void FinishLoading()

private async Task<Player> CreateLocalPlayer()
{
int num = Traverse.Create(this).Field("int_0").GetValue<int>();
num++;
int num = method_12();

Player.EUpdateMode eupdateMode = Player.EUpdateMode.Auto;
if (GClass549.Config.UseHandsFastAnimator)
Expand Down Expand Up @@ -978,7 +977,6 @@ private async Task WaitForPlayers()

FikaServer server = Singleton<FikaServer>.Instance;

numbersOfPlayersToWaitFor = MatchmakerAcceptPatches.HostExpectedNumberOfPlayers - (server.NetServer.ConnectedPeersCount + 1);
do
{
numbersOfPlayersToWaitFor = MatchmakerAcceptPatches.HostExpectedNumberOfPlayers - (server.NetServer.ConnectedPeersCount + 1);
Expand Down Expand Up @@ -1038,7 +1036,6 @@ private async Task WaitForPlayers()
NetDataWriter writer = new();
writer.Reset();
client.SendData(writer, ref packet, LiteNetLib.DeliveryMethod.ReliableOrdered);
numbersOfPlayersToWaitFor = MatchmakerAcceptPatches.HostExpectedNumberOfPlayers - (client.ConnectedClients + 1);
do
{
numbersOfPlayersToWaitFor = MatchmakerAcceptPatches.HostExpectedNumberOfPlayers - (client.ConnectedClients + 1);
Expand Down Expand Up @@ -1142,7 +1139,7 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co
botsController_0.BotSpawner.SetMaxBots(limits);
}

gameObject.AddComponent<FikaDynamicAI>();
dynamicAI = gameObject.AddComponent<FikaDynamicAI>();
}
else if (MatchmakerAcceptPatches.IsClient)
{
Expand Down Expand Up @@ -1209,6 +1206,8 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co
}

GClass579.Run(EBotsSpawnMode.Anyway);

FikaPlugin.DynamicAI.SettingChanged += DynamicAI_SettingChanged;
}
else
{
Expand Down Expand Up @@ -1238,6 +1237,14 @@ public override IEnumerator vmethod_4(float startDelay, BotControllerSettings co
yield break;
}

private void DynamicAI_SettingChanged(object sender, EventArgs e)
{
if (dynamicAI != null)
{
dynamicAI.SettingChanged(FikaPlugin.DynamicAI.Value);
}
}

private void SetupBorderzones()
{
GameWorld gameWorld = Singleton<GameWorld>.Instance;
Expand Down Expand Up @@ -1730,7 +1737,6 @@ public override void Dispose()
Singleton<GameWorld>.Instance.MineManager.OnExplosion -= OnMineExplode;
}

// Add these to coopgame directly?
if (MatchmakerAcceptPatches.IsServer)
{
CoopPlayer coopPlayer = (CoopPlayer)Singleton<GameWorld>.Instance.MainPlayer;
Expand All @@ -1744,6 +1750,8 @@ public override void Dispose()
{
Destroy(newDynamicAI);
}

FikaPlugin.DynamicAI.SettingChanged -= DynamicAI_SettingChanged;
}
else if (MatchmakerAcceptPatches.IsClient)
{
Expand Down
5 changes: 5 additions & 0 deletions Fika.Core/FikaPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,11 @@ protected void Awake()
StartCoroutine(RunModHandler());
}

private void Config_SettingChanged(object sender, SettingChangedEventArgs e)
{
throw new NotImplementedException();
}

/// <summary>
/// Coroutine to ensure all mods are loaded by waiting 5 seconds
/// </summary>
Expand Down
6 changes: 6 additions & 0 deletions Fika.Core/Utils/FikaModHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class FikaModHandler
private readonly ManualLogSource logger = Logger.CreateLogSource("FikaModHandler");

public bool QuestingBotsLoaded = false;
public bool SAINLoaded = false;

public void Run()
{
Expand All @@ -34,6 +35,11 @@ private void CheckSpecialMods(string key)
{
QuestingBotsLoaded = true;
}

if (key == "me.sol.sain")
{
SAINLoaded = true;
}
}
}
}

0 comments on commit 69d2b70

Please sign in to comment.