File: AIPathfinderConfig.cpp

package info (click to toggle)
vcmi 0.99%2Bdfsg%2Bgit20190113.f06c8a87-2
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 11,136 kB
  • sloc: cpp: 142,615; sh: 315; objc: 248; makefile: 32; ansic: 28; python: 13
file content (517 lines) | stat: -rw-r--r-- 13,282 bytes parent folder | download | duplicates (2)
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
* AIPathfinderConfig.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 "AIPathfinderConfig.h"
#include "../Goals/Goals.h"
#include "../../../CCallback.h"
#include "../../../lib/mapping/CMap.h"
#include "../../../lib/mapObjects/MapObjects.h"

namespace AIPathfinding
{
	class VirtualBoatAction : public ISpecialAction
	{
	private:
		uint64_t specialChain;

	public:
		VirtualBoatAction(uint64_t specialChain)
			:specialChain(specialChain)
		{
		}

		uint64_t getSpecialChain() const
		{
			return specialChain;
		}
	};

	class BuildBoatAction : public VirtualBoatAction
	{
	private:
		const IShipyard * shipyard;

	public:
		BuildBoatAction(const IShipyard * shipyard)
			:VirtualBoatAction(AINodeStorage::RESOURCE_CHAIN), shipyard(shipyard)
		{
		}

		virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
		{
			return sptr(Goals::BuildBoat(shipyard));
		}
	};

	class SummonBoatAction : public VirtualBoatAction
	{
	public:
		SummonBoatAction()
			:VirtualBoatAction(AINodeStorage::CAST_CHAIN)
		{
		}

		virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
		{
			return sptr(Goals::AdventureSpellCast(hero, SpellID::SUMMON_BOAT));
		}

		virtual void applyOnDestination(
			HeroPtr hero,
			CDestinationNodeInfo & destination,
			const PathNodeInfo & source,
			AIPathNode * dstMode,
			const AIPathNode * srcNode) const override
		{
			dstMode->manaCost = srcNode->manaCost + getManaCost(hero);
			dstMode->theNodeBefore = source.node;
		}

		bool isAffordableBy(HeroPtr hero, const AIPathNode * source) const
		{
#ifdef VCMI_TRACE_PATHFINDER
			logAi->trace(
				"Hero %s has %d mana and needed %d and already spent %d",
				hero->name,
				hero->mana,
				getManaCost(hero),
				source->manaCost);
#endif

			return hero->mana >= source->manaCost + getManaCost(hero);
		}

	private:
		uint32_t getManaCost(HeroPtr hero) const
		{
			SpellID summonBoat = SpellID::SUMMON_BOAT;

			return hero->getSpellCost(summonBoat.toSpell());
		}
	};

	class BattleAction : public ISpecialAction
	{
	private:
		const int3  target;
		const HeroPtr  hero;

	public:
		BattleAction(const int3 target)
			:target(target)
		{
		}

		virtual Goals::TSubgoal whatToDo(HeroPtr hero) const override
		{
			return sptr(Goals::VisitTile(target).sethero(hero));
		}
	};

	class AILayerTransitionRule : public LayerTransitionRule
	{
	private:
		CPlayerSpecificInfoCallback * cb;
		VCAI * ai;
		std::map<int3, std::shared_ptr<const BuildBoatAction>> virtualBoats;
		std::shared_ptr<AINodeStorage> nodeStorage;
		std::shared_ptr<const SummonBoatAction> summonableVirtualBoat;

	public:
		AILayerTransitionRule(CPlayerSpecificInfoCallback * cb, VCAI * ai, std::shared_ptr<AINodeStorage> nodeStorage)
			:cb(cb), ai(ai), nodeStorage(nodeStorage)
		{
			setup();
		}

		virtual void process(
			const PathNodeInfo & source,
			CDestinationNodeInfo & destination,
			const PathfinderConfig * pathfinderConfig,
			CPathfinderHelper * pathfinderHelper) const override
		{
			LayerTransitionRule::process(source, destination, pathfinderConfig, pathfinderHelper);

			if(!destination.blocked)
			{
				return;
			}

			if(source.node->layer == EPathfindingLayer::LAND && destination.node->layer == EPathfindingLayer::SAIL)
			{
				std::shared_ptr<const VirtualBoatAction> virtualBoat = findVirtualBoat(destination, source);

				if(virtualBoat && tryEmbarkVirtualBoat(destination, source, virtualBoat))
				{
#ifdef VCMI_TRACE_PATHFINDER
					logAi->trace("Embarking to virtual boat while moving %s -> %s!", source.coord.toString(), destination.coord.toString());
#endif
				}
			}
		}

	private:
		void setup()
		{
			std::vector<const IShipyard *> shipyards;

			for(const CGTownInstance * t : cb->getTownsInfo())
			{
				if(t->hasBuilt(BuildingID::SHIPYARD))
					shipyards.push_back(t);
			}

			for(const CGObjectInstance * obj : ai->visitableObjs)
			{
				if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
				{
					if(const IShipyard * shipyard = IShipyard::castFrom(obj))
						shipyards.push_back(shipyard);
				}
			}

			for(const IShipyard * shipyard : shipyards)
			{
				if(shipyard->shipyardStatus() == IShipyard::GOOD)
				{
					int3 boatLocation = shipyard->bestLocation();
					virtualBoats[boatLocation] = std::make_shared<BuildBoatAction>(shipyard);
					logAi->debug("Virtual boat added at %s", boatLocation.toString());
				}
			}

			auto hero = nodeStorage->getHero();
			auto summonBoatSpell = SpellID(SpellID::SUMMON_BOAT).toSpell();

			if(hero->canCastThisSpell(summonBoatSpell)
				&& hero->getSpellSchoolLevel(summonBoatSpell) >= SecSkillLevel::ADVANCED)
			{
				// TODO: For lower school level we might need to check the existance of some boat
				summonableVirtualBoat.reset(new SummonBoatAction());
			}
		}

		std::shared_ptr<const VirtualBoatAction> findVirtualBoat(
			CDestinationNodeInfo &destination,
			const PathNodeInfo &source) const
		{
			std::shared_ptr<const VirtualBoatAction> virtualBoat;

			if(vstd::contains(virtualBoats, destination.coord))
			{
				virtualBoat = virtualBoats.at(destination.coord);
			}
			else if(
				summonableVirtualBoat
				&& summonableVirtualBoat->isAffordableBy(nodeStorage->getHero(), nodeStorage->getAINode(source.node)))
			{
				virtualBoat = summonableVirtualBoat;
			}

			return virtualBoat;
		}

		bool tryEmbarkVirtualBoat(
			CDestinationNodeInfo &destination,
			const PathNodeInfo &source,
			std::shared_ptr<const VirtualBoatAction> virtualBoat) const
		{
			bool result = false;

			nodeStorage->updateAINode(destination.node, [&](AIPathNode * node)
			{
				auto boatNodeOptional = nodeStorage->getOrCreateNode(
					node->coord,
					node->layer,
					node->chainMask | virtualBoat->getSpecialChain());

				if(boatNodeOptional)
				{
					AIPathNode * boatNode = boatNodeOptional.get();

					if(boatNode->action == CGPathNode::UNKNOWN)
					{
						boatNode->specialAction = virtualBoat;
						destination.blocked = false;
						destination.action = CGPathNode::ENodeAction::EMBARK;
						destination.node = boatNode;
						result = true;
					}
					else
					{
#ifdef VCMI_TRACE_PATHFINDER
						logAi->trace(
							"Special transition node already allocated. Blocked moving %s -> %s",
							source.coord.toString(),
							destination.coord.toString());
#endif
					}
				}
				else
				{
					logAi->debug(
						"Can not allocate special transition node while moving %s -> %s",
						source.coord.toString(),
						destination.coord.toString());
				}
			});

			return result;
		}
	};

	class AIMovementAfterDestinationRule : public MovementAfterDestinationRule
	{
	private:
		CPlayerSpecificInfoCallback * cb;
		std::shared_ptr<AINodeStorage> nodeStorage;

	public:
		AIMovementAfterDestinationRule(CPlayerSpecificInfoCallback * cb, std::shared_ptr<AINodeStorage> nodeStorage)
			:cb(cb), nodeStorage(nodeStorage)
		{
		}

		virtual void process(
			const PathNodeInfo & source,
			CDestinationNodeInfo & destination,
			const PathfinderConfig * pathfinderConfig,
			CPathfinderHelper * pathfinderHelper) const override
		{
			if(nodeStorage->hasBetterChain(source, destination))
			{
				destination.blocked = true;

				return;
			}

			auto blocker = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);

			if(blocker == BlockingReason::NONE)
				return;

			if(blocker == BlockingReason::DESTINATION_BLOCKVIS && destination.nodeObject)
			{
				auto objID = destination.nodeObject->ID;
				auto enemyHero = objID == Obj::HERO && destination.objectRelations == PlayerRelations::ENEMIES;

				if(!enemyHero && !isObjectRemovable(destination.nodeObject))
				{
					destination.blocked = true;
				}

				return;
			}

			if(blocker == BlockingReason::DESTINATION_VISIT)
			{
				return;
			}

			if(blocker == BlockingReason::DESTINATION_GUARDED)
			{
				auto srcGuardians = cb->getGuardingCreatures(source.coord);
				auto destGuardians = cb->getGuardingCreatures(destination.coord);

				if(destGuardians.empty())
				{
					destination.blocked = true;

					return;
				}

				vstd::erase_if(destGuardians, [&](const CGObjectInstance * destGuard) -> bool
				{
					return vstd::contains(srcGuardians, destGuard);
				});

				auto guardsAlreadyBypassed = destGuardians.empty() && srcGuardians.size();
				if(guardsAlreadyBypassed && nodeStorage->isBattleNode(source.node))
				{
#ifdef VCMI_TRACE_PATHFINDER
					logAi->trace(
						"Bypass guard at destination while moving %s -> %s",
						source.coord.toString(),
						destination.coord.toString());
#endif

					return;
				}

				const AIPathNode * destNode = nodeStorage->getAINode(destination.node);
				auto battleNodeOptional = nodeStorage->getOrCreateNode(
					destination.coord,
					destination.node->layer,
					destNode->chainMask | AINodeStorage::BATTLE_CHAIN);

				if(!battleNodeOptional)
				{
#ifdef VCMI_TRACE_PATHFINDER
					logAi->trace(
						"Can not allocate battle node while moving %s -> %s",
						source.coord.toString(),
						destination.coord.toString());
#endif

					destination.blocked = true;

					return;
				}

				AIPathNode *  battleNode = battleNodeOptional.get();

				if(battleNode->locked)
				{
#ifdef VCMI_TRACE_PATHFINDER
					logAi->trace(
						"Block bypass guard at destination while moving %s -> %s",
						source.coord.toString(),
						destination.coord.toString());
#endif
					destination.blocked = true;

					return;
				}

				auto hero = nodeStorage->getHero();
				auto danger = evaluateDanger(destination.coord, hero);

				destination.node = battleNode;
				nodeStorage->commit(destination, source);

				if(battleNode->danger < danger)
				{
					battleNode->danger = danger;
				}

				battleNode->specialAction = std::make_shared<BattleAction>(destination.coord);
#ifdef VCMI_TRACE_PATHFINDER
				logAi->trace(
					"Begin bypass guard at destination with danger %s while moving %s -> %s",
					std::to_string(danger),
					source.coord.toString(),
					destination.coord.toString());
#endif
				return;
			}

			destination.blocked = true;
		}
	};

	class AIMovementToDestinationRule : public MovementToDestinationRule
	{
	private:
		std::shared_ptr<AINodeStorage> nodeStorage;

	public:
		AIMovementToDestinationRule(std::shared_ptr<AINodeStorage> nodeStorage)
			: nodeStorage(nodeStorage)
		{
		}

		virtual void process(
			const PathNodeInfo & source,
			CDestinationNodeInfo & destination,
			const PathfinderConfig * pathfinderConfig,
			CPathfinderHelper * pathfinderHelper) const override
		{
			auto blocker = getBlockingReason(source, destination, pathfinderConfig, pathfinderHelper);

			if(blocker == BlockingReason::NONE)
				return;

			if(blocker == BlockingReason::DESTINATION_BLOCKED
				&& destination.action == CGPathNode::EMBARK
				&& nodeStorage->getAINode(destination.node)->specialAction)
			{
				return;
			}

			if(blocker == BlockingReason::SOURCE_GUARDED && nodeStorage->isBattleNode(source.node))
			{
#ifdef VCMI_TRACE_PATHFINDER
				logAi->trace(
					"Bypass src guard while moving from %s to %s",
					source.coord.toString(),
					destination.coord.toString());
#endif
				return;
			}

			destination.blocked = true;
		}
	};

	class AIPreviousNodeRule : public MovementToDestinationRule
	{
	private:
		std::shared_ptr<AINodeStorage> nodeStorage;

	public:
		AIPreviousNodeRule(std::shared_ptr<AINodeStorage> nodeStorage)
			: nodeStorage(nodeStorage)
		{
		}

		virtual void process(
			const PathNodeInfo & source,
			CDestinationNodeInfo & destination,
			const PathfinderConfig * pathfinderConfig,
			CPathfinderHelper * pathfinderHelper) const override
		{
			if(source.node->action == CGPathNode::ENodeAction::BLOCKING_VISIT || source.node->action == CGPathNode::ENodeAction::VISIT)
			{
				// we can not directly bypass objects, we need to interact with them first
				destination.node->theNodeBefore = source.node;
#ifdef VCMI_TRACE_PATHFINDER
				logAi->trace(
					"Link src node %s to destination node %s while bypassing visitable obj",
					source.coord.toString(),
					destination.coord.toString());
#endif
				return;
			}

			auto aiSourceNode = nodeStorage->getAINode(source.node);

			if(aiSourceNode->specialAction)
			{
				// there is some action on source tile which should be performed before we can bypass it
				destination.node->theNodeBefore = source.node;
			}
		}
	};

	std::vector<std::shared_ptr<IPathfindingRule>> makeRuleset(
		CPlayerSpecificInfoCallback * cb,
		VCAI * ai,
		std::shared_ptr<AINodeStorage> nodeStorage)
	{
		std::vector<std::shared_ptr<IPathfindingRule>> rules = {
			std::make_shared<AILayerTransitionRule>(cb, ai, nodeStorage),
			std::make_shared<DestinationActionRule>(),
			std::make_shared<AIMovementToDestinationRule>(nodeStorage),
			std::make_shared<MovementCostRule>(),
			std::make_shared<AIPreviousNodeRule>(nodeStorage),
			std::make_shared<AIMovementAfterDestinationRule>(cb, nodeStorage)
		};

		return rules;
	}

	AIPathfinderConfig::AIPathfinderConfig(
		CPlayerSpecificInfoCallback * cb,
		VCAI * ai,
		std::shared_ptr<AINodeStorage> nodeStorage)
		:PathfinderConfig(nodeStorage, makeRuleset(cb, ai, nodeStorage))
	{
	}
}