Repository navigation
Expand file tree
/
Copy pathCPlayerInterface.cpp
More file actions
2721 lines (2343 loc) · 90.6 KB
/
Copy pathCPlayerInterface.cpp
File metadata and controls
2721 lines (2343 loc) · 90.6 KB
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 "windows/CAdvmapInterface.h"
#include "battle/CBattleInterface.h"
#include "battle/CBattleInterfaceClasses.h"
#include "../CCallback.h"
#include "windows/CCastleInterface.h"
#include "gui/CCursorHandler.h"
#include "windows/CKingdomInterface.h"
#include "CGameInfo.h"
#include "windows/CHeroWindow.h"
#include "windows/CCreatureWindow.h"
#include "windows/CQuestLog.h"
#include "CMessage.h"
#include "CPlayerInterface.h"
#include "gui/SDL_Extensions.h"
#include "widgets/CComponent.h"
#include "windows/CTradeWindow.h"
#include "../lib/CConfigHandler.h"
#include "battle/CCreatureAnimation.h"
#include "Graphics.h"
#include "windows/GUIClasses.h"
#include "../lib/CArtHandler.h"
#include "../lib/CGeneralTextHandler.h"
#include "../lib/CHeroHandler.h"
#include "../lib/Connection.h"
#include "../lib/spells/CSpellHandler.h"
#include "../lib/CTownHandler.h"
#include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
#include "../lib/BattleState.h"
#include "../lib/JsonNode.h"
#include "CMusicHandler.h"
#include "../lib/CondSh.h"
#include "../lib/NetPacks.h"
#include "../lib/mapping/CMap.h"
#include "../lib/VCMIDirs.h"
#include "mapHandler.h"
#include "../lib/CStopWatch.h"
#include "../lib/StartInfo.h"
#include "../lib/CGameState.h"
#include "../lib/GameConstants.h"
#include "gui/CGuiHandler.h"
#include "windows/InfoWindows.h"
#include "../lib/UnlockGuard.h"
#include <SDL.h>
/*
* CPlayerInterface.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
*
*/
// The macro below is used to mark functions that are called by client when game state changes.
// They all assume that CPlayerInterface::pim mutex is locked.
#define EVENT_HANDLER_CALLED_BY_CLIENT
// The macro marks functions that are run on a new thread by client.
// They do not own any mutexes intiially.
#define THREAD_CREATED_BY_CLIENT
#define RETURN_IF_QUICK_COMBAT \
if(isAutoFightOn && !battleInt) \
return;
#define BATTLE_EVENT_POSSIBLE_RETURN\
if(LOCPLINT != this) \
return; \
RETURN_IF_QUICK_COMBAT
using namespace CSDL_Ext;
void processCommand(const std::string &message, CClient *&client);
extern std::queue<SDL_Event> events;
extern boost::mutex eventsM;
boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
CPlayerInterface * LOCPLINT;
CBattleInterface * CPlayerInterface::battleInt;
enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
CondSh<EMoveState> stillMoveHero; //used during hero movement
int CPlayerInterface::howManyPeople = 0;
static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
{
return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
}
CPlayerInterface::CPlayerInterface(PlayerColor Player)
{
logGlobal->traceStream() << "\tHuman player interface for player " << Player << " being constructed";
destinationTeleport = ObjectInstanceID();
observerInDuelMode = false;
howManyPeople++;
GH.defActionsDef = 0;
LOCPLINT = this;
curAction = nullptr;
playerID=Player;
human=true;
currentSelection = nullptr;
castleInt = nullptr;
battleInt = nullptr;
//pim = new boost::recursive_mutex;
makingTurn = false;
showingDialog = new CondSh<bool>(false);
cingconsole = new CInGameConsole;
GH.terminate_cond.set(false);
firstCall = 1; //if loading will be overwritten in serialize
autosaveCount = 0;
isAutoFightOn = false;
duringMovement = false;
ignoreEvents = false;
}
CPlayerInterface::~CPlayerInterface()
{
logGlobal->traceStream() << "\tHuman player interface for player " << playerID << " being destructed";
//howManyPeople--;
//delete pim;
//vstd::clear_pointer(pim);
delete showingDialog;
delete cingconsole;
if(LOCPLINT == this)
LOCPLINT = nullptr;
}
void CPlayerInterface::init(shared_ptr<CCallback> CB)
{
cb = CB;
if(observerInDuelMode)
return;
if(!towns.size() && !wanderingHeroes.size())
initializeHeroTownList();
// always recreate advmap interface to avoid possible memory-corruption bugs
if(adventureInt)
delete adventureInt;
adventureInt = new CAdvMapInt();
}
void CPlayerInterface::yourTurn()
{
EVENT_HANDLER_CALLED_BY_CLIENT;
{
boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
LOCPLINT = this;
GH.curInt = this;
adventureInt->selection = nullptr;
if(firstCall)
{
if(howManyPeople == 1)
adventureInt->setPlayer(playerID);
autosaveCount = getLastIndex("Autosave_");
if(firstCall > 0) //new game, not loaded
{
int index = getLastIndex("Newgame_Autosave_");
index %= SAVES_COUNT;
cb->save("Saves/Newgame_Autosave_" + boost::lexical_cast<std::string>(index + 1));
}
firstCall = 0;
}
else
{
LOCPLINT->cb->save("Saves/Autosave_" + boost::lexical_cast<std::string>(autosaveCount++ + 1));
autosaveCount %= 5;
}
if(adventureInt->player != playerID)
adventureInt->setPlayer(playerID);
if(howManyPeople > 1) //hot seat message
{
adventureInt->startHotSeatWait(playerID);
makingTurn = true;
std::string msg = CGI->generaltexth->allTexts[13];
boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
std::vector<CComponent*> cmp;
cmp.push_back(new CComponent(CComponent::flag, playerID.getNum(), 0));
showInfoDialog(msg, cmp);
}
else
{
makingTurn = true;
adventureInt->startTurn();
}
}
acceptTurn();
}
STRONG_INLINE void subRect(const int & x, const int & y, const int & z, const SDL_Rect & r, const ObjectInstanceID & hid)
{
TerrainTile2 & hlp = CGI->mh->ttiles[x][y][z];
for(auto & elem : hlp.objects)
if(elem.obj && elem.obj->id == hid)
{
elem.rect = r;
return;
}
}
STRONG_INLINE void delObjRect(const int & x, const int & y, const int & z, const ObjectInstanceID & hid)
{
TerrainTile2 & hlp = CGI->mh->ttiles[x][y][z];
for(int h=0; h<hlp.objects.size(); ++h)
if(hlp.objects[h].obj && hlp.objects[h].obj->id == hid)
{
hlp.objects.erase(hlp.objects.begin()+h);
return;
}
}
void CPlayerInterface::heroMoved(const TryMoveHero & details)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
waitWhileDialog();
if(LOCPLINT != this)
return;
const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
int3 hp = details.start;
if(!hero)
{
//AI hero left the visible area (we can't obtain info)
//TODO very evil workaround -> retrieve pointer to hero so we could animate it
// TODO -> we should not need full CGHeroInstance structure to display animation or it should not be handled by playerint (but by the client itself)
const TerrainTile2 &tile = CGI->mh->ttiles[hp.x-1][hp.y][hp.z];
for(auto & elem : tile.objects)
if(elem.obj && elem.obj->id == details.id)
hero = dynamic_cast<const CGHeroInstance *>(elem.obj);
if(!hero) //still nothing...
return;
}
bool directlyAttackingCreature =
details.attackedFrom
&& adventureInt->terrain.currentPath //in case if movement has been canceled in the meantime and path was already erased
&& adventureInt->terrain.currentPath->nodes.size() == 3;//FIXME should be 2 but works nevertheless...
if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
{
//We may need to change music - select new track, music handler will change it if needed
CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(hero->visitablePos())->terType, true);
if(details.result == TryMoveHero::TELEPORTATION)
{
if(adventureInt->terrain.currentPath)
{
assert(adventureInt->terrain.currentPath->nodes.size() >= 2);
std::vector<CGPathNode>::const_iterator nodesIt = adventureInt->terrain.currentPath->nodes.end() - 1;
if((nodesIt)->coord == CGHeroInstance::convertPosition(details.start, false)
&& (nodesIt-1)->coord == CGHeroInstance::convertPosition(details.end, false))
{
//path was between entrance and exit of teleport -> OK, erase node as usual
removeLastNodeFromPath(hero);
}
else
{
//teleport was not along current path, it'll now be invalid (hero is somewhere else)
eraseCurrentPathOf(hero);
}
}
adventureInt->centerOn(hero, true); //actualizing screen pos
adventureInt->minimap.redraw();
adventureInt->heroList.update(hero);
return; //teleport - no fancy moving animation
//TODO: smooth disappear / appear effect
}
if (hero->pos != details.end //hero didn't change tile but visit succeeded
|| directlyAttackingCreature) // or creature was attacked from endangering tile.
{
eraseCurrentPathOf(hero, false);
}
else if(adventureInt->terrain.currentPath && hero->pos == details.end) //&& hero is moving
{
if(details.start != details.end) //so we don't touch path when revisiting with spacebar
removeLastNodeFromPath(hero);
}
}
if (details.result != TryMoveHero::SUCCESS) //hero failed to move
{
hero->isStanding = true;
stillMoveHero.setn(STOP_MOVE);
GH.totalRedraw();
adventureInt->heroList.update(hero);
return;
}
ui32 speed;
if (makingTurn) // our turn, our hero moves
speed = settings["adventure"]["heroSpeed"].Float();
else
speed = settings["adventure"]["enemySpeed"].Float();
if (speed == 0)
{
//FIXME: is this a proper solution?
CGI->mh->hideObject(hero);
CGI->mh->printObject(hero);
return; // no animation
}
adventureInt->centerOn(hero); //actualizing screen pos
adventureInt->minimap.redraw();
adventureInt->heroList.redraw();
initMovement(details, hero, hp);
//first initializing done
GH.mainFPSmng->framerateDelay(); // after first move
//main moving
for(int i=1; i<32; i+=2*speed)
{
movementPxStep(details, i, hp, hero);
adventureInt->updateScreen = true;
adventureInt->show(screen);
{
//evil returns here ...
//todo: get rid of it
logGlobal->traceStream() << "before [un]locks in " << __FUNCTION__;
auto unlockPim = vstd::makeUnlockGuard(*pim); //let frame to be rendered
GH.mainFPSmng->framerateDelay(); //for animation purposes
logGlobal->traceStream() << "after [un]locks in " << __FUNCTION__;
}
//CSDL_Ext::update(screen);
} //for(int i=1; i<32; i+=4)
//main moving done
//finishing move
finishMovement(details, hp, hero);
hero->isStanding = true;
//move finished
adventureInt->minimap.redraw();
adventureInt->heroList.update(hero);
//check if user cancelled movement
{
boost::unique_lock<boost::mutex> un(eventsM);
while(!events.empty())
{
SDL_Event ev = events.front();
events.pop();
switch(ev.type)
{
case SDL_MOUSEBUTTONDOWN:
stillMoveHero.setn(STOP_MOVE);
break;
case SDL_KEYDOWN:
if(ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
stillMoveHero.setn(STOP_MOVE);
break;
}
}
}
if(stillMoveHero.get() == WAITING_MOVE)
stillMoveHero.setn(DURING_MOVE);
// Hero attacked creature directly, set direction to face it.
if (directlyAttackingCreature) {
// Get direction to attacker.
int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
static const ui8 dirLookup[3][3] = {
{ 1, 2, 3 },
{ 8, 0, 4 },
{ 7, 6, 5 }
};
// FIXME: Avoid const_cast, make moveDir mutable in some other way?
const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
}
}
void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->name % playerID);
const CArmedInstance *newSelection = nullptr;
if (makingTurn)
{
//find new object for selection: either hero
int next = adventureInt->getNextHeroIndex(vstd::find_pos(wanderingHeroes, hero));
if (next >= 0)
newSelection = wanderingHeroes[next];
//or town
if (!newSelection || newSelection == hero)
{
if (towns.empty())
newSelection = nullptr;
else
newSelection = towns.front();
}
}
wanderingHeroes -= hero;
if(vstd::contains(paths, hero))
paths.erase(hero);
adventureInt->heroList.update(hero);
if (makingTurn && newSelection)
adventureInt->select(newSelection, true);
else if(adventureInt->selection == hero)
adventureInt->selection = nullptr;
}
void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
wanderingHeroes.push_back(hero);
adventureInt->heroList.update(hero);
}
void CPlayerInterface::openTownWindow(const CGTownInstance * town)
{
if (castleInt)
castleInt->close();
castleInt = new CCastleInterface(town);
GH.pushInt(castleInt);
}
int3 CPlayerInterface::repairScreenPos(int3 pos)
{
if(pos.x<-CGI->mh->frameW)
pos.x = -CGI->mh->frameW;
if(pos.y<-CGI->mh->frameH)
pos.y = -CGI->mh->frameH;
if(pos.x>CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW)
pos.x = CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW;
if(pos.y>CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH)
pos.y = CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH;
return pos;
}
void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(which == 4)
{
if(CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt()))
ctw->setExpToLevel();
}
else if(which < GameConstants::PRIMARY_SKILLS) //no need to redraw infowin if this is experience (exp is treated as prim skill with id==4)
updateInfo(hero);
}
void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt());
if(cuw) //university window is open
{
GH.totalRedraw();
}
}
void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
updateInfo(hero);
if(makingTurn && hero->tempOwner == playerID)
adventureInt->heroList.update(hero);
}
void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(makingTurn && hero->tempOwner == playerID)
adventureInt->heroList.update(hero);
}
void CPlayerInterface::receivedResource(int type, int val)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt()))
mw->resourceChanged(type, val);
GH.totalRedraw();
}
void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
waitWhileDialog();
CCS->soundh->playSound(soundBase::heroNewLevel);
CLevelWindow *lw = new CLevelWindow(hero,pskill,skills,
[=](ui32 selection){ cb->selectionMade(selection, queryID); });
GH.pushInt(lw);
}
void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
waitWhileDialog();
CCS->soundh->playSound(soundBase::heroNewLevel);
GH.pushInt(new CStackWindow(commander, skills, [=](ui32 selection)
{
cb->selectionMade(selection, queryID);
}));
}
void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
updateInfo(town);
if(town->garrisonHero && vstd::contains(wanderingHeroes,town->garrisonHero)) //wandering hero moved to the garrison
{
CGI->mh->hideObject(town->garrisonHero);
if (town->garrisonHero->tempOwner == playerID) // our hero
wanderingHeroes -= town->garrisonHero;
}
if(town->visitingHero && !vstd::contains(wanderingHeroes,town->visitingHero)) //hero leaves garrison
{
CGI->mh->printObject(town->visitingHero);
if (town->visitingHero->tempOwner == playerID) // our hero
wanderingHeroes.push_back(town->visitingHero);
}
adventureInt->heroList.update();
adventureInt->updateNextHero(nullptr);
if(CCastleInterface *c = castleInt)
{
c->garr->selectSlot(nullptr);
c->garr->setArmy(town->getUpperArmy(), 0);
c->garr->setArmy(town->visitingHero, 1);
c->garr->recreateSlots();
c->heroes->update();
}
for(IShowActivatable *isa : GH.listInt)
{
CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa);
if (ki)
{
ki->townChanged(town);
ki->updateGarrisons();
}
}
GH.totalRedraw();
}
void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(hero->tempOwner != playerID )
return;
waitWhileDialog();
openTownWindow(town);
}
void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
{
boost::unique_lock<boost::recursive_mutex> un(*pim);
for(auto object : objs)
updateInfo(object);
for(auto & elem : GH.listInt)
{
CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem);
if (cgh)
cgh->updateGarrisons();
if(CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem))
{
if(vstd::contains(objs, cmw->hero))
cmw->garrisonChanged();
}
}
GH.totalRedraw();
}
void CPlayerInterface::garrisonChanged( const CGObjectInstance * obj)
{
garrisonsChanged(std::vector<const CGObjectInstance *>(1, obj));
}
void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
{
EVENT_HANDLER_CALLED_BY_CLIENT;
switch (buildingID)
{
case BuildingID::FORT: case BuildingID::CITADEL: case BuildingID::CASTLE:
case BuildingID::VILLAGE_HALL: case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: case BuildingID::CAPITOL:
case BuildingID::RESOURCE_SILO:
updateInfo(town);
break;
}
if(!castleInt)
return;
if(castleInt->town!=town)
return;
switch(what)
{
case 1:
CCS->soundh->playSound(soundBase::newBuilding);
castleInt->addBuilding(buildingID);
break;
case 2:
castleInt->removeBuilding(buildingID);
break;
}
adventureInt->townList.update(town);
castleInt->townlist->update(town);
}
void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
{
//Don't wait for dialogs when we are non-active hot-seat player
if(LOCPLINT == this)
waitForAllDialogs();
}
void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(settings["adventure"]["quickCombat"].Bool())
{
autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String());
autofightingAI->init(cb);
autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
isAutoFightOn = true;
cb->registerBattleInterface(autofightingAI);
}
//Don't wait for dialogs when we are non-active hot-seat player
if(LOCPLINT == this)
waitForAllDialogs();
BATTLE_EVENT_POSSIBLE_RETURN;
}
void CPlayerInterface::battleStacksHealedRes(const std::vector<std::pair<ui32, ui32> > & healedStacks, bool lifeDrain, bool tentHeal, si32 lifeDrainFrom)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
for(auto & healedStack : healedStacks)
{
const CStack * healed = cb->battleGetStackByID(healedStack.first);
if(battleInt->creAnims[healed->ID]->isDead())
{
//stack has been resurrected
battleInt->creAnims[healed->ID]->setType(CCreatureAnim::HOLDING);
}
}
if (lifeDrain)
{
const CStack *attacker = cb->battleGetStackByID(healedStacks[0].first, false);
const CStack *defender = cb->battleGetStackByID(lifeDrainFrom, false);
int textOff = 0;
if (attacker)
{
battleInt->displayEffect(52, attacker->position); //TODO: transparency
if (attacker->count > 1)
{
textOff += 1;
}
CCS->soundh->playSound(soundBase::DRAINLIF);
//print info about life drain
auto txt = boost::format (CGI->generaltexth->allTexts[361 + textOff]) % attacker->getCreature()->nameSing % healedStacks[0].second % defender->getCreature()->namePl;
battleInt->console->addText(boost::to_string(txt));
}
}
if (tentHeal)
{
std::string text = CGI->generaltexth->allTexts[414];
boost::algorithm::replace_first(text, "%s", cb->battleGetStackByID(lifeDrainFrom, false)->getCreature()->nameSing);
boost::algorithm::replace_first(text, "%s", cb->battleGetStackByID(healedStacks[0].first, false)->getCreature()->nameSing);
boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(healedStacks[0].second));
battleInt->console->addText(text);
}
}
void CPlayerInterface::battleNewStackAppeared(const CStack * stack)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->newStack(stack);
}
void CPlayerInterface::battleObstaclesRemoved(const std::set<si32> & removedObstacles)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
// for(std::set<si32>::const_iterator it = removedObstacles.begin(); it != removedObstacles.end(); ++it)
// {
// for(std::map< int, CDefHandler * >::iterator itBat = battleInt->idToObstacle.begin(); itBat != battleInt->idToObstacle.end(); ++itBat)
// {
// if(itBat->first == *it) //remove this obstacle
// {
// battleInt->idToObstacle.erase(itBat);
// break;
// }
// }
// }
//update accessible hexes
battleInt->redrawBackgroundWithHexes(battleInt->activeStack);
}
void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->stackIsCatapulting(ca);
}
void CPlayerInterface::battleStacksRemoved(const BattleStacksRemoved & bsr)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
for(auto & elem : bsr.stackIDs) //for each removed stack
{
battleInt->stackRemoved(elem);
}
}
void CPlayerInterface::battleNewRound(int round) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->newRound(round);
}
void CPlayerInterface::actionStarted(const BattleAction &action)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
curAction = new BattleAction(action);
battleInt->startAction(curAction);
}
void CPlayerInterface::actionFinished(const BattleAction &action)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->endAction(curAction);
delete curAction;
curAction = nullptr;
}
BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
{
THREAD_CREATED_BY_CLIENT;
logGlobal->traceStream() << "Awaiting command for " << stack->nodeName();
if(autofightingAI)
{
if(isAutoFightOn)
{
auto ret = autofightingAI->activeStack(stack);
if(isAutoFightOn)
{
return ret;
}
}
cb->unregisterBattleInterface(autofightingAI);
autofightingAI.reset();
}
CBattleInterface *b = battleInt;
if (b->givenCommand->get())
{
logGlobal->errorStream() << "Command buffer must be clean! (we don't want to use old command)";
vstd::clear_pointer(b->givenCommand->data);
}
{
boost::unique_lock<boost::recursive_mutex> un(*pim);
b->stackActivated(stack);
//Regeneration & mana drain go there
}
//wait till BattleInterface sets its command
boost::unique_lock<boost::mutex> lock(b->givenCommand->mx);
while(!b->givenCommand->data)
{
b->givenCommand->cond.wait(lock);
if(!battleInt) //batle ended while we were waiting for movement (eg. because of spell)
throw boost::thread_interrupted(); //will shut the thread peacefully
}
//tidy up
BattleAction ret = *(b->givenCommand->data);
delete b->givenCommand->data;
b->givenCommand->data = nullptr;
//return command
logGlobal->traceStream() << "Giving command for " << stack->nodeName();
return ret;
}
void CPlayerInterface::battleEnd(const BattleResult *br)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
if(isAutoFightOn)
{
isAutoFightOn = false;
cb->unregisterBattleInterface(autofightingAI);
autofightingAI.reset();
if(!battleInt)
{
SDL_Rect temp_rect = genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
auto resWindow = new CBattleResultWindow(*br, temp_rect, *this);
GH.pushInt(resWindow);
// #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
// Otherwise NewTurn causes freeze.
waitWhileDialog();
return;
}
}
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->battleFinished(*br);
}
void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->stackMoved(stack, dest, distance);
}
void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->spellCast(sc);
}
void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->battleStacksEffectsSet(sse);
}
void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
//TODO why is this different (no return on LOPLINT != this) ?
RETURN_IF_QUICK_COMBAT;
battleInt->battleTriggerEffect(bte);
}
void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
std::vector<StackAttackedInfo> arg;
for(auto & elem : bsa)
{
const CStack *defender = cb->battleGetStackByID(elem.stackAttacked, false);
const CStack *attacker = cb->battleGetStackByID(elem.attackerID, false);
if(elem.isEffect())
{
if (defender && !elem.isSecondary())
battleInt->displayEffect(elem.effect, defender->position);
}
if(elem.isSpell())
{
if (defender)
battleInt->displaySpellEffect(elem.spellID, defender->position);
}
//FIXME: why action is deleted during enchanter cast?
bool remoteAttack = false;
if (LOCPLINT->curAction)
remoteAttack |= LOCPLINT->curAction->actionType != Battle::WALK_AND_ATTACK;
StackAttackedInfo to_put = {defender, elem.damageAmount, elem.killedAmount, attacker, remoteAttack, elem.killed(), elem.willRebirth(), elem.cloneKilled()};
arg.push_back(to_put);
}
battleInt->stacksAreAttacked(arg);
}
void CPlayerInterface::battleAttack(const BattleAttack *ba)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
assert(curAction);
if(ba->lucky()) //lucky hit
{
const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
std::string hlp = CGI->generaltexth->allTexts[45];
boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
battleInt->console->addText(hlp);
battleInt->displayEffect(18, stack->position);
CCS->soundh->playSound(soundBase::GOODLUCK);
}
if(ba->unlucky()) //unlucky hit
{
const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
std::string hlp = CGI->generaltexth->allTexts[44];
boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
battleInt->console->addText(hlp);
battleInt->displayEffect(48, stack->position);
CCS->soundh->playSound(soundBase::BADLUCK);
}
if (ba->deathBlow())
{
const CStack *stack = cb->battleGetStackByID(ba->stackAttacking);
std::string hlp = CGI->generaltexth->allTexts[(stack->count != 1) ? 366 : 365];
boost::algorithm::replace_first(hlp,"%s", (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str());
battleInt->console->addText(hlp);
for (auto & elem : ba->bsa)
{
const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
battleInt->displayEffect(73, attacked->position);
}
CCS->soundh->playSound(soundBase::deathBlow);
}
battleInt->waitForAnims();
const CStack * attacker = cb->battleGetStackByID(ba->stackAttacking);
if(ba->shot())
{
for(auto & elem : ba->bsa)
{
if (!elem.isSecondary()) //display projectile only for primary target
{
const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
battleInt->stackAttacking(attacker, attacked->position, attacked, true);
}
}
}
else
{
int shift = 0;
if(ba->counter() && BattleHex::mutualPosition(curAction->destinationTile, attacker->position) < 0)
{
int distp = BattleHex::getDistance(curAction->destinationTile + 1, attacker->position);
int distm = BattleHex::getDistance(curAction->destinationTile - 1, attacker->position);
if( distp < distm )
shift = 1;
else
shift = -1;
}
const CStack * attacked = cb->battleGetStackByID(ba->bsa.begin()->stackAttacked);
battleInt->stackAttacking( attacker, ba->counter() ? curAction->destinationTile + shift : curAction->additionalInfo, attacked, false);
}
//battleInt->waitForAnims(); //FIXME: freeze
if(ba->spellLike())
{
//display hit animation
SpellID spellID = ba->spellID;
battleInt->displaySpellHit(spellID,curAction->destinationTile);
}
}
void CPlayerInterface::battleObstaclePlaced(const CObstacleInstance &obstacle)
{
EVENT_HANDLER_CALLED_BY_CLIENT;
BATTLE_EVENT_POSSIBLE_RETURN;
battleInt->obstaclePlaced(obstacle);
}
void CPlayerInterface::yourTacticPhase(int distance)
{
THREAD_CREATED_BY_CLIENT;
while(battleInt && battleInt->tacticsMode)