Add: [AI] Get the number of vehicles in a given group #9462
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation / Problem
Using
AIVehicleList_Group(group_id).Count()
tends to become more cpu intensive over time as the number of vehicles in the game increases, because it has to iterate over all vehicles to check which belong to the group. When an AI uses it constantly, slowdowns become noticeable.If the intention is only to know how many vehicles are in a group, I thought of a less cpu intensive method, which is using the
GroupStatistics
ownnum_vehicle
. For that, this PR comes up with a new functionAIGroup.GetNumVehicles(group_id, vehicle_type)
.Description
With this function, instead of iterating over all vehicles just to get a count, it iterates over all groups. In normal circumstances, there's less groups than vehicles, so it is expected to be less intensive even when used repeatedly.
My own testings with my AI, with about 10k vehicles and 1600 groups, the ms peaks are much less noticeable.
35.95 ms
while(true) { AIGroup.GetNumVehicles(m_sentToDepotRoadGroup[1], AIVehicle.VT_ROAD); }
3,179.86 ms
while(true) { AIVehicleList_Group(m_sentToDepotRoadGroup[1]).Count(); }
Limitations
AIGroup.GetNumVehicles(group_id, vehicle_type)
gets the number of total vehicles in the group and its sub-groups.AIVehicleList_Group(group_id).Count()
gets the number of total vehicles in that group only and creates a list with vehicle_ids of that group.For my use case, since I don't use sub-groups and for the portion of the code I'm using it I have no need to know which vehicles they are, it's not an issue.
Checklist for review
Some things are not automated, and forgotten often. This list is a reminder for the reviewers.