File: CGHeroInstance.cpp

package info (click to toggle)
vcmi 0.99%2Bdfsg%2Bgit20190113.f06c8a87-1
  • links: PTS, VCS
  • area: contrib
  • in suites: buster
  • size: 11,096 kB
  • sloc: cpp: 142,605; sh: 315; objc: 248; makefile: 32; ansic: 28; python: 13
file content (1601 lines) | stat: -rw-r--r-- 44,922 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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
/*
 * CGHeroInstance.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 "CGHeroInstance.h"

#include "../NetPacks.h"
#include "../CGeneralTextHandler.h"
#include "../CHeroHandler.h"
#include "../CModHandler.h"
#include "../CSoundBase.h"
#include "../spells/CSpellHandler.h"
#include "../CSkillHandler.h"
#include "CObjectClassesHandler.h"
#include "../IGameCallback.h"
#include "../CGameState.h"
#include "../CCreatureHandler.h"
#include "../CTownHandler.h"
#include "../mapping/CMap.h"
#include "CGTownInstance.h"
#include "../serializer/JsonSerializeFormat.h"
#include "../StringConstants.h"
#include "../battle/Unit.h"


///helpers
static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID = 0)
{
	InfoWindow iw;
	iw.soundID = soundID;
	iw.player = playerID;
	iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
	IObjectInterface::cb->sendAndApply(&iw);
}

static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID = 0)
{
	const PlayerColor playerID = h->getOwner();
	showInfoDialog(playerID,txtID,soundID);
}

static int lowestSpeed(const CGHeroInstance * chi)
{
	if(!chi->stacksCount())
	{
		logGlobal->error("Hero %d (%s) has no army!", chi->id.getNum(), chi->name);
		return 20;
	}
	auto i = chi->Slots().begin();
	//TODO? should speed modifiers (eg from artifacts) affect hero movement?

	static const CSelector selectorSTACKS_SPEED = Selector::type(Bonus::STACKS_SPEED);
	static const std::string keySTACKS_SPEED = "type_"+std::to_string((si32)Bonus::STACKS_SPEED);

	int ret = (i++)->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED);
	for(; i != chi->Slots().end(); i++)
		ret = std::min(ret, i->second->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED));
	return ret;
}

ui32 CGHeroInstance::getTileCost(const TerrainTile & dest, const TerrainTile & from, const TurnInfo * ti) const
{
	unsigned ret = GameConstants::BASE_MOVEMENT_COST;

	//if there is road both on dest and src tiles - use road movement cost
	if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
	{
		int road = std::min(dest.roadType,from.roadType); //used road ID
		switch(road)
		{
		case ERoadType::DIRT_ROAD:
			ret = 75;
			break;
		case ERoadType::GRAVEL_ROAD:
			ret = 65;
			break;
		case ERoadType::COBBLESTONE_ROAD:
			ret = 50;
			break;
		default:
			logGlobal->error("Unknown road type: %d", road);
			break;
		}
	}
	else if(ti->nativeTerrain != from.terType && !ti->hasBonusOfType(Bonus::NO_TERRAIN_PENALTY, from.terType))
	{
		static const CSelector selectorPATHFINDING = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::PATHFINDING);
		static const std::string keyPATHFINDING = "type_"+std::to_string((si32)Bonus::SECONDARY_SKILL_PREMY)+"s_"+std::to_string((si32)SecondarySkill::PATHFINDING);

		ret = VLC->heroh->terrCosts[from.terType];
		ret -= valOfBonuses(selectorPATHFINDING, keyPATHFINDING);
		if(ret < GameConstants::BASE_MOVEMENT_COST)
			ret = GameConstants::BASE_MOVEMENT_COST;
	}
	return ret;
}

int CGHeroInstance::getNativeTerrain() const
{
	// NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
	// This is clearly bug in H3 however intended behaviour is not clear.
	// Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
	// will always have best penalty without any influence from player-defined stacks order

	// TODO: What should we do if all hero stacks are neutral creatures?
	int nativeTerrain = -1;
	for(auto stack : stacks)
	{
		int stackNativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
		if(stackNativeTerrain == -1)
			continue;

		if(nativeTerrain == -1)
			nativeTerrain = stackNativeTerrain;
		else if(nativeTerrain != stackNativeTerrain)
			return -1;
	}

	return nativeTerrain;
}

int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
{
	if (toh3m)
	{
		src.x+=1;
		return src;
	}
	else
	{
		src.x-=1;
		return src;
	}
}
int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
{
	if (h3m)
	{
		return pos;
	}
	else
	{
		return convertPosition(pos,false);
	}
}

ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
{
	for(auto & elem : secSkills)
		if(elem.first == skill)
			return elem.second;
	return 0;
}

void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
{
	if(getSecSkillLevel(which) == 0)
	{
		secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
		updateSkillBonus(which, val);
	}
	else
	{
		for (auto & elem : secSkills)
		{
			if(elem.first == which)
			{
				if(abs)
					elem.second = val;
				else
					elem.second += val;

				if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
				{
					logGlobal->warn("Skill %d increased over limit! Decreasing to Expert.", static_cast<int>(which.toEnum()));
					elem.second = 3;
				}
				updateSkillBonus(which, elem.second); //when we know final value
			}
		}
	}
}

bool CGHeroInstance::canLearnSkill() const
{
	return secSkills.size() < GameConstants::SKILL_PER_HERO;
}

int CGHeroInstance::maxMovePoints(bool onLand) const
{
	TurnInfo ti(this);
	return maxMovePointsCached(onLand, &ti);
}

int CGHeroInstance::maxMovePointsCached(bool onLand, const TurnInfo * ti) const
{
	int base;

	if(onLand)
	{
		// used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
		static const int baseSpeed = 1300; // base speed from creature with 0 speed

		int armySpeed = lowestSpeed(this) * 20 / 3;

		base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
		vstd::abetween(base, 1500, 2000); // base speed is limited by these values
	}
	else
	{
		base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
	}

	const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
	const int bonus = ti->valOfBonuses(Bonus::MOVEMENT) + ti->valOfBonuses(bt);

	const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
	const double modifier = ti->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;

	return int(base * (1 + modifier)) + bonus;
}

CGHeroInstance::CGHeroInstance()
 : IBoatGenerator(this)
{
	setNodeType(HERO);
	ID = Obj::HERO;
	tacticFormationEnabled = inTownGarrison = false;
	mana = UNINITIALIZED_MANA;
	movement = UNINITIALIZED_MOVEMENT;
	portrait = UNINITIALIZED_PORTRAIT;
	isStanding = true;
	moveDir = 4;
	level = 1;
	exp = 0xffffffff;
	visitedTown = nullptr;
	type = nullptr;
	boat = nullptr;
	commander = nullptr;
	sex = 0xff;
	secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
}

void CGHeroInstance::initHero(CRandomGenerator & rand, HeroTypeID SUBID)
{
	subID = SUBID.getNum();
	initHero(rand);
}

void CGHeroInstance::setType(si32 ID, si32 subID)
{
	assert(ID == Obj::HERO); // just in case
	type = VLC->heroh->heroes[subID];
	portrait = type->imageIndex;
	CGObjectInstance::setType(ID, type->heroClass->id); // to find object handler we must use heroClass->id
	this->subID = subID; // after setType subID used to store unique hero identify id. Check issue 2277 for details
	randomizeArmy(type->heroClass->faction);
}

void CGHeroInstance::initHero(CRandomGenerator & rand)
{
	assert(validTypes(true));
	if(!type)
		type = VLC->heroh->heroes[subID];

	if (ID == Obj::HERO)
		appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->id)->getTemplates().front();

	if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
	{
		for(auto spellID : type->spells)
			spells.insert(spellID);
	}
	else //remove placeholder
		spells -= SpellID::PRESET;

	if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
		putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(ArtifactID::SPELLBOOK));

	if(!getArt(ArtifactPosition::MACH4))
		putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(ArtifactID::CATAPULT)); //everyone has a catapult

	if(portrait < 0 || portrait == 255)
		portrait = type->imageIndex;
	if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
	{
		for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
		{
			pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
		}
	}
	if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
		secSkills = type->secSkillsInit;
	if (!name.length())
		name = type->name;

	if (sex == 0xFF)//sex is default
		sex = type->sex;

	setFormation(false);
	if (!stacksCount()) //standard army//initial army
	{
		initArmy(rand);
	}
	assert(validTypes());

	if(exp == 0xffffffff)
	{
		initExp(rand);
	}
	else
	{
		levelUpAutomatically(rand);
	}

	if (VLC->modh->modules.COMMANDERS && !commander)
	{
		commander = new CCommanderInstance(type->heroClass->commander->idNumber);
		commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
		commander->giveStackExp (exp); //after our exp is set
	}

	if (mana < 0)
		mana = manaLimit();
}

void CGHeroInstance::initArmy(CRandomGenerator & rand, IArmyDescriptor * dst)
{
	if(!dst)
		dst = this;

	int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
	int pom = rand.nextInt(99);
	int warMachinesGiven = 0;

	if(pom < 9)
		howManyStacks = 1;
	else if(pom < 79)
		howManyStacks = 2;
	else
		howManyStacks = 3;

	vstd::amin(howManyStacks, type->initialArmy.size());

	for(int stackNo=0; stackNo < howManyStacks; stackNo++)
	{
		auto & stack = type->initialArmy[stackNo];

		int count = rand.nextInt(stack.minAmount, stack.maxAmount);

		const CCreature * creature = stack.creature.toCreature();

		if(creature == nullptr)
		{
			logGlobal->error("Hero %s has invalid creature with id %d in initial army", name, stack.creature.toEnum());
			continue;
		}

		if(creature->warMachine != ArtifactID::NONE) //war machine
		{
			warMachinesGiven++;
			if(dst != this)
				continue;

			ArtifactID aid = creature->warMachine;
			const CArtifact * art = aid.toArtifact();

			if(art != nullptr && !art->possibleSlots.at(ArtBearer::HERO).empty())
			{
				//TODO: should we try another possible slots?
				ArtifactPosition slot = art->possibleSlots.at(ArtBearer::HERO).front();

				if(!getArt(slot))
					putArtifact(slot, CArtifactInstance::createNewArtifactInstance(aid));
				else
					logGlobal->warn("Hero %s already has artifact at %d, omitting giving artifact %d", name, slot.toEnum(), aid.toEnum());
			}
			else
			{
				logGlobal->error("Hero %s has invalid war machine in initial army", name);
			}
		}
		else
		{
			dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
		}
	}
}

CGHeroInstance::~CGHeroInstance()
{
	commander.dellNull();
}

bool CGHeroInstance::needsLastStack() const
{
	return true;
}

void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
{
	if(h == this) return; //exclude potential self-visiting

	if (ID == Obj::HERO)
	{
		if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
		{
			//exchange
			cb->heroExchange(h->id, id);
		}
		else //battle
		{
			if(visitedTown) //we're in town
				visitedTown->onHeroVisit(h); //town will handle attacking
			else
				cb->startBattleI(h,	this);
		}
	}
	else if(ID == Obj::PRISON)
	{
		int txt_id;

		if (cb->getHeroCount(h->tempOwner, false) < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)//GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
		{
			cb->changeObjPos(id,pos+int3(1,0,0),0);
			//update hero parameters
			SetMovePoints smp;
			smp.hid = id;
			smp.val = maxMovePoints (true); //TODO: hota prison on water?
			cb->setMovePoints (&smp);
			cb->setManaPoints (id, manaLimit());

			cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
			cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player

			txt_id = 102;
		}
		else //already 8 wandering heroes
		{
			txt_id = 103;
		}

		showInfoDialog(h,txt_id);
	}
}

std::string CGHeroInstance::getObjectName() const
{
	if(ID != Obj::PRISON)
	{
		std::string hoverName = VLC->generaltexth->allTexts[15];
		boost::algorithm::replace_first(hoverName,"%s",name);
		boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
		return hoverName;
	}
	else
		return CGObjectInstance::getObjectName();
}

const std::string & CGHeroInstance::getBiography() const
{
	if (biography.length())
		return biography;
	return type->biography;
}

ui8 CGHeroInstance::maxlevelsToMagicSchool() const
{
	return type->heroClass->isMagicHero() ? 3 : 4;
}
ui8 CGHeroInstance::maxlevelsToWisdom() const
{
	return type->heroClass->isMagicHero() ? 3 : 6;
}

CGHeroInstance::SecondarySkillsInfo::SecondarySkillsInfo()
{
	rand.setSeed(0);
	magicSchoolCounter = 1;
	wisdomCounter = 1;
}

void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
{
	magicSchoolCounter = 1;
}
void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
{
	wisdomCounter = 1;
}

void CGHeroInstance::initObj(CRandomGenerator & rand)
{
	blockVisit = true;

	if(!type)
		initHero(rand); //TODO: set up everything for prison before specialties are configured

	skillsInfo.rand.setSeed(rand.nextInt());
	skillsInfo.resetMagicSchoolCounter();
	skillsInfo.resetWisdomCounter();

	if (ID != Obj::PRISON)
	{
		auto customApp = VLC->objtypeh->getHandlerFor(ID, type->heroClass->id)->getOverride(cb->gameState()->getTile(visitablePos())->terType, this);
		if (customApp)
			appearance = customApp.get();
	}

	//copy active (probably growing) bonuses from hero prototype to hero object
	for(std::shared_ptr<Bonus> b : type->specialty)
		addNewBonus(b);
	//dito for old-style bonuses -> compatibility for old savegames
	for(SSpecialtyBonus & sb : type->specialtyDeprecated)
		for(std::shared_ptr<Bonus> b : sb.bonuses)
			addNewBonus(b);
	for(SSpecialtyInfo & spec : type->specDeprecated)
		for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, type->ID.getNum()))
			addNewBonus(b);

	//initialize bonuses
	recreateSecondarySkillsBonuses();

	mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
	type->name = name;
}

void CGHeroInstance::recreateSecondarySkillsBonuses()
{
	auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
	for(auto bonus : *secondarySkillsBonuses)
		removeBonus(bonus);

	for(auto skill_info : secSkills)
		if(skill_info.second > 0)
			updateSkillBonus(SecondarySkill(skill_info.first), skill_info.second);
}

void CGHeroInstance::recreateSpecialtyBonuses(std::vector<HeroSpecial *> & specialtyDeprecated)
{
	auto HeroSpecialToSpecialtyBonus = [](HeroSpecial & hs) -> SSpecialtyBonus
	{
		SSpecialtyBonus sb;
		sb.growsWithLevel = hs.growsWithLevel;
		sb.bonuses = hs.getBonusList();
		return sb;
	};

	for(HeroSpecial * hs : specialtyDeprecated)
	{
		for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(HeroSpecialToSpecialtyBonus(*hs), type->ID.getNum()))
			addNewBonus(b);
	}
}

void CGHeroInstance::updateSkillBonus(SecondarySkill which, int val)
{
	removeBonuses(Selector::source(Bonus::SECONDARY_SKILL, which));
	auto skillBonus = (*VLC->skillh)[which]->at(val).effects;
	for (auto b : skillBonus)
		addNewBonus(std::make_shared<Bonus>(*b));
}

void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
{
	if(what == ObjProperty::PRIMARY_STACK_COUNT)
		setStackCount(SlotID(0), val);
}

TFaction CGHeroInstance::getFaction() const
{
	return type->heroClass->faction;
}

double CGHeroInstance::getFightingStrength() const
{
	return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
}

double CGHeroInstance::getMagicStrength() const
{
	return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
}

double CGHeroInstance::getHeroStrength() const
{
	return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
}

ui64 CGHeroInstance::getTotalStrength() const
{
	double ret = getFightingStrength() * getArmyStrength();
	return (ui64) ret;
}

TExpType CGHeroInstance::calculateXp(TExpType exp) const
{
	return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
}

int32_t CGHeroInstance::getCasterUnitId() const
{
	return -1; //TODO: special value for attacker/defender hero
}

ui8 CGHeroInstance::getSpellSchoolLevel(const spells::Spell * spell, int * outSelectedSchool) const
{
	si16 skill = -1; //skill level

	spell->forEachSchool([&, this](const spells::SchoolInfo & cnf, bool & stop)
	{
		int thisSchool = std::max<int>(
			valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, cnf.skill),
			valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << ((ui8)cnf.id))); //FIXME: Bonus shouldn't be additive (Witchking Artifacts : Crown of Skies)
		if(thisSchool > skill)
		{
			skill = thisSchool;
			if(outSelectedSchool)
				*outSelectedSchool = (ui8)cnf.id;
		}
	});

	vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
	vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->getIndex())); //given by artifact or other effect

	vstd::amax(skill, 0); //in case we don't know any school
	vstd::amin(skill, 3);
	return skill;
}

int64_t CGHeroInstance::getSpellBonus(const spells::Spell * spell, int64_t base, const battle::Unit * affectedStack) const
{
	//applying sorcery secondary skill

	base *= (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
	base *= (100.0 + valOfBonuses(Bonus::SPELL_DAMAGE) + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0;

	int maxSchoolBonus = 0;

	spell->forEachSchool([&maxSchoolBonus, this](const spells::SchoolInfo & cnf, bool & stop)
	{
		vstd::amax(maxSchoolBonus, valOfBonuses(cnf.damagePremyBonus));
	});

	base *= (100.0 + maxSchoolBonus) / 100.0;

	if(affectedStack && affectedStack->creatureLevel() > 0) //Hero specials like Solmyr, Deemer
		base *= (100. + valOfBonuses(Bonus::SPECIAL_SPELL_LEV, spell->getIndex()) / affectedStack->creatureLevel()) / 100.0;

	return base;
}

int64_t CGHeroInstance::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
{
	base *= (100.0 + valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, spell->getIndex())) / 100.0;
	return base;
}

int CGHeroInstance::getEffectLevel(const spells::Spell * spell) const
{
	if(hasBonusOfType(Bonus::MAXED_SPELL, spell->getIndex()))
		return 3;//todo: recheck specialty from where this bonus is. possible bug
	else
		return getSpellSchoolLevel(spell);
}

int CGHeroInstance::getEffectPower(const spells::Spell * spell) const
{
	return getPrimSkillLevel(PrimarySkill::SPELL_POWER);
}

int CGHeroInstance::getEnchantPower(const spells::Spell * spell) const
{
	return getPrimSkillLevel(PrimarySkill::SPELL_POWER) + valOfBonuses(Bonus::SPELL_DURATION);
}

int64_t CGHeroInstance::getEffectValue(const spells::Spell * spell) const
{
	return 0;
}

const PlayerColor CGHeroInstance::getOwner() const
{
	return tempOwner;
}

void CGHeroInstance::getCasterName(MetaString & text) const
{
	//FIXME: use local name, MetaString need access to gamestate as hero name is part of map object
	text.addReplacement(name);
}

void CGHeroInstance::getCastDescription(const spells::Spell * spell, const std::vector<const battle::Unit *> & attacked, MetaString & text) const
{
	const bool singleTarget = attacked.size() == 1;
	const int textIndex = singleTarget ? 195 : 196;

	text.addTxt(MetaString::GENERAL_TXT, textIndex);
	getCasterName(text);
	text.addReplacement(MetaString::SPELL_NAME, spell->getIndex());
	if(singleTarget)
		attacked.at(0)->addNameReplacement(text, true);
}

void CGHeroInstance::spendMana(const spells::PacketSender * server, const int spellCost) const
{
	if(spellCost != 0)
	{
		SetMana sm;
		sm.absolute = false;
		sm.hid = id;
		sm.val = -spellCost;

		server->sendAndApply(&sm);
	}
}

bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
{
	const bool isAllowed = IObjectInterface::cb->isAllowed(0, spell->id);

	const bool inSpellBook = vstd::contains(spells, spell->id) && hasSpellbook();
	const bool specificBonus = hasBonusOfType(Bonus::SPELL, spell->id);

	bool schoolBonus = false;

	spell->forEachSchool([this, &schoolBonus](const spells::SchoolInfo & cnf, bool & stop)
	{
		if(hasBonusOfType(cnf.knoledgeBonus))
		{
			schoolBonus = stop = true;
		}
	});

	const bool levelBonus = hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level);

	if(spell->isSpecialSpell())
	{
		if(inSpellBook)
		{//hero has this spell in spellbook
			logGlobal->error("Special spell %s in spellbook.", spell->name);
		}
		return specificBonus;
	}
	else if(!isAllowed)
	{
		if(inSpellBook)
		{
			//hero has this spell in spellbook
			//it is normal if set in map editor, but trace it to possible debug of magic guild
			logGlobal->trace("Banned spell %s in spellbook.", spell->name);
		}
		return inSpellBook || specificBonus || schoolBonus || levelBonus;
	}
	else
	{
		return inSpellBook || schoolBonus || specificBonus || levelBonus;
	}
}

bool CGHeroInstance::canLearnSpell(const CSpell * spell) const
{
    if(!hasSpellbook())
		return false;

	if(spell->level > maxSpellLevel()) //not enough wisdom
		return false;

	if(vstd::contains(spells, spell->id))//already known
		return false;

	if(spell->isSpecialSpell())
	{
		logGlobal->warn("Hero %s try to learn special spell %s", nodeName(), spell->name);
		return false;//special spells can not be learned
	}

	if(spell->isCreatureAbility())
	{
		logGlobal->warn("Hero %s try to learn creature spell %s", nodeName(), spell->name);
		return false;//creature abilities can not be learned
	}

	if(!IObjectInterface::cb->isAllowed(0, spell->id))
	{
		logGlobal->warn("Hero %s try to learn banned spell %s", nodeName(), spell->name);
		return false;//banned spells should not be learned
	}

	return true;
}

/**
 * Calculates what creatures and how many to be raised from a battle.
 * @param battleResult The results of the battle.
 * @return Returns a pair with the first value indicating the ID of the creature
 * type and second value the amount. Both values are returned as -1 if necromancy
 * could not be applied.
 */
CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
{
	const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
	// need skill or cloak of undead king - lesser artifacts don't work without skill
	if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
	{
		double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY) / 100.0;
		vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
		const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
		// figure out what to raise - pick strongest creature meeting requirements
		CreatureID creatureTypeRaised = CreatureID::SKELETON;
		int requiredCasualtyLevel = 1;
		const TBonusListPtr improvedNecromancy = getBonuses(Selector::type(Bonus::IMPROVED_NECROMANCY));
		if(!improvedNecromancy->empty())
		{
			auto getCreatureID = [necromancyLevel](std::shared_ptr<Bonus> bonus) -> CreatureID
			{
				const CreatureID legacyTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
				return CreatureID(bonus->subtype >= 0 ? bonus->subtype : legacyTypes[necromancyLevel]);
			};
			int maxCasualtyLevel = 1;
			for(auto & casualty : casualties)
				vstd::amax(maxCasualtyLevel, VLC->creh->creatures[casualty.first]->level);
			// pick best bonus available
			std::shared_ptr<Bonus> topPick;
			for(std::shared_ptr<Bonus> newPick : *improvedNecromancy)
			{
				// addInfo[0] = required necromancy skill, addInfo[1] = required casualty level
				if(newPick->additionalInfo[0] > necromancyLevel || newPick->additionalInfo[1] > maxCasualtyLevel)
					continue;
				if(!topPick)
				{
					topPick = newPick;
				}
				else
				{
					auto quality = [getCreatureID](std::shared_ptr<Bonus> pick) -> std::vector<int>
					{
						const CCreature * c = VLC->creh->creatures[getCreatureID(pick)];
						std::vector<int> v = {c->level, static_cast<int>(c->cost.marketValue()), -pick->additionalInfo[1]};
						return v;
					};
					if(quality(topPick) < quality(newPick))
						topPick = newPick;
				}
			}
			if(topPick)
			{
				creatureTypeRaised = getCreatureID(topPick);
				requiredCasualtyLevel = std::max(topPick->additionalInfo[1], 1);
			}
		}
		// raise upgraded creature (at 2/3 rate) if no space available otherwise
		if(getSlotFor(creatureTypeRaised) == SlotID())
		{
			for(CreatureID upgraded : VLC->creh->creatures[creatureTypeRaised]->upgrades)
			{
				if(getSlotFor(upgraded) != SlotID())
				{
					creatureTypeRaised = upgraded;
					necromancySkill *= 2/3.0;
					break;
				}
			}
		}
		// calculate number of creatures raised - low level units contribute at 50% rate
		const double raisedUnitHealth = VLC->creh->creatures[creatureTypeRaised]->MaxHealth();
		double raisedUnits = 0;
		for(auto & casualty : casualties)
		{
			const CCreature * c = VLC->creh->creatures[casualty.first];
			double raisedFromCasualty = std::min(c->MaxHealth() / raisedUnitHealth, 1.0) * casualty.second * necromancySkill;
			if(c->level < requiredCasualtyLevel)
				raisedFromCasualty *= 0.5;
			raisedUnits += raisedFromCasualty;
		}
		return CStackBasicDescriptor(creatureTypeRaised, std::max(static_cast<int>(raisedUnits), 1));
	}

	return CStackBasicDescriptor();
}

/**
 * Show the necromancy dialog with information about units raised.
 * @param raisedStack Pair where the first element represents ID of the raised creature
 * and the second element the amount.
 */
void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack, CRandomGenerator & rand) const
{
	InfoWindow iw;
	iw.soundID = soundBase::pickup01 + rand.nextInt(6);
	iw.player = tempOwner;
	iw.components.push_back(Component(raisedStack));

	if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
	{
		iw.text.addTxt(MetaString::GENERAL_TXT, 145);
		iw.text.addReplacement(raisedStack.count);
	}
	else // Practicing the dark arts of necromancy, ... (singular)
	{
		iw.text.addTxt(MetaString::GENERAL_TXT, 146);
	}
	iw.text.addReplacement(raisedStack);

	cb->showInfoDialog(&iw);
}
/*
int3 CGHeroInstance::getSightCenter() const
{
	return getPosition(false);
}*/

int CGHeroInstance::getSightRadius() const
{
	return 5 + valOfBonuses(Bonus::SIGHT_RADIOUS); // scouting gives SIGHT_RADIUS bonus
}

si32 CGHeroInstance::manaRegain() const
{
	if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
		return manaLimit();

	return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::MYSTICISM) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
}

si32 CGHeroInstance::getManaNewTurn() const
{
	if(visitedTown && visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
	{
		//if hero starts turn in town with mage guild - restore all mana
		return std::max(mana, manaLimit());
	}
	si32 res = mana + manaRegain();
	res = std::min(res, manaLimit());
	res = std::max(res, mana);
	res = std::max(res, 0);
	return res;
}

// /**
//  * Places an artifact in hero's backpack. If it's a big artifact equips it
//  * or discards it if it cannot be equipped.
//  */
// void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
// {
// 	CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
// 	CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
// 	ai->putAt(this, ai->firstAvailableSlot(this));
// }

int CGHeroInstance::getBoatType() const
{
	switch(type->heroClass->getAlignment())
	{
	case EAlignment::GOOD:
		return 1;
	case EAlignment::EVIL:
		return 0;
	case EAlignment::NEUTRAL:
		return 2;
	default:
		throw std::runtime_error("Wrong alignment!");
	}
}

void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
{
	// FIXME: Offsets need to be fixed once we get rid of convertPosition
	// Check issue 515 for details
	offsets =
	{
		int3(-1,1,0), int3(-1,-1,0), int3(-2,0,0), int3(0,0,0), int3(0,1,0), int3(-2,1,0), int3(0,-1,0), int3(-2,-1,0)
	};
}

int CGHeroInstance::getSpellCost(const CSpell * sp) const
{
	return sp->getCost(getSpellSchoolLevel(sp));
}

void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
{
	assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
						.And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
	addNewBonus(std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
}

EAlignment::EAlignment CGHeroInstance::getAlignment() const
{
	return type->heroClass->getAlignment();
}

void CGHeroInstance::initExp(CRandomGenerator & rand)
{
	exp = rand.nextInt(40, 89);
}

std::string CGHeroInstance::nodeName() const
{
	return "Hero " + name;
}

void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
{
	assert(!getArt(pos));
	art->putAt(ArtifactLocation(this, pos));
}

void CGHeroInstance::putInBackpack(CArtifactInstance *art)
{
	putArtifact(art->firstBackpackSlot(this), art);
}

bool CGHeroInstance::hasSpellbook() const
{
	return getArt(ArtifactPosition::SPELLBOOK);
}

void CGHeroInstance::addSpellToSpellbook(SpellID spell)
{
	spells.insert(spell);
}

void CGHeroInstance::removeSpellFromSpellbook(SpellID spell)
{
	spells.erase(spell);
}

bool CGHeroInstance::spellbookContainsSpell(SpellID spell) const
{
	return vstd::contains(spells, spell);
}

void CGHeroInstance::removeSpellbook()
{
	spells.clear();

	if(hasSpellbook())
	{
		ArtifactLocation(this, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
	}
}

const std::set<SpellID> & CGHeroInstance::getSpellsInSpellbook() const
{
	return spells;
}

int CGHeroInstance::maxSpellLevel() const
{
	return std::min(GameConstants::SPELL_LEVELS, 2 + valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::WISDOM)));
}

void CGHeroInstance::deserializationFix()
{
	artDeserializationFix(this);
}

CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
{
	if(visitedTown)
	{
		if(inTownGarrison)
			return visitedTown;
		else
			return &visitedTown->townAndVis;
	}
	else
		return CArmedInstance::whereShouldBeAttached(gs);
}

int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark, const TurnInfo * ti) const
{
	int ret = 0; //take all MPs by default
	bool localTi = false;
	if(!ti)
	{
		localTi = true;
		ti = new TurnInfo(this);
	}

	int mp1 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
	int mp2 = ti->getMaxMovePoints(disembark ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND);
	if(ti->hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
		ret = (MPsBefore - basicCost) * static_cast<double>(mp1) / mp2;

	if(localTi)
		delete ti;

	return ret;
}

EDiggingStatus CGHeroInstance::diggingStatus() const
{
	if(movement < maxMovePoints(true))
		return EDiggingStatus::LACK_OF_MOVEMENT;

	return cb->getTile(getPosition(false))->getDiggingStatus();
}

ArtBearer::ArtBearer CGHeroInstance::bearerType() const
{
	return ArtBearer::HERO;
}

std::vector<SecondarySkill> CGHeroInstance::getLevelUpProposedSecondarySkills() const
{
	std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
	if (!skillsInfo.wisdomCounter)
	{
		if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
			obligatorySkills.push_back(SecondarySkill::WISDOM);
	}
	if (!skillsInfo.magicSchoolCounter)
	{
		std::vector<SecondarySkill> ss =
		{
			SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC
		};

		std::shuffle(ss.begin(), ss.end(), skillsInfo.rand.getStdGenerator());

		for (auto skill : ss)
		{
			if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
			{
				obligatorySkills.push_back(skill);
				break; //only one
			}
		}
	}

	std::vector<SecondarySkill> skills;
	//picking sec. skills for choice
	std::set<SecondarySkill> basicAndAdv, expert, none;
	for(int i = 0; i < VLC->skillh->size(); i++)
		if (cb->isAllowed(2,i))
			none.insert(SecondarySkill(i));

	for(auto & elem : secSkills)
	{
		if(elem.second < SecSkillLevel::EXPERT)
			basicAndAdv.insert(elem.first);
		else
			expert.insert(elem.first);
		none.erase(elem.first);
	}
	for (auto s : obligatorySkills) //don't duplicate them
	{
		none.erase (s);
		basicAndAdv.erase (s);
		expert.erase (s);
	}

	//first offered skill:
	// 1) give obligatory skill
	// 2) give any other new skill
	// 3) upgrade existing
	if (canLearnSkill() && obligatorySkills.size() > 0)
	{
		skills.push_back (obligatorySkills[0]);
	}
	else if(none.size() && canLearnSkill()) //hero have free skill slot
	{
		skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //new skill
		none.erase(skills.back());
	}
	else if(!basicAndAdv.empty())
	{
		skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand)); //upgrade existing
		basicAndAdv.erase(skills.back());
	}

	//second offered skill:
	//1) upgrade existing
	//2) give obligatory skill
	//3) give any other new skill
	if(!basicAndAdv.empty())
	{
		SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.rand);//upgrade existing
		skills.push_back(s);
		basicAndAdv.erase(s);
	}
	else if (canLearnSkill() && obligatorySkills.size() > 1)
	{
		skills.push_back (obligatorySkills[1]);
	}
	else if(none.size() && canLearnSkill())
	{
		skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.rand)); //give new skill
		none.erase(skills.back());
	}

	if (skills.size() == 2) // Fix for #1868 to avoid changing logic (possibly causing bugs in process)
		std::swap(skills[0], skills[1]);
	return skills;
}

PrimarySkill::PrimarySkill CGHeroInstance::nextPrimarySkill(CRandomGenerator & rand) const
{
	assert(gainsLevel());
	int randomValue = rand.nextInt(99), pom = 0, primarySkill = 0;
	const auto & skillChances = (level > 9) ? type->heroClass->primarySkillLowLevel : type->heroClass->primarySkillHighLevel;

	for(; primarySkill < GameConstants::PRIMARY_SKILLS; ++primarySkill)
	{
		pom += skillChances[primarySkill];
		if(randomValue < pom)
		{
			break;
		}
	}

	logGlobal->trace("The hero gets the primary skill %d with a probability of %d %%.", primarySkill, randomValue);
	return static_cast<PrimarySkill::PrimarySkill>(primarySkill);
}

boost::optional<SecondarySkill> CGHeroInstance::nextSecondarySkill(CRandomGenerator & rand) const
{
	assert(gainsLevel());

	boost::optional<SecondarySkill> chosenSecondarySkill;
	const auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();
	if(!proposedSecondarySkills.empty())
	{
		std::vector<SecondarySkill> learnedSecondarySkills;
		for(auto secondarySkill : proposedSecondarySkills)
		{
			if(getSecSkillLevel(secondarySkill) > 0)
			{
				learnedSecondarySkills.push_back(secondarySkill);
			}
		}

		if(learnedSecondarySkills.empty())
		{
			// there are only new skills to learn, so choose anyone of them
			chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(proposedSecondarySkills, rand));
		}
		else
		{
			// preferably upgrade a already learned secondary skill
			chosenSecondarySkill = boost::make_optional(*RandomGeneratorUtil::nextItem(learnedSecondarySkills, rand));
		}
	}
	return chosenSecondarySkill;
}

void CGHeroInstance::setPrimarySkill(PrimarySkill::PrimarySkill primarySkill, si64 value, ui8 abs)
{
	if(primarySkill < PrimarySkill::EXPERIENCE)
	{
		auto skill = getBonusLocalFirst(Selector::type(Bonus::PRIMARY_SKILL)
			.And(Selector::subtype(primarySkill))
			.And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));
		assert(skill);

		if(abs)
		{
			skill->val = value;
		}
		else
		{
			skill->val += value;
		}
		CBonusSystemNode::treeHasChanged();
	}
	else if(primarySkill == PrimarySkill::EXPERIENCE)
	{
		if(abs)
		{
			exp = value;
		}
		else
		{
			exp += value;
		}
	}
}

bool CGHeroInstance::gainsLevel() const
{
	return exp >= VLC->heroh->reqExp(level+1);
}

void CGHeroInstance::levelUp(std::vector<SecondarySkill> skills)
{
	++level;

	//deterministic secondary skills
	skillsInfo.magicSchoolCounter = (skillsInfo.magicSchoolCounter + 1) % maxlevelsToMagicSchool();
	skillsInfo.wisdomCounter = (skillsInfo.wisdomCounter + 1) % maxlevelsToWisdom();
	if(vstd::contains(skills, SecondarySkill::WISDOM))
	{
		skillsInfo.resetWisdomCounter();
	}

	SecondarySkill spellSchools[] = {
		SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC};
	for(auto skill : spellSchools)
	{
		if(vstd::contains(skills, skill))
		{
			skillsInfo.resetMagicSchoolCounter();
			break;
		}
	}

	//update specialty and other bonuses that scale with level
	treeHasChanged();
}

void CGHeroInstance::levelUpAutomatically(CRandomGenerator & rand)
{
	while(gainsLevel())
	{
		const auto primarySkill = nextPrimarySkill(rand);
		setPrimarySkill(primarySkill, 1, false);

		auto proposedSecondarySkills = getLevelUpProposedSecondarySkills();

		const auto secondarySkill = nextSecondarySkill(rand);
		if(secondarySkill)
		{
			setSecSkillLevel(*secondarySkill, 1, false);
		}

		//TODO why has the secondary skills to be passed to the method?
		levelUp(proposedSecondarySkills);
	}
}

bool CGHeroInstance::hasVisions(const CGObjectInstance * target, const int subtype) const
{
	//VISIONS spell support

	const std::string cached = boost::to_string((boost::format("type_%d__subtype_%d") % Bonus::VISIONS % subtype));

	const int visionsMultiplier = valOfBonuses(Selector::typeSubtype(Bonus::VISIONS,subtype), cached);

	int visionsRange =  visionsMultiplier * getPrimSkillLevel(PrimarySkill::SPELL_POWER);

	if (visionsMultiplier > 0)
		vstd::amax(visionsRange, 3); //minimum range is 3 tiles, but only if VISIONS bonus present

	const int distance = target->pos.dist2d(getPosition(false));

	//logGlobal->debug(boost::to_string(boost::format("Visions: dist %d, mult %d, range %d") % distance % visionsMultiplier % visionsRange));

	return (distance < visionsRange) && (target->pos.z == pos.z);
}

std::string CGHeroInstance::getHeroTypeName() const
{
	if(ID == Obj::HERO || ID == Obj::PRISON)
	{
		if(type)
		{
			return type->identifier;
		}
		else
		{
			return VLC->heroh->heroes[subID]->identifier;
		}
	}
	return "";
}

void CGHeroInstance::afterAddToMap(CMap * map)
{
	if(ID == Obj::HERO)
		map->heroesOnMap.push_back(this);
}

void CGHeroInstance::setHeroTypeName(const std::string & identifier)
{
	if(ID == Obj::HERO || ID == Obj::PRISON)
	{
		auto rawId = VLC->modh->identifiers.getIdentifier("core", "hero", identifier);

		if(rawId)
			subID = rawId.get();
		else
			subID = 0; //fallback to Orrin, throw error instead?
	}
}

void CGHeroInstance::serializeCommonOptions(JsonSerializeFormat & handler)
{
	handler.serializeString("biography", biography);
	handler.serializeInt("experience", exp, 0);
	handler.serializeString("name", name);
	handler.serializeBool<ui8>("female", sex, 1, 0, 0xFF);

	{
		const int legacyHeroes = VLC->modh->settings.data["textData"]["hero"].Integer();
		const int moddedStart = legacyHeroes + GameConstants::HERO_PORTRAIT_SHIFT;

		if(handler.saving)
		{
			if(portrait >= 0)
			{
				if(portrait < legacyHeroes || portrait >= moddedStart)
					handler.serializeId("portrait", portrait, -1, &VLC->heroh->decodeHero, &VLC->heroh->encodeHero);
				else
					handler.serializeInt("portrait", portrait, -1);
			}
		}
		else
		{
			const JsonNode & portraitNode = handler.getCurrent()["portrait"];

			if(portraitNode.getType() == JsonNode::JsonType::DATA_STRING)
				handler.serializeId("portrait", portrait, -1, &VLC->heroh->decodeHero, &VLC->heroh->encodeHero);
			else
				handler.serializeInt("portrait", portrait, -1);
		}
	}

	//primary skills
	if(handler.saving)
	{
		const bool haveSkills = hasBonus(Selector::type(Bonus::PRIMARY_SKILL).And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));

		if(haveSkills)
		{
			auto primarySkills = handler.enterStruct("primarySkills");

			for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
			{
				int value = valOfBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, i).And(Selector::sourceType(Bonus::HERO_BASE_SKILL)));

				handler.serializeInt(PrimarySkill::names[i], value, 0);
			}
		}
	}
	else
	{
		auto primarySkills = handler.enterStruct("primarySkills");

		if(handler.getCurrent().getType() == JsonNode::JsonType::DATA_STRUCT)
		{
			for(int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
			{
				int value = 0;
				handler.serializeInt(PrimarySkill::names[i], value, 0);
				pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), value);
			}
		}
	}

	//secondary skills
	if(handler.saving)
	{
		//does hero have default skills?
		bool defaultSkills = false;
		bool normalSkills = false;
		for(const auto & p : secSkills)
		{
			if(p.first == SecondarySkill(SecondarySkill::DEFAULT))
				defaultSkills = true;
			else
				normalSkills = true;
		}

		if(defaultSkills && normalSkills)
			logGlobal->error("Mixed default and normal secondary skills");

		//in json default skills means no field/null
		if(!defaultSkills)
		{
			//enter structure here as handler initialize it
			auto secondarySkills = handler.enterStruct("secondarySkills");

			for(auto & p : secSkills)
			{
				const si32 rawId = p.first.num;

				if(rawId < 0 || rawId >= VLC->skillh->size())
					logGlobal->error("Invalid secondary skill %d", rawId);

				handler.serializeEnum((*VLC->skillh)[SecondarySkill(rawId)]->identifier, p.second, 0, NSecondarySkill::levels);
			}
		}
	}
	else
	{
		auto secondarySkills = handler.enterStruct("secondarySkills");
		const JsonNode & skillMap = handler.getCurrent();

		secSkills.clear();
		if(skillMap.getType() == JsonNode::JsonType::DATA_NULL)
		{
			secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1));
		}
		else
		{
			for(const auto & p : skillMap.Struct())
			{
				const std::string skillId = p.first;
				const std::string levelId =  p.second.String();

				const int rawId = CSkillHandler::decodeSkill(skillId);
				if(rawId < 0)
				{
					logGlobal->error("Invalid secondary skill %s", skillId);
					continue;
				}

				const int level = vstd::find_pos(NSecondarySkill::levels, levelId);
				if(level < 0)
				{
					logGlobal->error("Invalid secondary skill level%s", levelId);
					continue;
				}

				secSkills.push_back(std::pair<SecondarySkill,ui8>(SecondarySkill(rawId), level));
			}
		}
	}

	handler.serializeIdArray("spellBook", spells);

	if(handler.saving)
		CArtifactSet::serializeJsonArtifacts(handler, "artifacts", nullptr);
}

void CGHeroInstance::serializeJsonOptions(JsonSerializeFormat & handler)
{
	serializeCommonOptions(handler);

	serializeJsonOwner(handler);

	if(ID == Obj::HERO || ID == Obj::PRISON)
	{
		std::string typeName;
		if(handler.saving)
			typeName = getHeroTypeName();
		handler.serializeString("type", typeName);
		if(!handler.saving)
			setHeroTypeName(typeName);
	}

	CCreatureSet::serializeJson(handler, "army", 7);
	handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);

	{
		static const int NO_PATROLING = -1;
		int rawPatrolRadius = NO_PATROLING;

		if(handler.saving)
		{
			rawPatrolRadius = patrol.patrolling ? patrol.patrolRadius : NO_PATROLING;
		}

		handler.serializeInt("patrolRadius", rawPatrolRadius, NO_PATROLING);

		if(!handler.saving)
		{
			patrol.patrolling = (rawPatrolRadius > NO_PATROLING);
			patrol.initialPos = convertPosition(pos, false);
			patrol.patrolRadius = (rawPatrolRadius > NO_PATROLING) ? rawPatrolRadius : 0;
		}
	}
}

void CGHeroInstance::serializeJsonDefinition(JsonSerializeFormat & handler)
{
	serializeCommonOptions(handler);
}

bool CGHeroInstance::isMissionCritical() const
{
	for(const TriggeredEvent & event : IObjectInterface::cb->getMapHeader()->triggeredEvents)
	{
		if(event.trigger.test([&](const EventCondition & condition)
		{
			if ((condition.condition == EventCondition::CONTROL || condition.condition == EventCondition::HAVE_0) && condition.object)
			{
				auto hero = dynamic_cast<const CGHeroInstance*>(condition.object);
				return (hero != this);
			}
			else if(condition.condition == EventCondition::IS_HUMAN)
			{
				return true;
			}
			return false;
		}))
		{
			return true;
		}
	}
	return false;
}