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

Add: [AI] Get the number of vehicles in a given group #9462

merged 1 commit into from Aug 12, 2021


Copy link

@SamuXarick SamuXarick commented Aug 4, 2021

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 own num_vehicle. For that, this PR comes up with a new function AIGroup.GetNumVehicles(group_id, vehicle_type).


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(); }



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.

  • The bug fix is important enough to be backported? (label: 'backport requested')
  • This PR affects the save game format? (label 'savegame upgrade')
  • This PR affects the GS/AI API? (label 'needs review: Script API')
    • ai_changelog.hpp, gs_changelog.hpp need updating.
    • The compatibility wrappers (compat_*.nut) need updating.
  • This PR affects the NewGRF API? (label 'needs review: NewGRF')

@michicc michicc merged commit 120d216 into OpenTTD:master Aug 12, 2021
15 checks passed
@SamuXarick SamuXarick deleted the AIGroup-GetNumVehicles branch Aug 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

Successfully merging this pull request may close these issues.

None yet

2 participants