Improve BotModule performance.

Several parts of bot module logic, often through the AIUtils helper class, will query or count over all actors in the world. This is not a fast operation and the AI tends to repeat it often.

Introduce some ActorIndex classes that can maintain an index of actors in the world that match a query based on a mix of actor name, owner or trait. These indexes introduce some overhead to maintain, but allow the queries or counts that bot modules needs to perform to be greatly sped up, as the index means there is a much smaller starting set of actors to consider. This is beneficial to the bot logic as the TraitDictionary index maintained by the world works only in terms of traits and doesn't allow the bot logic to perform a sufficiently selective lookup. This is because the bot logic is usually defined in terms of actor names rather than traits.
This commit is contained in:
RoosterDragon
2024-02-24 18:44:13 +00:00
committed by Gustas
parent d4457a4028
commit dc0f26a1cd
9 changed files with 273 additions and 70 deletions

View File

@@ -41,31 +41,14 @@ namespace OpenRA.Mods.Common
.Select(a => a.Trait);
}
public static IEnumerable<Actor> GetActorsWithTrait<T>(World world)
public static int CountActorsWithNameAndTrait<T>(string actorName, Player owner)
{
return world.ActorsHavingTrait<T>();
return owner.World.ActorsHavingTrait<T>().Count(a => a.Owner == owner && a.Info.Name == actorName);
}
public static int CountActorsWithTrait<T>(string actorName, Player owner)
public static int CountActorByCommonName<T>(ActorIndex.OwnerAndNamesAndTrait<T> actorIndex)
{
return GetActorsWithTrait<T>(owner.World).Count(a => a.Owner == owner && a.Info.Name == actorName);
}
public static int CountActorByCommonName(HashSet<string> commonNames, Player owner)
{
return owner.World.Actors.Count(a => !a.IsDead && a.Owner == owner &&
commonNames.Contains(a.Info.Name));
}
public static int CountBuildingByCommonName(HashSet<string> buildings, Player owner)
{
return GetActorsWithTrait<Building>(owner.World)
.Count(a => a.Owner == owner && buildings.Contains(a.Info.Name));
}
public static ActorInfo GetInfoByCommonName(HashSet<string> names, Player owner)
{
return owner.World.Map.Rules.Actors.Where(k => names.Contains(k.Key)).Random(owner.World.LocalRandom).Value;
return actorIndex.Actors.Count(a => !a.IsDead);
}
public static void BotDebug(string format, params object[] args)