File: ExecuteHeroChain.cpp

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (309 lines) | stat: -rw-r--r-- 8,133 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
* ExecuteHeroChain.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "ExecuteHeroChain.h"
#include "../AIGateway.h"
#include "../Engine/Nullkiller.h"

namespace NKAI
{

using namespace Goals;

ExecuteHeroChain::ExecuteHeroChain(const AIPath & path, const CGObjectInstance * obj)
	:ElementarGoal(Goals::EXECUTE_HERO_CHAIN), chainPath(path), closestWayRatio(1)
{
	hero = path.targetHero;
	tile = path.targetTile();
	closestWayRatio = 1;

	if(obj)
	{
		objid = obj->id.getNum();

#if NKAI_TRACE_LEVEL >= 1
		targetName = obj->getObjectName() + tile.toString();
#else
		targetName = obj->getTypeName() + tile.toString();
#endif
	}
	else
	{
		targetName = "tile" + tile.toString();
	}
}

bool ExecuteHeroChain::operator==(const ExecuteHeroChain & other) const
{
	return tile == other.tile 
		&& chainPath.targetHero == other.chainPath.targetHero
		&& chainPath.nodes.size() == other.chainPath.nodes.size()
		&& chainPath.chainMask == other.chainPath.chainMask;
}

std::vector<ObjectInstanceID> ExecuteHeroChain::getAffectedObjects() const
{
	std::vector<ObjectInstanceID> affectedObjects = { chainPath.targetHero->id };

	if(objid != -1)
		affectedObjects.push_back(ObjectInstanceID(objid));

	for(auto & node : chainPath.nodes)
	{
		if(node.targetHero)
			affectedObjects.push_back(node.targetHero->id);
	}

	vstd::removeDuplicates(affectedObjects);

	return affectedObjects;
}

bool ExecuteHeroChain::isObjectAffected(ObjectInstanceID id) const
{
	if(chainPath.targetHero->id == id || objid == id)
		return true;

	for(auto & node : chainPath.nodes)
	{
		if(node.targetHero && node.targetHero->id == id)
			return true;
	}

	return false;
}

void ExecuteHeroChain::accept(AIGateway * ai)
{
	logAi->debug("Executing hero chain towards %s. Path %s", targetName, chainPath.toString());

	ai->nullkiller->setActive(chainPath.targetHero, tile);
	ai->nullkiller->setTargetObject(objid);
	ai->nullkiller->objectClusterizer->reset();

	auto targetObject = ai->myCb->getObj(static_cast<ObjectInstanceID>(objid), false);

	if(chainPath.turn() == 0 && targetObject && targetObject->ID == Obj::TOWN)
	{
		auto relations = ai->myCb->getPlayerRelations(ai->playerID, targetObject->getOwner());

		if(relations == PlayerRelations::ENEMIES)
		{
			ai->nullkiller->armyFormation->rearrangeArmyForSiege(
				dynamic_cast<const CGTownInstance *>(targetObject),
				chainPath.targetHero);
		}
	}

	std::set<int> blockedIndexes;

	for(int i = chainPath.nodes.size() - 1; i >= 0; i--)
	{
		auto  * node = &chainPath.nodes[i];

		const CGHeroInstance * hero = node->targetHero;
		HeroPtr heroPtr = hero;

		if(!heroPtr.validAndSet())
		{
			logAi->error("Hero %s was lost. Exit hero chain.", heroPtr.name());

			return;
		}

		if(node->parentIndex >= i)
		{
			logAi->error("Invalid parentIndex while executing node " + node->coord.toString());
		}

		if(vstd::contains(blockedIndexes, i))
		{
			blockedIndexes.insert(node->parentIndex);
			ai->nullkiller->lockHero(hero, HeroLockedReason::HERO_CHAIN);

			continue;
		}

		logAi->debug("Executing chain node %d. Moving hero %s to %s", i, hero->getNameTranslated(), node->coord.toString());

		try
		{
			if(hero->movementPointsRemaining() > 0)
			{
				ai->nullkiller->setActive(hero, node->coord);

				if(node->specialAction)
				{
					if(node->actionIsBlocked)
					{
						throw cannotFulfillGoalException("Path is nondeterministic.");
					}
					
					node->specialAction->execute(ai, hero);
					
					if(!heroPtr.validAndSet())
					{
						logAi->error("Hero %s was lost trying to execute special action. Exit hero chain.", heroPtr.name());

						return;
					}
				}
				else if(i > 0 && ai->nullkiller->isObjectGraphAllowed())
				{
					auto chainMask = i < chainPath.nodes.size() - 1 ? chainPath.nodes[i + 1].chainMask : node->chainMask;

					for(auto j = i - 1; j >= 0; j--)
					{
						auto & nextNode = chainPath.nodes[j];

						if(nextNode.specialAction || nextNode.chainMask != chainMask)
							break;

						auto targetNode = ai->nullkiller->getPathsInfo(hero)->getPathInfo(nextNode.coord);

						if(!targetNode->reachable()
							|| targetNode->getCost() > nextNode.cost)
							break;

						i = j;
						node = &nextNode;

						if(targetNode->action == EPathNodeAction::BATTLE || targetNode->action == EPathNodeAction::TELEPORT_BATTLE)
							break;
					}
				}

				if(node->turns == 0 && node->coord != hero->visitablePos())
				{
					auto targetNode = ai->nullkiller->getPathsInfo(hero)->getPathInfo(node->coord);

					if(targetNode->accessible == EPathAccessibility::NOT_SET
						|| targetNode->accessible == EPathAccessibility::BLOCKED
						|| targetNode->accessible == EPathAccessibility::FLYABLE
						|| targetNode->turns != 0)
					{
						logAi->error(
							"Unable to complete chain. Expected hero %s to arrive to %s in 0 turns but he cannot do this",
							hero->getNameTranslated(),
							node->coord.toString());

						return;
					}
				}

				auto findWhirlpool = [&ai](const int3 & pos) -> ObjectInstanceID
				{
					auto objs = ai->myCb->getVisitableObjs(pos);
					auto whirlpool = std::find_if(objs.begin(), objs.end(), [](const CGObjectInstance * o)->bool
						{
							return o->ID == Obj::WHIRLPOOL;
						});

					return whirlpool != objs.end() ? dynamic_cast<const CGWhirlpool *>(*whirlpool)->id : ObjectInstanceID(-1);
				};

				auto sourceWhirlpool = findWhirlpool(hero->visitablePos());
				auto targetWhirlpool = findWhirlpool(node->coord);
				
				if(i != chainPath.nodes.size() - 1 && sourceWhirlpool.hasValue() && sourceWhirlpool == targetWhirlpool)
				{
					logAi->trace("AI exited whirlpool at %s but expected at %s", hero->visitablePos().toString(), node->coord.toString());
					continue;
				}

				if(hero->movementPointsRemaining())
				{
					try
					{
						if(moveHeroToTile(ai, hero, node->coord))
						{
							continue;
						}
					}
					catch(const cannotFulfillGoalException &)
					{
						if(!heroPtr.validAndSet())
						{
							logAi->error("Hero %s was lost. Exit hero chain.", heroPtr.name());

							return;
						}

						if(hero->movementPointsRemaining() > 0)
						{
							CGPath path;
							bool isOk = ai->nullkiller->getPathsInfo(hero)->getPath(path, node->coord);

							if(isOk && path.nodes.back().turns > 0)
							{
								logAi->warn("Hero %s has %d mp which is not enough to continue his way towards %s.", hero->getNameTranslated(), hero->movementPointsRemaining(), node->coord.toString());

								ai->nullkiller->lockHero(hero, HeroLockedReason::HERO_CHAIN);
								return;
							}
						}

						throw;
					}
				}
			}

			if(node->coord == hero->visitablePos())
				continue;

			if(node->turns == 0)
			{
				logAi->error(
					"Unable to complete chain. Expected hero %s to arrive to %s but he is at %s",
					hero->getNameTranslated(),
					node->coord.toString(),
					hero->visitablePos().toString());

				return;
			}
			
			// no exception means we were not able to reach the tile
			ai->nullkiller->lockHero(hero, HeroLockedReason::HERO_CHAIN);
			blockedIndexes.insert(node->parentIndex);
		}
		catch(const goalFulfilledException &)
		{
			if(!heroPtr.validAndSet())
			{
				logAi->debug("Hero %s was killed while attempting to reach %s", heroPtr.name(), node->coord.toString());

				return;
			}
		}
	}
}

std::string ExecuteHeroChain::toString() const
{
#if NKAI_TRACE_LEVEL >= 1
	return "ExecuteHeroChain " + targetName + " by " + chainPath.toString();
#else
	return "ExecuteHeroChain " + targetName + " by " + chainPath.targetHero->getNameTranslated();
#endif
}

bool ExecuteHeroChain::moveHeroToTile(AIGateway * ai, const CGHeroInstance * hero, const int3 & tile)
{
	if(tile == hero->visitablePos() && ai->myCb->getVisitableObjs(hero->visitablePos()).size() < 2)
	{
		logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", hero->getNameTranslated(), tile.toString());

		return true;
	}

	return ai->moveHeroToTile(tile, hero);
}

}