forked from freeorion/freeorion
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmpire.cpp
More file actions
2300 lines (1926 loc) · 92.4 KB
/
Copy pathEmpire.cpp
File metadata and controls
2300 lines (1926 loc) · 92.4 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 "Empire.h"
#include "../util/i18n.h"
#include "../util/Random.h"
#include "../util/Logger.h"
#include "../util/AppInterface.h"
#include "../util/SitRepEntry.h"
#include "../universe/Building.h"
#include "../universe/Fleet.h"
#include "../universe/Ship.h"
#include "../universe/ShipDesign.h"
#include "../universe/Planet.h"
#include "../universe/System.h"
#include "../universe/Tech.h"
#include "../universe/UniverseObject.h"
#include "EmpireManager.h"
#include "Supply.h"
#include <unordered_set>
namespace {
const float EPSILON = 0.01f;
const std::string EMPTY_STRING;
}
////////////
// Empire //
////////////
Empire::Empire() :
m_authenticated(false),
m_research_queue(m_id),
m_production_queue(m_id)
{ Init(); }
Empire::Empire(const std::string& name, const std::string& player_name,
int empire_id, const GG::Clr& color, bool authenticated) :
m_id(empire_id),
m_name(name),
m_player_name(player_name),
m_authenticated(authenticated),
m_color(color),
m_research_queue(m_id),
m_production_queue(m_id)
{
DebugLogger() << "Empire::Empire(" << name << ", " << player_name << ", " << empire_id << ", colour)";
Init();
}
void Empire::Init() {
m_resource_pools[RE_RESEARCH] = std::make_shared<ResourcePool>(RE_RESEARCH);
m_resource_pools[RE_INDUSTRY] = std::make_shared<ResourcePool>(RE_INDUSTRY);
m_resource_pools[RE_TRADE] = std::make_shared<ResourcePool>(RE_TRADE);
m_eliminated = false;
m_meters[UserStringNop("METER_DETECTION_STRENGTH")];
m_meters[UserStringNop("METER_BUILDING_COST_FACTOR")];
m_meters[UserStringNop("METER_SHIP_COST_FACTOR")];
m_meters[UserStringNop("METER_TECH_COST_FACTOR")];
}
Empire::~Empire()
{ ClearSitRep(); }
const std::string& Empire::Name() const
{ return m_name; }
const std::string& Empire::PlayerName() const
{ return m_player_name; }
bool Empire::IsAuthenticated() const
{ return m_authenticated; }
int Empire::EmpireID() const
{ return m_id; }
const GG::Clr& Empire::Color() const
{ return m_color; }
int Empire::CapitalID() const
{ return m_capital_id; }
int Empire::SourceID() const {
auto good_source = Source();
return good_source ? good_source->ID() : INVALID_OBJECT_ID;
}
std::shared_ptr<const UniverseObject> Empire::Source() const {
if (m_eliminated)
return nullptr;
// Use the current source if valid
auto valid_current_source = GetUniverseObject(m_source_id);
if (valid_current_source && valid_current_source->OwnedBy(m_id))
return valid_current_source;
// Try the capital
auto capital_as_source = GetUniverseObject(m_capital_id);
if (capital_as_source && capital_as_source->OwnedBy(m_id)) {
m_source_id = m_capital_id;
return capital_as_source;
}
// Find any object owned by the empire
// TODO determine if ExistingObjects() is faster and acceptable
for (const auto& obj_it : Objects()) {
if (obj_it->OwnedBy(m_id)) {
m_source_id = obj_it->ID();
return (obj_it);
}
}
m_source_id = INVALID_OBJECT_ID;
return nullptr;
}
std::string Empire::Dump() const {
std::string retval = "Empire name: " + m_name +
" ID: " + std::to_string(m_id) +
" Capital ID: " + std::to_string(m_capital_id);
retval += " meters:\n";
for (const auto& meter : m_meters) {
retval += UserString(meter.first) + ": " +
std::to_string(meter.second.Initial()) + "\n";
}
return retval;
}
void Empire::SetCapitalID(int id) {
m_capital_id = INVALID_OBJECT_ID;
m_source_id = INVALID_OBJECT_ID;
if (id == INVALID_OBJECT_ID)
return;
// Verify that the capital exists and is owned by the empire
auto possible_capital = Objects().ExistingObject(id);
if (possible_capital && possible_capital->OwnedBy(m_id))
m_capital_id = id;
auto possible_source = GetUniverseObject(id);
if (possible_source && possible_source->OwnedBy(m_id))
m_source_id = id;
}
Meter* Empire::GetMeter(const std::string& name) {
auto it = m_meters.find(name);
if (it != m_meters.end())
return &(it->second);
else
return nullptr;
}
const Meter* Empire::GetMeter(const std::string& name) const {
auto it = m_meters.find(name);
if (it != m_meters.end())
return &(it->second);
else
return nullptr;
}
void Empire::BackPropagateMeters() {
for (auto& meter : m_meters)
meter.second.BackPropagate();
}
bool Empire::ResearchableTech(const std::string& name) const {
const Tech* tech = GetTech(name);
if (!tech)
return false;
for (const auto& prereq : tech->Prerequisites()) {
if (!m_techs.count(prereq))
return false;
}
return true;
}
bool Empire::HasResearchedPrereqAndUnresearchedPrereq(const std::string& name) const {
const Tech* tech = GetTech(name);
if (!tech)
return false;
bool one_unresearched = false;
bool one_researched = false;
for (const auto& prereq : tech->Prerequisites()) {
if (m_techs.count(prereq))
one_researched = true;
else
one_unresearched = true;
}
return one_unresearched && one_researched;
}
const ResearchQueue& Empire::GetResearchQueue() const
{ return m_research_queue; }
float Empire::ResearchProgress(const std::string& name) const {
auto it = m_research_progress.find(name);
if (it == m_research_progress.end())
return 0.0f;
const Tech* tech = GetTech(it->first);
if (!tech)
return 0.0f;
float tech_cost = tech->ResearchCost(m_id);
return it->second * tech_cost;
}
const std::map<std::string, int>& Empire::ResearchedTechs() const
{ return m_techs; }
bool Empire::TechResearched(const std::string& name) const
{ return m_techs.count(name); }
TechStatus Empire::GetTechStatus(const std::string& name) const {
if (TechResearched(name)) return TS_COMPLETE;
if (ResearchableTech(name)) return TS_RESEARCHABLE;
if (HasResearchedPrereqAndUnresearchedPrereq(name)) return TS_HAS_RESEARCHED_PREREQ;
return TS_UNRESEARCHABLE;
}
const std::string& Empire::TopPriorityEnqueuedTech() const {
if (m_research_queue.empty())
return EMPTY_STRING;
auto it = m_research_queue.begin();
const std::string& tech = it->name;
return tech;
}
const std::string& Empire::MostExpensiveEnqueuedTech() const {
if (m_research_queue.empty())
return EMPTY_STRING;
float biggest_cost = -99999.9f; // arbitrary small number
const ResearchQueue::Element* best_elem = nullptr;
for (const auto& elem : m_research_queue) {
const Tech* tech = GetTech(elem.name);
if (!tech)
continue;
float tech_cost = tech->ResearchCost(m_id);
if (tech_cost > biggest_cost) {
biggest_cost = tech_cost;
best_elem = &elem;
}
}
if (best_elem)
return best_elem->name;
return EMPTY_STRING;
}
const std::string& Empire::LeastExpensiveEnqueuedTech() const {
if (m_research_queue.empty())
return EMPTY_STRING;
float smallest_cost = 999999.9f; // arbitrary large number
const ResearchQueue::Element* best_elem = nullptr;
for (const auto& elem : m_research_queue) {
const Tech* tech = GetTech(elem.name);
if (!tech)
continue;
float tech_cost = tech->ResearchCost(m_id);
if (tech_cost < smallest_cost) {
smallest_cost = tech_cost;
best_elem = &elem;
}
}
if (best_elem)
return best_elem->name;
return EMPTY_STRING;
}
const std::string& Empire::MostRPSpentEnqueuedTech() const {
float most_spent = -999999.9f; // arbitrary small number
const std::map<std::string, float>::value_type* best_progress = nullptr;
for (const auto& progress : m_research_progress) {
const auto& tech_name = progress.first;
if (!m_research_queue.InQueue(tech_name))
continue;
float rp_spent = progress.second;
if (rp_spent > most_spent) {
best_progress = &progress;
most_spent = rp_spent;
}
}
if (best_progress)
return best_progress->first;
return EMPTY_STRING;
}
const std::string& Empire::MostRPCostLeftEnqueuedTech() const {
float most_left = -999999.9f; // arbitrary small number
const std::map<std::string, float>::value_type* best_progress = nullptr;
for (const auto& progress : m_research_progress) {
const auto& tech_name = progress.first;
const Tech* tech = GetTech(tech_name);
if (!tech)
continue;
if (!m_research_queue.InQueue(tech_name))
continue;
float rp_spent = progress.second;
float rp_total_cost = tech->ResearchCost(m_id);
float rp_left = std::max(0.0f, rp_total_cost - rp_spent);
if (rp_left > most_left) {
best_progress = &progress;
most_left = rp_left;
}
}
if (best_progress)
return best_progress->first;
return EMPTY_STRING;
}
const std::string& Empire::TopPriorityResearchableTech() const {
if (m_research_queue.empty())
return EMPTY_STRING;
for (const auto& elem : m_research_queue) {
if (this->ResearchableTech(elem.name))
return elem.name;
}
return EMPTY_STRING;
}
const std::string& Empire::MostExpensiveResearchableTech() const {
return EMPTY_STRING; // TODO: IMPLEMENT THIS
}
const std::string& Empire::LeastExpensiveResearchableTech() const {
return EMPTY_STRING; // TODO: IMPLEMENT THIS
}
const std::string& Empire::MostRPSpentResearchableTech() const {
return EMPTY_STRING; // TODO: IMPLEMENT THIS
}
const std::string& Empire::MostRPCostLeftResearchableTech() const {
return EMPTY_STRING; // TODO: IMPLEMENT THIS
}
const std::set<std::string>& Empire::AvailableBuildingTypes() const
{ return m_available_building_types; }
bool Empire::BuildingTypeAvailable(const std::string& name) const
{ return m_available_building_types.count(name); }
const std::set<int>& Empire::ShipDesigns() const
{ return m_known_ship_designs; }
std::set<int> Empire::AvailableShipDesigns() const {
// create new map containing all ship designs that are available
std::set<int> retval;
for (int design_id : m_known_ship_designs) {
if (ShipDesignAvailable(design_id))
retval.insert(design_id);
}
return retval;
}
bool Empire::ShipDesignAvailable(int ship_design_id) const {
const ShipDesign* design = GetShipDesign(ship_design_id);
return design ? ShipDesignAvailable(*design) : false;
}
bool Empire::ShipDesignAvailable(const ShipDesign& design) const {
if (!design.Producible()) return false;
// design is kept, but still need to verify that it is buildable at this time. Part or hull tech
// requirements might prevent it from being built.
for (const auto& name : design.Parts()) {
if (name.empty())
continue; // empty slot can't be unavailable
if (!ShipPartAvailable(name))
return false;
}
if (!ShipHullAvailable(design.Hull()))
return false;
// if there are no reasons the design isn't available, then by default it is available
return true;
}
bool Empire::ShipDesignKept(int ship_design_id) const
{ return m_known_ship_designs.count(ship_design_id); }
const std::set<std::string>& Empire::AvailableShipParts() const
{ return m_available_part_types; }
bool Empire::ShipPartAvailable(const std::string& name) const
{ return m_available_part_types.count(name); }
const std::set<std::string>& Empire::AvailableShipHulls() const
{ return m_available_hull_types; }
bool Empire::ShipHullAvailable(const std::string& name) const
{ return m_available_hull_types.count(name); }
const ProductionQueue& Empire::GetProductionQueue() const
{ return m_production_queue; }
float Empire::ProductionStatus(int i) const {
if (0 > i || i >= static_cast<int>(m_production_queue.size()))
return -1.0f;
float item_progress = m_production_queue[i].progress;
float item_cost;
int item_time;
std::tie(item_cost, item_time) = this->ProductionCostAndTime(m_production_queue[i]);
return item_progress * item_cost * m_production_queue[i].blocksize;
}
std::pair<float, int> Empire::ProductionCostAndTime(const ProductionQueue::Element& element) const
{ return ProductionCostAndTime(element.item, element.location); }
std::pair<float, int> Empire::ProductionCostAndTime(const ProductionQueue::ProductionItem& item,
int location_id) const
{
if (item.build_type == BT_BUILDING) {
const BuildingType* type = GetBuildingType(item.name);
if (!type)
return std::make_pair(-1.0, -1);
return std::make_pair(type->ProductionCost(m_id, location_id),
type->ProductionTime(m_id, location_id));
} else if (item.build_type == BT_SHIP) {
const ShipDesign* design = GetShipDesign(item.design_id);
if (design)
return std::make_pair(design->ProductionCost(m_id, location_id),
design->ProductionTime(m_id, location_id));
return std::make_pair(-1.0, -1);
} else if (item.build_type == BT_STOCKPILE) {
return std::make_pair(1.0, 1);
}
ErrorLogger() << "Empire::ProductionCostAndTime was passed a ProductionItem with an invalid BuildType";
return std::make_pair(-1.0, -1);
}
bool Empire::HasExploredSystem(int ID) const
{ return m_explored_systems.count(ID); }
bool Empire::ProducibleItem(BuildType build_type, int location_id) const {
if (build_type == BT_SHIP)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_SHIP with no further parameters, but ship designs are tracked by number");
if (build_type == BT_BUILDING)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_BUILDING with no further parameters, but buildings are tracked by name");
if (location_id == INVALID_OBJECT_ID)
return false;
// must own the production location...
auto location = GetUniverseObject(location_id);
if (!location) {
WarnLogger() << "Empire::ProducibleItem for BT_STOCKPILE unable to get location object with id " << location_id;
return false;
}
if (!location->OwnedBy(m_id))
return false;
if (!std::dynamic_pointer_cast<const ResourceCenter>(location))
return false;
if (build_type == BT_STOCKPILE) {
return true;
} else {
ErrorLogger() << "Empire::ProducibleItem was passed an invalid BuildType";
return false;
}
}
bool Empire::ProducibleItem(BuildType build_type, const std::string& name, int location) const {
// special case to check for ships being passed with names, not design ids
if (build_type == BT_SHIP)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_SHIP with a name, but ship designs are tracked by number");
if (build_type == BT_STOCKPILE)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_STOCKPILE with a name, but the stockpile does not need an identification");
if (build_type == BT_BUILDING && !BuildingTypeAvailable(name))
return false;
const auto* building_type = GetBuildingType(name);
if (!building_type || !building_type->Producible())
return false;
auto build_location = GetUniverseObject(location);
if (!build_location)
return false;
if (build_type == BT_BUILDING) {
// specified location must be a valid production location for that building type
return building_type->ProductionLocation(m_id, location);
} else {
ErrorLogger() << "Empire::ProducibleItem was passed an invalid BuildType";
return false;
}
}
bool Empire::ProducibleItem(BuildType build_type, int design_id, int location) const {
// special case to check for buildings being passed with ids, not names
if (build_type == BT_BUILDING)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_BUILDING with a design id number, but buildings are tracked by name");
if (build_type == BT_STOCKPILE)
throw std::invalid_argument("Empire::ProducibleItem was passed BuildType BT_STOCKPILE with a design id, but the stockpile does not need an identification");
if (build_type == BT_SHIP && !ShipDesignAvailable(design_id))
return false;
// design must be known to this empire
const ShipDesign* ship_design = GetShipDesign(design_id);
if (!ship_design || !ship_design->Producible())
return false;
auto build_location = GetUniverseObject(location);
if (!build_location) return false;
if (build_type == BT_SHIP) {
// specified location must be a valid production location for this design
return ship_design->ProductionLocation(m_id, location);
} else {
ErrorLogger() << "Empire::ProducibleItem was passed an invalid BuildType";
return false;
}
}
bool Empire::ProducibleItem(const ProductionQueue::ProductionItem& item, int location) const {
if (item.build_type == BT_BUILDING)
return ProducibleItem(item.build_type, item.name, location);
else if (item.build_type == BT_SHIP)
return ProducibleItem(item.build_type, item.design_id, location);
else if (item.build_type == BT_STOCKPILE)
return ProducibleItem(item.build_type, location);
else
throw std::invalid_argument("Empire::ProducibleItem was passed a ProductionItem with an invalid BuildType");
return false;
}
bool Empire::EnqueuableItem(BuildType build_type, const std::string& name, int location) const {
if (build_type != BT_BUILDING)
return false;
const auto* building_type = GetBuildingType(name);
if (!building_type || !building_type->Producible())
return false;
auto build_location = GetUniverseObject(location);
if (!build_location)
return false;
// specified location must be a valid production location for that building type
return building_type->EnqueueLocation(m_id, location);
}
bool Empire::EnqueuableItem(const ProductionQueue::ProductionItem& item, int location) const {
if (item.build_type == BT_BUILDING)
return EnqueuableItem(item.build_type, item.name, location);
else if (item.build_type == BT_SHIP) // ships don't have a distinction between enqueuable and producible
return ProducibleItem(item.build_type, item.design_id, location);
else if (item.build_type == BT_STOCKPILE) // stockpile does not have a distinction between enqueuable and producible
return ProducibleItem(item.build_type, location);
else
throw std::invalid_argument("Empire::ProducibleItem was passed a ProductionItem with an invalid BuildType");
return false;
}
int Empire::NumSitRepEntries(int turn/* = INVALID_GAME_TURN*/) const {
if (turn == INVALID_GAME_TURN)
return m_sitrep_entries.size();
int count = 0;
for (const SitRepEntry& sitrep : m_sitrep_entries)
if (sitrep.GetTurn() == turn)
count++;
return count;
}
bool Empire::Eliminated() const {
return m_eliminated;
}
void Empire::Eliminate() {
m_eliminated = true;
for (auto& entry : Empires())
entry.second->AddSitRepEntry(CreateEmpireEliminatedSitRep(EmpireID()));
// some Empire data not cleared when eliminating since it might be useful
// to remember later, and having it doesn't hurt anything (as opposed to
// the production queue that might actually cause some problems if left
// uncleared after elimination
m_capital_id = INVALID_OBJECT_ID;
// m_newly_researched_techs
// m_techs
m_research_queue.clear();
m_research_progress.clear();
m_production_queue.clear();
// m_available_building_types;
// m_available_part_types;
// m_available_hull_types;
// m_explored_systems;
// m_known_ship_designs;
m_sitrep_entries.clear();
for (auto& entry : m_resource_pools)
entry.second->SetObjects(std::vector<int>());
m_population_pool.SetPopCenters(std::vector<int>());
// m_ship_names_used;
m_supply_system_ranges.clear();
m_supply_unobstructed_systems.clear();
}
bool Empire::Won() const {
return !m_victories.empty();
}
void Empire::Win(const std::string& reason) {
if (m_victories.insert(reason).second) {
for (auto& entry : Empires()) {
entry.second->AddSitRepEntry(CreateVictorySitRep(reason, EmpireID()));
}
}
}
void Empire::UpdateSystemSupplyRanges(const std::set<int>& known_objects) {
//std::cout << "Empire::UpdateSystemSupplyRanges() for empire " << this->Name() << std::endl;
m_supply_system_ranges.clear();
// as of this writing, only planets can generate supply propagation
std::vector<std::shared_ptr<const UniverseObject>> owned_planets;
for (int object_id : known_objects) {
if (auto planet = GetPlanet(object_id))
if (planet->OwnedBy(this->EmpireID()))
owned_planets.push_back(planet);
}
//std::cout << "... empire owns " << owned_planets.size() << " planets" << std::endl;
for (auto& obj : owned_planets) {
//std::cout << "... considering owned planet: " << obj->Name() << std::endl;
// ensure object is within a system, from which it can distribute supplies
int system_id = obj->SystemID();
if (system_id == INVALID_OBJECT_ID)
continue; // TODO: consider future special case if current object is itself a system
// check if object has a supply meter
if (obj->GetMeter(METER_SUPPLY)) {
// get resource supply range for next turn for this object
float supply_range = obj->InitialMeterValue(METER_SUPPLY);
// if this object can provide more supply range than the best previously checked object in this system, record its range as the new best for the system
auto system_it = m_supply_system_ranges.find(system_id); // try to find a previous entry for this system's supply range
if (system_it == m_supply_system_ranges.end() || supply_range > system_it->second) {// if there is no previous entry, or the previous entry is shorter than the new one, add or replace the entry
//std::cout << " ... object " << obj->Name() << " has resource supply range: " << resource_supply_range << std::endl;
m_supply_system_ranges[system_id] = supply_range;
}
}
}
}
void Empire::UpdateSystemSupplyRanges() {
const Universe& universe = GetUniverse();
const ObjectMap& empire_known_objects = EmpireKnownObjects(this->EmpireID());
// get ids of objects partially or better visible to this empire.
std::vector<int> known_objects_vec = empire_known_objects.FindObjectIDs();
const std::set<int>& known_destroyed_objects = universe.EmpireKnownDestroyedObjectIDs(this->EmpireID());
std::set<int> known_objects_set;
// exclude objects known to have been destroyed (or rather, include ones that aren't known by this empire to be destroyed)
for (int object_id : known_objects_vec)
if (!known_destroyed_objects.count(object_id))
known_objects_set.insert(object_id);
UpdateSystemSupplyRanges(known_objects_set);
}
void Empire::UpdateUnobstructedFleets() {
const std::set<int>& known_destroyed_objects =
GetUniverse().EmpireKnownDestroyedObjectIDs(this->EmpireID());
for (int system_id : m_supply_unobstructed_systems) {
auto system = GetSystem(system_id);
if (!system)
continue;
for (auto& fleet : Objects().FindObjects<Fleet>(system->FleetIDs())) {
if (known_destroyed_objects.count(fleet->ID()))
continue;
if (fleet->OwnedBy(m_id))
fleet->SetArrivalStarlane(system_id);
}
}
}
void Empire::UpdateSupplyUnobstructedSystems(bool precombat /*=false*/) {
Universe& universe = GetUniverse();
// get ids of systems partially or better visible to this empire.
// TODO: make a UniverseObjectVisitor for objects visible to an empire at a specified visibility or greater
std::vector<int> known_systems_vec = EmpireKnownObjects(this->EmpireID()).FindObjectIDs<System>();
const std::set<int>& known_destroyed_objects = universe.EmpireKnownDestroyedObjectIDs(this->EmpireID());
std::set<int> known_systems_set;
// exclude systems known to have been destroyed (or rather, include ones that aren't known to be destroyed)
for (int system_id : known_systems_vec)
if (!known_destroyed_objects.count(system_id))
known_systems_set.insert(system_id);
UpdateSupplyUnobstructedSystems(known_systems_set, precombat);
}
void Empire::UpdateSupplyUnobstructedSystems(const std::set<int>& known_systems, bool precombat /*=false*/) {
//DebugLogger() << "UpdateSupplyUnobstructedSystems for empire " << m_id;
m_supply_unobstructed_systems.clear();
// get systems with historically at least partial visibility
std::set<int> systems_with_at_least_partial_visibility_at_some_point;
for (int system_id : known_systems) {
const auto& vis_turns = GetUniverse().GetObjectVisibilityTurnMapByEmpire(system_id, m_id);
if (vis_turns.count(VIS_PARTIAL_VISIBILITY))
systems_with_at_least_partial_visibility_at_some_point.insert(system_id);
}
// get all fleets, or just those visible to this client's empire
const auto& known_destroyed_objects = GetUniverse().EmpireKnownDestroyedObjectIDs(this->EmpireID());
// get empire supply ranges
std::map<int, std::map<int, float>> empire_system_supply_ranges;
for (const auto& entry : Empires()) {
const Empire* empire = entry.second;
empire_system_supply_ranges[entry.first] = empire->SystemSupplyRanges();
}
// find systems that contain fleets that can either maintain supply or block supply.
// to affect supply in either manner, a fleet must be armed & aggressive, & must be not
// trying to depart the systme. Qualifying enemy fleets will blockade if no friendly fleets
// are present, or if the friendly fleets were already blockade-restricted and the enemy
// fleets were not (meaning that the enemy fleets were continuing an existing blockade)
// Friendly fleets can preserve available starlane accesss even if they are trying to leave the system
// Unrestricted lane access (i.e, (fleet->ArrivalStarlane() == system->ID()) ) is used as a proxy for
// order of arrival -- if an enemy has unrestricted lane access and you don't, they must have arrived
// before you, or be in cahoots with someone who did.
std::set<int> systems_containing_friendly_fleets;
std::set<int> systems_with_lane_preserving_fleets;
std::set<int> unrestricted_friendly_systems;
std::set<int> systems_containing_obstructing_objects;
std::set<int> unrestricted_obstruction_systems;
for (auto& fleet : GetUniverse().Objects().FindObjects<Fleet>()) {
int system_id = fleet->SystemID();
if (system_id == INVALID_OBJECT_ID) {
continue; // not in a system, so can't affect system obstruction
} else if (known_destroyed_objects.count(fleet->ID())) {
continue; //known to be destroyed so can't affect supply, important just in case being updated on client side
}
//DebugLogger() << "Fleet " << fleet->ID() << " is in system " << system_id << " with next system " << fleet->NextSystemID() << " and is owned by " << fleet->Owner() << " armed: " << fleet->HasArmedShips() << " and agressive: " << fleet->Aggressive();
if (fleet->HasArmedShips() && fleet->Aggressive()) {
if (fleet->OwnedBy(m_id)) {
if (fleet->NextSystemID() == INVALID_OBJECT_ID || fleet->NextSystemID() == fleet->SystemID()) {
systems_containing_friendly_fleets.insert(system_id);
if (fleet->ArrivalStarlane() == system_id)
unrestricted_friendly_systems.insert(system_id);
else
systems_with_lane_preserving_fleets.insert(system_id);
}
} else if (fleet->NextSystemID() == INVALID_OBJECT_ID || fleet->NextSystemID() == fleet->SystemID()) {
int fleet_owner = fleet->Owner();
bool fleet_at_war = fleet_owner == ALL_EMPIRES || Empires().GetDiplomaticStatus(m_id, fleet_owner) == DIPLO_WAR;
// newly created ships are not allowed to block supply since they have not even potentially gone
// through a combat round at the present location. Potential sources for such new ships are monsters
// created via Effect. (Ships/fleets constructed by empires are currently created at a later stage of
// turn processing, but even if such were moved forward they should be similarly restricted.) For
// checks after combat and prior to turn advancement, we check against age zero here. For checks
// after turn advancement but prior to combat we check against age 1. Because the
// fleets themselves may be created and/or destroyed purely as organizational matters, we check ship
// age not fleet age.
int cutoff_age = precombat ? 1 : 0;
if (fleet_at_war && fleet->MaxShipAgeInTurns() > cutoff_age) {
systems_containing_obstructing_objects.insert(system_id);
if (fleet->ArrivalStarlane() == system_id)
unrestricted_obstruction_systems.insert(system_id);
}
}
}
}
//std::stringstream ss;
//for (int obj_id : systems_containing_obstructing_objects)
//{ ss << obj_id << ", "; }
//DebugLogger() << "systems with obstructing objects for empire " << m_id << " : " << ss.str();
// check each potential supplyable system for whether it can propagate supply.
for (int sys_id : known_systems) {
//DebugLogger() << "deciding unobstructedness for system " << sys_id;
// has empire ever seen this system with partial or better visibility?
if (!systems_with_at_least_partial_visibility_at_some_point.count(sys_id))
continue;
// if system is explored, then whether it can propagate supply depends
// on what friendly / enemy ships and planets are in the system
if (unrestricted_friendly_systems.count(sys_id))
// if there are unrestricted friendly ships, supply can propagate
m_supply_unobstructed_systems.insert(sys_id);
else if (systems_containing_friendly_fleets.count(sys_id)) {
if (!unrestricted_obstruction_systems.count(sys_id))
// if there are (previously) restricted friendly ships, and no unrestricted enemy fleets, supply can propagate
m_supply_unobstructed_systems.insert(sys_id);
} else if (!systems_containing_obstructing_objects.count(sys_id))
m_supply_unobstructed_systems.insert(sys_id);
else if (!systems_with_lane_preserving_fleets.count(sys_id)) {
// otherwise, if system contains no friendly fleets capable of
// maintaining lane access but does contain an unfriendly fleet,
// so it is obstructed, so isn't included in the unobstructed
// systems set. Furthermore, this empire's available system exit
// lanes for this system are cleared
if (!m_preserved_system_exit_lanes[sys_id].empty()) {
//DebugLogger() << "Empire::UpdateSupplyUnobstructedSystems clearing available lanes for system ("<<sys_id<<"); available lanes were:";
//for (int system_id : m_preserved_system_exit_lanes[sys_id])
// DebugLogger() << "...... "<< system_id;
m_preserved_system_exit_lanes[sys_id].clear();
}
}
}
}
void Empire::RecordPendingLaneUpdate(int start_system_id, int dest_system_id) {
if (!m_supply_unobstructed_systems.count(start_system_id))
m_pending_system_exit_lanes[start_system_id].insert(dest_system_id);
else { // if the system is unobstructed, mark all its lanes as avilable
auto system = GetSystem(start_system_id);
for (const auto& lane : system->StarlanesWormholes()) {
m_pending_system_exit_lanes[start_system_id].insert(lane.first); // will add both starlanes and wormholes
}
}
}
void Empire::UpdatePreservedLanes() {
for (auto& system : m_pending_system_exit_lanes) {
m_preserved_system_exit_lanes[system.first].insert(system.second.begin(), system.second.end());
system.second.clear();
}
m_pending_system_exit_lanes.clear(); // TODO: consider: not really necessary, & may be more efficient to not clear.
}
const std::map<int, float>& Empire::SystemSupplyRanges() const
{ return m_supply_system_ranges; }
const std::set<int>& Empire::SupplyUnobstructedSystems() const
{ return m_supply_unobstructed_systems; }
const bool Empire::PreservedLaneTravel(int start_system_id, int dest_system_id) const {
auto find_it = m_preserved_system_exit_lanes.find(start_system_id);
return find_it != m_preserved_system_exit_lanes.end()
&& find_it->second.count(dest_system_id);
}
const std::set<int>& Empire::ExploredSystems() const
{ return m_explored_systems; }
const std::map<int, std::set<int>> Empire::KnownStarlanes() const {
// compile starlanes leading into or out of each system
std::map<int, std::set<int>> retval;
const Universe& universe = GetUniverse();
const std::set<int>& known_destroyed_objects = universe.EmpireKnownDestroyedObjectIDs(this->EmpireID());
for (auto sys_it = Objects().const_begin<System>();
sys_it != Objects().const_end<System>(); ++sys_it)
{
int start_id = sys_it->ID();
// exclude lanes starting at systems known to be destroyed
if (known_destroyed_objects.count(start_id))
continue;
for (const auto& lane : sys_it->StarlanesWormholes()) {
if (lane.second || known_destroyed_objects.count(lane.second))
continue; // is a wormhole, not a starlane, or is connected to a known destroyed system
int end_id = lane.first;
retval[start_id].insert(end_id);
retval[end_id].insert(start_id);
}
}
return retval;
}
const std::map<int, std::set<int>> Empire::VisibleStarlanes() const {
std::map<int, std::set<int>> retval; // compile starlanes leading into or out of each system
const Universe& universe = GetUniverse();
const ObjectMap& objects = universe.Objects();
for (auto sys_it = objects.const_begin<System>();
sys_it != objects.const_end<System>(); ++sys_it)
{
int start_id = sys_it->ID();
// is system visible to this empire?
if (universe.GetObjectVisibilityByEmpire(start_id, m_id) <= VIS_NO_VISIBILITY)
continue;
// get system's visible lanes for this empire
for (auto& lane : sys_it->VisibleStarlanesWormholes(m_id)) {
if (lane.second)
continue; // is a wormhole, not a starlane
int end_id = lane.first;
retval[start_id].insert(end_id);
retval[end_id].insert(start_id);
}
}
return retval;
}
Empire::SitRepItr Empire::SitRepBegin() const
{ return m_sitrep_entries.begin(); }
Empire::SitRepItr Empire::SitRepEnd() const
{ return m_sitrep_entries.end(); }
float Empire::ProductionPoints() const
{ return GetResourcePool(RE_INDUSTRY)->TotalOutput(); }
const std::shared_ptr<ResourcePool> Empire::GetResourcePool(ResourceType resource_type) const {
auto it = m_resource_pools.find(resource_type);
if (it == m_resource_pools.end())
return nullptr;
return it->second;
}
float Empire::ResourceStockpile(ResourceType type) const {
auto it = m_resource_pools.find(type);
if (it == m_resource_pools.end())
throw std::invalid_argument("Empire::ResourceStockpile passed invalid ResourceType");
return it->second->Stockpile();
}
float Empire::ResourceOutput(ResourceType type) const {
auto it = m_resource_pools.find(type);
if (it == m_resource_pools.end())
throw std::invalid_argument("Empire::ResourceOutput passed invalid ResourceType");
return it->second->TotalOutput();
}
float Empire::ResourceAvailable(ResourceType type) const {
auto it = m_resource_pools.find(type);
if (it == m_resource_pools.end())
throw std::invalid_argument("Empire::ResourceAvailable passed invalid ResourceType");
return it->second->TotalAvailable();
}
const PopulationPool& Empire::GetPopulationPool() const
{ return m_population_pool; }
float Empire::Population() const
{ return m_population_pool.Population(); }
void Empire::SetResourceStockpile(ResourceType resource_type, float stockpile) {
auto it = m_resource_pools.find(resource_type);
if (it == m_resource_pools.end())
throw std::invalid_argument("Empire::SetResourceStockpile passed invalid ResourceType");
return it->second->SetStockpile(stockpile);
}
void Empire::PlaceTechInQueue(const std::string& name, int pos/* = -1*/) {
// do not add tech that is already researched
if (name.empty() || TechResearched(name) || m_techs.count(name) || m_newly_researched_techs.count(name))
return;
const Tech* tech = GetTech(name);
if (!tech || !tech->Researchable())
return;
auto it = m_research_queue.find(name);
if (pos < 0 || static_cast<int>(m_research_queue.size()) <= pos) {
// default to putting at end
bool paused = false;
if (it != m_research_queue.end()) {
paused = it->paused;
m_research_queue.erase(it);
}