-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathGamePlayer.cpp
More file actions
2389 lines (2062 loc) · 82.1 KB
/
Copy pathGamePlayer.cpp
File metadata and controls
2389 lines (2062 loc) · 82.1 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
// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org)
//
// SPDX-License-Identifier: GPL-2.0-or-later
#include "GamePlayer.h"
#include "AddonHelperFunctions.h"
#include "Cheats.h"
#include "EventManager.h"
#include "FindWhConditions.h"
#include "GameInterface.h"
#include "GlobalGameSettings.h"
#include "LeatherLoader.h"
#include "RoadSegment.h"
#include "SerializedGameData.h"
#include "TradePathCache.h"
#include "Ware.h"
#include "WineLoader.h"
#include "addons/const_addons.h"
#include "buildings/noBuildingSite.h"
#include "buildings/nobHQ.h"
#include "buildings/nobHarborBuilding.h"
#include "buildings/nobMilitary.h"
#include "buildings/nobUsual.h"
#include "figures/nofCarrier.h"
#include "figures/nofFlagWorker.h"
#include "helpers/containerUtils.h"
#include "helpers/mathFuncs.h"
#include "lua/LuaInterfaceGame.h"
#include "notifications/ToolNote.h"
#include "pathfinding/RoadPathFinder.h"
#include "postSystem/DiplomacyPostQuestion.h"
#include "postSystem/PostManager.h"
#include "random/Random.h"
#include "world/GameWorld.h"
#include "world/TradeRoute.h"
#include "nodeObjs/noFlag.h"
#include "nodeObjs/noShip.h"
#include "gameTypes/BuildingCount.h"
#include "gameTypes/GoodTypes.h"
#include "gameTypes/JobTypes.h"
#include "gameTypes/PactTypes.h"
#include "gameTypes/VisualSettings.h"
#include "gameData/BuildingConsts.h"
#include "gameData/BuildingProperties.h"
#include "gameData/GoodConsts.h"
#include "gameData/SettingTypeConv.h"
#include "gameData/ShieldConsts.h"
#include "gameData/ToolConsts.h"
#include "s25util/Log.h"
#include <limits>
#include <numeric>
GamePlayer::GamePlayer(unsigned playerId, const PlayerInfo& playerInfo, GameWorld& world)
: GamePlayerInfo(playerId, playerInfo), world(world), hqPos(MapPoint::Invalid()), emergency(false)
{
std::fill(building_enabled.begin(), building_enabled.end(), true);
LoadStandardDistribution();
useCustomBuildOrder_ = false;
build_order = GetStandardBuildOrder();
transportPrio = STD_TRANSPORT_PRIO;
LoadStandardMilitarySettings();
LoadStandardToolSettings();
// Inventur nullen
global_inventory.clear();
// Statistiken mit 0en füllen
statistic = {};
statisticCurrentData = {};
statisticCurrentMerchandiseData = {};
RecalcDistribution();
}
void GamePlayer::LoadStandardToolSettings()
{
// metalwork tool request
// manually
std::fill(tools_ordered.begin(), tools_ordered.end(), 0u);
std::fill(tools_ordered_delta.begin(), tools_ordered_delta.end(), 0);
// percentage (tool-settings-window-slider, in 10th percent)
toolsSettings_[Tool::Tongs] = 1;
toolsSettings_[Tool::Hammer] = 4;
toolsSettings_[Tool::Axe] = 2;
toolsSettings_[Tool::Saw] = 5;
toolsSettings_[Tool::PickAxe] = 7;
toolsSettings_[Tool::Shovel] = 1;
toolsSettings_[Tool::Crucible] = 3;
toolsSettings_[Tool::RodAndLine] = 1;
toolsSettings_[Tool::Scythe] = 2;
toolsSettings_[Tool::Cleaver] = 1;
toolsSettings_[Tool::Rollingpin] = 2;
toolsSettings_[Tool::Bow] = 1;
}
void GamePlayer::LoadStandardMilitarySettings()
{
// military settings (military-window-slider, in 10th percent)
militarySettings_[0] = MILITARY_SETTINGS_SCALE[0]; //-V525
militarySettings_[1] = 3;
militarySettings_[2] = MILITARY_SETTINGS_SCALE[2];
militarySettings_[3] = 3;
militarySettings_[4] = 0;
militarySettings_[5] = 1;
militarySettings_[6] = MILITARY_SETTINGS_SCALE[6];
militarySettings_[7] = MILITARY_SETTINGS_SCALE[7];
}
BuildOrders GamePlayer::GetStandardBuildOrder()
{
BuildOrders ordering;
// Baureihenfolge füllen
unsigned curPrio = 0;
for(const auto bld : helpers::enumRange<BuildingType>())
{
if(bld == BuildingType::Headquarters || !BuildingProperties::IsValid(bld))
continue;
RTTR_Assert(curPrio < ordering.size());
ordering[curPrio] = bld;
++curPrio;
}
RTTR_Assert(curPrio == ordering.size());
return ordering;
}
void GamePlayer::LoadStandardDistribution()
{
// Verteilung mit Standardwerten füllen bei Waren mit nur einem Ziel (wie z.B. Mehl, Holz...)
distribution[GoodType::Flour].client_buildings.push_back(BuildingType::Bakery);
distribution[GoodType::Gold].client_buildings.push_back(BuildingType::Mint);
distribution[GoodType::IronOre].client_buildings.push_back(BuildingType::Ironsmelter);
distribution[GoodType::Ham].client_buildings.push_back(BuildingType::Slaughterhouse);
distribution[GoodType::Stones].client_buildings.push_back(
BuildingType::Headquarters); // BuildingType::Headquarters = Baustellen!
distribution[GoodType::Stones].client_buildings.push_back(BuildingType::Catapult);
distribution[GoodType::Grapes].client_buildings.push_back(BuildingType::Winery);
distribution[GoodType::Wine].client_buildings.push_back(BuildingType::Temple);
distribution[GoodType::Skins].client_buildings.push_back(BuildingType::Tannery);
distribution[GoodType::Leather].client_buildings.push_back(BuildingType::LeatherWorks);
// Waren mit mehreren möglichen Zielen erstmal nullen, kann dann im Fenster eingestellt werden
for(const auto i : helpers::enumRange<GoodType>())
{
std::fill(distribution[i].percent_buildings.begin(), distribution[i].percent_buildings.end(), 0);
distribution[i].selected_goal = 0;
}
// Standardverteilung der Waren
for(const DistributionMapping& mapping : distributionMap)
{
distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)] = std::get<2>(mapping);
}
}
GamePlayer::~GamePlayer() = default;
void GamePlayer::Serialize(SerializedGameData& sgd) const
{
// PlayerStatus speichern, ehemalig
sgd.PushEnum<uint8_t>(ps);
// Nur richtige Spieler serialisieren
if(ps != PlayerState::Occupied && ps != PlayerState::AI)
return;
sgd.PushBool(isDefeated);
buildings.Serialize(sgd);
sgd.PushObjectContainer(roads, true);
sgd.PushUnsignedInt(jobs_wanted.size());
for(const JobNeeded& job : jobs_wanted)
{
sgd.PushEnum<uint8_t>(job.job);
sgd.PushObject(job.workplace);
}
sgd.PushObjectContainer(ware_list, true);
sgd.PushObjectContainer(flagworkers);
sgd.PushObjectContainer(ships, true);
helpers::pushContainer(sgd, shouldSendDefenderList);
helpers::pushPoint(sgd, hqPos);
for(const Distribution& dist : distribution)
{
helpers::pushContainer(sgd, dist.percent_buildings);
helpers::pushContainer(sgd, dist.client_buildings);
helpers::pushContainer(sgd, dist.goals);
sgd.PushUnsignedInt(dist.selected_goal);
}
sgd.PushBool(useCustomBuildOrder_);
helpers::pushContainer(sgd, build_order);
helpers::pushContainer(sgd, transportPrio);
helpers::pushContainer(sgd, militarySettings_);
helpers::pushContainer(sgd, toolsSettings_);
helpers::pushContainer(sgd, tools_ordered);
helpers::pushContainer(sgd, global_inventory.goods);
helpers::pushContainer(sgd, global_inventory.people);
helpers::pushContainer(sgd, global_inventory.armoredSoldiers);
// für Statistik
for(const Statistic& curStatistic : statistic)
{
// normale Statistik
for(const auto& curData : curStatistic.data)
helpers::pushContainer(sgd, curData);
// Warenstatistik
for(unsigned j = 0; j < NUM_STAT_MERCHANDISE_TYPES; ++j)
helpers::pushContainer(sgd, curStatistic.merchandiseData[j]);
sgd.PushUnsignedShort(curStatistic.currentIndex);
sgd.PushUnsignedShort(curStatistic.counter);
}
helpers::pushContainer(sgd, statisticCurrentData);
helpers::pushContainer(sgd, statisticCurrentMerchandiseData);
// Serialize Pacts:
for(const auto& playerPacts : pacts)
{
for(const Pact& pact : playerPacts)
pact.Serialize(sgd);
}
sgd.PushBool(emergency);
}
void GamePlayer::Deserialize(SerializedGameData& sgd)
{
std::fill(building_enabled.begin(), building_enabled.end(), true);
// Ehemaligen PS auslesen
auto origin_ps = sgd.Pop<PlayerState>();
// Nur richtige Spieler serialisieren
if(origin_ps != PlayerState::Occupied && origin_ps != PlayerState::AI)
return;
isDefeated = sgd.PopBool();
buildings.Deserialize(sgd);
sgd.PopObjectContainer(roads, GO_Type::Roadsegment);
jobs_wanted.resize(sgd.PopUnsignedInt());
for(JobNeeded& job : jobs_wanted)
{
job.job = sgd.Pop<Job>();
job.workplace = sgd.PopObject<noRoadNode>();
}
if(sgd.GetGameDataVersion() < 2)
buildings.Deserialize2(sgd);
sgd.PopObjectContainer(ware_list, GO_Type::Ware);
sgd.PopObjectContainer(flagworkers);
sgd.PopObjectContainer(ships, GO_Type::Ship);
sgd.PopContainer(shouldSendDefenderList);
hqPos = sgd.PopMapPoint();
for(const auto i : helpers::enumRange<GoodType>())
{
if(sgd.GetGameDataVersion() < 11 && wineaddon::isWineAddonGoodType(i))
continue;
if(sgd.GetGameDataVersion() < 12 && leatheraddon::isLeatherAddonGoodType(i))
continue;
Distribution& dist = distribution[i];
helpers::popContainer(sgd, dist.percent_buildings);
// Set standard value otherwise its zero and Slaughterhouse never gets ham
// because the ham distribution was not there in earlier versions
if(sgd.GetGameDataVersion() < 12 && i == GoodType::Ham)
dist.percent_buildings[BuildingType::Slaughterhouse] = 8;
if(sgd.GetGameDataVersion() < 7)
{
dist.client_buildings.resize(sgd.PopUnsignedInt());
helpers::popContainer(sgd, dist.client_buildings, true);
dist.goals.resize(sgd.PopUnsignedInt());
helpers::popContainer(sgd, dist.goals, true);
} else
{
helpers::popContainer(sgd, dist.client_buildings);
helpers::popContainer(sgd, dist.goals);
}
dist.selected_goal = sgd.PopUnsignedInt();
}
useCustomBuildOrder_ = sgd.PopBool();
if(sgd.GetGameDataVersion() < 12)
{
auto countOfNotAvailableBuildingsInSaveGame =
sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonBuildings : numLeatherAddonBuildings;
std::vector<BuildingType> build_order_raw(build_order.size() - countOfNotAvailableBuildingsInSaveGame);
helpers::popContainer(sgd, build_order_raw, true);
if(sgd.GetGameDataVersion() < 11)
{
build_order_raw.insert(build_order_raw.end(),
{BuildingType::Vineyard, BuildingType::Winery, BuildingType::Temple});
}
if(sgd.GetGameDataVersion() < 12)
{
build_order_raw.insert(build_order_raw.end(),
{BuildingType::Skinner, BuildingType::Tannery, BuildingType::LeatherWorks});
}
std::copy(build_order_raw.begin(), build_order_raw.end(), build_order.begin());
auto countOfNotAvailableGoodsInSaveGame =
sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonGoods : numLeatherAddonGoods;
std::vector<uint8_t> transportPrio_raw(transportPrio.size() - countOfNotAvailableGoodsInSaveGame);
helpers::popContainer(sgd, transportPrio_raw, true);
std::copy(transportPrio_raw.begin(), transportPrio_raw.end(), transportPrio.begin());
std::transform(transportPrio.begin(), transportPrio.end() - countOfNotAvailableGoodsInSaveGame,
transportPrio.begin(),
[](uint8_t& prio) { return prio < transportPrioOfLeatherworks ? prio : prio + 1; });
} else
{
helpers::popContainer(sgd, build_order);
helpers::popContainer(sgd, transportPrio);
}
helpers::popContainer(sgd, militarySettings_);
helpers::popContainer(sgd, toolsSettings_);
// qx:tools
helpers::popContainer(sgd, tools_ordered);
tools_ordered_delta = {};
if(sgd.GetGameDataVersion() < 12)
{
auto countOfNotAvailableGoodsInSaveGame =
sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonGoods : numLeatherAddonGoods;
std::vector<unsigned int> global_inventory_good_raw(global_inventory.goods.size()
- countOfNotAvailableGoodsInSaveGame);
helpers::popContainer(sgd, global_inventory_good_raw, true);
std::copy(global_inventory_good_raw.begin(), global_inventory_good_raw.end(), global_inventory.goods.begin());
auto countOfNotAvailableJobsInSaveGame =
sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonJobs : numLeatherAddonJobs;
std::vector<unsigned int> global_inventory_people_raw(global_inventory.people.size()
- countOfNotAvailableJobsInSaveGame);
helpers::popContainer(sgd, global_inventory_people_raw, true);
std::copy(global_inventory_people_raw.begin(), global_inventory_people_raw.end(),
global_inventory.people.begin());
std::fill(global_inventory.armoredSoldiers.begin(), global_inventory.armoredSoldiers.end(), 0);
} else
{
helpers::popContainer(sgd, global_inventory.goods);
helpers::popContainer(sgd, global_inventory.people);
helpers::popContainer(sgd, global_inventory.armoredSoldiers);
}
// Visuelle Einstellungen festlegen
// für Statistik
for(Statistic& curStatistic : statistic)
{
// normale Statistik
for(auto& curData : curStatistic.data)
helpers::popContainer(sgd, curData);
// Warenstatistik
for(unsigned j = 0; j < NUM_STAT_MERCHANDISE_TYPES; ++j)
helpers::popContainer(sgd, curStatistic.merchandiseData[j]);
curStatistic.currentIndex = sgd.PopUnsignedShort();
curStatistic.counter = sgd.PopUnsignedShort();
}
helpers::popContainer(sgd, statisticCurrentData);
helpers::popContainer(sgd, statisticCurrentMerchandiseData);
// Deserialize Pacts:
for(auto& playerPacts : pacts)
{
for(Pact& pact : playerPacts)
pact = GamePlayer::Pact(sgd);
}
emergency = sgd.PopBool();
}
template<class T_IsWarehouseGood>
nobBaseWarehouse* GamePlayer::FindWarehouse(const noRoadNode& start, const T_IsWarehouseGood& isWarehouseGood,
bool to_wh, bool use_boat_roads, unsigned* length,
const RoadSegment* forbidden) const
{
nobBaseWarehouse* best = nullptr;
unsigned best_length = std::numeric_limits<unsigned>::max();
for(nobBaseWarehouse* wh : buildings.GetStorehouses())
{
// Lagerhaus geeignet?
RTTR_Assert(wh);
if(!isWarehouseGood(*wh))
continue;
if(start.GetPos() == wh->GetPos())
{
// We are already there -> Take it
if(length)
*length = 0;
return wh;
}
// now check if there is at least a chance that the next wh is closer than current best because pathfinding
// takes time
if(world.CalcDistance(start.GetPos(), wh->GetPos()) > best_length)
continue;
// Bei der erlaubten Benutzung von Bootsstraßen Waren-Pathfinding benutzen wenns zu nem Lagerhaus gehn soll
// start <-> ziel tauschen bei der wegfindung
unsigned tlength;
if(world.GetRoadPathFinder().FindPath(to_wh ? start : *wh, to_wh ? *wh : start, use_boat_roads, best_length,
forbidden, &tlength))
{
if(tlength < best_length || !best)
{
best_length = tlength;
best = wh;
}
}
}
if(length)
*length = best_length;
return best;
}
void GamePlayer::AddBuildingSite(noBuildingSite* bldSite)
{
RTTR_Assert(bldSite->GetPlayer() == GetPlayerId());
buildings.Add(bldSite);
}
void GamePlayer::RemoveBuildingSite(noBuildingSite* bldSite)
{
RTTR_Assert(bldSite->GetPlayer() == GetPlayerId());
buildings.Remove(bldSite);
}
bool GamePlayer::IsHQTent() const
{
if(const nobHQ* hq = GetHQ())
return hq->IsTent();
return false;
}
void GamePlayer::SetHQIsTent(bool isTent)
{
if(nobHQ* hq = GetHQ())
hq->SetIsTent(isTent);
}
void GamePlayer::AddBuilding(noBuilding* bld, BuildingType bldType)
{
RTTR_Assert(bld->GetPlayer() == GetPlayerId());
buildings.Add(bld, bldType);
ChangeStatisticValue(StatisticType::Buildings, 1);
// Order a worker if needed
const auto& description = BLD_WORK_DESC[bldType];
if(description.job && !isSoldierJob(*description.job))
{
AddJobWanted(*description.job, bld);
}
if(bldType == BuildingType::HarborBuilding)
{
// Schiff durchgehen und denen Bescheid sagen
for(noShip* ship : ships)
ship->NewHarborBuilt(static_cast<nobHarborBuilding*>(bld));
} else if(bldType == BuildingType::Headquarters)
{
// If there is more than one HQ, keep the original position.
if(!hqPos.isValid())
hqPos = bld->GetPos();
} else if(BuildingProperties::IsMilitary(bldType))
{
auto* milBld = static_cast<nobMilitary*>(bld);
// New built? -> Calculate frontier distance
if(milBld->IsNewBuilt())
milBld->LookForEnemyBuildings();
}
}
void GamePlayer::RemoveBuilding(noBuilding* bld, BuildingType bldType)
{
RTTR_Assert(bld->GetPlayer() == GetPlayerId());
buildings.Remove(bld, bldType);
ChangeStatisticValue(StatisticType::Buildings, -1);
if(bldType == BuildingType::HarborBuilding)
{ // Schiffen Bescheid sagen
for(noShip* ship : ships)
ship->HarborDestroyed(static_cast<nobHarborBuilding*>(bld));
} else if(bldType == BuildingType::Headquarters && bld->GetPos() == hqPos)
{
hqPos = MapPoint::Invalid();
for(const noBaseBuilding* bld : buildings.GetStorehouses())
{
if(bld->GetBuildingType() == BuildingType::Headquarters)
{
hqPos = bld->GetPos();
break;
}
}
}
if(BuildingProperties::IsWareHouse(bldType) || BuildingProperties::IsMilitary(bldType))
TestDefeat();
}
void GamePlayer::NewRoadConnection(RoadSegment* rs)
{
// Zu den Straßen hinzufgen, da's ja ne neue ist
roads.push_back(rs);
// Alle Straßen müssen nun gucken, ob sie einen Weg zu einem Warehouse finden
FindCarrierForAllRoads();
// Alle Straßen müssen gucken, ob sie einen Esel bekommen können
for(RoadSegment* rs : roads)
rs->TryGetDonkey();
// Alle Arbeitsplätze müssen nun gucken, ob sie einen Weg zu einem Lagerhaus mit entsprechender Arbeitskraft finden
FindWarehouseForAllJobs();
// Alle Baustellen müssen nun gucken, ob sie ihr benötigtes Baumaterial bekommen (evtl war vorher die Straße zum
// Lagerhaus unterbrochen
FindMaterialForBuildingSites();
// Alle Lost-Wares müssen gucken, ob sie ein Lagerhaus finden
FindClientForLostWares();
// Alle Militärgebäude müssen ihre Truppen überprüfen und können nun ggf. neue bestellen
// und müssen prüfen, ob sie evtl Gold bekommen
for(nobMilitary* mil : buildings.GetMilitaryBuildings())
{
mil->RegulateTroops();
mil->SearchCoins();
}
}
void GamePlayer::AddRoad(RoadSegment* rs)
{
roads.push_back(rs);
}
void GamePlayer::DeleteRoad(RoadSegment* rs)
{
RTTR_Assert(helpers::contains(roads, rs));
roads.remove(rs);
}
void GamePlayer::FindClientForLostWares()
{
// Alle Lost-Wares müssen gucken, ob sie ein Lagerhaus finden
for(Ware* ware : ware_list)
{
if(ware->IsLostWare())
{
if(ware->FindRouteToWarehouse() && ware->IsWaitingAtFlag())
ware->CallCarrier();
}
}
}
void GamePlayer::RoadDestroyed()
{
// Alle Waren, die an Flagge liegen und in Lagerhäusern, müssen gucken, ob sie ihr Ziel noch erreichen können, jetzt
// wo eine Straße fehlt
for(auto it = ware_list.begin(); it != ware_list.end();)
{
Ware* ware = *it;
if(ware->IsWaitingAtFlag()) // Liegt die Flagge an einer Flagge, muss ihr Weg neu berechnet werden
{
RoadPathDirection last_next_dir = ware->GetNextDir();
ware->RecalcRoute();
// special case: ware was lost some time ago and the new goal is at this flag and not a warehouse,hq,harbor
// and the "flip-route" picked so a carrier would pick up the ware carry it away from goal then back and
// drop it off at the goal was just destroyed?
// -> try to pick another flip route or tell the goal about failure.
noRoadNode& wareLocation = *ware->GetLocation();
noBaseBuilding* wareGoal = ware->GetGoal();
if(wareGoal && ware->GetNextDir() == RoadPathDirection::NorthWest
&& wareLocation.GetPos() == wareGoal->GetFlagPos()
&& ((wareGoal->GetBuildingType() != BuildingType::Storehouse
&& wareGoal->GetBuildingType() != BuildingType::Headquarters
&& wareGoal->GetBuildingType() != BuildingType::HarborBuilding)
|| wareGoal->GetType() == NodalObjectType::Buildingsite))
{
Direction newWareDir = Direction::NorthWest;
for(auto dir : helpers::EnumRange<Direction>{})
{
dir += 2u; // Need to skip Direction::NorthWest and we used to start with an offset of 2. TODO:
// Increase gameDataVersion and just skip NW
if(wareLocation.GetRoute(dir))
{
newWareDir = dir;
break;
}
}
if(newWareDir != Direction::NorthWest)
{
ware->SetNextDir(toRoadPathDirection(newWareDir));
} else // no route to goal -> notify goal, try to send ware to a warehouse
{
ware->NotifyGoalAboutLostWare();
ware->FindRouteToWarehouse();
}
}
// end of special case
// notify carriers/flags about news if there are any
if(ware->GetNextDir() != last_next_dir)
{
// notify current flag that transport in the old direction might not longer be required
ware->RemoveWareJobForDir(last_next_dir);
if(ware->GetNextDir() != RoadPathDirection::None)
ware->CallCarrier();
}
} else if(ware->IsWaitingInWarehouse())
{
if(!ware->IsRouteToGoal())
{
// Das Ziel wird nun nich mehr beliefert
ware->NotifyGoalAboutLostWare();
// Ware aus der Warteliste des Lagerhauses entfernen
static_cast<nobBaseWarehouse*>(ware->GetLocation())->CancelWare(ware);
// Ware aus der Liste raus
it = ware_list.erase(it);
continue;
}
} else if(ware->IsWaitingForShip())
{
// Weg neu berechnen
ware->RecalcRoute();
}
++it;
}
// Alle Häfen müssen ihre Figuren den Weg überprüfen lassen
for(nobHarborBuilding* hb : buildings.GetHarbors())
{
hb->ExamineShipRouteOfPeople();
}
}
bool GamePlayer::FindCarrierForRoad(RoadSegment& rs) const
{
RTTR_Assert(rs.GetF1() != nullptr && rs.GetF2() != nullptr);
std::array<unsigned, 2> length;
std::array<nobBaseWarehouse*, 2> best;
// Braucht der ein Boot?
if(rs.GetRoadType() == RoadType::Water)
{
// dann braucht man Träger UND Boot
best[0] = FindWarehouse(*rs.GetF1(), FW::HasWareAndFigure(GoodType::Boat, Job::Helper, false), false, false,
length.data(), &rs);
// 2. Flagge des Weges
best[1] = FindWarehouse(*rs.GetF2(), FW::HasWareAndFigure(GoodType::Boat, Job::Helper, false), false, false,
&length[1], &rs);
} else
{
// 1. Flagge des Weges
best[0] = FindWarehouse(*rs.GetF1(), FW::HasFigure(Job::Helper, false), false, false, length.data(), &rs);
// 2. Flagge des Weges
best[1] = FindWarehouse(*rs.GetF2(), FW::HasFigure(Job::Helper, false), false, false, &length[1], &rs);
}
// überhaupt nen Weg gefunden?
// Welche Flagge benutzen?
if(best[0] && (!best[1] || length[0] < length[1]))
best[0]->OrderCarrier(*rs.GetF1(), rs);
else if(best[1])
best[1]->OrderCarrier(*rs.GetF2(), rs);
else
return false;
return true;
}
bool GamePlayer::IsWarehouseValid(nobBaseWarehouse* wh) const
{
return helpers::contains(buildings.GetStorehouses(), wh);
}
void GamePlayer::RecalcDistribution()
{
GoodType lastWare = GoodType::Nothing;
for(const DistributionMapping& mapping : distributionMap)
{
if(lastWare == std::get<0>(mapping))
continue;
lastWare = std::get<0>(mapping);
RecalcDistributionOfWare(std::get<0>(mapping));
}
}
void GamePlayer::RecalcDistributionOfWare(const GoodType ware)
{
// Punktesystem zur Verteilung, in der Liste alle Gebäude sammeln, die die Ware wollen
distribution[ware].client_buildings.clear();
// 1. Anteile der einzelnen Waren ausrechnen
/// Mapping of buildings that want the current ware to its percentage
using BldEntry = std::pair<BuildingType, uint8_t>;
std::vector<BldEntry> bldPercentageMap;
unsigned goal_count = 0;
for(const auto bld : helpers::enumRange<BuildingType>())
{
uint8_t percentForCurBld = distribution[ware].percent_buildings[bld];
if(percentForCurBld)
{
distribution[ware].client_buildings.push_back(bld);
goal_count += percentForCurBld;
bldPercentageMap.emplace_back(bld, percentForCurBld);
}
}
// TODO: evtl noch die counts miteinander kürzen (ggt berechnen)
// Array für die Gebäudtypen erstellen
std::vector<BuildingType>& wareGoals = distribution[ware].goals;
wareGoals.clear();
wareGoals.reserve(goal_count);
// just drop them in the list, the distribution will be handled by going through this list using a prime as step
// (see GameClientPlayer::FindClientForWare)
for(const BldEntry& bldEntry : bldPercentageMap)
{
for(unsigned char i = 0; i < bldEntry.second; ++i)
wareGoals.push_back(bldEntry.first);
}
distribution[ware].selected_goal = 0;
}
void GamePlayer::FindCarrierForAllRoads()
{
for(RoadSegment* rs : roads)
{
if(!rs->hasCarrier(0))
FindCarrierForRoad(*rs);
}
}
void GamePlayer::FindMaterialForBuildingSites()
{
for(noBuildingSite* bldSite : buildings.GetBuildingSites())
bldSite->OrderConstructionMaterial();
}
void GamePlayer::AddJobWanted(const Job job, noRoadNode* workplace)
{
if(!FindWarehouseForJob(job, *workplace))
{
JobNeeded jn = {job, workplace};
jobs_wanted.push_back(jn);
}
}
void GamePlayer::JobNotWanted(noRoadNode* workplace, bool all)
{
for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
{
if(it->workplace == workplace)
{
it = jobs_wanted.erase(it);
if(!all)
return;
} else
{
++it;
}
}
}
void GamePlayer::OneJobNotWanted(const Job job, noRoadNode* workplace)
{
const auto it = helpers::find_if(
jobs_wanted, [workplace, job](const auto& it) { return it.workplace == workplace && it.job == job; });
if(it != jobs_wanted.end())
jobs_wanted.erase(it);
}
void GamePlayer::SendPostMessage(std::unique_ptr<PostMsg> msg)
{
world.GetPostMgr().SendMsg(GetPlayerId(), std::move(msg));
}
unsigned GamePlayer::GetToolsOrderedVisual(Tool tool) const
{
return std::max(0, int(tools_ordered[tool] + tools_ordered_delta[tool]));
}
unsigned GamePlayer::GetToolsOrdered(Tool tool) const
{
return tools_ordered[tool];
}
bool GamePlayer::ChangeToolOrderVisual(Tool tool, int changeAmount) const
{
if(std::abs(changeAmount) > 100)
return false;
int newOrderAmount = int(GetToolsOrderedVisual(tool)) + changeAmount;
if(newOrderAmount < 0 || newOrderAmount > 100)
return false;
tools_ordered_delta[tool] += changeAmount;
return true;
}
unsigned GamePlayer::GetToolPriority(Tool tool) const
{
return toolsSettings_[tool];
}
void GamePlayer::ToolOrderProcessed(Tool tool)
{
if(tools_ordered[tool])
{
--tools_ordered[tool];
world.GetNotifications().publish(ToolNote(ToolNote::OrderCompleted, GetPlayerId()));
}
}
bool GamePlayer::FindWarehouseForJob(const Job job, noRoadNode& goal) const
{
// Optimization: return early if building is isolated
if(goal.GetType() == NodalObjectType::Building || goal.GetType() == NodalObjectType::Buildingsite)
{
if(!static_cast<noBaseBuilding&>(goal).IsConnected())
return false;
}
nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasFigure(job, true), false, false);
if(wh)
{
// Es wurde ein Lagerhaus gefunden, wo es den geforderten Beruf gibt, also den Typen zur Arbeit rufen
wh->OrderJob(job, goal, true);
return true;
}
return false;
}
void GamePlayer::FindWarehouseForAllJobs()
{
for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
{
if(FindWarehouseForJob(it->job, *it->workplace))
it = jobs_wanted.erase(it);
else
++it;
}
}
void GamePlayer::FindWarehouseForAllJobs(const Job job)
{
for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
{
if(it->job == job)
{
if(FindWarehouseForJob(it->job, *it->workplace))
it = jobs_wanted.erase(it);
else
++it;
} else
++it;
}
}
Ware* GamePlayer::OrderWare(const GoodType ware, noBaseBuilding& goal)
{
/// Gibt es ein Lagerhaus mit dieser Ware?
nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasMinWares(ware, 1), false, true);
if(wh)
{
// Prüfe ob Notfallprogramm aktiv
if(!emergency)
return wh->OrderWare(ware, goal);
else
{
// Wenn Notfallprogramm aktiv nur an Holzfäller und Sägewerke Bretter/Steine liefern
if((ware != GoodType::Boards && ware != GoodType::Stones)
|| goal.GetBuildingType() == BuildingType::Woodcutter || goal.GetBuildingType() == BuildingType::Sawmill)
return wh->OrderWare(ware, goal);
else
return nullptr;
}
} else // no warehouse can deliver the ware -> check all our wares for lost wares that might match the order
{
unsigned bestLength = std::numeric_limits<unsigned>::max();
Ware* bestWare = nullptr;
for(Ware* curWare : ware_list)
{
if(curWare->IsLostWare() && curWare->type == ware)
{
// got a lost ware with a road to goal -> find best
unsigned curLength = curWare->CheckNewGoalForLostWare(goal);
if(curLength < bestLength)
{
bestLength = curLength;
bestWare = curWare;
}
}
}
if(bestWare)
{
bestWare->SetNewGoalForLostWare(goal);
return bestWare;
}
}
return nullptr;
}
nofCarrier* GamePlayer::OrderDonkey(RoadSegment& road) const
{
std::array<unsigned, 2> length;
std::array<nobBaseWarehouse*, 2> best;
// 1. Flagge des Weges
best[0] = FindWarehouse(*road.GetF1(), FW::HasFigure(Job::PackDonkey, false), false, false, length.data(), &road);
// 2. Flagge des Weges
best[1] = FindWarehouse(*road.GetF2(), FW::HasFigure(Job::PackDonkey, false), false, false, &length[1], &road);
// überhaupt nen Weg gefunden?
// Welche Flagge benutzen?
if(best[0] && (!best[1] || length[0] < length[1]))
return best[0]->OrderDonkey(road, *road.GetF1());
else if(best[1])
return best[1]->OrderDonkey(road, *road.GetF2());
else
return nullptr;
}
RoadSegment* GamePlayer::FindRoadForDonkey(noRoadNode& start, noRoadNode** goal)
{
// Bisher höchste Trägerproduktivität und die entsprechende Straße dazu
unsigned best_productivity = 0;
RoadSegment* best_road = nullptr;
// Beste Flagge dieser Straße
*goal = nullptr;
for(RoadSegment* roadSeg : roads)
{
// Braucht die Straße einen Esel?
if(roadSeg->NeedDonkey())
{
// Beste Flagge von diesem Weg, und beste Wegstrecke
noRoadNode* current_best_goal = nullptr;
// Weg zu beiden Flaggen berechnen
unsigned length1, length2;
bool isF1Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF1(), &length1, nullptr, roadSeg)
!= RoadPathDirection::None;
bool isF2Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF2(), &length2, nullptr, roadSeg)
!= RoadPathDirection::None;
// Wenn man zu einer Flagge nich kommt, die jeweils andere nehmen
if(!isF1Reachable)
current_best_goal = (isF2Reachable) ? roadSeg->GetF2() : nullptr;
else if(!isF2Reachable)
current_best_goal = roadSeg->GetF1();
else
{
// ansonsten die kürzeste von beiden
current_best_goal = (length1 < length2) ? roadSeg->GetF1() : roadSeg->GetF2();
}
// Kein Weg führt hin, nächste Straße bitte
if(!current_best_goal)
continue;
// Jeweiligen Weg bestimmen
unsigned current_best_way = (roadSeg->GetF1() == current_best_goal) ? length1 : length2;
// Produktivität ausrechnen, *10 die Produktivität + die Wegstrecke, damit die
// auch noch mit einberechnet wird
unsigned current_productivity = 10 * roadSeg->getCarrier(0)->GetProductivity() + current_best_way;