/
CGameHandler.cpp
5920 lines (5099 loc) · 174 KB
/
CGameHandler.cpp
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
#include "StdInc.h"
#include "../lib/filesystem/Filesystem.h"
#include "../lib/filesystem/CFileInfo.h"
#include "../lib/int3.h"
#include "../lib/mapping/CCampaignHandler.h"
#include "../lib/StartInfo.h"
#include "../lib/CModHandler.h"
#include "../lib/CArtHandler.h"
#include "../lib/CBuildingHandler.h"
#include "../lib/CHeroHandler.h"
#include "../lib/spells/CSpellHandler.h"
#include "../lib/CGeneralTextHandler.h"
#include "../lib/CTownHandler.h"
#include "../lib/CCreatureHandler.h"
#include "../lib/CGameState.h"
#include "../lib/BattleState.h"
#include "../lib/CondSh.h"
#include "../lib/NetPacks.h"
#include "../lib/VCMI_Lib.h"
#include "../lib/mapping/CMap.h"
#include "../lib/VCMIDirs.h"
#include "../lib/ScopeGuard.h"
#include "../lib/CSoundBase.h"
#include "CGameHandler.h"
#include "CVCMIServer.h"
#include "../lib/CCreatureSet.h"
#include "../lib/CThreadHelper.h"
#include "../lib/GameConstants.h"
#include "../lib/registerTypes/RegisterTypes.h"
/*
* CGameHandler.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
*
*/
#ifndef _MSC_VER
#include <boost/thread/xtime.hpp>
#endif
extern bool end2;
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
#define COMPLAIN_RET_IF(cond, txt) do {if(cond){complain(txt); return;}} while(0)
#define COMPLAIN_RET_FALSE_IF(cond, txt) do {if(cond){complain(txt); return false;}} while(0)
#define COMPLAIN_RET(txt) {complain(txt); return false;}
#define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
#define NEW_ROUND BattleNextRound bnr;\
bnr.round = gs->curB->round + 1;\
sendAndApply(&bnr);
class ServerSpellCastEnvironment: public SpellCastEnvironment
{
public:
ServerSpellCastEnvironment(CGameHandler * gh);
~ServerSpellCastEnvironment(){};
void sendAndApply(CPackForClient * info) const override;
CRandomGenerator & getRandomGenerator() const override;
void complain(const std::string & problem) const override;
const CMap * getMap() const override;
const CGameInfoCallback * getCb() const override;
bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, PlayerColor asker = PlayerColor::NEUTRAL) const override;
private:
mutable CGameHandler * gh;
};
CondSh<bool> battleMadeAction;
CondSh<BattleResult *> battleResult(nullptr);
template <typename T> class CApplyOnGH;
class CBaseForGHApply
{
public:
virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack, PlayerColor player) const =0;
virtual ~CBaseForGHApply(){}
template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
{
return new CApplyOnGH<U>;
}
};
template <typename T> class CApplyOnGH : public CBaseForGHApply
{
public:
bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack, PlayerColor player) const
{
T *ptr = static_cast<T*>(pack);
ptr->c = c;
ptr->player = player;
return ptr->applyGh(gh);
}
};
template <>
class CApplyOnGH<CPack> : public CBaseForGHApply
{
public:
bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack, PlayerColor player) const
{
logGlobal->errorStream() << "Cannot apply on GH plain CPack!";
assert(0);
return false;
}
};
static CApplier<CBaseForGHApply> *applier = nullptr;
CMP_stack cmpst ;
static inline double distance(int3 a, int3 b)
{
return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
}
static void giveExp(BattleResult &r)
{
r.exp[0] = 0;
r.exp[1] = 0;
for(auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
{
r.exp[r.winner] += VLC->creh->creatures.at(i->first)->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
}
}
PlayerStatus PlayerStatuses::operator[](PlayerColor player)
{
boost::unique_lock<boost::mutex> l(mx);
if(players.find(player) != players.end())
{
return players.at(player);
}
else
{
throw std::runtime_error("No such player!");
}
}
void PlayerStatuses::addPlayer(PlayerColor player)
{
boost::unique_lock<boost::mutex> l(mx);
players[player];
}
bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
{
boost::unique_lock<boost::mutex> l(mx);
if(players.find(player) != players.end())
{
return players[player].*flag;
}
else
{
throw std::runtime_error("No such player!");
}
}
void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
{
boost::unique_lock<boost::mutex> l(mx);
if(players.find(player) != players.end())
{
players[player].*flag = val;
}
else
{
throw std::runtime_error("No such player!");
}
cv.notify_all();
}
template <typename T>
void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
{
fun(args[which]);
}
void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
{
changeSecSkill(hero, skill, 1, 0);
expGiven(hero);
}
void CGameHandler::levelUpHero(const CGHeroInstance * hero)
{
// required exp for at least 1 lvl-up hasn't been reached
if(!hero->gainsLevel())
{
return;
}
// give primary skill
logGlobal->traceStream() << hero->name << " got level "<< hero->level;
auto primarySkill = hero->nextPrimarySkill();
SetPrimSkill sps;
sps.id = hero->id;
sps.which = primarySkill;
sps.abs = false;
sps.val = 1;
sendAndApply(&sps);
HeroLevelUp hlu;
hlu.hero = hero;
hlu.primskill = primarySkill;
hlu.skills = hero->getLevelUpProposedSecondarySkills();
if(hlu.skills.size() == 0)
{
sendAndApply(&hlu);
levelUpHero(hero);
}
else if(hlu.skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
{
sendAndApply(&hlu);
levelUpHero(hero, *RandomGeneratorUtil::nextItem(hlu.skills, hero->skillsInfo.rand));
}
else if(hlu.skills.size() > 1)
{
auto levelUpQuery = make_shared<CHeroLevelUpDialogQuery>(hlu);
hlu.queryID = levelUpQuery->queryID;
queries.addQuery(levelUpQuery);
sendAndApply(&hlu);
//level up will be called on query reply
}
}
void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
{
SetCommanderProperty scp;
auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
if (hero)
scp.heroid = hero->id;
else
{
complain ("Commander is not led by hero!");
return;
}
scp.accumulatedBonus.subtype = 0;
scp.accumulatedBonus.additionalInfo = 0;
scp.accumulatedBonus.duration = Bonus::PERMANENT;
scp.accumulatedBonus.turnsRemain = 0;
scp.accumulatedBonus.source = Bonus::COMMANDER;
scp.accumulatedBonus.valType = Bonus::BASE_NUMBER;
if (skill <= ECommander::SPELL_POWER)
{
scp.which = SetCommanderProperty::BONUS;
auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
{
int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
};
switch (skill)
{
case ECommander::ATTACK:
scp.accumulatedBonus.type = Bonus::PRIMARY_SKILL;
scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
break;
case ECommander::DEFENSE:
scp.accumulatedBonus.type = Bonus::PRIMARY_SKILL;
scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
break;
case ECommander::HEALTH:
scp.accumulatedBonus.type = Bonus::STACK_HEALTH;
scp.accumulatedBonus.valType = Bonus::PERCENT_TO_BASE;
break;
case ECommander::DAMAGE:
scp.accumulatedBonus.type = Bonus::CREATURE_DAMAGE;
scp.accumulatedBonus.subtype = 0;
scp.accumulatedBonus.valType = Bonus::PERCENT_TO_BASE;
break;
case ECommander::SPEED:
scp.accumulatedBonus.type = Bonus::STACKS_SPEED;
break;
case ECommander::SPELL_POWER:
scp.accumulatedBonus.type = Bonus::MAGIC_RESISTANCE;
scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
sendAndApply (&scp); //additional pack
scp.accumulatedBonus.type = Bonus::CREATURE_SPELL_POWER;
scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
sendAndApply (&scp); //additional pack
scp.accumulatedBonus.type = Bonus::CASTS;
scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
sendAndApply (&scp); //additional pack
scp.accumulatedBonus.type = Bonus::CREATURE_ENCHANT_POWER; //send normally
break;
}
scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
sendAndApply (&scp);
scp.which = SetCommanderProperty::SECONDARY_SKILL;
scp.additionalInfo = skill;
scp.amount = c->secondarySkills.at(skill) + 1;
sendAndApply (&scp);
}
else if (skill >= 100)
{
scp.which = SetCommanderProperty::SPECIAL_SKILL;
scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
scp.additionalInfo = skill; //unnormalized
sendAndApply (&scp);
}
expGiven(hero);
}
void CGameHandler::levelUpCommander(const CCommanderInstance * c)
{
if (!c->gainsLevel())
{
return;
}
CommanderLevelUp clu;
auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
if (hero)
clu.hero = hero;
else
{
complain ("Commander is not led by hero!");
return;
}
//picking sec. skills for choice
for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
{
if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
clu.skills.push_back(i);
}
int i = 100;
for (auto specialSkill : VLC->creh->skillRequirements)
{
if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
&& c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
&& !vstd::contains (c->specialSKills, i))
clu.skills.push_back (i);
++i;
}
int skillAmount = clu.skills.size();
if(!skillAmount)
{
sendAndApply(&clu);
levelUpCommander(c);
}
else if(skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
{
sendAndApply(&clu);
levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, gs->getRandomGenerator()));
}
else if(skillAmount > 1) //apply and ask for secondary skill
{
auto commanderLevelUp = make_shared<CCommanderLevelUpDialogQuery>(clu);
clu.queryID = commanderLevelUp->queryID;
queries.addQuery(commanderLevelUp);
sendAndApply(&clu);
}
}
void CGameHandler::expGiven(const CGHeroInstance *hero)
{
if(hero->gainsLevel())
levelUpHero(hero);
else if(hero->commander && hero->commander->gainsLevel())
levelUpCommander(hero->commander);
//if(hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
// levelUpCommander(hero->commander);
// else
// levelUpHero(hero);
}
void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
{
if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
{
if (gs->map->levelLimit != 0)
{
TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
TExpType resultingExp = abs ? val : hero->exp + val;
if (resultingExp > expLimit)
{
// set given experience to max possible, but don't decrease if hero already over top
abs = true;
val = std::max(expLimit, hero->exp);
InfoWindow iw;
iw.player = hero->tempOwner;
iw.text.addTxt(MetaString::GENERAL_TXT, 1); //can gain no more XP
iw.text.addReplacement(hero->name);
sendAndApply(&iw);
}
}
}
SetPrimSkill sps;
sps.id = hero->id;
sps.which = which;
sps.abs = abs;
sps.val = val;
sendAndApply(&sps);
//only for exp - hero may level up
if (which == PrimarySkill::EXPERIENCE)
{
if(hero->commander && hero->commander->alive)
{
//FIXME: trim experience according to map limit?
SetCommanderProperty scp;
scp.heroid = hero->id;
scp.which = SetCommanderProperty::EXPERIENCE;
scp.amount = val;
sendAndApply (&scp);
CBonusSystemNode::treeHasChanged();
}
expGiven(hero);
}
}
void CGameHandler::changeSecSkill( const CGHeroInstance * hero, SecondarySkill which, int val, bool abs/*=false*/ )
{
SetSecSkill sss;
sss.id = hero->id;
sss.which = which;
sss.val = val;
sss.abs = abs;
sendAndApply(&sss);
if(which == SecondarySkill::WISDOM)
{
if(hero && hero->visitedTown)
giveSpells(hero->visitedTown, hero);
}
}
void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
{
LOG_TRACE(logGlobal);
//Fill BattleResult structure with exp info
giveExp(*battleResult.data);
if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
{
if (hero1)
battleResult.data->exp[1] += 500;
if (hero2)
battleResult.data->exp[0] += 500;
}
if (hero1)
battleResult.data->exp[0] = hero1->calculateXp(battleResult.data->exp[0]);//scholar skill
if (hero2)
battleResult.data->exp[1] = hero2->calculateXp(battleResult.data->exp[1]);
const CArmedInstance *bEndArmy1 = gs->curB->sides.at(0).armyObject;
const CArmedInstance *bEndArmy2 = gs->curB->sides.at(1).armyObject;
const BattleResult::EResult result = battleResult.get()->result;
auto findBattleQuery = [this] () -> shared_ptr<CBattleQuery>
{
for(auto &q : queries.allQueries())
{
if(auto bq = std::dynamic_pointer_cast<CBattleQuery>(q))
if(bq->bi == gs->curB)
return bq;
}
return shared_ptr<CBattleQuery>();
};
auto battleQuery = findBattleQuery();
if(!battleQuery)
{
logGlobal->errorStream() << "Cannot find battle query!";
if(gs->initialOpts->mode == StartInfo::DUEL)
{
battleQuery = make_shared<CBattleQuery>(gs->curB);
}
}
if(battleQuery != queries.topQuery(gs->curB->sides[0].color))
complain("Player " + boost::lexical_cast<std::string>(gs->curB->sides[0].color) + " although in battle has no battle query at the top!");
battleQuery->result = *battleResult.data;
//Check how many battle queries were created (number of players blocked by battle)
const int queriedPlayers = battleQuery ? boost::count(queries.allQueries(), battleQuery) : 0;
finishingBattle = make_unique<FinishingBattleHelper>(battleQuery, gs->initialOpts->mode == StartInfo::DUEL, queriedPlayers);
CasualtiesAfterBattle cab1(bEndArmy1, gs->curB), cab2(bEndArmy2, gs->curB); //calculate casualties before deleting battle
if(finishingBattle->duel)
{
duelFinished();
sendAndApply(battleResult.data); //after this point casualties objects are destroyed
return;
}
ChangeSpells cs; //for Eagle Eye
if(finishingBattle->winnerHero)
{
if(int eagleEyeLevel = finishingBattle->winnerHero->getSecSkillLevel(SecondarySkill::EAGLE_EYE))
{
int maxLevel = eagleEyeLevel + 1;
double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::EAGLE_EYE);
for(const CSpell *sp : gs->curB->sides.at(!battleResult.data->winner).usedSpellsHistory)
if(sp->level <= maxLevel && !vstd::contains(finishingBattle->winnerHero->spells, sp->id) && gs->getRandomGenerator().nextInt(99) < eagleEyeChance)
cs.spells.insert(sp->id);
}
}
std::vector<ui32> arts; //display them in window
if (result == BattleResult::NORMAL && finishingBattle->winnerHero)
{
if (finishingBattle->loserHero)
{
auto artifactsWorn = finishingBattle->loserHero->artifactsWorn; //TODO: wrap it into a function, somehow (boost::variant -_-)
for (auto artSlot : artifactsWorn)
{
MoveArtifact ma;
ma.src = ArtifactLocation (finishingBattle->loserHero, artSlot.first);
const CArtifactInstance * art = ma.src.getArt();
if (art && !art->artType->isBig() && art->artType->id != ArtifactID::SPELLBOOK) // don't move war machines or locked arts (spellbook)
{
arts.push_back (art->artType->id);
ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero));
sendAndApply(&ma);
}
}
while (!finishingBattle->loserHero->artifactsInBackpack.empty())
{
//we assume that no big artifacts can be found
MoveArtifact ma;
ma.src = ArtifactLocation (finishingBattle->loserHero,
ArtifactPosition(GameConstants::BACKPACK_START)); //backpack automatically shifts arts to beginning
const CArtifactInstance * art = ma.src.getArt();
arts.push_back (art->artType->id);
ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero));
sendAndApply(&ma);
}
if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
{
artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
for (auto artSlot : artifactsWorn)
{
MoveArtifact ma;
ma.src = ArtifactLocation (finishingBattle->loserHero->commander.get(), artSlot.first);
const CArtifactInstance * art = ma.src.getArt();
if (art && !art->artType->isBig())
{
arts.push_back (art->artType->id);
ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero));
sendAndApply(&ma);
}
}
}
}
for (auto armySlot : gs->curB->battleGetArmyObject(!battleResult.data->winner)->stacks)
{
auto artifactsWorn = armySlot.second->artifactsWorn;
for (auto artSlot : artifactsWorn)
{
MoveArtifact ma;
ma.src = ArtifactLocation (armySlot.second, artSlot.first);
const CArtifactInstance * art = ma.src.getArt();
if (art && !art->artType->isBig())
{
arts.push_back (art->artType->id);
ma.dst = ArtifactLocation (finishingBattle->winnerHero, art->firstAvailableSlot(finishingBattle->winnerHero));
sendAndApply(&ma);
}
}
}
}
sendAndApply(battleResult.data); //after this point casualties objects are destroyed
if (arts.size()) //display loot
{
InfoWindow iw;
iw.player = finishingBattle->winnerHero->tempOwner;
iw.text.addTxt (MetaString::GENERAL_TXT, 30); //You have captured enemy artifact
for (auto id : arts) //TODO; separate function to display loot for various ojects?
{
iw.components.push_back (Component (Component::ARTIFACT, id, 0, 0));
if(iw.components.size() >= 14)
{
sendAndApply(&iw);
iw.components.clear();
}
}
if (iw.components.size())
{
sendAndApply(&iw);
}
}
//Eagle Eye secondary skill handling
if(!cs.spells.empty())
{
cs.learn = 1;
cs.hid = finishingBattle->winnerHero->id;
InfoWindow iw;
iw.player = finishingBattle->winnerHero->tempOwner;
iw.text.addTxt(MetaString::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
iw.text.addReplacement(finishingBattle->winnerHero->name);
std::ostringstream names;
for(int i = 0; i < cs.spells.size(); i++)
{
names << "%s";
if(i < cs.spells.size() - 2)
names << ", ";
else if(i < cs.spells.size() - 1)
names << "%s";
}
names << ".";
iw.text.addReplacement(names.str());
auto it = cs.spells.begin();
for(int i = 0; i < cs.spells.size(); i++, it++)
{
iw.text.addReplacement(MetaString::SPELL_NAME, it->toEnum());
if(i == cs.spells.size() - 2) //we just added pre-last name
iw.text.addReplacement(MetaString::GENERAL_TXT, 141); // " and "
iw.components.push_back(Component(Component::SPELL, *it, 0, 0));
}
sendAndApply(&iw);
sendAndApply(&cs);
}
cab1.takeFromArmy(this);
cab2.takeFromArmy(this); //take casualties after battle is deleted
//if one hero has lost we will erase him
if(battleResult.data->winner!=0 && hero1)
{
RemoveObject ro(hero1->id);
sendAndApply(&ro);
}
if(battleResult.data->winner!=1 && hero2)
{
RemoveObject ro(hero2->id);
sendAndApply(&ro);
}
//give exp
if (battleResult.data->exp[0] && hero1 && battleResult.get()->winner == 0)
changePrimSkill(hero1, PrimarySkill::EXPERIENCE, battleResult.data->exp[0]);
else if (battleResult.data->exp[1] && hero2 && battleResult.get()->winner == 1)
changePrimSkill(hero2, PrimarySkill::EXPERIENCE, battleResult.data->exp[1]);
queries.popIfTop(battleQuery);
//--> continuation (battleAfterLevelUp) occurs after level-up queries are handled or on removing query (above)
}
void CGameHandler::battleAfterLevelUp( const BattleResult &result )
{
LOG_TRACE(logGlobal);
finishingBattle->remainingBattleQueriesCount--;
logGlobal->traceStream() << "Decremented queries count to " << finishingBattle->remainingBattleQueriesCount;
if(finishingBattle->remainingBattleQueriesCount > 0)
//Battle results will be handled when all battle queries are closed
return;
//TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
// but the battle consequences are applied after final player is unblocked. Hard to abuse...
// Still, it looks like a hole.
// Necromancy if applicable.
const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
// Give raised units to winner and show dialog, if any were raised,
// units will be given after casualties are taken
const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
if (necroSlot != SlotID())
{
finishingBattle->winnerHero->showNecromancyDialog(raisedStack);
addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
}
BattleResultsApplied resultsApplied;
resultsApplied.player1 = finishingBattle->victor;
resultsApplied.player2 = finishingBattle->loser;
sendAndApply(&resultsApplied);
setBattle(nullptr);
if(visitObjectAfterVictory && result.winner==0)
{
logGlobal->traceStream() << "post-victory visit";
visitObjectOnTile(*getTile(finishingBattle->winnerHero->getPosition()), finishingBattle->winnerHero);
}
visitObjectAfterVictory = false;
//handle victory/loss of engaged players
std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
checkVictoryLossConditions(playerColors);
if(result.result == BattleResult::SURRENDER || result.result == BattleResult::ESCAPE) //loser has escaped or surrendered
{
SetAvailableHeroes sah;
sah.player = finishingBattle->loser;
sah.hid[0] = finishingBattle->loserHero->subID;
if(result.result == BattleResult::ESCAPE) //retreat
{
sah.army[0].clear();
sah.army[0].setCreature(SlotID(0), finishingBattle->loserHero->type->initialArmy.at(0).creature, 1);
}
if(const CGHeroInstance *another = getPlayer(finishingBattle->loser)->availableHeroes.at(1))
sah.hid[1] = another->subID;
else
sah.hid[1] = -1;
sendAndApply(&sah);
}
}
void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex)
{
bat.bsa.clear();
bat.stackAttacking = att->ID;
const int attackerLuck = att->LuckVal();
auto sideHeroBlocksLuck = [](const SideInBattle &side){ return NBonus::hasOfType(side.hero, Bonus::BLOCK_LUCK); };
if(!vstd::contains_if(gs->curB->sides, sideHeroBlocksLuck))
{
if(attackerLuck > 0 && gs->getRandomGenerator().nextInt(23) < attackerLuck)
{
bat.flags |= BattleAttack::LUCKY;
}
if (VLC->modh->settings.data["hardcodedFeatures"]["NEGATIVE_LUCK"].Bool()) // negative luck enabled
{
if (attackerLuck < 0 && gs->getRandomGenerator().nextInt(23) < abs(attackerLuck))
{
bat.flags |= BattleAttack::UNLUCKY;
}
}
}
if(gs->getRandomGenerator().nextInt(99) < att->valOfBonuses(Bonus::DOUBLE_DAMAGE_CHANCE))
{
bat.flags |= BattleAttack::DEATH_BLOW;
}
if(att->getCreature()->idNumber == CreatureID::BALLISTA)
{
static const int artilleryLvlToChance[] = {0, 50, 75, 100};
const CGHeroInstance * owner = gs->curB->getHero(att->owner);
int chance = artilleryLvlToChance[owner->getSecSkillLevel(SecondarySkill::ARTILLERY)];
if(chance > gs->getRandomGenerator().nextInt(99))
{
bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
}
}
// only primary target
applyBattleEffects(bat, att, def, distance, false);
if (!bat.shot()) //multiple-hex attack - only in meele
{
std::set<const CStack*> attackedCreatures = gs->curB->getAttackedCreatures(att, targetHex); //creatures other than primary target
for(const CStack * stack : attackedCreatures)
{
if (stack != def) //do not hit same stack twice
{
applyBattleEffects(bat, att, stack, distance, true);
}
}
}
const Bonus * bonus = att->getBonusLocalFirst(Selector::type(Bonus::SPELL_LIKE_ATTACK));
if (bonus && (bat.shot())) //TODO: make it work in melee?
{
//this is need for displaying hit animation
bat.flags |= BattleAttack::SPELL_LIKE;
bat.spellID = SpellID(bonus->subtype);
//TODO: should spell override creature`s projectile?
std::set<const CStack*> attackedCreatures = SpellID(bonus->subtype).toSpell()->getAffectedStacks(gs->curB, ECastingMode::SPELL_LIKE_ATTACK, att->owner, bonus->val, targetHex);
//TODO: get exact attacked hex for defender
for(const CStack * stack : attackedCreatures)
{
if (stack != def) //do not hit same stack twice
{
applyBattleEffects(bat, att, stack, distance, true);
}
}
//now add effect info for all attacked stacks
for(BattleStackAttacked & bsa : bat.bsa)
{
if(bsa.attackerID == att->ID) //this is our attack and not f.e. fire shield
{
//this is need for displaying affect animation
bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
bsa.spellID = SpellID(bonus->subtype);
}
}
}
}
void CGameHandler::applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary) //helper function for prepareAttack
{
BattleStackAttacked bsa;
if (secondary)
bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
bsa.attackerID = att->ID;
bsa.stackAttacked = def->ID;
bsa.damageAmount = gs->curB->calculateDmg(att, def, gs->curB->battleGetOwner(att), gs->curB->battleGetOwner(def),
bat.shot(), distance, bat.lucky(), bat.unlucky(), bat.deathBlow(), bat.ballistaDoubleDmg(), gs->getRandomGenerator());
def->prepareAttacked(bsa, gs->getRandomGenerator()); //calculate casualties
//life drain handling
if (att->hasBonusOfType(Bonus::LIFE_DRAIN) && def->isLiving())
{
StacksHealedOrResurrected shi;
shi.lifeDrain = (ui8)true;
shi.tentHealing = (ui8)false;
shi.drainedFrom = def->ID;
StacksHealedOrResurrected::HealInfo hi;
hi.stackID = att->ID;
hi.healedHP = std::min<int> (bsa.damageAmount * att->valOfBonuses (Bonus::LIFE_DRAIN) / 100,
att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
hi.lowLevelResurrection = false;
shi.healedStacks.push_back(hi);
if (hi.healedHP > 0)
{
bsa.healedStacks.push_back(shi);
}
}
bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
//fire shield handling
if(!bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !att->hasBonusOfType (Bonus::FIRE_IMMUNITY))
{
BattleStackAttacked bsa2;
bsa2.stackAttacked = att->ID; //invert
bsa2.attackerID = def->ID;
bsa2.flags |= BattleStackAttacked::EFFECT; //FIXME: play animation upon efreet and not attacker
bsa2.effect = 11;
bsa2.damageAmount = (bsa.damageAmount * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100; //TODO: scale with attack/defense
att->prepareAttacked(bsa2, gameState()->getRandomGenerator());
bat.bsa.push_back(bsa2);
}
}
void CGameHandler::handleConnection(std::set<PlayerColor> players, CConnection &c)
{
setThreadName("CGameHandler::handleConnection");
try
{
while(1)//server should never shut connection first //was: while(!end2)
{
CPack *pack = nullptr;
PlayerColor player = PlayerColor::NEUTRAL;
si32 requestID = -999;
int packType = 0;
{
boost::unique_lock<boost::mutex> lock(*c.rmx);
c >> player >> requestID >> pack; //get the package
if(!pack)
{
logGlobal ->errorStream() << boost::format("Received a null package marked as request %d from player %d") % requestID % player;
}
packType = typeList.getTypeID(pack); //get the id of type
logGlobal->traceStream() << boost::format("Received client message (request %d by player %d) of type with ID=%d (%s).\n")
% requestID % player.getNum() % packType % typeid(*pack).name();
}
//prepare struct informing that action was applied
auto sendPackageResponse = [&](bool succesfullyApplied)
{
PackageApplied applied;
applied.player = player;
applied.result = succesfullyApplied;
applied.packType = packType;
applied.requestID = requestID;
boost::unique_lock<boost::mutex> lock(*c.wmx);
c << &applied;
};
CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
if(isBlockedByQueries(pack, player))
{
sendPackageResponse(false);
}
else if(apply)
{
const bool result = apply->applyOnGH(this,&c,pack, player);
if(!result)
complain("Got false in applying... that request must have been fishy!");
logGlobal->traceStream() << "Message successfully applied (result=" << result << ")!";
sendPackageResponse(true);
}
else
{
logGlobal->errorStream() << "Message cannot be applied, cannot find applier (unregistered type)!";
sendPackageResponse(false);
}
vstd::clear_pointer(pack);
}
}
catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
{
assert(!c.connected); //make sure that connection has been marked as broken
logGlobal->errorStream() << e.what();
end2 = true;
}
catch(...)
{
end2 = true;
handleException();
throw;
}
logGlobal->errorStream() << "Ended handling connection";
}
int CGameHandler::moveStack(int stack, BattleHex dest)
{
int ret = 0;
const CStack *curStack = gs->curB->battleGetStackByID(stack),
*stackAtEnd = gs->curB->battleGetStackByPos(dest);
assert(curStack);
assert(dest < GameConstants::BFIELD_SIZE);
if (gs->curB->tacticDistance)
{
assert(gs->curB->isInTacticRange(dest));
}
if(curStack->position == dest)
return 0;
//initing necessary tables
auto accessibility = getAccesibility(curStack);
//shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
{
if(curStack->attackerOwned)
{
if(accessibility.accessible(dest+1, curStack))
dest += BattleHex::RIGHT;
}
else
{
if(accessibility.accessible(dest-1, curStack))
dest += BattleHex::LEFT;
}
}
if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
{
complain("Given destination is not accessible!");
return 0;
}
std::pair< std::vector<BattleHex>, int > path = gs->curB->getPath(curStack->position, dest, curStack);