AI Development Guide and M27AI v8 Devlog

9

Following the recent Supreme Computer Cup I was inspired to have a go at developing a basic AI for FAF. As I had zero experience of coding in Lua, I thought at the same time I would write down things as I learnt them to have both a guide for other people interested in getting started in developing an AI, and a dev log for the creation of my AI.

See below for a link to the current AI development guide and devlog:
https://docs.google.com/document/d/1uQlEoN-kti7G2MnhwD60uaaHwVevPNYH/edit?usp=sharing&ouid=100973959280546778272&rtpof=true&sd=true

The current AI has been uploaded as a mod, and the files can also be accessed from the below:
https://drive.google.com/drive/folders/1jnLd67CVIpBB-ulXPlJP_GSS5QPZjK0R?usp=sharing

I've copied the current overview from the guide below:

This document is intended to do 3 things at once (meaning it does none of them very well!):
• Act as a guide to people new to FAF AI development, including collating any other useful resources out there on AI development
• Be a sort of dev log of my thought process and development steps for creating my first FAF AI, with extracts of code thrown in
• Form my main ‘todo’ list for further developments of my AI
If you see any errors, or have any comments or suggestions (in particular any AI developers who read this since you’ll probably know better/easier ways of doing things than the methods I’ve chosen) let me know and I can update the guide where relevant.

If you’re here for useful resources and/or details of how to write AI and don’t care about the dev log aspect then just skip to section 2) Setup and background and section 4) Index of useful functions, and/or browse the index for points that may be of interest.

In terms of the dev log section, if you start seeing lots of yellow highlighting/square brackets you’ve reached the end of the dev log part and the start of my todo list of things I’m planning on working on next.

Latest changes (v7) summary:
T2 is now here! My changes were focused on creating my own engineer and platoon formation functionality, but at the end I threw in some basic upgrade logic so my AI now gets T2.

  • Various bug fixes. More notable ones are that the AI should work better on adaptive maps that 'hide' some of their mexes, and should be less likely to try and build on unpathable mexes
  • Custom platoon formation and engineer functionality. A couple of more notable features of this are that engineers now work together to build 1 building (e.g. power) rather than independently try and build 5 at once, and factor in what mexes theyre already planning to build on when choosing where to expand
  • Building upgrade logic - AI will now upgrade mexes and land factories (meaning for the first time T2 units can hit the battlefield!)
  • Load spreading of functionality to help counter the CPU performance hit of these changes

I've also updated the guide for a couple of points (e.g. including a section on events)

Key areas of focus by version (history):
v1-3: Release
v4 - Intel and threat detection
v5 - Use of ACU
v6 - Hotfix for patch
v7 - Engineers and building upgrades
v8 - Hotfix (fixed crash)

4
  1. Overview 15
    1.1) AI goals 15
    1.2) Background 16
    1.3) Approach 16
  2. Setup and background 17
    2.1) Lua editors 17
    2.1.1) Intellij IDEA 17
    2.2) Other guides which include a section on AI: 18
    2.2.1) General information: 18
    2.2.2) How AI in FAF works 18
    2.2.3) AI markers and how AI uses them: 19
    2.2.4) Hooking (e.g. replacing/appending existing game code) 19
    2.2.5) Creating custom scripts for Sorian AI: 19
    2.2.6) Pathfinding 19
    2.2.7) How platoons work 19
    2.3) Lua coding 20
    2.3.1) How to code in Lua 20
    2.3.2) Stand alone Lua code testing 20
    2.3.3) Lua optimisation 20
    2.3.4) Common causes of errors for non-Lua coders 20
    2.4) Debugging in FAF 21
    2.4.1) Console 21
    2.4.2) Cheats 21
    2.4.3) Log window and error messages 21
    2.4.4) Debug window and shortcuts 21
    2.4.5) Platoon names for debugging 22
    2.4.6) Fast speed 22
    2.4.7) Other shortcuts and game startup options 22
    2.4.8) Error handling 23
    2.4.9) Optimisation – benchmarks and monitoring 24
    2.4.10) Debugging via replay 26
    2.5) AI development discord 26
    2.6) Core FAF Lua files 26
    2.6.1) Accessing core Lua code 26
    2.6.2) Other built in functions 27
    2.6.3) Unit blueprints 27
    2.7) Testing AI against other AI 27
    2.7.1) Simple offline testing 27
    2.7.2) Mass offline AI testing 27
    2.8) Getting started – using a simple AI template as a starting point 28
    2.9) Downloading and setting up MicroAI 28
    2.10) Giving the AI mod your own name 28
    2.11) General - Hooks, and getting the code to recognise if it’s running your AI 29
    2.12) Github 29
    2.12.1) Linking Github with a local repo via creating your own init file 30
    2.12.2) Pro Git ebook 30
    2.12.3) Git commit messages 30
    2.13) Uploading your AI to FAF 30
    2.13.1) Pre-upload checklist 30
    2.13.2) FAF rules on uploading mods 30
    2.13.3) Uploading to FAF 30
    2.14) Other AI documentation 31
  3. AI changes 31
    3.1) Build order - Changing the initial build order 31
    3.1.1) Adding/removing buildings 31
    3.1.2) Change build order based on map resource positions 31
    3.1.3) Build order conditions 32
    3.2) Build order – ACU builds without moving at start 32
    3.2.1) BaseTemplate 32
    3.3) Build factory and power to benefit from adjacency 34
    3.3.1) Record all mexes on the map, and reference this information 34
    3.3.2) Determine com start position 35
    3.3.3) Identify mexes near to start 35
    3.3.4) Hook onto the core code relating to building a structure at a location 36
    3.3.5) Call build order from custom aiBrain function, to edit how things are built 36
    3.3.6) Adjust build template based on mex location - conditions 37
    3.3.7) Adjust build template based on mex location – build location adjustment 38
    3.3.8) Build initial PGens by existing factory 38
    3.3.9) Adjacency bonus where ACU is away from start location 40
    3.3.10) Referencing unit blueprints for information such as unit size 42
    3.4) Platoons and sending engineers to reclaim 44
    3.4.1) How platoons work 44
    3.4.2) Send the first engineer on reclaim duty 49
    3.4.3) Determine where to send the engineer to reclaim 51
    3.4.4) Identifying reclaim mass value 51
    3.4.5) Find out if a location is accessible by ground: 51
    3.4.6) Mapping reclaim locations and assigning preferred location to an engineer 53
    3.4.7) Don’t send early reclaiming engi if there’s minimal starting reclaim 54
    3.4.8) Issue new reclaim command if engineer becomes idle 54
    3.4.9) Send more engineers to reclaim later (as lower priority) based on the reclaim currently on the map 54
    3.4.10) Send 5 engineers at the start to reclaim and build mexes 55
    3.4.11) Reclaiming trees when no main mass left 56
    3.5) Building and assisting hydro 56
    3.5.1) Check if hydro near start area and have engineer build hydro 56
    3.5.2) Have ACU assist engineer with hydro 57
    3.5.3) Get ACU to continue build order after hydro complete 58
    3.5.4) Subsequent build order changes 59
    3.6) Attack force composition changes and check of AI performance 59
    3.6.1) Build Moar Tanks 59
    3.7) Pre-v1: AI Progress check 60
    3.7.1) Land factory buildings and other build order refinements 60
    3.8) Raiding AI 62
    3.8.1) Raiding behaviour - overview 62
    3.8.2) Queue up move commands for mexes 62
    3.8.3) Identify mexes to target 63
    3.8.4) Locating mexes near to an existing pathing route 66
    3.8.5) Determine when raiders need new targets 66
    3.8.6) Handling complications (stuck units, move orders built on, platoon units dying) 66
    3.8.7) Change factory rally point so units are assigned orders sooner 68
    3.8.8) Making use of platoon names for debugging 70
    3.8.9) Ensure 1 land scout included in each platoon 71
    3.8.10) Use microbots before switching to tanks 72
    3.8.11) Have scouts stay with the platoon 74
    3.8.12) AI scouting, threat detection, and identifying nearby enemy units 74
    3.8.13) Attack engineers en-route: Overview 77
    3.8.14) Tracking when have reached movement points 77
    3.8.15) Determining the platoon minimum range 78
    3.8.16) Identifying nearby enemy units and assessing their threat 79
    3.8.17) Actions based on enemy threat 81
    3.8.18) Avoid attacking enemy mexes for small platoons 82
    3.8.19) Other issues – cheating, walls and min range 83
    3.8.20) Larger raiding platoons 84
    3.9) Large attack wave 85
    3.9.1) Checking when to form a large attack wave 85
    3.9.2) Generalising raider AI 85
    3.9.3) Creating separate platoon AI for the large attack force 86
    3.9.4) Run nearer to base when outnumbered 86
    3.9.5) Recalling nearby raiders to join attack force 87
    3.9.6) Updating threat assessment for ACU health and upgrades 88
    3.9.7) Don’t chase small numbers of faster units 90
    3.9.8) Switch to hunt and kill enemies once reached destination 91
    3.10) Pre-v1: AI Progress check 91
    3.10.1) Summer duel 92
    3.10.2) Theta passage 92
    3.10.3) New issues 92
    3.11) Platoon AI – Generalised approach and further enhancements 93
    3.11.1) Embracing the table 93
    3.11.2) Moving units when shots blocked by cliffs 96
    3.11.3) Anti-stuttering protection 96
    3.11.4) Large attack AI – Rally point for merged units 96
    3.11.5) Raiders assume small numbers of enemies are engis/scouts 97
    3.11.6) T1 Artillery specifically target structures, and spread-attack units 97
    3.11.7) Keep scouts at back of platoon 98
    3.11.8) Platoons with non-Seraphim T1 artillery and no tanks don’t run unless against slower enemy 99
    3.11.9) Factor in nearby platoons when faced with enemies 99
    3.11.10) More T1 arti in platoons once reached certain level of tanks 100
    3.11.11) Don’t treat AA as a direct fire unit when forming a platoon 100
    3.11.12) Build hydro where it’s far away from base 100
    3.12) Expansion bases 101
    3.12.1) Background – expansions and the main base 101
    3.12.2) Having all units treated as available for platoons 101
    3.13) Upgrade ACU with gun and attack 102
    3.13.1) How to upgrade an ACU 102
    3.13.2) Get enough energy to support guncom 102
    3.13.3) Upgrade ACU’s gun once have enough energy 103
    3.13.4) Attack with ACU once upgrade finished 104
    3.13.5) ACU overcharge 104
    3.14) V1-3 release incl AI progress check 105
    3.14.1) Performance – v1-3 of M27AI 105
    3.14.2) Issues and planned improvements from testing 105
    3.14.3) Debug issues and other bug fixes 106
    3.14.4) Attack lauched as soon as ACU gun ready 111
    3.14.5) Default attack-move direct fire units at enemy (attack-move if platoon scattered) 111
    3.14.6) Limit of 1 microbot per early raider platoon, and tank defenders 112
    3.14.7) Skip move location if are closer to the next move location than the first one 112
    3.14.8) Build more engineers if are close to overflowing mass 113
    3.14.9) Add energy storage requirements to ACU initial land factory build order 114
    3.14.10) ACU and Engineers will move near mex to build 114
    3.14.11) Other minor misc changes 116
    3.15) On demand basic pathfinding 116
    3.15.1) Revised approach 116
    3.15.2) Mex raiding path optimisations 118
    3.15.3) Useful maps for testing map based logic 118
    3.15.4) Move to build structure – check pathing 119
    3.15.5) Platoon Merge location – have it check no pathing issues in nearby segments 119
    3.16) AI Overseer - responding to enemy attacks 119
    3.16.1) Overview 119
    3.16.2) Planned initial logic 119
    3.16.3) Run overseer on AI creation 120
    3.16.4) Assigning units to defender platoons 121
    3.16.5) Recording enemy threats 122
    3.16.6) Sending units to deal with enemy threats 124
    3.16.7) Sorting a multi-dimensional table 124
    3.16.8) Disbanded units return to base 126
    3.16.9) Intercepting platoons should leave at least 1 scout when removing spare units 126
    3.16.10) Don’t remove units when in combat 127
    3.16.11) Platoon and other build conditions 127
    3.16.12) Limit number of mobile AA in an intercepting defending platoon 128
    3.16.13) Remove ACU from defender platoon once the threat is dealt with 128
    3.16.14) Don’t have ACU join a platoon if its upgrading 128
    3.16.15) Disabling sorian base manager distress logic 129
    3.17) AI Overseer – Intel and ACU managers 129
    3.17.1) Intel manager - overview 129
    3.17.2) Planned logic – 1-off 129
    3.17.3) Planned logic – recurring 130
    3.17.4) Scout localised platoon AI 131
    3.17.5) ACU manager 132
    3.18) V4 release (incl AI progress check) 133
    3.18.1) Pre-release checklist 134
    3.18.2) AI performance results 134
    3.18.3) Notable issues noted from performance 135
    3.18.4) Resolution of immediate issues/bugs post-release 136
    3.19) ACU –aggression, support and micro enhancements 141
    3.19.1) ACU custom platoon - overview 141
    3.19.2) ACU expansion – choice of location 142
    3.19.3) Platoon completion actions 144
    3.19.4) Expanding more than once 145
    3.19.5) Getting nearby reclaim and/or unclaimed mexes while moving 146
    3.19.6) Assisting hydro construction (reworked) 148
    3.19.7) ACU defender platoon refinements 149
    3.19.8) ACU Scout helper and general scout build order 149
    3.19.9) ACU MAA helper and general behaviour 152
    3.19.10) Air threat assessment and MAA to build (initial) 152
    3.19.11) Large platoon scout and MAA helpers 153
    3.19.12) ACU attacks independently to large attack platoon 153
    3.19.13) ACU Build order tweaks 153
    3.19.14) Aeon ACU gets both gun upgrades 154
    3.19.15) ACU retreat 154
    3.19.16) ACU kiting 154
    3.19.17) Have ACU attack-move if kiting doesn’t return any action 155
    3.19.18) Manual overcharge 155
    3.19.19) Other misc changes/refinements 159
    3.20) V5 release (incl AI progress check) 159
    3.20.1) Pre-release checklist 159
    3.20.2) AI performance results 159
    3.20.3) Resolution of immediate issues/bugs 160
    3.21) Refinements, basic water based actions, v6 hotfix 161
    3.21.1) Misc refinements pre v6 161
    3.21.2) ACU water based actions – reclaim and move to shore 161
    3.21.3) V6 hotfix 162
    3.21.4) Error fixes subsequent to v6 163
    3.22) Custom build orders and platoon formers 166
    3.22.1) Proof of concept 166
    3.22.2) Initial complications – LABs and no valid units 167
    3.22.3) Related changes – scout conditions; tracking construction orders 168
    3.22.4) Linking production with threat detection overseer 168
    3.22.5) Increasing indirect fire units based on enemy PD usage 168
    3.22.6) Assign MAA similarly to how scouts are assigned 169
    3.22.7) Platoon former – manually assigning platoons based on threat distance 169
    3.22.8) Try to save raider scouts 170
    3.22.9) Not got enough units for a platoon – send spare units to intel path 170
    3.22.10) Call the platoon former if disband a platoon containing combat units 170
    3.22.11) Platoon merger – Periodically combining attack platoons where they’re nearby 170
    3.22.12) Delayed platoon formation 170
    3.22.13) Factories away from main base or with nearby enemies don’t build engineers 172
    3.23) Engineer overseer 172
    3.23.1) Overview 172
    3.23.2) Spare engineer action logic 172
    3.23.3) Nearby enemy logic 172
    3.23.4) Unclaimed mex logic 173
    3.23.5) Threat detector – adjust distance calculation and record 173
    3.23.6) Update engineer names to reflect their action 173
    3.23.7) Clear unit actions if factory idle (unexpected bug workaround) 173
    3.23.8) Have ACU assist assigned hydro builder and build land factory 174
    3.23.9) Retain existing engineer assignments in favour of nearest engineer 175
    3.23.10) Power assignment – longer term requirement check 175
    3.23.11) Optimisations and rollbacks 176
    3.23.12) Adjacency refinements 176
    3.23.13) Misc changes 177
    3.23.14) If an engineer changes its action and its being guarded, clear the current action and commands of the guards so they can be reassigned 177
    3.23.15) Consider engineer actions as soon as a factory finishes construction 178
    3.23.16) Constructing building – first check if part-complete similar building 178
    3.23.17) Building more engineers 178
    3.23.18) Engineers take into account ACU expansion path 178
    3.23.19) Initial engineers keep building mexes until they die or half the map is covered 179
    3.23.20) Have engineers queue up nearby unclaimed mexes and multiple T1 power 179
    3.23.21) Build a second power at the same time 179
    3.23.22) Build more energy storage based on power income 180
    3.24) Building Upgrade overseer 180
    3.24.1) Overview 180
    3.24.2) Refinements 181
    3.24.3) Have engineer overseer switch to assisting an upgrade instead of building a land factory 181
    3.24.4) Pause upgrade if low on resources (and track so can resume later) 181
    3.24.5) Mass stall – pause factories over mexes 182
    3.25) Idle platoon 182
    3.25.1) Army pool platoon and new idle platoon 182
    3.25.2) Approach 182
    3.26) Misc changes 183
    3.26.1) ACU is removed from defender platoons when allocating new threats 183
    3.26.2) Allocating overseers to different ticks 183
    3.26.3) Have defender platoons move in formation 183
    3.26.4) State of game log 183
    3.26.5) Intel path – allow scouts to move +/- 1 path 184
    3.26.6) ACU shots blocked 184
    3.26.7) Enemy ACU threat increase 184
    3.27) V7 release (incl AI progress check) 184
    3.27.1) Minor enhancements to overseers due to testing (pre-release) 184
    3.27.2) Tracking revision 185
    3.27.3) Choosing nearby engineers based on mex location 186
    3.27.4) Pre-release check results 186
  4. Future likely planned changes 186
    4.1) Misc changes (not yet organised) 186
    4.1.1) Idle units run from enemies 186
    4.1.2) ACU Upgrader 187
    4.1.3) Only build MMLs if T2 PD detected 187
    4.1.4) Pause gun upgrade when power stalling 187
    4.1.5) Review overseer threat assignment 187
    4.1.6) Extra energy storage 187
    4.1.7) Second Power queue 187
    4.1.8) Pre-empt future FAF patch error 188
    4.1.9) ACU Mobile assisters still try going into water when ACU makes it back to land 188
    4.1.10) Mex raider target error 188
    4.1.11) ACU factors in part-complete buildings 188
    4.1.12) MAA build order 188
    4.1.13) ACU upgrade logic and support requests 188
    4.1.14) Spare unit overseer 188
    4.1.15) ACU should ignore enemy ACU if its underwater 188
    4.1.16) Overcharge further refinements – enemy ACU position and low health PD 188
    4.1.17) Engineer reclaim target selection 189
    4.1.18) Adjust number of mex raiders based on mexes on map outside enemy bases 189
    4.1.19) Have the first intel path really close to our base 189
    4.1.20) Have large attack platoons attack out of formation if ACU in combat against high threat 189
    4.1.21) Adjacency priority 189
    4.1.22) Setons Clutch – Fix the ACU going on a scenic tour of the seabed 189
    4.1.23) Artillery only attack platoon? 190
    4.1.24) Other changes 190
    4.2) Air scouting 190
    4.3) Air overseer 190
    4.4) Anti-turtle overseer and ecoing 190
    4.5) Replace remaining build order and platoon former logic 190
    4.5.1) Air factory build order via overseer 190
    4.5.2) ACU gun upgrades via overseer 190
    4.5.3) ACU initial build order via overseer 190
    4.5.4) See if can remove core game functionality 191
    4.6) CPU performance optimisation/benchmarking 191
    4.6.1) Platoon rewrite? 191
    4.7) AI Overseer – Other changes 191
    4.7.1) Fix AI assisters when ACU goes into water 191
    4.7.2) Initial raiders head straight to enemy mex 191
    4.7.3) Stop initial raiders standing by power plants theyre attacking 191
    4.7.4) Air threat overseer sends MAA to intercept (if not too far away) 191
    4.7.5) Update intercept location for defenders 191
    4.7.6) Limit the range of the defender logic? 192
    4.7.7) Determine when an enemy threat is killed/disband defenders earlier 192
    4.7.8) T2 range adjustments 192
    4.7.9) Split up a large platoon to chase small units 192
    4.7.10) Attack with all land units once ACU near enemy main base 193
    4.7.11) Point defence included in ACU threat? 193
    4.7.12) Platoon composition manager and/or PD hunters 193
    4.7.13) Air threat MAA intercept 193
    4.7.14) Choice of reclaim target – factor in engineers assigned to nearby location 194
    4.7.15) Queue up multiple mexes and power 194
    4.7.16) Performance optimisations 195
    4.7.17) Interupted buildings are compelted by assisting engineers 195
    4.7.18) Intel pathing – use land based pathing 196
    4.7.19) Intel pathing – have scouts advance independently if no threats 196
    4.7.20) Initial movement path for defenders based on intel 196
    4.7.21) Platoon completion – next action based on intel coverage 196
    4.7.22) Backup logic for unforeseen errors – idle ACU 196
    4.7.23) Backup logic for unforeseen errors – idle units 197
    4.7.24) ACU treated as building on initial mexes 197
    4.7.25) Upgrade overseer - Refine the logic for upgrading to allow for T3 and mass storage 197
    4.7.26) Upgrade overseer – don’t upgrade if in range of T2 artillery 197
    4.7.27) Other (TBC) 197
    4.8) More micro improvements and other enhancements 197
    4.8.1) Assist building being constructed instead of building new one 197
    4.8.2) Engineer assist AI will assist factories 198
    4.8.3) ACU and small platoons move if under attack from artillery 198
    4.8.4) ACU/General platoon target prioritisation 198
    4.8.5) Initial raider build order tweaks 199
    4.8.6) Factory builder – instance count bug 199
    4.8.7) Indirect fire units near the ACU when its upgrading? 199
    4.8.8) Attack platoons merge with larger attack platoons they come near 199
    4.8.9) Support platoon units run away from enemies nearest them 199
    4.8.10) T1 Arti composition based on PD 200
    4.8.11) Platoon merge path when attacking? 200
    4.8.12) Aeon T1 tanks kiting 200
    4.8.13) Indirect fire structure targeting 200
    4.8.14) ACU new land factory/adjacency bonus – target nearest mexes first? 200
    4.8.15) Target low health units (small platoon sizes) 200
    4.8.16) Anti-capture protection 200
    4.8.17) Advanced reclaim prioritisation 200
    4.8.18) Air factory adjacency 201
    4.8.19) Engineer management – combine to construct a single building instead of 2 separate ones 201
    4.8.20) Engineers attack-move to nearby enemies 201
    4.8.21) Improved blip threat detection 201
    4.8.22) Protecting engineers 201
    4.8.23) Saving scouts when a platoon is dying 201
    4.8.24) Replace existing construction orders if closer 201
    4.8.25) Factory adjacency location - Build land factories nearer our base if not near base 202
    4.8.26) Integrate IsShotBlocked into wider unit stuck and targeting logic 202
    4.8.27) Advanced Kiting – Com vs Com 202
    4.8.28) Overcharge further refinements 202
    4.9) Resource stall and overflow 202
    4.9.1) Mass stall – pause non-mex production 202
    4.9.2) Energy stall – pause non-PGen production 202
    4.9.3) Mass overflow – upgrade a mex 202
    4.10) T2 upgrades and anti-turtle tactics 202
    4.11) Enhanced pathfinding information – how long to path 203
    4.12) AI scouting, threat detection, and safe paths 203
    4.12.1) General discussion on scouting and threat detection 203
    4.12.2) Naval pathfinding 206
    4.12.3) Determining a safe path for raiders 206
    4.12.4) Engineer mex selection – calculating safe paths 207
    4.12.5) Basic air scouting 207
    4.13) Other enhancements 207
    4.13.1) Fix guide hyperlinks 207
    4.13.2) What to do if early hydro is destroyed 207
    4.13.3) Transports 207
    4.14) Optimisations 208
    4.14.1) Base game removal - Consumption values 208
    4.14.2) Determining nearest enemy start position every 10s instead of on the fly 209
    4.15) Lower priority enhancements to earlier code 209
    4.15.1) Enhancements flagged earlier 209
    4.15.2) Per-unit micro to win early exchanges 209
    4.15.3) ACU building land factory – link to engineer overseer 209
    4.15.4) If control >50% of mexes then consider upgrading to T2 mexes and land 209
    4.15.5) Overseer and full share 209
    4.15.6) Free for all and multiple opponents 209
    4.15.7) Enemy ACU upgrade 209
    4.15.8) Extra energy storage and power build decision – Factor in enemy tech level 209
    4.15.9) Improve intel pathing choice based on enemy threats 210
  5. Index of useful functions 210
    5.1) Map, game setup and general aiBrain information 211
    5.1.1) aiBrain - general 211
    5.1.2) AI Brain – Economy 212
    5.1.3) Map Markers and start positions 213
    5.1.4) Map size 213
    5.1.5) Terrain info 214
    5.2) Getting a list of units by category, location, or other method 214
    5.2.1) All units that meet a particular category 214
    5.2.2) Units at/near a location 215
    5.3) Unit information 216
    5.3.1) Units on radar 216
    5.3.2) Blueprints 216
    5.3.3) Unit upgrades 217
    5.3.4) Whether a blueprint matches category conditions 217
    5.3.5) Location and pathfinding 217
    5.3.6) Unit’s ai Brain owner 218
    5.3.7) Unit’s current commands and whether it’s alive 218
    5.3.8) Unit bones 218
    5.4) Unit and platoon commands 218
    5.4.1) Building 218
    5.4.2) Assisting 219
    5.4.3) Pausing 219
    5.4.4) Reclaim 219
    Note: The core AI functionality appears to run ProcessBuildCommand on a unit given an issuereclaim order (even if that unit is in a custom platoon) and will then disband that platoon (meaning less than 1 second after the reclaim order is given, the unit stops reclaim and is disbanded). 219
    One solution is to add extra code to ProcessBuildCommand to not disband the platoon is the unit is reclaiming. 219
    5.4.5) Factory specific commands 219
    5.4.6) Movement and attack-move 220
    5.4.7) Transport 220
    5.4.8) Combat related 220
    5.4.9) Stopping 221
    5.4.10) Upgrades 221
    5.4.11) Current commands and targets 221
    5.4.12) Unit status 221
    5.4.13) Change a unit’s name 223
    5.5) Platoon additional functions 223
    5.5.1) Units platoon handle 223
    5.5.2) Get AIBrain 223
    5.5.3) Get units in a platoon 223
    5.5.4) Disband 223
    5.5.5) Platoon exists 223
    5.5.6) Platoon position 224
    5.5.7) Get all platoons 224
    5.5.8) Platoon ai plan name 224
    5.5.9) Add units to a platoon 224
    5.5.10) Army pool and removing units from a platoon 224
    5.5.11) Create a platoon 225
    5.5.12) Change or reset an AI plan 225
    5.5.13) Platoon movement formation 225
    5.6) Time and thread related 225
    5.6.1) Game time 225
    5.6.2) Wait/delay the code 225
    5.6.3) Fork thread (run independently) 225
    5.7) Events 226
    5.8) Other 228
    5.8.1) Visual changes – Draw Circles and Lines 228
    5.8.2) On Intel Change 228
0

Not exactly an AI comment, but you wanna have things right, right? 🙂

"Lua" (pronounced LOO-ah) means "Moon" in Portuguese. As such, it is neither an acronym nor an abbreviation, but a noun. More specifically, "Lua" is a name, the name of the Earth's moon and the name of the language. Like most names, it should be written in lower case with an initial capital, that is, "Lua". Please do not write it as "LUA", which is both ugly and confusing, because then it becomes an acronym with different meanings for different people. So, please, write "Lua" right!

1

Thanks, I'll reflect the correct case usage of Lua in the next version of the guide (I'll probably update it whenever I release an AI update so the two are in sync)

1

So I decided I might actually post something more relevant 🙂

Full stops vs colons – continuing the above example, oUnit.GetUnitId() will return an error, but oUnit:GetUnitId() won’t.

It's maybe worth mentioning why that happens. oUnit:GetUnitId() is syntactic sugar for oUnit.GetUnitId(self). So if you wanna you the version with . you have to pass self as first arg.

F9 opens up the debug window (you may want to change the game resolution to windowed to more easily access this).

That's a log window, not debug. You can open the debugger with Ctrl+F9 or /debug and that's way better for debugging then trying to print things into the log. Since it works as any debugger you are used to, pauses the execution on the line you seleceted and lets you see whats inside global and local variables.

The below link also appears to give a list of core/global functions that can be used (I’ve not tested these to see if they all work, or even if they’re for FAF rather than SupCom2):
https://supcom.fandom.com/wiki/LUADOC_1.5.3599

It is for FA, some of these functions are documented here https://github.com/FAForever/fa/tree/deploy/fafdevelop/engine

I’m not using Github since I’m working on this on my own, and since I doubt I can get the same ease of use I currently have with changing something offline and instantly seeing the results in-game after a Ctrl+F10 restart. However, Github is used by a number of the AI developers so there’s likely some significant benefits to it.

Git is very useful even if you're working alone, as you have history of changes and you can easily switch to previous versions if something breaks. The game can use files from any location, so for my development, it uses files from my local git repo. It's just a matter of setting your own init file https://github.com/FAForever/fa#running-the-game-with-your-changes

To keep things simple (as I couldn’t get more complex builderconditions{} with multiple variables to work, despite seeing it being used in other AIs people have done)

So build conditions are defined in a table

BuildConditions = {
    {BMBC, 'BaseEngineersEnabled', {self.BaseName}},
    {BMBC, 'BaseBuildingEngineers', {self.BaseName}},
    {BMBC, 'HighestFactoryLevel', {i, self.BaseName}},
    {BMBC, 'FactoryCountAndNeed', {i, j, pType, self.BaseName}},
    {BMBC, 'BaseActive', {self.BaseName}},
},

so here, you have 5 build conditions, each in it's own table.

local BMBC = '/lua/editor/BaseManagerBuildConditions.lua'

first value ( BMBC) in the table is thr path the file you wanna use
second one ('BaseEngineersEnabled') is name of the function in that file to use
third ({self.BaseName}) is table of arguments to pass into that function
AI brain is always passed as first argument, and then all other that you specify in the table

So you could rewrite your example to this:

-- Inside the builder
BuilderConditions = {
    {MIBC, 'Is1NearbyMex', {11}}
},


-- Inside MiscBuildConditions.lua
function Is1NearbyMex(aiBrain, distance)
    local iNearbyMex = MapInfo.RecordMexNearStartPosition(Utilities.GetAIBrainArmyNumber(aiBrain), distance, true)
    if iNearbyMex == 1 then
        return true
    end
    return false
end

This way you can already specify the distance for chehcking the nearby mexes.

Determine com start position

This function should do the trick 🙂
brain:GetArmyStartPos()

To help with this, I first wanted to understand what the various variables feeding into it were, so made use of the log function for each variable in turn; where it returned an error due to being a table value that I was trying to put into the log

Best would be to use the debugger to see whats what, as you can open the tables.
But if you really wanna dump the table into the log you have to use LOG(repr(table))

0

@speed2
Thanks, in particular for the debug window - I expect using that would've drastically cut my debugging time! I'll update for your comments in the latest version.

Unfortunately I can't get the debug window to work for me (I just get an error message) and some other people have had the same problem. Asking in the AI discord Jip thought that you need to do an install from the cd version of the game not steam but that you may know the exact procedure?

Error message below in case it helps:
DebugWindow.png

0

unpack this https://mega.nz/file/VlRCXajY#UMsAx9IR1dIOqX72bPpOYytR6FS3zO1DGVPT2AhSPAY
into \THQ\Gas Powered Games\Supreme Commander - Forged Alliance\coderes\Engine

0

@speed2
Don't think I've got that folder with the steam install, I've got the following:
C:\Program Files (x86)\Steam\steamapps\common\Supreme Commander Forged Alliance
(this doesn't have a coderecs folder, and adding one in doesnt resolve the issue)

I've also got the FAF location:
C:\ProgramData\FAForever
same issue as with the steamapps folder

(just in case I also tried the \Documents\My Games\Gas Powered Games\Supreme Commander Forged Alliance folder but no luck).

Is there anywhere else I may have missed for a steam version?

Although I'd hoped I'd got the CDs for both as well, checking I've only got the CD for the original supcom so cant try a fresh install via disc.

0

It belong to the game instalation folders, and fast few ppl having this issue resolved it by creating those folders

0

@maudlin27

I am not finished reading your guide, but excellent work so far!

2

v4 changes (in reality v2, but when I uploaded the mod on its first release I had to rush out a couple of hotfixes where I'd forgotten to remove debug logic and accidently introduced a bug that affected all games!)

  • Fixed various bugs (see 3.14.3)
  • Slightly improved pathfinding performance (see 3.15)
  • New AI logic which will detect enemy threats and send units to deal with them (see 3.16)
  • New AI logic which attempts to maintain intel over the map to stop surprise attacks (see 3.17)

I've also updated the guide to reflect speed2's comments (as well as a couple of other minor points/sections, such as a bit on uploading a mod and some tests that I now run before uploading)

2

I am stunned.

Really good work, maudlin27!

2

v5 changes - these were mostly about the ACU, making it more aggressive and less suicidal

  • Fixed various bugs and improved some error handling (see 3.18.4)
    ACU improvements (see 3.19):
  • ACU will try to expand to high reclaim or mex locations, while building on mexes it comes across and reclaiming
  • ACU will have scout and MAA support
  • ACU tries to kite enemies it comes across
  • ACU uses manual overcharge to overcharge optimal targets

Also updated the guide slightly to add details of the AI development discord channel in FAF (separate to the main AI development discord), and a couple of common hard crash errors

1

v6 Hotfix - My AI broke with the recent FAF patch, so this is primarily to fix that. I was in the middle of more extensive changes so my AI is less stable than I'd like but I figured it's better than a broken one! I've also held off on updating the dev log for this release.

Main changes made:

  • ACU performs better underwater (reclaims units, tries to move to nearby land when it cant shoot)
  • Improvements to ACU overcharge behaviour (it should OC when retreating, and also positions better against enemy PD)
  • Switch to new error handling approach (orange messages now appear in the log with more detail; this also happens when any ACU dies)

Issues currently present I'm aware of (which shouldnt have a noticeably detrimental impact on performance, but will be noticeable to anyone looking at the log):

  • 'MergeLocations' error message on certain maps - should just mean larger platoons dont regroup at a midpoint before attacking
  • 'MexRaider' warning about the final waypoint - in most cases just affects which mexes are targetted (in rare cases might cause a delay in the platoon doing anything)
  • 'Stuttering'/delays in performance on certain maps (e.g. open palms)
3

V7 Update - T2 is now here! My changes were focused on creating my own engineer and platoon formation functionality (which took far far longer than I was expecting due to various difficult bugs - a lot of work for not much benefit), but at the end I threw in some basic upgrade logic so my AI now gets T2.

Various bug fixes. More notable ones are that the AI should work better on adaptive maps that 'hide' some of their mexes, and should be less likely to try and build on unpathable mexes
Custom platoon formation and engineer functionality. A couple of more notable features of this are that engineers now work together to build 1 building (e.g. power) rather than independently try and build 5 at once, and factor in what mexes theyre already planning to build on when choosing where to expand
Building upgrade logic - AI will now upgrade mexes and land factories (meaning for the first time T2 units can hit the battlefield!)
Load spreading of functionality to help counter the CPU performance hit of these changes
I've also updated the guide for a couple of points (e.g. including a section on events)

As before, much more detail on the changes/my thought process as I went about implementing them is in the dev log.

2

v8 Hotfix - Fixed a game crash that could happen if the AI lost an upgrading building (thanks to relent0r for for flagging there was a crash), along with a couple of other minor bug fixes.