-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathplayer_control.cpp
3965 lines (3779 loc) · 157 KB
/
player_control.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
/* Copyright (C) 2013-2014 Michal Brzozowski ([email protected])
This file is part of KeeperRL.
KeeperRL is free software; you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
KeeperRL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.gnu.org/licenses/ . */
#include "stdafx.h"
#include "player_control.h"
#include "level.h"
#include "task.h"
#include "model.h"
#include "statistics.h"
#include "options.h"
#include "technology.h"
#include "util.h"
#include "village_control.h"
#include "item.h"
#include "item_factory.h"
#include "creature.h"
#include "square.h"
#include "view_id.h"
#include "collective.h"
#include "effect.h"
#include "music.h"
#include "encyclopedia.h"
#include "map_memory.h"
#include "item_action.h"
#include "equipment.h"
#include "collective_teams.h"
#include "minion_equipment.h"
#include "task_map.h"
#include "construction_map.h"
#include "minion_activity_map.h"
#include "spell.h"
#include "tribe.h"
#include "visibility_map.h"
#include "creature_name.h"
#include "view.h"
#include "view_index.h"
#include "collective_attack.h"
#include "territory.h"
#include "sound.h"
#include "game.h"
#include "collective_name.h"
#include "creature_attributes.h"
#include "collective_config.h"
#include "villain_type.h"
#include "workshops.h"
#include "attack_trigger.h"
#include "view_object.h"
#include "body.h"
#include "furniture.h"
#include "furniture_type.h"
#include "furniture_factory.h"
#include "known_tiles.h"
#include "zones.h"
#include "inventory.h"
#include "immigration.h"
#include "scroll_position.h"
#include "tutorial.h"
#include "tutorial_highlight.h"
#include "container_range.h"
#include "collective_warning.h"
#include "furniture_usage.h"
#include "message_generator.h"
#include "message_buffer.h"
#include "minion_controller.h"
#include "build_info.h"
#include "vision.h"
#include "external_enemies.h"
#include "resource_info.h"
#include "workshop_item.h"
#include "time_queue.h"
#include "unknown_locations.h"
#include "furniture_click.h"
#include "campaign.h"
#include "game_event.h"
#include "view_object_action.h"
#include "storage_id.h"
#include "fx_name.h"
#include "content_factory.h"
#include "tech_id.h"
#include "pretty_printing.h"
#include "game_save_type.h"
#include "immigrant_info.h"
#include "special_trait.h"
#include "user_input.h"
#include "automaton_part.h"
#include "shortest_path.h"
#include "scripted_ui_data.h"
#include "item_types.h"
#include "furnace.h"
#include "promotion_info.h"
template <class Archive>
void PlayerControl::serialize(Archive& ar, const unsigned int version) {
ar& SUBCLASS(CollectiveControl) & SUBCLASS(EventListener);
ar(memory, introText, nextKeeperWarning, tribeAlignment);
ar(newAttacks, notifiedAttacks, messages, hints, soloKeeper);
ar(visibilityMap, unknownLocations, dismissedVillageInfos, buildInfo, battleSummary);
ar(messageHistory, tutorial, controlModeMessages, stunnedCreatures, usedResources, allianceAttack);
}
SERIALIZABLE(PlayerControl)
SERIALIZATION_CONSTRUCTOR_IMPL(PlayerControl)
using ResourceId = Collective::ResourceId;
const LocalTime hintFrequency = LocalTime(700);
static vector<TString> getHints() {
return {
TStringId("MINION_MORALE_HINT"),
// "You can turn these hints off in the settings (F2).",
TStringId("KILLING_LEADER_HINT"),
// "Your minions' morale is boosted when they are commanded by the Keeper.",
};
}
PlayerControl::PlayerControl(Private, Collective* col, TribeAlignment alignment)
: CollectiveControl(col), hints(getHints()), tribeAlignment(alignment) {
controlModeMessages = make_shared<MessageBuffer>();
visibilityMap = make_shared<VisibilityMap>();
unknownLocations = make_shared<UnknownLocations>();
memory.reset(new MapMemory());
for (auto pos : col->getModel()->getGroundLevel()->getAllPositions())
if (auto f = pos.getFurniture(FurnitureLayer::MIDDLE))
if (f->isClearFogOfWar())
addToMemory(pos);
}
PPlayerControl PlayerControl::create(Collective* col, vector<TString> introText, TribeAlignment alignment) {
auto ret = makeOwner<PlayerControl>(Private{}, col, alignment);
ret->subscribeTo(col->getModel());
ret->introText = introText;
return ret;
}
PlayerControl::~PlayerControl() {
}
static TString getPopulationIncreaseDescription(const Furniture::PopulationInfo& info, const TString& populationString) {
if (info.limit)
return TSentence("INCREASES_POP_LIMIT_BY_UP_TO", {populationString, TString(info.increase), TString(*info.limit)});
else
return TSentence("INCREASES_POP_LIMIT_BY", populationString, TString(info.increase));
}
void PlayerControl::loadBuildingMenu(const ContentFactory* contentFactory, const KeeperCreatureInfo& keeperCreatureInfo) {
for (auto& group : keeperCreatureInfo.buildingGroups)
buildInfo.append(contentFactory->buildInfo.at(group));
auto factory = getGame()->getContentFactory();
for (auto& info : buildInfo)
if (auto furniture = info.type.getReferenceMaybe<BuildInfoTypes::Furniture>()) {
usedResources.insert(furniture->cost.id);
for (auto type : furniture->types) {
double luxury = factory->furniture.getData(type).getLuxury();
if (luxury > 0) {
info.help = TSentence("COMBINE_SENTENCES", std::move(info.help),
TSentence("INCREASES_LUXURY_BY", TString(luxury)));
break;
}
}
auto increase = factory->furniture.getData(furniture->types[0]).getPopulationIncrease();
if (increase.increase > 0) {
info.help = TSentence("COMBINE_SENTENCES", std::move(info.help),
getPopulationIncreaseDescription(increase, keeperCreatureInfo.populationString));
if (increase.limit)
const_cast<optional<int>&>(furniture->limit) = int(*increase.limit / increase.increase);
}
auto& maxTraining = factory->furniture.getData(furniture->types[0]).getMaxTraining();
for (auto& elem : maxTraining)
info.help = TSentence("COMBINE_SENTENCES", std::move(info.help),
TSentence("ADDS_TRAINING_LEVELS", TString(elem.second), factory->attrInfo.at(elem.first).name));
}
}
void PlayerControl::loadImmigrationAndWorkshops(ContentFactory* contentFactory,
const KeeperCreatureInfo& keeperCreatureInfo) {
Technology technology = contentFactory->technology;
for (auto& tech : copyOf(technology.techs))
if (!keeperCreatureInfo.technology.contains(tech.first))
technology.techs.erase(tech.first);
WorkshopArray merged;
for (auto& group : keeperCreatureInfo.workshopGroups)
for (auto& elem : contentFactory->workshopGroups.at(group))
for (auto& workshopItem : elem.second)
if (!workshopItem.tech || technology.techs.count(*workshopItem.tech))
merged[elem.first].push_back(workshopItem);
collective->setWorkshops(make_unique<Workshops>(std::move(merged), contentFactory));
for (auto& workshop : collective->getWorkshops().types)
for (auto& option : workshop.second.getOptions())
usedResources.insert(option.cost.id);
vector<ImmigrantInfo> immigrants;
for (auto elem : keeperCreatureInfo.immigrantGroups)
append(immigrants, contentFactory->immigrantsData.at(elem));
for (auto& elem : immigrants)
for (auto& req : elem.requirements)
if (auto cost = req.type.getReferenceMaybe<CostInfo>())
usedResources.insert(cost->id);
CollectiveConfig::addBedRequirementToImmigrants(immigrants, contentFactory);
collective->setImmigration(makeOwner<Immigration>(collective, std::move(immigrants)));
collective->setTechnology(std::move(technology));
loadBuildingMenu(contentFactory, keeperCreatureInfo);
}
const vector<Creature*>& PlayerControl::getControlled() const {
return getGame()->getPlayerCreatures();
}
optional<TeamId> PlayerControl::getCurrentTeam() const {
for (TeamId team : getTeams().getAllActive())
if (getTeams().getLeader(team)->isPlayer())
return team;
return none;
}
void PlayerControl::onControlledKilled(Creature* victim) {
TeamId currentTeam = *getCurrentTeam();
if (getTeams().getLeader(currentTeam) == victim && getGame()->getPlayerCreatures().size() == 1) {
vector<PlayerInfo> team;
for (auto c : getTeams().getMembers(currentTeam))
if (c != victim)
team.push_back(PlayerInfo(c, getGame()->getContentFactory()));
optional<Creature::Id> newLeader;
if (team.size() == 1)
newLeader = team[0].creatureId;
else if (!team.empty())
newLeader = getView()->chooseCreature(TStringId("CHOOSE_NEW_TEAM_LEADER"), team,
TStringId("ORDER_TEAM_BACK_TO_BASE"));
if (newLeader) {
if (Creature* c = getCreature(*newLeader)) {
getTeams().setLeader(currentTeam, c);
if (!c->isPlayer())
c->pushController(createMinionController(c));
if (victim->isPlayer())
victim->popController();
return;
}
}
leaveControl();
}
if (victim->isPlayer())
victim->popController();
}
void PlayerControl::onSunlightVisibilityChanged() {
auto& f = getGame()->getContentFactory()->furniture;
for (auto type : f.getAllFurnitureType())
if (f.getData(type).isEyeball())
for (auto pos : collective->getConstructions().getBuiltPositions(type))
visibilityMap->updateEyeball(pos);
}
void PlayerControl::setTutorial(STutorial t) {
tutorial = t;
}
STutorial PlayerControl::getTutorial() const {
return tutorial;
}
bool PlayerControl::canControlSingle(const Creature* c) const {
return !collective->hasTrait(c, MinionTrait::PRISONER) && !c->isAffected(LastingEffect::TURNED_OFF);
}
bool PlayerControl::canControlInTeam(const Creature* c) const {
return (collective->hasTrait(c, MinionTrait::FIGHTER) || collective->hasTrait(c, MinionTrait::LEADER)) &&
!c->isAffected(LastingEffect::STEED);
}
void PlayerControl::addToCurrentTeam(Creature* c) {
collective->freeTeamMembers({c});
if (auto teamId = getCurrentTeam()) {
getTeams().add(*teamId, c);
if (getGame()->getPlayerCreatures().size() > 1)
c->pushController(createMinionController(c));
}
}
void PlayerControl::teamMemberAction(TeamMemberAction action, Creature::Id id) {
if (Creature* c = getCreature(id))
switch (action) {
case TeamMemberAction::MOVE_NOW:
c->getPosition().getModel()->getTimeQueue().moveNow(c);
break;
case TeamMemberAction::CHANGE_LEADER:
if (auto teamId = getCurrentTeam())
if (getTeams().getMembers(*teamId).size() > 1 && canControlInTeam(c)) {
auto controlled = getControlled();
if (controlled.size() == 1) {
getTeams().getLeader(*teamId)->popController();
getTeams().setLeader(*teamId, c);
c->pushController(createMinionController(c));
}
}
break;
case TeamMemberAction::REMOVE_MEMBER: {
auto& teams = getTeams();
if (auto teamId = getCurrentTeam())
if (teams.getMembers(*teamId).size() > 1 && teams.contains(*teamId, c)) {
teams.remove(*teamId, c);
if (c->isPlayer()) {
c->popController();
auto newLeader = teams.getLeader(*teamId);
if (!newLeader->isPlayer())
newLeader->pushController(createMinionController(newLeader));
}
}
break;
}
}
}
static ScriptedUIDataElems::Record getCreatureRecord(const ContentFactory* factory, const Creature* creature) {
auto bestAttack = creature->getBestAttack(factory);
return ScriptedUIDataElems::Record {{
{"view_id", creature->getViewObject().getViewIdList()},
{"attack_view_id", ViewIdList{bestAttack.viewId}},
{"attack_value", TString(toString(bestAttack.value))},
{"name", capitalFirst(creature->getName().aOrTitle())},
}};
}
void PlayerControl::presentMinionsFreedMessage(const vector<Creature*>& creatures) {
auto data = ScriptedUIDataElems::List{};
auto factory = getGame()->getContentFactory();
for (auto c : creatures)
data.push_back(getCreatureRecord(factory, c));
getView()->scriptedUI("prisoners_freed", data);
}
void PlayerControl::presentAndClearBattleSummary() {
auto data = ScriptedUIDataElems::Record{};
auto factory = getGame()->getContentFactory();
auto getCreatureList = [factory] (const vector<Creature*>& creatures) {
auto ret = ScriptedUIDataElems::List{};
for (auto c : creatures)
ret.push_back(getCreatureRecord(factory, c));
return ret;
};
if (!battleSummary.minionsKilled.empty())
data.elems["minions_killed"] = getCreatureList(battleSummary.minionsKilled);
if (!battleSummary.minionsCaptured.empty())
data.elems["minions_captured"] = getCreatureList(battleSummary.minionsCaptured);
if (!battleSummary.enemiesKilled.empty())
data.elems["enemies_killed"] = getCreatureList(battleSummary.enemiesKilled);
if (!battleSummary.enemiesCaptured.empty())
data.elems["enemies_captured"] = getCreatureList(battleSummary.enemiesCaptured);
if (!data.elems.empty())
getView()->scriptedUI("battle_summary", data);
battleSummary = BattleSummary {};
}
void PlayerControl::leaveControl() {
set<TeamId> allTeams;
for (auto controlled : copyOf(getControlled())) {
if (collective->hasTrait(controlled, MinionTrait::LEADER))
nextKeeperWarning = collective->getGlobalTime();
auto controlledLevel = controlled->getPosition().getLevel();
if (!!getModel()->getMainLevelDepth(controlledLevel))
setScrollPos(controlled->getPosition());
controlled->popController();
for (TeamId team : getTeams().getActive(controlled))
allTeams.insert(team);
}
for (auto team : allTeams) {
// a creature may die when landing and be removed from the team so copy the members vector
for (Creature* c : copyOf(getTeams().getMembers(team)))
// c might be dead if it was just killed which caused a crash if it was riding a steed
if (!c->isDead() && c->getPosition().getModel() != getModel() && !c->isAffected(LastingEffect::STUNNED)) {
getGame()->transferCreature(c, getModel());
if (c->isAffected(LastingEffect::RIDER))
if (auto steed = collective->getSteedOrRider(c))
c->forceMount(steed);
}
if (getTeams().getMembers(team).size() == 1)
getTeams().cancel(team);
else
getTeams().deactivate(team);
break;
}
getView()->stopClock();
presentAndClearBattleSummary();
}
void PlayerControl::render(View* view) {
PROFILE;
//collective->getConstructions().checkDebtConsistency();
if (getControlled().empty()) {
view->updateView(this, false);
}
if (firstRender) {
firstRender = false;
for (Creature* c : getCreatures())
updateMinionVisibility(c);
if (getGame()->getOptions()->getBoolValue(OptionId::CONTROLLER_HINT_REAL_TIME)) {
getView()->scriptedUI("controller_hint_real_time", ScriptedUIData{});
getGame()->getOptions()->setValue(OptionId::CONTROLLER_HINT_REAL_TIME, 0);
}
}
if (!tutorial && !introText.empty() && getGame()->getOptions()->getBoolValue(OptionId::HINTS)) {
view->updateView(this, false);
for (auto& msg : introText)
view->presentText(none, msg);
introText.clear();
}
}
void PlayerControl::addConsumableItem(Creature* creature) {
ScriptedUIState state;
while (1) {
Item* chosenItem = chooseEquipmentItem(creature, {}, [&](const Item* it) {
return !collective->getMinionEquipment().isOwner(it, creature)
&& !it->canEquip()
&& collective->getMinionEquipment().needsItem(creature, it, true); }, &state);
if (chosenItem) {
creature->removeEffect(LastingEffect::SLEEP);
CHECK(collective->getMinionEquipment().tryToOwn(creature, chosenItem));
} else
break;
}
}
void PlayerControl::addEquipment(Creature* creature, EquipmentSlot slot) {
vector<Item*> currentItems = creature->getEquipment().getSlotItems(slot);
Item* chosenItem = chooseEquipmentItem(creature, currentItems, [&](const Item* it) {
return !collective->getMinionEquipment().isOwner(it, creature)
&& creature->canEquipIfEmptySlot(it, nullptr) && it->getEquipmentSlot() == slot; });
if (chosenItem) {
if (!chosenItem->getAutoEquipPredicate().apply(creature, nullptr) &&
!getView()->yesOrNoPrompt(chosenItem->getEquipWarning()))
return;
vector<Item*> conflictingItems;
for (auto it : collective->getMinionEquipment().getItemsOwnedBy(creature))
if (it->isConflictingEquipment(chosenItem))
conflictingItems.push_back(it);
if (getView()->confirmConflictingItems(getGame()->getContentFactory(), conflictingItems)) {
if (auto creatureId = collective->getMinionEquipment().getOwner(chosenItem))
if (Creature* c = getCreature(*creatureId))
c->removeEffect(LastingEffect::SLEEP);
creature->removeEffect(LastingEffect::SLEEP);
CHECK(collective->getMinionEquipment().tryToOwn(creature, chosenItem));
}
}
}
void PlayerControl::minionEquipmentAction(const EquipmentActionInfo& action) {
if (auto creature = getCreature(action.creature))
switch (action.action) {
case ItemAction::DROP_STEED:
collective->setSteed(creature, nullptr);
break;
case ItemAction::DROP:
for (auto id : action.ids)
collective->getMinionEquipment().discard(id);
break;
case ItemAction::REPLACE_STEED:
if (auto steed = chooseSteed(creature, getCreatures().filter(
[creature](Creature* c) { return c->isAffected(LastingEffect::STEED) && creature->isSteedGoodSize(c); })))
collective->setSteed(creature, steed);
break;
case ItemAction::REPLACE:
if (action.slot)
addEquipment(creature, *action.slot);
else
addConsumableItem(creature);
break;
case ItemAction::LOCK:
/*if (action.ids.empty() && action.slot)
collective->getMinionEquipment().toggleLocked(creature, *action.slot);
else*/
for (auto id : action.ids)
collective->getMinionEquipment().toggleLocked(creature, id);
break;
default:
break;
}
}
void PlayerControl::minionAIAction(const AIActionInfo& action) {
if (auto c = getCreature(action.creature)) {
c->getAttributes().setAIType(action.switchTo);
if (action.override)
for (auto other : getMinionGroup(action.groupName))
other->getAttributes().setAIType(action.switchTo);
}
}
void PlayerControl::minionTaskAction(const TaskActionInfo& action) {
auto considerResettingActivity = [this] (Creature* c) {
if (!collective->isActivityGoodAssumingHaveTasks(c, collective->getCurrentActivity(c).activity))
collective->setMinionActivity(c, MinionActivity::IDLE);
};
if (auto c = getCreature(action.creature)) {
if (action.switchTo)
collective->setMinionActivity(c, *action.switchTo);
for (MinionActivity task : action.lock)
c->getAttributes().getMinionActivities().toggleLock(task);
collective->flipGroupLockedActivities(action.groupName, action.lockGroup);
if (!action.lock.isEmpty())
considerResettingActivity(c);
}
if (!action.lockGroup.isEmpty())
for (auto c : collective->getCreatures())
considerResettingActivity(c);
}
void PlayerControl::equipmentGroupAction(const EquipmentGroupAction& action) {
auto& groupSet = collective->lockedEquipmentGroups[action.group];
for (auto& elem : action.flip)
if (groupSet.count(elem))
groupSet.erase(elem);
else
groupSet.insert(elem);
}
static ItemInfo getItemInfo(const ContentFactory* factory, const vector<Item*>& stack, bool equiped, bool pending, bool locked,
optional<ItemInfo::Type> type = none) {
PROFILE;
return CONSTRUCT(ItemInfo,
c.name = stack[0]->getShortName(factory, nullptr, stack.size() > 1);
c.fullName = stack[0]->getNameAndModifiers(factory, false);
c.description = stack[0]->getDescription(factory);
c.number = stack.size();
if (stack[0]->canEquip())
c.slot = stack[0]->getEquipmentSlot();
c.viewId = stack[0]->getViewObject().getViewIdList();
c.ids.reserve(stack.size());
for (auto it : stack)
c.ids.push_back(it->getUniqueId());
c.actions = {ItemAction::DROP};
c.equiped = equiped;
c.locked = locked;
if (type)
c.type = *type;
c.pending = pending;
);
}
static ViewId getSlotViewId(EquipmentSlot slot) {
switch (slot) {
case EquipmentSlot::BOOTS: return ViewId("leather_boots");
case EquipmentSlot::WEAPON: return ViewId("sword");
case EquipmentSlot::RINGS: return ViewId("ring");
case EquipmentSlot::HELMET: return ViewId("leather_helm");
case EquipmentSlot::RANGED_WEAPON: return ViewId("bow");
case EquipmentSlot::GLOVES: return ViewId("leather_gloves");
case EquipmentSlot::BODY_ARMOR: return ViewId("leather_armor");
case EquipmentSlot::AMULET: return ViewId("amulet1");
case EquipmentSlot::SHIELD: return ViewId("wooden_shield");
case EquipmentSlot::PRAYER_BOOK: return ViewId("book");
case EquipmentSlot::DEVOTIONAL_ITEMS: return ViewId("devotional_medal");
}
}
static ItemInfo getEmptySlotItem(EquipmentSlot slot, bool locked) {
return CONSTRUCT(ItemInfo,
c.name = ""_s;
c.fullName = ""_s;
c.slot = slot;
c.number = 1;
c.viewId = {getSlotViewId(slot)};
c.actions = {ItemAction::REPLACE};
c.locked = locked;
c.equiped = false;
c.pending = false;);
}
static CollectiveInfo::PromotionOption getPromotionOption(const ContentFactory* factory, const PromotionInfo& info) {
return {info.viewId, info.name, info.applied.getDescription(factory)};
}
void PlayerControl::fillPromotions(Creature* creature, CollectiveInfo& info) const {
CollectiveInfo::MinionPromotionInfo promotionInfo;
promotionInfo.viewId = creature->getViewObject().getViewIdList();
promotionInfo.name = creature->getName().firstOrBare();
promotionInfo.id = creature->getUniqueId();
promotionInfo.canAdvance = creature->getPromotions().size() < creature->getAttributes().maxPromotions &&
collective->getDungeonLevel().numPromotionsAvailable() > 0;
for (auto& promotion : creature->getPromotions())
promotionInfo.promotions.push_back(getPromotionOption(getGame()->getContentFactory(), promotion));
auto contentFactory = getGame()->getContentFactory();
for (auto& promotion : contentFactory->promotions.at(*creature->getAttributes().promotionGroup))
promotionInfo.options.push_back(getPromotionOption(contentFactory, promotion));
info.minionPromotions.push_back(std::move(promotionInfo));
info.availablePromotions = int(0.001
+ double(collective->getDungeonLevel().numPromotionsAvailable()) / creature->getAttributes().promotionCost);
}
static ItemInfo getEmptySteedItemInfo(const ContentFactory* factory) {
return CONSTRUCT(ItemInfo,
c.name = ""_s;
c.fullName = ""_s;
c.viewId = {ViewId("horse")};
c.actions = {ItemAction::REPLACE_STEED};
);
}
static ItemInfo getSteedItemInfo(const ContentFactory* factory, const Creature* rider, const Creature* steed,
bool currentlyRiding) {
return CONSTRUCT(ItemInfo,
if (rider->getFirstCompanion() == steed)
c.name = TSentence("ITEM_INFO_NAME_COMPANION_STEED", steed->getName().bare());
else
c.name = steed->getName().bare();
c.fullName = steed->getName().aOrTitle();
c.viewId = steed->getViewObject().getViewIdList();
c.equiped = currentlyRiding;
c.pending = !currentlyRiding;
c.actions = {ItemAction::DROP_STEED};
c.ids.push_back(Item::Id(123));
);
}
void PlayerControl::fillSteedInfo(Creature* creature, PlayerInfo& info) const {
if (creature->isAffected(LastingEffect::RIDER)) {
auto factory = getGame()->getContentFactory();
if (auto steed = collective->getSteedOrRider(creature))
info.inventory.push_back(getSteedItemInfo(factory, creature, steed, creature->getSteed() == steed));
else
info.inventory.push_back(getEmptySteedItemInfo(factory));
}
}
void PlayerControl::fillEquipment(Creature* creature, PlayerInfo& info) const {
if (!collective->usesEquipment(creature))
return;
auto factory = getGame()->getContentFactory();
vector<EquipmentSlot> slots;
for (auto slot : Equipment::slotTitles)
slots.push_back(slot.first);
vector<Item*> ownedItems = collective->getMinionEquipment().getItemsOwnedBy(creature);
for (auto slot : slots) {
vector<Item*> items;
for (Item* it : ownedItems)
if (it->canEquip() && it->getEquipmentSlot() == slot)
items.push_back(it);
for (int i = creature->getEquipment().getMaxItems(slot, creature); i < items.size(); ++i)
// a rare occurence that minion owns too many items of the same slot,
//should happen only when an item leaves the fortress and then is braught back
if (!collective->getMinionEquipment().isLocked(creature, items[i]->getUniqueId()))
collective->getMinionEquipment().discard(items[i]);
for (Item* item : items) {
ownedItems.removeElement(item);
bool equiped = creature->getEquipment().isEquipped(item);
bool locked = collective->getMinionEquipment().isLocked(creature, item->getUniqueId());
info.inventory.push_back(getItemInfo(factory, {item}, equiped, !equiped, locked, ItemInfo::EQUIPMENT));
}
for (int i : Range(creature->getEquipment().getMaxItems(slot, creature) - items.size()))
info.inventory.push_back(getEmptySlotItem(slot, collective->getMinionEquipment().isLocked(creature, slot)));
if (slot == EquipmentSlot::WEAPON && tutorial &&
tutorial->getHighlights(getGame()).contains(TutorialHighlight::EQUIPMENT_SLOT_WEAPON))
info.inventory.back().tutorialHighlight = true;
}
vector<vector<Item*>> consumables = Item::stackItems(factory, ownedItems,
[&](const Item* it) { if (!creature->getEquipment().hasItem(it)) return " (pending)"; else return ""; } );
for (auto& stack : consumables)
info.inventory.push_back(getItemInfo(factory, stack, false,
!creature->getEquipment().hasItem(stack[0]), false, ItemInfo::CONSUMABLE));
vector<Item*> otherItems;
for (auto item : creature->getEquipment().getItems())
if (!collective->getMinionEquipment().isItemUseful(item))
otherItems.push_back(item);
for (auto item : Item::stackItems(factory, otherItems))
info.inventory.push_back(getItemInfo(factory, {item}, false, false, false, ItemInfo::OTHER));
auto lockedSet = getReferenceMaybe(collective->lockedEquipmentGroups, info.groupName);
for (auto& group : factory->equipmentGroups) {
info.equipmentGroups.push_back(PlayerInfo::EquipmentGroupInfo {
group.second,
group.first,
lockedSet && lockedSet->count(group.first)
});
}
}
static ScriptedUIDataElems::Record getItemRecord(const ContentFactory* factory, const vector<Item*> itemStack) {
auto elem = ScriptedUIDataElems::Record{};
elem.elems["view_id"] = itemStack[0]->getViewObject().getViewIdList();
TString label = itemStack[0]->getShortName(factory, nullptr, itemStack.size() > 1);
if (itemStack.size() > 1)
label = TSentence("MULTIPLE_ITEMS", TString(itemStack.size()), std::move(label));
elem.elems["name"] = capitalFirst(std::move(label));
auto tooltipElems = ScriptedUIDataElems::List {
capitalFirst(itemStack[0]->getNameAndModifiers(factory))
};
for (auto& elem : itemStack[0]->getDescription(factory))
tooltipElems.push_back(elem);
elem.elems["tooltip"] = std::move(tooltipElems);
return elem;
}
static ScriptedUIDataElems::Record getItemOwnerRecord(const ContentFactory* factory, const Creature* creature,
int count) {
auto ret = getCreatureRecord(factory, creature);
ret.elems["count"] = TString(toString(count));
return ret;
}
Item* PlayerControl::chooseEquipmentItem(Creature* creature, vector<Item*> currentItems, ItemPredicate predicate,
ScriptedUIState* uiState) {
auto allItems = collective->getAllItems().filter(predicate);
vector<Item*> availableItems;
vector<Item*> usedItems;
collective->getMinionEquipment().sortByEquipmentValue(creature, allItems);
for (Item* item : allItems)
if (!currentItems.contains(item)) {
auto owner = collective->getMinionEquipment().getOwner(item);
if (owner && getCreature(*owner))
usedItems.push_back(item);
else
availableItems.push_back(item);
}
if (currentItems.empty() && availableItems.empty() && usedItems.empty())
return nullptr;
auto factory = getGame()->getContentFactory();
vector<vector<Item*>> usedStacks = Item::stackItems(factory, usedItems,
[&](const Item* it) {
const Creature* c = getCreature(*collective->getMinionEquipment().getOwner(it));
return c->getName().bare().data() + toString<int>(c->getBestAttack(factory).value);});
auto data = ScriptedUIDataElems::Record{};
data.elems["title"] = TString(TStringId("AVAILABLE_ITEMS_TITLE"));
data.elems["is_equipment_choice"] = TString("blabla"_s);
auto itemsList = ScriptedUIDataElems::List{};
Item* ret = nullptr;
for (Item* it : currentItems) {
auto r = getItemRecord(factory, {it});
r.elems["equiped"] = TString("blabla"_s);
r.elems["callback"] = ScriptedUIDataElems::Callback {
[it, &ret] { ret = it; return true; }
};
itemsList.push_back(std::move(r));
}
for (auto& stack : concat(Item::stackItems(factory, availableItems), usedStacks)) {
auto r = getItemRecord(factory, stack);
r.elems["callback"] = ScriptedUIDataElems::Callback {
[item = stack[0], &ret] { ret = item; return true; }
};
unordered_set<const Creature*> allOwners;
for (auto item : stack)
if (auto creatureId = collective->getMinionEquipment().getOwner(item))
if (const Creature* c = getCreature(*creatureId))
allOwners.insert(c);
if (!allOwners.empty())
r.elems["owner"] = getItemOwnerRecord(factory, *allOwners.begin(), allOwners.size());
itemsList.push_back(std::move(r));
}
data.elems["elems"] = std::move(itemsList);
ScriptedUIState state;
getView()->scriptedUI("pillage_menu", data, uiState ? *uiState : state);
return ret;
}
static ScriptedUIDataElems::Record getSteedItemRecord(const ContentFactory* factory, const Creature* steed,
const Creature* rider) {
auto elem = ScriptedUIDataElems::Record{};
elem.elems["view_id"] = steed->getViewObject().getViewIdList();
if (rider->getFirstCompanion() == steed)
elem.elems["name"] = TString(TSentence("ITEM_INFO_NAME_COMPANION_STEED",
capitalFirst(steed->getName().bare())));
else
elem.elems["name"] = capitalFirst(steed->getName().bare());
elem.elems["tooltip"] = ScriptedUIDataElems::List {
capitalFirst(steed->getName().aOrTitle()),
capitalFirst(steed->getAttributes().getDescription(factory))
};
return elem;
}
Creature* PlayerControl::chooseSteed(Creature* creature, vector<Creature*> allSteeds) {
vector<Creature*> availableItems;
vector<Creature*> usedItems;
if (auto c = creature->getFirstCompanion())
if (c->isAffected(LastingEffect::STEED))
allSteeds.insert(0, c);
for (auto item : allSteeds) {
if (auto owner = collective->getSteedOrRider(item))
usedItems.push_back(item);
else
availableItems.push_back(item);
}
if (availableItems.empty() && usedItems.empty())
return nullptr;
auto factory = getGame()->getContentFactory();
vector<vector<Creature*>> usedStacks = Creature::stack(usedItems,
[&](Creature* it) {
const Creature* c = collective->getSteedOrRider(it);
return c->getName().bare().data() + toString<int>(c->getBestAttack(factory).value);
});
auto data = ScriptedUIDataElems::Record{};
data.elems["title"] = TString(TSentence("AVAILABLE_STEEDS", combineWithAnd(creature->getSteedSizes())));
data.elems["is_equipment_choice"] = TString("blabla"_s);
auto itemsList = ScriptedUIDataElems::List{};
Creature* ret = nullptr;
for (auto& stack : concat(Creature::stack(availableItems), usedStacks)) {
auto r = getSteedItemRecord(getGame()->getContentFactory(), stack[0], creature);
if (auto c = collective->getSteedOrRider(stack[0]))
r.elems["owner"] = getItemOwnerRecord(factory, c, stack.size());
r.elems["callback"] = ScriptedUIDataElems::Callback {
[creature = stack[0], &ret] { ret = creature; return true; }
};
itemsList.push_back(std::move(r));
}
data.elems["elems"] = std::move(itemsList);
getView()->scriptedUI("pillage_menu", data);
return ret;
}
int PlayerControl::getNumMinions() const {
return (int) collective->getCreatures(MinionTrait::FIGHTER).size();
}
typedef CollectiveInfo::Button Button;
optional<pair<ViewId, int>> PlayerControl::getCostObj(CostInfo cost) const {
auto& resourceInfo = collective->getResourceInfo(cost.id);
if (cost.value > 0 && resourceInfo.viewId)
return make_pair(*resourceInfo.viewId, (int) cost.value);
else
return none;
}
optional<pair<ViewId, int>> PlayerControl::getCostObj(const optional<CostInfo>& cost) const {
if (cost)
return getCostObj(*cost);
else
return none;
}
ViewId PlayerControl::getViewId(const BuildInfoTypes::BuildType& info) const {
PROFILE;
return info.visit<ViewId>(
[&](const BuildInfoTypes::Furniture& elem) {
return getGame()->getContentFactory()->furniture.getData(elem.types[0]).getViewObject()->id();
},
[&](const BuildInfoTypes::Dig&) {
return ViewId("dig_icon");
},
[&](const BuildInfoTypes::CutTree&) {
return ViewId("dig_icon");
},
[&](const BuildInfoTypes::FillPit&) {
return ViewId("fill_pit_icon");
},
[&](const BuildInfoTypes::Chain& c) {
return getViewId(c[0]);
},
[&](const BuildInfoTypes::ImmediateDig&) {
return ViewId("dig_icon");
},
[&](ZoneId zone) {
return ::getViewId(getHighlight(zone), true);
},
[&](BuildInfoTypes::ClaimTile) {
return ViewId("keeper_floor");
},
[&](BuildInfoTypes::UnclaimTile) {
return ViewId("floor");
},
[&](BuildInfoTypes::Dispatch) {
return ViewId("imp");
},
[&](const BuildInfoTypes::DestroyLayers&) {
return ViewId("destroy_button");
},
[&](BuildInfoTypes::ForbidZone) {
return ViewId("forbid_zone");
},
[&](BuildInfoTypes::PlaceMinion) {
return ViewId("special_blbn");
},
[&](BuildInfoTypes::PlaceItem) {
return ViewId("potion1");
}
);
}
vector<Button> PlayerControl::fillButtons() const {
PROFILE;
vector<Button> buttons;
HashMap<CollectiveResourceId, int> resourceCache;
auto contentFactory = getGame()->getContentFactory();
for (auto& button : buildInfo) {
PROFILE_BLOCK("BUTTON")
button.type.visit<void>(
[&](const BuildInfoTypes::Furniture& elem) {
PROFILE_BLOCK("Furniture")
TString description;
if (elem.cost.value > 0) {
int num = 0;
for (auto type : elem.types)
num += collective->getConstructions().getBuiltCount(type);
if (num > 0)
description = "[" + toString(num) + "]";
}
int availableNow = [&] {
if (!elem.cost.value)
return 1;
if (auto res = getValueMaybe(resourceCache, elem.cost.id))
return *res / elem.cost.value;
auto res = collective->numResource(elem.cost.id);
resourceCache[elem.cost.id] = res;
return res / elem.cost.value;
}();
if (!collective->getResourceInfo(elem.cost.id).viewId && availableNow)
description = combineSentences(std::move(description),
TSentence("BUILDINGS_COUNT_AVAILABLE", TString(availableNow)));
buttons.push_back(Button{getViewId(button.type), capitalFirst(button.getName(contentFactory)),
getCostObj(elem.cost),
description,
(elem.noCredit && !availableNow) ?
CollectiveInfo::Button::GRAY_CLICKABLE : CollectiveInfo::Button::ACTIVE });
},
[&](const auto&) {
PROFILE;
buttons.push_back({this->getViewId(button.type), button.getName(contentFactory), none, TString(), CollectiveInfo::Button::ACTIVE});
}
);
vector<TString> unmetReqText;
for (auto& req : button.requirements) {
PROFILE_BLOCK("Requirement")
if (!BuildInfo::meetsRequirement(collective, req)) {
unmetReqText.push_back(BuildInfo::getRequirementText(req, contentFactory));
buttons.back().state = CollectiveInfo::Button::INACTIVE;
}
}
if (unmetReqText.empty())
buttons.back().help = button.help;
else
buttons.back().help = combineSentences(concat({button.help}, unmetReqText));
buttons.back().key = button.key;
buttons.back().groupName = button.groupName;
buttons.back().hotkeyOpensGroup = button.hotkeyOpensGroup;
buttons.back().tutorialHighlight = button.tutorialHighlight;
buttons.back().isBuilding = button.isBuilding;
}
return buttons;
}
TString PlayerControl::getTriggerLabel(const AttackTrigger& trigger) const {
return trigger.visit<TString>(
[&](const Timer&) {
return TStringId("YOUR_EVIL_TRIGGER");
},
[&](const RoomTrigger& t) {
auto myCount = collective->getConstructions().getBuiltCount(t.type);
return getGame()->getContentFactory()->furniture.getData(t.type).getName(myCount);
},
[&](const Power&) {
return TStringId("YOUR_POWER_TRIGGER");
},
[&](const FinishOff&) {
return TStringId("FINISHING_YOU_TRIGGER");
},
[&](const SelfVictims&) {
return TStringId("KILLED_MEMBERS_TRIGGER");
},
[&](const EnemyPopulation&) {
return TStringId("POPULATION_TRIGGER");
},
[&](const Resource& r) {
return collective->getResourceInfo(r.resource).name;
},
[&](const StolenItems&) {
return TStringId("THEFT_TRIGGER");
},
[&](const MiningInProximity&) {
return TStringId("BREACH_TRIGGER");
},
[&](const Proximity&) {
return TStringId("PROXIMITY_TRIGGER");
},
[&](const NumConquered&) {
return TStringId("PROXIMITY_TRIGGER");
},
[&](Immediate) {
return TStringId("IMMEDIATE_TRIGGER");
},
[&](AggravatingMinions) {
return TStringId("AGGRAVATED_TRIGGER");
}
);
}
VillageInfo::Village PlayerControl::getVillageInfo(const Collective* col) const {
PROFILE;
VillageInfo::Village info;
if (col->getName()->shortened) {
info.name = *col->getName()->shortened;
info.tribeName = col->getName()->race;
} else