Hearts of Iron IV - Development Diary 54 - AI

  • We have updated our Community Code of Conduct. Please read through the new rules for the forum that are an integral part of Paradox Interactive’s User Agreement.
Showing developer posts only. Show all posts in this thread.

SteelVolt

Technomancer
2 Badges
Aug 4, 2014
735
4.201
  • Paradox Order
  • Hearts of Iron IV Sign-up
Greetings every one!

This weeks DD is about something I know many of you have been hoping and waiting for a long time; AI!

"The field of ridiculously high expectations and abysmally low standards." - Wiz

Being the only one crazy enough to want to take on the AI in HoI4 as Wiz went on to other projects, I was thrown in to it over a year ago now, and while it has been the hardest job I have ever had, it has also been the most fun and rewarding one.

So, lets jump in, shall we?

Right off the bat there were a couple of MASSIVE challenges in making the HoI4 AI;
1: Maintaining plausible historical behavior in a relatively dynamic and sandbox oriented game
2: Making the execution of player drawn battle plans solid enough that it would feel beneficial to use it.

Rest assured that significant amounts of sweat, blood and tears have been shed to tackle these issues.

For the first challenge, a couple of things sets the AI of Heart of Iron apart from the other PDS titles. First of all the chronologically compact and recent nature means people have different expectations on the HoI AI to act more or less according to history. While HoI4 is more of a sandbox experience than at the very least its latest predecessor, the set up is still historical and there were often reasons for countries to take certain actions at the times that they did. The challenge here was to have an AI capable of handling new situations dynamically in a way that makes at least some sense, regardless of if they are historical or not.

Our approach to this problem is a dynamic AI as a foundation, with game mechanics pushing countries in certain directions both for players and AI. The primary mechanic for this is, of course, the national foci, which have been covered in previous diaries. These direct the player and AI towards various goals both before and during the great war that eventually happens. But how does the AI pick focuses? This can either be strictly scripted on a per country basis and activated by playing the game in 'historical focus mode'. While it is fully moddable a historical setup for this is included. When that mode is NOT active, the AI picks foci using a combination of scripted weights and dynamic underlying systems that look at the situation of the country.

That dynamic system pushed by scripted weights is something that runs throughout all of the AI. Aside from well over 200 tweakable defines which tweak various aspects of the internal dynamic AI behavior, the weights can pretty much always be tweaked using the trigger system discussed in the modding DD. All in all there are practically no aspect of the AI which cannot be touched through defines, weight tweaks or both.

For example, the desire for Austria to accept the Anschluss event could look like this:
Code:
ai_chance = {
    base = 30
    modifier = {
        add = -25
        GER = { has_army_size = { size < 20 } }
    }
    modifier = {
        factor = 10
        GER = { has_army_size = { size > 19 } }
    }
}

And if they refuse, Germanys attitude towards them can be altered like this:
Code:
anschluss_rejected = {

    # Conditions
    enable = {
        tag = GER
        has_completed_focus = GER_anschluss
        country_exists = AUS
    }
    abort = {
        NOT = {
            country_exists = AUS
        }
    }
   
    # Modification if strategy is enabled
    ai_strategy = {
        type = antagonize
        id = "AUS"           
        value = 300
    }       
}

To give even more flavor to the behavior of countries, there are ways to modify things like the attitude towards other countries with...well, modifiers. These modifiers can be attached to to things like ministers, laws or even leader traits. This means that depending on who is in charge of a country, their interactions with other countries can vary, not just because of their ideology. This is something I want to look at expanding on even more in the future, but the modding possibilities are already notable.

Such a trait may look like this:
Code:
warrior_code = {
    random = no
    ai_call_ally_desire_factor = -40
}

Or this:
Code:
warmonger = {
    random = no
    ai_focus_aggressive_factor = 0.5
}

A couple of areas that gives the modder extra freedom is division template design, where you can tweak target templates, weight which stats the dynamic system should prioritize for specific division types, per country. The dynamic system will even pick up on if they have an unused equipment type and make a template design to accommodate it.
The other noteworthy system is how the AI scores its options in peace deals, which is fully scriptable, both per ideology as well as per country, if you so wish. Big thanks to Groogy for spending the time required on that!

The second big challenge; making the execution of player drawn battle plans good enough to feel useful. Whenever you give over control of a system to the computer, you expose all the weaknesses of the system for player scrutiny. An AI country that makes mistakes with its own troops can often get away with it, but messing up with the players units will lead to frustration.
The solution to this is mainly design; the system is not intended or built to be a magical "win war" button, but rather a tool to organize large numbers of units when every single detail is not critical. Both the AI and the player is expected to oversee critical operations, but they will not have to think about no-brainer situations, and is thus free to handle much much bigger armies and operations than if they had to micromanage them. This means that the internal workings of how the AI handles the units that are part of plans needs fewer bells and whistles, and by extension has fewer things that can go bonkers.
Even so, making it has been as hard as it has been rewarding.

So lets have a peek behind the curtains, into the mind of the AI.
In this situation, Germany has just gone to war against Poland. This tooltip tells us about the general, long term attitude of a country towards other countries. Germany, as we can see, is looking with unkind eyes towards its closest democracies while being supportive towards its fascist faction members.

DD1.jpg


Netherlands, meanwhile, is feeling the heat. Being threatened by Germany, they either want to see it weakened or to be their friend, but do not want to openly antagonize them at the clear risk of being crushed:

DD2.jpg


A more detailed look at Englands attitude towards Netherlands at this time shows us they want to protect the democratic minor of western Europe:

DD3.jpg


But as England has entered the war against Germany moments later, Netherlands is very reluctant to join the Allies, being at clear risk of ending up under the heel of Germany at this time:

DD4.jpg


And lastly, I want to give you a peek at how the AI determines troop levels for orders. Keep in mind that many groups need to share troops, and they may end up with less than they want or need if another group has a much higher priority:

DD5.jpg


Exactly which types of troops end up in which order is also done dynamically, but I have no cool tooltip screenshot of that.

I would say that the proudest moment for any AI developer is when their own creation defeats them in an unexpected manner. For me, such a moment came about two weeks ago when I was playing singleplayer as Germany. I had taken over western Europe easily enough through careful planning and superior weaponry. Wanting to take out England before looking east I was covering guarding my coast in case the Allies got and D-Day ambitions, as well as making sure my border with Soviet was covered, while putting as much resources as I could towards building up my forces for a naval invasion of Britain. It was then that England and USA managed to overwhelm BOTH the Italian and Spanish coastal defenses and gain a solid foot hold. Sending troops to back my friends up, once they arrived both England and USA had landed A LOT more troops, overwhelming both the Italian/Spanish defenses as well as my reinforcements. I could probably have taken on one of them, but both together with such a solid hold in southern Europe was more than I could manage.
Save for that, my best days are when Da9l comes and tells me the AI kicked his ass in one way or another, or just forcing him to change his plans.

A few bullet points that should answer the most burning questions:
* There is no 'hard coding' outside of the scripts. No where in the code does it say "if country is X, then do Y" or similar.
* The dynamic AI systems does not cheat. They use the same information as is available to the player, including estimating enemy forces based on intel numbers.
* Save for boosting party popularity, there is no feature in the game that the AI is completely barred from using. It being intended more as a sandbox feature for players. We have also had to limit it a lot when it comes to staging coups.

Extra kudos goes out to Wiz as head AI honcho, who makes sure I don't fuck everything up, and Groogy, who has gotten to step in and help out when the work load has become too much for one person. I would also like to extend gratitude towards all the amazing beta testers, who have provided tons of valuable feedback and support!

As a closing comment I just want to say that, while no one can hope to meet everyones hopes and expectations of the 'best' possible AI for a game like this, we at Paradox fell it is shaping up really well, and I really hope you all will enjoy playing HoI4 as much, and even more, as I have had making and playing it.
 
  • 179
  • 114
  • 1
Reactions:
Please tell me that there will be an option to turn off AI control and controlling your units manually without losing any bonuses that come from planning.

You can micromanage units that are part of an order as much as you want. Planning bonuses are currently not lost as long as the unit remains a part of the order.
 
  • 42
  • 8
Reactions:
Will the AI adapt its production or division templates based on what they know their enemy is building/using?
To a degree. As the player, it does not have access to what other countries are building, but to what it encounters in the field.

For instance if as Germany I focus on battleships instead of submarines will UK AI give more weight to producing battleships or carriers?
Given that most naval production is slow, this is determined more through national foci, and the AI the tries to use what it has as well as possible.

Likewise, if as Germany I have an infantry only army will Russia AI be more likely to add artillery on their divisions than to add anti tank?
See question 1 :)
 
  • 28
  • 4
Reactions:
It looks great. I have a question though. In Daniels´ games the AI usually gets pretty gamed. But then he goes to war with all, loses and starts another game. If we´d be able to see the rest of the game and he wouldn´t just keep attacking everybody, would the AI still eventually react to him and maybe beat him?

In the last WWW it was indeed looking grim for Hungary at the end. They even stated that they were pretty much done for. The AI will pick up on threat generation and typically gang up on common enemies.
 
  • 22
  • 5
Reactions:
Yeah, but after the order is fullfilled, the unit returns to AI control and AI will move it around eventually. Is it possible to tell AI not to move units on its own (aka turning off AI) even if part of a battleplan?

One of the biggest focuses when designing and working on the "unitcontroller", as we call it internally, is that it should not get in the way of the player, and a player given order must always have priority.

We have been experimenting lately with a system of "stickiness"; if you give a unit a manual order it will stick to that location until front has moved on.

All in all, a combination of using battle plans and giving some detailed orders in critical situations seems to be working very well :)
 
  • 31
  • 8
Reactions:
@SteelVolt
How complicated can AI scripts be?
Like can we actually use the intelligence available to AI in decision script?
Can we check what kind of army/resources/factories does AI have?

Have you tought AI to use combined arms mobile warfare? Does AI plays around capability to surround enemy troops? Will we see AI being able to execute Blitzkrieg with massive encirclements at least against other AIs?

You cannot script actual algorithms, but determining weights can be as complex as the triggers allow.

Not sure what you mean by this. By tweaking various values you can significantly alter the behavior of countries, but the underlying algorithms are C++, and as such not changeable through scripts.

In script? There are triggers for things like that, yes.
In the game, as a player vs AI? To the same extent as is allowed against human players.

I cannot say either yes or no with any conviction here. The AI does know things like taking advantaage of weak spots etc, and the multiple systems that touch movements and priority can certainly give rise to such behaviour. But planning large complicated operations in advance is tricky. Something I want to look more at in the future.

Also keep in mind that the AI is still in deveoplment, and will continue to be improved even beyond release :)
 
Last edited:
  • 19
  • 2
Reactions:
Lets say I want to delegate as much as I can to the AI. Can I just tell it "wage war for me" and have automatically produce equipment, supply it to units, assign units to fight on different fronts and fight hostile armies? What is absolute minimum for player to do for his country to semi-effectively wage war?

In short: no. You would need to draw the plans and then set them to execute. There is no thing as "manage this entire theatre for me" or "conquer country X", but when facing an inferior enemy, just setting your plan to cover their territory is usually enough.
 
  • 20
  • 1
Reactions:
Sounds great! Looking forward to seeing your creation!
You didn`t mention the tactical AI. Will we be able to tweak unit behaviour and battleplan writing for the AI?

Good catch! Sorry about that!

The AI uses the battle plan system under the exact same rules as the player. There are some defines that effect parts of it, but almost all of it is a dynamic system in C++, by necessity. It is quite a hard problem to tackle :)
 
  • 18
Reactions:
How do you feel about the AI's performance in defending from naval invasions? Can you lure the whole British navy away from the channel with your two German battleships as long as your invasion needs preparation, sneak one division into a port and transport the rest over, and then you basically won? Or do you feel like that will be no longer possible?

I am actually working on improving the naval AI right now, but I can't say I have seen that specifically be an issue in HoI4.
 
  • 17
Reactions:
Some question about AI that come to my mind :

- Did it uses xp to make variants ?
- How it handles research to make new division template ? Is there any "pre-made" template with latest tank/infantry equipment researched, or did the AI make his own according to some algorithm ?
- Last but most important : are the naval invasion by AI in HoI 3 corrected ? I saw Australia launch an invasion of Yugoslavia with one division like a suicide in the last WWW, it remember me the AI of HoI3 when USA send 2 infantry division in Murmansk or 6 armored division in Holland without support... It's my greatest fear, as without a proper uses of naval invasion by the AI, USA and Japan are doomed to make nothing...

- Yes, same rules apply as for human players.
- While "target templates" are scriptable, the AI creates them using the same functionality as the player. The research it picks depends on many things.
- While I never worked on HoI3, the naval invasions in HoI4 are shaping up fairly well. Still some minor hickups to take care of, but it is looking promising.
 
  • 17
Reactions:
Good Read. Intresting stuff. Most of the time AI countries getting cought unprepared is there are going to be "helping" feature to make sure they are ready for war?
Also Is there going to be second AI diary for Battle AI? Thats the other half of the gameplay.

AI countries are actually reluctant to enter wars before they are ready, and try to prepare as soon as they pick up on anyone generating a wargoal against them or taking a national focus that will likely lead to war. If you want to help your allies out, you have some options: leandleasing equipment, stationing your own troops on the relevant borders in their territory (which you can give them as expeditionary forces if you want to).

The DD schedule is unfortunately filled. As for the battle AI, I assume you mean how the AI carries out drawn plans. The short answer is: as straitforward as possible without making obvious mistakes. The long answer is that it is probably best to read the battle plan AI and then watch the WWW streams.
 
  • 12
  • 2
Reactions:
@SteelVolt
Important things for modders:

1) How hard/easy is it to implement new unit types and tell the AI how to use it and how much to produce (balancing production numbers)?
1a) F.e example I want to add escort ships. So they have Special Tasks:
- Do not mix with fleets
- Just go for submarine hunting
- go mostly on convoy escort duty

2) Can we tell the AI some Kind of production Ratio, or at least how does AI handle and itself produce and develop the techs of them?
- So AI sees the use of it
- AI decides how much are usefull of them (because of the missiontypes it has)

In Hoi3 I find it very complicated because of lacking programming/Scripting skills

The production part is highly scriptable, but roles are less so, at least for now. Hope that answers it.
 
  • 13
Reactions:
Cheers for the DD Steelvolt , and to you, Wiz and Groogy for all your work :D. Really looking forward to HoI4, and for me the AI is the most important part, and it looks like it's in a good pair of hands :). So much coolness in the various scriptable features - specific behaviours for different leaders is brilliant (and will be a boon to modders), as is the peace deal side of things and being able to push the AI towards specific templates (presumably altering this based on whatever triggers we roll with?) Debug view also all kinds of awesome :).



Does this mean the AI has both the Battleplan AI (shared with player) and it's own "tweak things to deal with situations as they arise" AI? Very cool if so :).



On the first - big props, non-cheating AI is always my preference :). On the second, will it still be possible to mod in a bit more coup and influence party popularity-friendliness for crazy sandbox games?



Only answer if easy, but are there triggers for intelligence (ie, is it possible for an AI UK to focus production more on battleships if its intelligence sees nations its threatened by (or GER/JAP specifically, however it's best to set it up) building BBs, and similarly if instead it sees Germany building a stack of u-boats, to focus on destroyers instead?


Thank you :)

1: The AI is capable of micromanaging units beyond what the battle plan system does to take care of certain types of situations. Just as the player is expected to.

2: I will try to take the time to have a look at this!

3: Short answer: no. What makes it hard is that neither the player or the AI has access to info about what other countries are producing. Naval production also tends to be largely long term. But the balances are scriptable.
 
  • 12
  • 1
Reactions:
Does this mean there will be leaders like Patton who are much more aggressive (risking losing more troops for a faster land win) and more careful (risking less troops but advancing not so fast) leaders like Montgomery?

Currently these traits are primarily for country leaders, but I hope to expand on it and it would be cool to do something like that.
 
  • 9
  • 5
Reactions:
Let`s say I want AI to launch invasion of Romania if AI can`t purchase Romanian oil for some reason, being either their law, prohibiting them from trading, or them being of wrong ideology.

I would need to determine IF Germany has troops to spare, are those troops strong/weak/mediocre compared to Germany, what kind of countries can jump to Romanian defence. Let`s say it is a national focus, so if conditions are fine, Germany declares war. That is what I mean. How complicated of a logic can we put into this scripts?

Or, let`s say I want AI to occasionally try different troops composition. So, let`s say I want Germany to have 3 broad strategies:
-historical
-focus on cheaper troops and faster wars, motorised instead of tanks, ex.
-go for navy.

I want the plan being set somehow, and then AI knowing it, would work towards it, let`s say a hiden event, depending on who player is, picks an AI strategy, depending on some weights.

Can I make all areas of strategic AI to work with the plan?

In HOI3, I would just set a country flag, and then would check the flag in country - specific LUA script.

Can something like this be done for HOI4?

It doesn`t have to be huge, even if AI would be able to consistently recognise and exploit small 1-5 divisions 1-3 province pockets, it would be huge improvement ;)

You cannot set the AI to "make a naval invasion plan against country X", that is handled dynamically. What you can do is push the country in the direction of war, but how exactly the war is fought is determined dynamically.

We are not using LUA for HoI4. This was a decision made before I started working at PDS, and was based primarily on lack of in house LUA skills and performance cost.
 
  • 13
Reactions:
Awesome DD, and one I have been waiting for for a long time!

Really interesting to see how everything is working behind the scene One question though, purely out of interest:

How did you start building up the AI? I mean, what part did you start with? Is there some base in the Clausewitz engine or did you have to start from scratch? If so, what part did you start with?

The base structure (parts of which are in the engine) was already done when I entered the project. I started out looking at diplomacy, as that is one of the most easily contained systems to code basic decision making for.
 
  • 8
Reactions: