• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Return-To-The-Roots / s25client / 22035817203

15 Feb 2026 12:39PM UTC coverage: 50.326% (-0.5%) from 50.826%
22035817203

Pull #1720

github

web-flow
Merge 45697e37f into e6489dca6
Pull Request #1720: Add leather addon

277 of 1060 new or added lines in 65 files covered. (26.13%)

51 existing lines in 28 files now uncovered.

23002 of 45706 relevant lines covered (50.33%)

41826.03 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.91
/libs/s25main/GamePlayer.cpp
1
// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org)
2
//
3
// SPDX-License-Identifier: GPL-2.0-or-later
4

5
#include "GamePlayer.h"
6
#include "AddonHelperFunctions.h"
7
#include "Cheats.h"
8
#include "EventManager.h"
9
#include "FindWhConditions.h"
10
#include "GameInterface.h"
11
#include "GlobalGameSettings.h"
12
#include "LeatherLoader.h"
13
#include "RoadSegment.h"
14
#include "SerializedGameData.h"
15
#include "TradePathCache.h"
16
#include "Ware.h"
17
#include "WineLoader.h"
18
#include "addons/const_addons.h"
19
#include "buildings/noBuildingSite.h"
20
#include "buildings/nobHQ.h"
21
#include "buildings/nobHarborBuilding.h"
22
#include "buildings/nobMilitary.h"
23
#include "buildings/nobUsual.h"
24
#include "figures/nofCarrier.h"
25
#include "figures/nofFlagWorker.h"
26
#include "helpers/containerUtils.h"
27
#include "helpers/mathFuncs.h"
28
#include "lua/LuaInterfaceGame.h"
29
#include "notifications/ToolNote.h"
30
#include "pathfinding/RoadPathFinder.h"
31
#include "postSystem/DiplomacyPostQuestion.h"
32
#include "postSystem/PostManager.h"
33
#include "random/Random.h"
34
#include "world/GameWorld.h"
35
#include "world/TradeRoute.h"
36
#include "nodeObjs/noFlag.h"
37
#include "nodeObjs/noShip.h"
38
#include "gameTypes/BuildingCount.h"
39
#include "gameTypes/GoodTypes.h"
40
#include "gameTypes/JobTypes.h"
41
#include "gameTypes/PactTypes.h"
42
#include "gameTypes/VisualSettings.h"
43
#include "gameData/BuildingConsts.h"
44
#include "gameData/BuildingProperties.h"
45
#include "gameData/GoodConsts.h"
46
#include "gameData/SettingTypeConv.h"
47
#include "gameData/ShieldConsts.h"
48
#include "gameData/ToolConsts.h"
49
#include "s25util/Log.h"
50
#include <limits>
51
#include <numeric>
52

53
GamePlayer::GamePlayer(unsigned playerId, const PlayerInfo& playerInfo, GameWorld& world)
399✔
54
    : GamePlayerInfo(playerId, playerInfo), world(world), hqPos(MapPoint::Invalid()), emergency(false)
399✔
55
{
56
    std::fill(building_enabled.begin(), building_enabled.end(), true);
399✔
57

58
    LoadStandardDistribution();
399✔
59
    useCustomBuildOrder_ = false;
399✔
60
    build_order = GetStandardBuildOrder();
399✔
61
    transportPrio = STD_TRANSPORT_PRIO;
399✔
62
    LoadStandardMilitarySettings();
399✔
63
    LoadStandardToolSettings();
399✔
64

65
    // Inventur nullen
66
    global_inventory.clear();
399✔
67

68
    // Statistiken mit 0en füllen
69
    statistic = {};
399✔
70
    statisticCurrentData = {};
399✔
71
    statisticCurrentMerchandiseData = {};
399✔
72

73
    RecalcDistribution();
399✔
74
}
399✔
75

76
void GamePlayer::LoadStandardToolSettings()
399✔
77
{
78
    // metalwork tool request
79

80
    // manually
81
    std::fill(tools_ordered.begin(), tools_ordered.end(), 0u);
399✔
82
    std::fill(tools_ordered_delta.begin(), tools_ordered_delta.end(), 0);
399✔
83

84
    // percentage (tool-settings-window-slider, in 10th percent)
85
    toolsSettings_[Tool::Tongs] = 1;
399✔
86
    toolsSettings_[Tool::Hammer] = 4;
399✔
87
    toolsSettings_[Tool::Axe] = 2;
399✔
88
    toolsSettings_[Tool::Saw] = 5;
399✔
89
    toolsSettings_[Tool::PickAxe] = 7;
399✔
90
    toolsSettings_[Tool::Shovel] = 1;
399✔
91
    toolsSettings_[Tool::Crucible] = 3;
399✔
92
    toolsSettings_[Tool::RodAndLine] = 1;
399✔
93
    toolsSettings_[Tool::Scythe] = 2;
399✔
94
    toolsSettings_[Tool::Cleaver] = 1;
399✔
95
    toolsSettings_[Tool::Rollingpin] = 2;
399✔
96
    toolsSettings_[Tool::Bow] = 1;
399✔
97
}
399✔
98

99
void GamePlayer::LoadStandardMilitarySettings()
399✔
100
{
101
    // military settings (military-window-slider, in 10th percent)
102
    militarySettings_[0] = MILITARY_SETTINGS_SCALE[0]; //-V525
399✔
103
    militarySettings_[1] = 3;
399✔
104
    militarySettings_[2] = MILITARY_SETTINGS_SCALE[2];
399✔
105
    militarySettings_[3] = 3;
399✔
106
    militarySettings_[4] = 0;
399✔
107
    militarySettings_[5] = 1;
399✔
108
    militarySettings_[6] = MILITARY_SETTINGS_SCALE[6];
399✔
109
    militarySettings_[7] = MILITARY_SETTINGS_SCALE[7];
399✔
110
}
399✔
111

112
BuildOrders GamePlayer::GetStandardBuildOrder()
401✔
113
{
114
    BuildOrders ordering;
115

116
    // Baureihenfolge füllen
117
    unsigned curPrio = 0;
401✔
118
    for(const auto bld : helpers::enumRange<BuildingType>())
33,684✔
119
    {
120
        if(bld == BuildingType::Headquarters || !BuildingProperties::IsValid(bld))
16,040✔
121
            continue;
802✔
122

123
        RTTR_Assert(curPrio < ordering.size());
15,238✔
124
        ordering[curPrio] = bld;
15,238✔
125
        ++curPrio;
15,238✔
126
    }
127
    RTTR_Assert(curPrio == ordering.size());
401✔
128
    return ordering;
401✔
129
}
130

131
void GamePlayer::LoadStandardDistribution()
399✔
132
{
133
    // Verteilung mit Standardwerten füllen bei Waren mit nur einem Ziel (wie z.B. Mehl, Holz...)
134
    distribution[GoodType::Flour].client_buildings.push_back(BuildingType::Bakery);
399✔
135
    distribution[GoodType::Gold].client_buildings.push_back(BuildingType::Mint);
399✔
136
    distribution[GoodType::IronOre].client_buildings.push_back(BuildingType::Ironsmelter);
399✔
137
    distribution[GoodType::Ham].client_buildings.push_back(BuildingType::Slaughterhouse);
399✔
138
    distribution[GoodType::Stones].client_buildings.push_back(
399✔
139
      BuildingType::Headquarters); // BuildingType::Headquarters = Baustellen!
399✔
140
    distribution[GoodType::Stones].client_buildings.push_back(BuildingType::Catapult);
399✔
141
    distribution[GoodType::Grapes].client_buildings.push_back(BuildingType::Winery);
399✔
142
    distribution[GoodType::Wine].client_buildings.push_back(BuildingType::Temple);
399✔
143
    distribution[GoodType::Skins].client_buildings.push_back(BuildingType::Tannery);
399✔
144
    distribution[GoodType::Leather].client_buildings.push_back(BuildingType::LeatherWorks);
399✔
145

146
    // Waren mit mehreren möglichen Zielen erstmal nullen, kann dann im Fenster eingestellt werden
147
    for(const auto i : helpers::enumRange<GoodType>())
33,516✔
148
    {
149
        std::fill(distribution[i].percent_buildings.begin(), distribution[i].percent_buildings.end(), 0);
15,960✔
150
        distribution[i].selected_goal = 0;
15,960✔
151
    }
152

153
    // Standardverteilung der Waren
154
    for(const DistributionMapping& mapping : distributionMap)
11,970✔
155
    {
156
        distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)] = std::get<2>(mapping);
11,571✔
157
    }
158
}
399✔
159

160
GamePlayer::~GamePlayer() = default;
806✔
161

162
void GamePlayer::Serialize(SerializedGameData& sgd) const
17✔
163
{
164
    // PlayerStatus speichern, ehemalig
165
    sgd.PushEnum<uint8_t>(ps);
17✔
166

167
    // Nur richtige Spieler serialisieren
168
    if(ps != PlayerState::Occupied && ps != PlayerState::AI)
17✔
169
        return;
3✔
170

171
    sgd.PushBool(isDefeated);
14✔
172

173
    buildings.Serialize(sgd);
14✔
174

175
    sgd.PushObjectContainer(roads, true);
14✔
176

177
    sgd.PushUnsignedInt(jobs_wanted.size());
14✔
178
    for(const JobNeeded& job : jobs_wanted)
18✔
179
    {
180
        sgd.PushEnum<uint8_t>(job.job);
4✔
181
        sgd.PushObject(job.workplace);
4✔
182
    }
183

184
    sgd.PushObjectContainer(ware_list, true);
14✔
185
    sgd.PushObjectContainer(flagworkers);
14✔
186
    sgd.PushObjectContainer(ships, true);
14✔
187

188
    helpers::pushContainer(sgd, shouldSendDefenderList);
14✔
189
    helpers::pushPoint(sgd, hqPos);
14✔
190

191
    for(const Distribution& dist : distribution)
574✔
192
    {
193
        helpers::pushContainer(sgd, dist.percent_buildings);
560✔
194
        helpers::pushContainer(sgd, dist.client_buildings);
560✔
195
        helpers::pushContainer(sgd, dist.goals);
560✔
196
        sgd.PushUnsignedInt(dist.selected_goal);
560✔
197
    }
198

199
    sgd.PushBool(useCustomBuildOrder_);
14✔
200
    helpers::pushContainer(sgd, build_order);
14✔
201
    helpers::pushContainer(sgd, transportPrio);
14✔
202
    helpers::pushContainer(sgd, militarySettings_);
14✔
203
    helpers::pushContainer(sgd, toolsSettings_);
14✔
204
    helpers::pushContainer(sgd, tools_ordered);
14✔
205
    helpers::pushContainer(sgd, global_inventory.goods);
14✔
206
    helpers::pushContainer(sgd, global_inventory.people);
14✔
207
    helpers::pushContainer(sgd, global_inventory.armoredSoldiers);
14✔
208

209
    // für Statistik
210
    for(const Statistic& curStatistic : statistic)
70✔
211
    {
212
        // normale Statistik
213
        for(const auto& curData : curStatistic.data)
560✔
214
            helpers::pushContainer(sgd, curData);
504✔
215

216
        // Warenstatistik
217
        for(unsigned j = 0; j < NUM_STAT_MERCHANDISE_TYPES; ++j)
840✔
218
            helpers::pushContainer(sgd, curStatistic.merchandiseData[j]);
784✔
219

220
        sgd.PushUnsignedShort(curStatistic.currentIndex);
56✔
221
        sgd.PushUnsignedShort(curStatistic.counter);
56✔
222
    }
223
    helpers::pushContainer(sgd, statisticCurrentData);
14✔
224
    helpers::pushContainer(sgd, statisticCurrentMerchandiseData);
14✔
225

226
    // Serialize Pacts:
227
    for(const auto& playerPacts : pacts)
126✔
228
    {
229
        for(const Pact& pact : playerPacts)
336✔
230
            pact.Serialize(sgd);
224✔
231
    }
232

233
    sgd.PushBool(emergency);
14✔
234
}
235

236
void GamePlayer::Deserialize(SerializedGameData& sgd)
8✔
237
{
238
    std::fill(building_enabled.begin(), building_enabled.end(), true);
8✔
239

240
    // Ehemaligen PS auslesen
241
    auto origin_ps = sgd.Pop<PlayerState>();
8✔
242
    // Nur richtige Spieler serialisieren
243
    if(origin_ps != PlayerState::Occupied && origin_ps != PlayerState::AI)
8✔
244
        return;
1✔
245

246
    isDefeated = sgd.PopBool();
7✔
247
    buildings.Deserialize(sgd);
7✔
248

249
    sgd.PopObjectContainer(roads, GO_Type::Roadsegment);
7✔
250

251
    jobs_wanted.resize(sgd.PopUnsignedInt());
7✔
252
    for(JobNeeded& job : jobs_wanted)
9✔
253
    {
254
        job.job = sgd.Pop<Job>();
2✔
255
        job.workplace = sgd.PopObject<noRoadNode>();
2✔
256
    }
257

258
    if(sgd.GetGameDataVersion() < 2)
7✔
259
        buildings.Deserialize2(sgd);
×
260

261
    sgd.PopObjectContainer(ware_list, GO_Type::Ware);
7✔
262
    sgd.PopObjectContainer(flagworkers);
7✔
263
    sgd.PopObjectContainer(ships, GO_Type::Ship);
7✔
264

265
    sgd.PopContainer(shouldSendDefenderList);
7✔
266

267
    hqPos = sgd.PopMapPoint();
7✔
268

269
    for(const auto i : helpers::enumRange<GoodType>())
588✔
270
    {
271
        if(sgd.GetGameDataVersion() < 11 && wineaddon::isWineAddonGoodType(i))
280✔
272
            continue;
×
273

274
        if(sgd.GetGameDataVersion() < 12 && leatheraddon::isLeatherAddonGoodType(i))
280✔
NEW
275
            continue;
×
276

277
        Distribution& dist = distribution[i];
280✔
278
        helpers::popContainer(sgd, dist.percent_buildings);
280✔
279
        // Set standard value otherwise its zero and Slaughterhouse never gets ham
280
        // because the ham distribution was not there in earlier versions
281
        if(sgd.GetGameDataVersion() < 12 && i == GoodType::Ham)
280✔
282
        {
NEW
283
            dist.percent_buildings[BuildingType::Slaughterhouse] = 8;
×
284
        }
285

286
        if(sgd.GetGameDataVersion() < 7)
280✔
287
        {
288
            dist.client_buildings.resize(sgd.PopUnsignedInt());
×
289
            helpers::popContainer(sgd, dist.client_buildings, true);
×
290
            dist.goals.resize(sgd.PopUnsignedInt());
×
291
            helpers::popContainer(sgd, dist.goals, true);
×
292
        } else
293
        {
294
            helpers::popContainer(sgd, dist.client_buildings);
280✔
295
            helpers::popContainer(sgd, dist.goals);
280✔
296
        }
297
        dist.selected_goal = sgd.PopUnsignedInt();
280✔
298
    }
299

300
    useCustomBuildOrder_ = sgd.PopBool();
7✔
301

302
    if(sgd.GetGameDataVersion() < 12)
7✔
303
    {
304
        auto countOfNotAvailableBuildingsInSaveGame =
NEW
305
          sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonBuildings : numLeatherAddonBuildings;
×
NEW
306
        std::vector<BuildingType> build_order_raw(build_order.size() - countOfNotAvailableBuildingsInSaveGame);
×
307
        helpers::popContainer(sgd, build_order_raw, true);
×
308

NEW
309
        if(sgd.GetGameDataVersion() < 11)
×
NEW
310
            build_order_raw.insert(build_order_raw.end(),
×
NEW
311
                                   {BuildingType::Vineyard, BuildingType::Winery, BuildingType::Temple});
×
312

NEW
313
        if(sgd.GetGameDataVersion() < 12)
×
NEW
314
            build_order_raw.insert(build_order_raw.end(),
×
NEW
315
                                   {BuildingType::Skinner, BuildingType::Tannery, BuildingType::LeatherWorks});
×
316

UNCOV
317
        std::copy(build_order_raw.begin(), build_order_raw.end(), build_order.begin());
×
318

319
        auto countOfNotAvailableGoodsInSaveGame =
NEW
320
          sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonGoods : numLeatherAddonGoods;
×
NEW
321
        std::vector<uint8_t> transportPrio_raw(transportPrio.size() - countOfNotAvailableGoodsInSaveGame);
×
322
        helpers::popContainer(sgd, transportPrio_raw, true);
×
323
        std::copy(transportPrio_raw.begin(), transportPrio_raw.end(), transportPrio.begin());
×
NEW
324
        std::transform(transportPrio.begin(), transportPrio.end() - countOfNotAvailableGoodsInSaveGame,
×
325
                       transportPrio.begin(),
NEW
326
                       [](uint8_t& prio) { return prio < transportPrioOfLeatherworks ? prio : prio + 1; });
×
327
    } else
328
    {
329
        helpers::popContainer(sgd, build_order);
7✔
330
        helpers::popContainer(sgd, transportPrio);
7✔
331
    }
332

333
    helpers::popContainer(sgd, militarySettings_);
7✔
334
    helpers::popContainer(sgd, toolsSettings_);
7✔
335

336
    // qx:tools
337
    helpers::popContainer(sgd, tools_ordered);
7✔
338
    tools_ordered_delta = {};
7✔
339

340
    if(sgd.GetGameDataVersion() < 12)
7✔
341
    {
342
        auto countOfNotAvailableGoodsInSaveGame =
NEW
343
          sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonGoods : numLeatherAddonGoods;
×
NEW
344
        std::vector<unsigned int> global_inventory_good_raw(global_inventory.goods.size()
×
NEW
345
                                                            - countOfNotAvailableGoodsInSaveGame);
×
346
        helpers::popContainer(sgd, global_inventory_good_raw, true);
×
347
        std::copy(global_inventory_good_raw.begin(), global_inventory_good_raw.end(), global_inventory.goods.begin());
×
348

349
        auto countOfNotAvailableJobsInSaveGame =
NEW
350
          sgd.GetGameDataVersion() < 11 ? numWineAndLeatherAddonJobs : numLeatherAddonJobs;
×
NEW
351
        std::vector<unsigned int> global_inventory_people_raw(global_inventory.people.size()
×
NEW
352
                                                              - countOfNotAvailableJobsInSaveGame);
×
353
        helpers::popContainer(sgd, global_inventory_people_raw, true);
×
354
        std::copy(global_inventory_people_raw.begin(), global_inventory_people_raw.end(),
×
355
                  global_inventory.people.begin());
356

NEW
357
        std::fill(global_inventory.armoredSoldiers.begin(), global_inventory.armoredSoldiers.end(), 0);
×
358
    } else
359
    {
360
        helpers::popContainer(sgd, global_inventory.goods);
7✔
361
        helpers::popContainer(sgd, global_inventory.people);
7✔
362
        helpers::popContainer(sgd, global_inventory.armoredSoldiers);
7✔
363
    }
364

365
    // Visuelle Einstellungen festlegen
366

367
    // für Statistik
368
    for(Statistic& curStatistic : statistic)
35✔
369
    {
370
        // normale Statistik
371
        for(auto& curData : curStatistic.data)
280✔
372
            helpers::popContainer(sgd, curData);
252✔
373

374
        // Warenstatistik
375
        for(unsigned j = 0; j < NUM_STAT_MERCHANDISE_TYPES; ++j)
420✔
376
            helpers::popContainer(sgd, curStatistic.merchandiseData[j]);
392✔
377

378
        curStatistic.currentIndex = sgd.PopUnsignedShort();
28✔
379
        curStatistic.counter = sgd.PopUnsignedShort();
28✔
380
    }
381
    helpers::popContainer(sgd, statisticCurrentData);
7✔
382
    helpers::popContainer(sgd, statisticCurrentMerchandiseData);
7✔
383

384
    // Deserialize Pacts:
385
    for(auto& playerPacts : pacts)
63✔
386
    {
387
        for(Pact& pact : playerPacts)
168✔
388
            pact = GamePlayer::Pact(sgd);
112✔
389
    }
390

391
    emergency = sgd.PopBool();
7✔
392
}
393

394
template<class T_IsWarehouseGood>
395
nobBaseWarehouse* GamePlayer::FindWarehouse(const noRoadNode& start, const T_IsWarehouseGood& isWarehouseGood,
4,488✔
396
                                            bool to_wh, bool use_boat_roads, unsigned* length,
397
                                            const RoadSegment* forbidden) const
398
{
399
    nobBaseWarehouse* best = nullptr;
4,488✔
400

401
    unsigned best_length = std::numeric_limits<unsigned>::max();
4,488✔
402

403
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
15,282✔
404
    {
405
        // Lagerhaus geeignet?
406
        RTTR_Assert(wh);
10,799✔
407
        if(!isWarehouseGood(*wh))
10,799✔
408
            continue;
8,174✔
409

410
        if(start.GetPos() == wh->GetPos())
2,634✔
411
        {
412
            // We are already there -> Take it
413
            if(length)
5✔
414
                *length = 0;
×
415
            return wh;
5✔
416
        }
417

418
        // now check if there is at least a chance that the next wh is closer than current best because pathfinding
419
        // takes time
420
        if(world.CalcDistance(start.GetPos(), wh->GetPos()) > best_length)
2,629✔
421
            continue;
9✔
422
        // Bei der erlaubten Benutzung von Bootsstraßen Waren-Pathfinding benutzen wenns zu nem Lagerhaus gehn soll
423
        // start <-> ziel tauschen bei der wegfindung
424
        unsigned tlength;
425
        if(world.GetRoadPathFinder().FindPath(to_wh ? start : *wh, to_wh ? *wh : start, use_boat_roads, best_length,
2,620✔
426
                                              forbidden, &tlength))
427
        {
428
            if(tlength < best_length || !best)
439✔
429
            {
430
                best_length = tlength;
435✔
431
                best = wh;
435✔
432
            }
433
        }
434
    }
435

436
    if(length)
4,483✔
437
        *length = best_length;
378✔
438

439
    return best;
4,483✔
440
}
441

442
void GamePlayer::AddBuildingSite(noBuildingSite* bldSite)
28✔
443
{
444
    RTTR_Assert(bldSite->GetPlayer() == GetPlayerId());
28✔
445
    buildings.Add(bldSite);
28✔
446
}
28✔
447

448
void GamePlayer::RemoveBuildingSite(noBuildingSite* bldSite)
15✔
449
{
450
    RTTR_Assert(bldSite->GetPlayer() == GetPlayerId());
15✔
451
    buildings.Remove(bldSite);
15✔
452
}
15✔
453

454
bool GamePlayer::IsHQTent() const
8✔
455
{
456
    if(const nobHQ* hq = GetHQ())
8✔
457
        return hq->IsTent();
8✔
458
    return false;
×
459
}
460

461
void GamePlayer::SetHQIsTent(bool isTent)
6✔
462
{
463
    if(nobHQ* hq = GetHQ())
6✔
464
        hq->SetIsTent(isTent);
5✔
465
}
6✔
466

467
void GamePlayer::AddBuilding(noBuilding* bld, BuildingType bldType)
632✔
468
{
469
    RTTR_Assert(bld->GetPlayer() == GetPlayerId());
632✔
470
    buildings.Add(bld, bldType);
632✔
471
    ChangeStatisticValue(StatisticType::Buildings, 1);
632✔
472

473
    // Order a worker if needed
474
    const auto& description = BLD_WORK_DESC[bldType];
632✔
475
    if(description.job && !isSoldierJob(*description.job))
632✔
476
    {
477
        AddJobWanted(*description.job, bld);
111✔
478
    }
479

480
    if(bldType == BuildingType::HarborBuilding)
632✔
481
    {
482
        // Schiff durchgehen und denen Bescheid sagen
483
        for(noShip* ship : ships)
51✔
484
            ship->NewHarborBuilt(static_cast<nobHarborBuilding*>(bld));
11✔
485
    } else if(bldType == BuildingType::Headquarters)
592✔
486
    {
487
        // If there is more than one HQ, keep the original position.
488
        if(!hqPos.isValid())
354✔
489
            hqPos = bld->GetPos();
345✔
490
    } else if(BuildingProperties::IsMilitary(bldType))
238✔
491
    {
492
        auto* milBld = static_cast<nobMilitary*>(bld);
116✔
493
        // New built? -> Calculate frontier distance
494
        if(milBld->IsNewBuilt())
116✔
495
            milBld->LookForEnemyBuildings();
106✔
496
    }
497
}
632✔
498

499
void GamePlayer::RemoveBuilding(noBuilding* bld, BuildingType bldType)
115✔
500
{
501
    RTTR_Assert(bld->GetPlayer() == GetPlayerId());
115✔
502
    buildings.Remove(bld, bldType);
115✔
503
    ChangeStatisticValue(StatisticType::Buildings, -1);
115✔
504
    if(bldType == BuildingType::HarborBuilding)
115✔
505
    { // Schiffen Bescheid sagen
506
        for(noShip* ship : ships)
27✔
507
            ship->HarborDestroyed(static_cast<nobHarborBuilding*>(bld));
12✔
508
    } else if(bldType == BuildingType::Headquarters)
100✔
509
    {
510
        hqPos = MapPoint::Invalid();
31✔
511
        for(const noBaseBuilding* bld : buildings.GetStorehouses())
31✔
512
        {
513
            if(bld->GetBuildingType() == BuildingType::Headquarters)
1✔
514
            {
515
                hqPos = bld->GetPos();
1✔
516
                break;
1✔
517
            }
518
        }
519
    }
520
    if(BuildingProperties::IsWareHouse(bldType) || BuildingProperties::IsMilitary(bldType))
115✔
521
        TestDefeat();
82✔
522
}
115✔
523

524
void GamePlayer::NewRoadConnection(RoadSegment* rs)
157✔
525
{
526
    // Zu den Straßen hinzufgen, da's ja ne neue ist
527
    roads.push_back(rs);
157✔
528

529
    // Alle Straßen müssen nun gucken, ob sie einen Weg zu einem Warehouse finden
530
    FindCarrierForAllRoads();
157✔
531

532
    // Alle Straßen müssen gucken, ob sie einen Esel bekommen können
533
    for(RoadSegment* rs : roads)
341✔
534
        rs->TryGetDonkey();
184✔
535

536
    // Alle Arbeitsplätze müssen nun gucken, ob sie einen Weg zu einem Lagerhaus mit entsprechender Arbeitskraft finden
537
    FindWarehouseForAllJobs();
157✔
538

539
    // Alle Baustellen müssen nun gucken, ob sie ihr benötigtes Baumaterial bekommen (evtl war vorher die Straße zum
540
    // Lagerhaus unterbrochen
541
    FindMaterialForBuildingSites();
157✔
542

543
    // Alle Lost-Wares müssen gucken, ob sie ein Lagerhaus finden
544
    FindClientForLostWares();
157✔
545

546
    // Alle Militärgebäude müssen ihre Truppen überprüfen und können nun ggf. neue bestellen
547
    // und müssen prüfen, ob sie evtl Gold bekommen
548
    for(nobMilitary* mil : buildings.GetMilitaryBuildings())
176✔
549
    {
550
        mil->RegulateTroops();
19✔
551
        mil->SearchCoins();
19✔
552
    }
553
}
157✔
554

555
void GamePlayer::AddRoad(RoadSegment* rs)
18✔
556
{
557
    roads.push_back(rs);
18✔
558
}
18✔
559

560
void GamePlayer::DeleteRoad(RoadSegment* rs)
103✔
561
{
562
    RTTR_Assert(helpers::contains(roads, rs));
103✔
563
    roads.remove(rs);
103✔
564
}
103✔
565

566
void GamePlayer::FindClientForLostWares()
163✔
567
{
568
    // Alle Lost-Wares müssen gucken, ob sie ein Lagerhaus finden
569
    for(Ware* ware : ware_list)
219✔
570
    {
571
        if(ware->IsLostWare())
56✔
572
        {
573
            if(ware->FindRouteToWarehouse() && ware->IsWaitingAtFlag())
×
574
                ware->CallCarrier();
×
575
        }
576
    }
577
}
163✔
578

579
void GamePlayer::RoadDestroyed()
223✔
580
{
581
    // Alle Waren, die an Flagge liegen und in Lagerhäusern, müssen gucken, ob sie ihr Ziel noch erreichen können, jetzt
582
    // wo eine Straße fehlt
583
    for(auto it = ware_list.begin(); it != ware_list.end();)
233✔
584
    {
585
        Ware* ware = *it;
10✔
586
        if(ware->IsWaitingAtFlag()) // Liegt die Flagge an einer Flagge, muss ihr Weg neu berechnet werden
10✔
587
        {
588
            RoadPathDirection last_next_dir = ware->GetNextDir();
2✔
589
            ware->RecalcRoute();
2✔
590
            // special case: ware was lost some time ago and the new goal is at this flag and not a warehouse,hq,harbor
591
            // and the "flip-route" picked so a carrier would pick up the ware carry it away from goal then back and
592
            // drop  it off at the goal was just destroyed?
593
            // -> try to pick another flip route or tell the goal about failure.
594
            noRoadNode& wareLocation = *ware->GetLocation();
2✔
595
            noBaseBuilding* wareGoal = ware->GetGoal();
2✔
596
            if(wareGoal && ware->GetNextDir() == RoadPathDirection::NorthWest
2✔
597
               && wareLocation.GetPos() == wareGoal->GetFlagPos()
2✔
598
               && ((wareGoal->GetBuildingType() != BuildingType::Storehouse
6✔
599
                    && wareGoal->GetBuildingType() != BuildingType::Headquarters
2✔
600
                    && wareGoal->GetBuildingType() != BuildingType::HarborBuilding)
×
601
                   || wareGoal->GetType() == NodalObjectType::Buildingsite))
2✔
602
            {
603
                Direction newWareDir = Direction::NorthWest;
×
604
                for(auto dir : helpers::EnumRange<Direction>{})
×
605
                {
606
                    dir += 2u; // Need to skip Direction::NorthWest and we used to start with an offset of 2. TODO:
×
607
                               // Increase gameDataVersion and just skip NW
608
                    if(wareLocation.GetRoute(dir))
×
609
                    {
610
                        newWareDir = dir;
×
611
                        break;
×
612
                    }
613
                }
614
                if(newWareDir != Direction::NorthWest)
×
615
                {
616
                    ware->SetNextDir(toRoadPathDirection(newWareDir));
×
617
                } else // no route to goal -> notify goal, try to send ware to a warehouse
618
                {
619
                    ware->NotifyGoalAboutLostWare();
×
620
                    ware->FindRouteToWarehouse();
×
621
                }
622
            }
623
            // end of special case
624

625
            // notify carriers/flags about news if there are any
626
            if(ware->GetNextDir() != last_next_dir)
2✔
627
            {
628
                // notify current flag that transport in the old direction might not longer be required
629
                ware->RemoveWareJobForDir(last_next_dir);
×
630
                if(ware->GetNextDir() != RoadPathDirection::None)
×
631
                    ware->CallCarrier();
×
632
            }
633
        } else if(ware->IsWaitingInWarehouse())
8✔
634
        {
635
            if(!ware->IsRouteToGoal())
×
636
            {
637
                // Das Ziel wird nun nich mehr beliefert
638
                ware->NotifyGoalAboutLostWare();
×
639
                // Ware aus der Warteliste des Lagerhauses entfernen
640
                static_cast<nobBaseWarehouse*>(ware->GetLocation())->CancelWare(ware);
×
641
                // Ware aus der Liste raus
642
                it = ware_list.erase(it);
×
643
                continue;
×
644
            }
645
        } else if(ware->IsWaitingForShip())
8✔
646
        {
647
            // Weg neu berechnen
648
            ware->RecalcRoute();
1✔
649
        }
650

651
        ++it;
10✔
652
    }
653

654
    // Alle Häfen müssen ihre Figuren den Weg überprüfen lassen
655
    for(nobHarborBuilding* hb : buildings.GetHarbors())
240✔
656
    {
657
        hb->ExamineShipRouteOfPeople();
17✔
658
    }
659
}
223✔
660

661
bool GamePlayer::FindCarrierForRoad(RoadSegment& rs) const
186✔
662
{
663
    RTTR_Assert(rs.GetF1() != nullptr && rs.GetF2() != nullptr);
186✔
664
    std::array<unsigned, 2> length;
665
    std::array<nobBaseWarehouse*, 2> best;
666

667
    // Braucht der ein Boot?
668
    if(rs.GetRoadType() == RoadType::Water)
186✔
669
    {
670
        // dann braucht man Träger UND Boot
671
        best[0] = FindWarehouse(*rs.GetF1(), FW::HasWareAndFigure(GoodType::Boat, Job::Helper, false), false, false,
×
672
                                length.data(), &rs);
673
        // 2. Flagge des Weges
674
        best[1] = FindWarehouse(*rs.GetF2(), FW::HasWareAndFigure(GoodType::Boat, Job::Helper, false), false, false,
×
675
                                &length[1], &rs);
×
676
    } else
677
    {
678
        // 1. Flagge des Weges
679
        best[0] = FindWarehouse(*rs.GetF1(), FW::HasFigure(Job::Helper, false), false, false, length.data(), &rs);
186✔
680
        // 2. Flagge des Weges
681
        best[1] = FindWarehouse(*rs.GetF2(), FW::HasFigure(Job::Helper, false), false, false, &length[1], &rs);
186✔
682
    }
683

684
    // überhaupt nen Weg gefunden?
685
    // Welche Flagge benutzen?
686
    if(best[0] && (!best[1] || length[0] < length[1]))
186✔
687
        best[0]->OrderCarrier(*rs.GetF1(), rs);
65✔
688
    else if(best[1])
121✔
689
        best[1]->OrderCarrier(*rs.GetF2(), rs);
42✔
690
    else
691
        return false;
79✔
692
    return true;
107✔
693
}
694

695
bool GamePlayer::IsWarehouseValid(nobBaseWarehouse* wh) const
×
696
{
697
    return helpers::contains(buildings.GetStorehouses(), wh);
×
698
}
699

700
void GamePlayer::RecalcDistribution()
405✔
701
{
702
    GoodType lastWare = GoodType::Nothing;
405✔
703
    for(const DistributionMapping& mapping : distributionMap)
12,150✔
704
    {
705
        if(lastWare == std::get<0>(mapping))
11,745✔
706
            continue;
8,505✔
707
        lastWare = std::get<0>(mapping);
3,240✔
708
        RecalcDistributionOfWare(std::get<0>(mapping));
3,240✔
709
    }
710
}
405✔
711

712
void GamePlayer::RecalcDistributionOfWare(const GoodType ware)
3,240✔
713
{
714
    // Punktesystem zur Verteilung, in der Liste alle Gebäude sammeln, die die Ware wollen
715
    distribution[ware].client_buildings.clear();
3,240✔
716

717
    // 1. Anteile der einzelnen Waren ausrechnen
718

719
    /// Mapping of buildings that want the current ware to its percentage
720
    using BldEntry = std::pair<BuildingType, uint8_t>;
721
    std::vector<BldEntry> bldPercentageMap;
3,240✔
722

723
    unsigned goal_count = 0;
3,240✔
724

725
    for(const auto bld : helpers::enumRange<BuildingType>())
272,160✔
726
    {
727
        uint8_t percentForCurBld = distribution[ware].percent_buildings[bld];
129,600✔
728
        if(percentForCurBld)
129,600✔
729
        {
730
            distribution[ware].client_buildings.push_back(bld);
11,744✔
731
            goal_count += percentForCurBld;
11,744✔
732
            bldPercentageMap.emplace_back(bld, percentForCurBld);
11,744✔
733
        }
734
    }
735

736
    // TODO: evtl noch die counts miteinander kürzen (ggt berechnen)
737

738
    // Array für die Gebäudtypen erstellen
739

740
    std::vector<BuildingType>& wareGoals = distribution[ware].goals;
3,240✔
741
    wareGoals.clear();
3,240✔
742
    wareGoals.reserve(goal_count);
3,240✔
743

744
    // just drop them in the list, the distribution will be handled by going through this list using a prime as step
745
    // (see GameClientPlayer::FindClientForWare)
746
    for(const BldEntry& bldEntry : bldPercentageMap)
14,984✔
747
    {
748
        for(unsigned char i = 0; i < bldEntry.second; ++i)
76,371✔
749
            wareGoals.push_back(bldEntry.first);
64,627✔
750
    }
751

752
    distribution[ware].selected_goal = 0;
3,240✔
753
}
3,240✔
754

755
void GamePlayer::FindCarrierForAllRoads()
180✔
756
{
757
    for(RoadSegment* rs : roads)
396✔
758
    {
759
        if(!rs->hasCarrier(0))
216✔
760
            FindCarrierForRoad(*rs);
164✔
761
    }
762
}
180✔
763

764
void GamePlayer::FindMaterialForBuildingSites()
176✔
765
{
766
    for(noBuildingSite* bldSite : buildings.GetBuildingSites())
199✔
767
        bldSite->OrderConstructionMaterial();
23✔
768
}
176✔
769

770
void GamePlayer::AddJobWanted(const Job job, noRoadNode* workplace)
147✔
771
{
772
    if(!FindWarehouseForJob(job, *workplace))
147✔
773
    {
774
        JobNeeded jn = {job, workplace};
134✔
775
        jobs_wanted.push_back(jn);
134✔
776
    }
777
}
147✔
778

779
void GamePlayer::JobNotWanted(noRoadNode* workplace, bool all)
56✔
780
{
781
    for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
60✔
782
    {
783
        if(it->workplace == workplace)
45✔
784
        {
785
            it = jobs_wanted.erase(it);
41✔
786
            if(!all)
41✔
787
                return;
41✔
788
        } else
789
        {
790
            ++it;
4✔
791
        }
792
    }
793
}
794

795
void GamePlayer::OneJobNotWanted(const Job job, noRoadNode* workplace)
2✔
796
{
797
    const auto it = helpers::find_if(
798
      jobs_wanted, [workplace, job](const auto& it) { return it.workplace == workplace && it.job == job; });
2✔
799
    if(it != jobs_wanted.end())
2✔
800
        jobs_wanted.erase(it);
×
801
}
2✔
802

803
void GamePlayer::SendPostMessage(std::unique_ptr<PostMsg> msg)
35✔
804
{
805
    world.GetPostMgr().SendMsg(GetPlayerId(), std::move(msg));
35✔
806
}
35✔
807

808
unsigned GamePlayer::GetToolsOrderedVisual(Tool tool) const
×
809
{
810
    return std::max(0, int(tools_ordered[tool] + tools_ordered_delta[tool]));
×
811
}
812

813
unsigned GamePlayer::GetToolsOrdered(Tool tool) const
369✔
814
{
815
    return tools_ordered[tool];
369✔
816
}
817

818
bool GamePlayer::ChangeToolOrderVisual(Tool tool, int changeAmount) const
×
819
{
820
    if(std::abs(changeAmount) > 100)
×
821
        return false;
×
822
    int newOrderAmount = int(GetToolsOrderedVisual(tool)) + changeAmount;
×
823
    if(newOrderAmount < 0 || newOrderAmount > 100)
×
824
        return false;
×
825
    tools_ordered_delta[tool] += changeAmount;
×
826
    return true;
×
827
}
828

829
unsigned GamePlayer::GetToolPriority(Tool tool) const
271✔
830
{
831
    return toolsSettings_[tool];
271✔
832
}
833

834
void GamePlayer::ToolOrderProcessed(Tool tool)
4✔
835
{
836
    if(tools_ordered[tool])
4✔
837
    {
838
        --tools_ordered[tool];
4✔
839
        world.GetNotifications().publish(ToolNote(ToolNote::OrderCompleted, GetPlayerId()));
4✔
840
    }
841
}
4✔
842

843
bool GamePlayer::FindWarehouseForJob(const Job job, noRoadNode& goal) const
166✔
844
{
845
    nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasFigure(job, true), false, false);
166✔
846

847
    if(wh)
166✔
848
    {
849
        // Es wurde ein Lagerhaus gefunden, wo es den geforderten Beruf gibt, also den Typen zur Arbeit rufen
850
        wh->OrderJob(job, goal, true);
32✔
851
        return true;
32✔
852
    }
853

854
    return false;
134✔
855
}
856

857
void GamePlayer::FindWarehouseForAllJobs()
179✔
858
{
859
    for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
198✔
860
    {
861
        if(FindWarehouseForJob(it->job, *it->workplace))
19✔
862
            it = jobs_wanted.erase(it);
19✔
863
        else
864
            ++it;
×
865
    }
866
}
179✔
867

868
void GamePlayer::FindWarehouseForAllJobs(const Job job)
340✔
869
{
870
    for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
340✔
871
    {
872
        if(it->job == job)
×
873
        {
874
            if(FindWarehouseForJob(it->job, *it->workplace))
×
875
                it = jobs_wanted.erase(it);
×
876
            else
877
                ++it;
×
878
        } else
879
            ++it;
×
880
    }
881
}
340✔
882

883
Ware* GamePlayer::OrderWare(const GoodType ware, noBaseBuilding& goal)
149✔
884
{
885
    /// Gibt es ein Lagerhaus mit dieser Ware?
886
    nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasMinWares(ware, 1), false, true);
149✔
887

888
    if(wh)
149✔
889
    {
890
        // Prüfe ob Notfallprogramm aktiv
891
        if(!emergency)
108✔
892
            return wh->OrderWare(ware, goal);
108✔
893
        else
894
        {
895
            // Wenn Notfallprogramm aktiv nur an Holzfäller und Sägewerke Bretter/Steine liefern
896
            if((ware != GoodType::Boards && ware != GoodType::Stones)
×
897
               || goal.GetBuildingType() == BuildingType::Woodcutter || goal.GetBuildingType() == BuildingType::Sawmill)
×
898
                return wh->OrderWare(ware, goal);
×
899
            else
900
                return nullptr;
×
901
        }
902
    } else // no warehouse can deliver the ware -> check all our wares for lost wares that might match the order
903
    {
904
        unsigned bestLength = std::numeric_limits<unsigned>::max();
41✔
905
        Ware* bestWare = nullptr;
41✔
906
        for(Ware* curWare : ware_list)
85✔
907
        {
908
            if(curWare->IsLostWare() && curWare->type == ware)
44✔
909
            {
910
                // got a lost ware with a road to goal -> find best
911
                unsigned curLength = curWare->CheckNewGoalForLostWare(goal);
×
912
                if(curLength < bestLength)
×
913
                {
914
                    bestLength = curLength;
×
915
                    bestWare = curWare;
×
916
                }
917
            }
918
        }
919
        if(bestWare)
41✔
920
        {
921
            bestWare->SetNewGoalForLostWare(goal);
×
922
            return bestWare;
×
923
        }
924
    }
925
    return nullptr;
41✔
926
}
927

928
nofCarrier* GamePlayer::OrderDonkey(RoadSegment& road) const
3✔
929
{
930
    std::array<unsigned, 2> length;
931
    std::array<nobBaseWarehouse*, 2> best;
932

933
    // 1. Flagge des Weges
934
    best[0] = FindWarehouse(*road.GetF1(), FW::HasFigure(Job::PackDonkey, false), false, false, length.data(), &road);
3✔
935
    // 2. Flagge des Weges
936
    best[1] = FindWarehouse(*road.GetF2(), FW::HasFigure(Job::PackDonkey, false), false, false, &length[1], &road);
3✔
937

938
    // überhaupt nen Weg gefunden?
939
    // Welche Flagge benutzen?
940
    if(best[0] && (!best[1] || length[0] < length[1]))
3✔
941
        return best[0]->OrderDonkey(road, *road.GetF1());
2✔
942
    else if(best[1])
1✔
943
        return best[1]->OrderDonkey(road, *road.GetF2());
×
944
    else
945
        return nullptr;
1✔
946
}
947

948
RoadSegment* GamePlayer::FindRoadForDonkey(noRoadNode& start, noRoadNode** goal)
10✔
949
{
950
    // Bisher höchste Trägerproduktivität und die entsprechende Straße dazu
951
    unsigned best_productivity = 0;
10✔
952
    RoadSegment* best_road = nullptr;
10✔
953
    // Beste Flagge dieser Straße
954
    *goal = nullptr;
10✔
955

956
    for(RoadSegment* roadSeg : roads)
12✔
957
    {
958
        // Braucht die Straße einen Esel?
959
        if(roadSeg->NeedDonkey())
2✔
960
        {
961
            // Beste Flagge von diesem Weg, und beste Wegstrecke
962
            noRoadNode* current_best_goal = nullptr;
×
963
            // Weg zu beiden Flaggen berechnen
964
            unsigned length1, length2;
965
            bool isF1Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF1(), &length1, nullptr, roadSeg)
×
966
                                 != RoadPathDirection::None;
×
967
            bool isF2Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF2(), &length2, nullptr, roadSeg)
×
968
                                 != RoadPathDirection::None;
×
969

970
            // Wenn man zu einer Flagge nich kommt, die jeweils andere nehmen
971
            if(!isF1Reachable)
×
972
                current_best_goal = (isF2Reachable) ? roadSeg->GetF2() : nullptr;
×
973
            else if(!isF2Reachable)
×
974
                current_best_goal = roadSeg->GetF1();
×
975
            else
976
            {
977
                // ansonsten die kürzeste von beiden
978
                current_best_goal = (length1 < length2) ? roadSeg->GetF1() : roadSeg->GetF2();
×
979
            }
980

981
            // Kein Weg führt hin, nächste Straße bitte
982
            if(!current_best_goal)
×
983
                continue;
×
984

985
            // Jeweiligen Weg bestimmen
986
            unsigned current_best_way = (roadSeg->GetF1() == current_best_goal) ? length1 : length2;
×
987

988
            // Produktivität ausrechnen, *10 die Produktivität + die Wegstrecke, damit die
989
            // auch noch mit einberechnet wird
990
            unsigned current_productivity = 10 * roadSeg->getCarrier(0)->GetProductivity() + current_best_way;
×
991

992
            // Besser als der bisher beste?
993
            if(current_productivity > best_productivity)
×
994
            {
995
                // Dann wird der vom Thron gestoßen
996
                best_productivity = current_productivity;
×
997
                best_road = roadSeg;
×
998
                *goal = current_best_goal;
×
999
            }
1000
        }
1001
    }
1002

1003
    return best_road;
10✔
1004
}
1005

1006
struct ClientForWare
1007
{
1008
    noBaseBuilding* bld;
1009
    unsigned estimate; // points minus half the optimal distance
1010
    unsigned points;
1011

1012
    ClientForWare(noBaseBuilding* bld, unsigned estimate, unsigned points)
×
1013
        : bld(bld), estimate(estimate), points(points)
×
1014
    {}
×
1015

1016
    bool operator<(const ClientForWare& b) const
×
1017
    {
1018
        // use estimate, points and object id (as tie breaker) for sorting
1019
        if(estimate != b.estimate)
×
1020
            return estimate > b.estimate;
×
1021
        else if(points != b.points)
×
1022
            return points > b.points;
×
1023
        else
1024
            return bld->GetObjId() > b.bld->GetObjId();
×
1025
    }
1026
};
1027

1028
noBaseBuilding* GamePlayer::FindClientForWare(const Ware& ware)
12✔
1029
{
1030
    // If the ware is a coin or an armor, the goal is determined by another logic
1031
    if(ware.type == GoodType::Coins)
12✔
1032
        return FindClientForCoin(ware);
×
1033
    else if(ware.type == GoodType::Armor)
12✔
NEW
1034
        return FindClientForArmor(ware);
×
1035

1036
    // Warentyp herausfinden
1037
    GoodType gt = ware.type;
12✔
1038
    // All food is considered fish in the distribution table
1039
    Distribution& wareDistribution =
1040
      (gt == GoodType::Bread || gt == GoodType::Meat) ? distribution[GoodType::Fish] : distribution[gt];
12✔
1041

1042
    std::vector<ClientForWare> possibleClients;
12✔
1043

1044
    const noRoadNode* start = ware.GetLocation();
12✔
1045

1046
    // Bretter und Steine können evtl. auch Häfen für Expeditionen gebrauchen
1047
    if(gt == GoodType::Stones || gt == GoodType::Boards)
12✔
1048
    {
1049
        for(nobHarborBuilding* harbor : buildings.GetHarbors())
8✔
1050
        {
1051
            unsigned points = harbor->CalcDistributionPoints(gt);
×
1052
            if(!points)
×
1053
                continue;
×
1054

1055
            points += 10 * 30; // Verteilung existiert nicht, Expeditionen haben allerdings hohe Priorität
×
1056
            unsigned distance = world.CalcDistance(start->GetPos(), harbor->GetPos()) / 2;
×
1057
            possibleClients.push_back(ClientForWare(harbor, points > distance ? points - distance : 0, points));
×
1058
        }
1059
    }
1060

1061
    for(const auto bldType : wareDistribution.client_buildings)
49✔
1062
    {
1063
        // BuildingType::Headquarters sind Baustellen!!, da HQs ja sowieso nicht gebaut werden können
1064
        if(bldType == BuildingType::Headquarters)
37✔
1065
        {
1066
            // Bei Baustellen die Extraliste abfragen
1067
            for(noBuildingSite* bldSite : buildings.GetBuildingSites())
8✔
1068
            {
1069
                unsigned points = bldSite->CalcDistributionPoints(gt);
×
1070
                if(!points)
×
1071
                    continue;
×
1072

1073
                points += wareDistribution.percent_buildings[BuildingType::Headquarters] * 30;
×
1074
                unsigned distance = world.CalcDistance(start->GetPos(), bldSite->GetPos()) / 2;
×
1075
                possibleClients.push_back(ClientForWare(bldSite, points > distance ? points - distance : 0, points));
×
1076
            }
1077
        } else
1078
        {
1079
            // Für übrige Gebäude
1080
            for(nobUsual* bld : buildings.GetBuildings(bldType))
29✔
1081
            {
1082
                unsigned points = bld->CalcDistributionPoints(gt);
×
1083
                if(!points)
×
1084
                    continue; // Ware not needed
×
1085

1086
                if(!wareDistribution.goals.empty())
×
1087
                {
1088
                    if(bld->GetBuildingType()
×
1089
                       == static_cast<BuildingType>(wareDistribution.goals[wareDistribution.selected_goal]))
×
1090
                        points += 300;
×
1091
                    else if(points >= 300) // avoid overflows (async!)
×
1092
                        points -= 300;
×
1093
                    else
1094
                        points = 0;
×
1095
                }
1096

1097
                unsigned distance = world.CalcDistance(start->GetPos(), bld->GetPos()) / 2;
×
1098
                possibleClients.push_back(ClientForWare(bld, points > distance ? points - distance : 0, points));
×
1099
            }
1100
        }
1101
    }
1102

1103
    // sort our clients, highest score first
1104
    std::sort(possibleClients.begin(), possibleClients.end());
12✔
1105

1106
    noBaseBuilding* lastBld = nullptr;
12✔
1107
    noBaseBuilding* bestBld = nullptr;
12✔
1108
    unsigned best_points = 0;
12✔
1109
    for(auto& possibleClient : possibleClients)
12✔
1110
    {
1111
        unsigned path_length;
1112

1113
        // If our estimate is worse (or equal) best_points, the real value cannot be better.
1114
        // As our list is sorted, further entries cannot be better either, so stop searching.
1115
        if(possibleClient.estimate <= best_points)
×
1116
            break;
×
1117

1118
        // get rid of double building entries. TODO: why are there double entries!?
1119
        if(possibleClient.bld == lastBld)
×
1120
            continue;
×
1121

1122
        lastBld = possibleClient.bld;
×
1123

1124
        // Just to be sure no underflow happens...
1125
        if(possibleClient.points < best_points + 1)
×
1126
            continue;
×
1127

1128
        // Find path ONLY if it may be better. Pathfinding is limited to the worst path score that would lead to a
1129
        // better score. This eliminates the worst case scenario where all nodes in a split road network would be hit by
1130
        // the pathfinding only to conclude that there is no possible path.
1131
        if(world.FindPathForWareOnRoads(*start, *possibleClient.bld, &path_length, nullptr,
×
1132
                                        (possibleClient.points - best_points) * 2 - 1)
×
1133
           != RoadPathDirection::None)
×
1134
        {
1135
            unsigned score = possibleClient.points - (path_length / 2);
×
1136

1137
            // As we have limited our pathfinding to take a maximum of (points - best_points) * 2 - 1 steps,
1138
            // path_length / 2 can at most be points - best_points - 1, so the score will be greater than best_points.
1139
            // :)
1140
            RTTR_Assert(score > best_points);
×
1141

1142
            best_points = score;
×
1143
            bestBld = possibleClient.bld;
×
1144
        }
1145
    }
1146

1147
    if(bestBld && !wareDistribution.goals.empty())
12✔
1148
        wareDistribution.selected_goal =
×
1149
          (wareDistribution.selected_goal + 907) % unsigned(wareDistribution.goals.size());
×
1150

1151
    // Wenn kein Abnehmer gefunden wurde, muss es halt in ein Lagerhaus
1152
    if(!bestBld)
12✔
1153
        bestBld = FindWarehouseForWare(ware);
12✔
1154

1155
    return bestBld;
12✔
1156
}
1157

1158
nobBaseWarehouse* GamePlayer::FindWarehouseForWare(const Ware& ware) const
16✔
1159
{
1160
    // Check whs that collect this ware
1161
    nobBaseWarehouse* wh = FindWarehouse(*ware.GetLocation(), FW::CollectsWare(ware.type), true, true);
16✔
1162
    // If there is none, check those that accept it
1163
    if(!wh)
16✔
1164
    {
1165
        // First find the ones, that do not send it right away (IMPORTANT: This avoids sending a ware to the wh that is
1166
        // sending the ware out)
1167
        wh = FindWarehouse(*ware.GetLocation(), FW::AcceptsWareButNoSend(ware.type), true, true);
16✔
1168
        // The others only if this fails
1169
        if(!wh)
16✔
1170
            wh = FindWarehouse(*ware.GetLocation(), FW::AcceptsWare(ware.type), true, true);
5✔
1171
    }
1172
    return wh;
16✔
1173
}
1174

1175
nobBaseMilitary* GamePlayer::FindClientForCoin(const Ware& ware) const
×
1176
{
1177
    nobBaseMilitary* bb = nullptr;
×
1178
    unsigned best_points = 0, points;
×
1179

1180
    // Militärgebäude durchgehen
1181
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
×
1182
    {
1183
        unsigned way_points;
1184

1185
        points = milBld->CalcCoinsPoints();
×
1186
        // Wenn 0, will er gar keine Münzen (Goldzufuhr gestoppt)
1187
        if(points)
×
1188
        {
1189
            // Weg dorthin berechnen
1190
            if(world.FindPathForWareOnRoads(*ware.GetLocation(), *milBld, &way_points) != RoadPathDirection::None)
×
1191
            {
1192
                // Die Wegpunkte noch davon abziehen
1193
                points -= way_points;
×
1194
                // Besser als der bisher Beste?
1195
                if(points > best_points)
×
1196
                {
1197
                    best_points = points;
×
1198
                    bb = milBld;
×
1199
                }
1200
            }
1201
        }
1202
    }
1203

1204
    // Wenn kein Abnehmer gefunden wurde, muss es halt in ein Lagerhaus
1205
    if(!bb)
×
1206
        bb = FindWarehouseForWare(ware);
×
1207

1208
    return bb;
×
1209
}
1210

NEW
1211
nobBaseMilitary* GamePlayer::FindClientForArmor(const Ware& ware) const
×
1212
{
NEW
1213
    nobBaseMilitary* bb = nullptr;
×
NEW
1214
    unsigned best_points = 0, points;
×
1215

NEW
1216
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
×
1217
    {
1218
        unsigned way_points;
1219

NEW
1220
        points = milBld->CalcArmorPoints();
×
1221
        // If 0, it does not want any armor (armor delivery stopped)
NEW
1222
        if(points)
×
1223
        {
1224
            // Find the nearest building
NEW
1225
            if(world.FindPathForWareOnRoads(*ware.GetLocation(), *milBld, &way_points) != RoadPathDirection::None)
×
1226
            {
NEW
1227
                points -= way_points;
×
NEW
1228
                if(points > best_points)
×
1229
                {
NEW
1230
                    best_points = points;
×
NEW
1231
                    bb = milBld;
×
1232
                }
1233
            }
1234
        }
1235
    }
1236

NEW
1237
    if(!bb)
×
NEW
1238
        bb = FindWarehouseForWare(ware);
×
1239

NEW
1240
    return bb;
×
1241
}
1242

UNCOV
1243
unsigned GamePlayer::GetBuidingSitePriority(const noBuildingSite* building_site)
×
1244
{
1245
    if(useCustomBuildOrder_)
×
1246
    {
1247
        // Spezielle Reihenfolge
1248

1249
        // Typ in der Reihenfolge suchen und Position als Priorität zurückgeben
1250
        for(unsigned i = 0; i < build_order.size(); ++i)
×
1251
        {
1252
            if(building_site->GetBuildingType() == build_order[i])
×
1253
                return i;
×
1254
        }
1255
    } else
1256
    {
1257
        // Reihenfolge der Bauaufträge, also was zuerst in Auftrag gegeben wurde, wird zuerst gebaut
1258
        unsigned i = 0;
×
1259
        for(noBuildingSite* bldSite : buildings.GetBuildingSites())
×
1260
        {
1261
            if(building_site == bldSite)
×
1262
                return i;
×
1263
            i++;
×
1264
        }
1265
    }
1266

1267
    LOG.write("GameClientPlayer::GetBuidingSitePriority: ERROR: Buildingsite or type of it not found in the list!\n");
×
1268
    RTTR_Assert(false);
×
1269
    // We may want to multiply this value so don't return the absolute max value
1270
    return std::numeric_limits<unsigned>::max() / 1000;
1271
}
1272

1273
void GamePlayer::ConvertTransportData(const TransportOrders& transport_data)
2✔
1274
{
1275
    for(const auto ware : helpers::EnumRange<GoodType>{})
168✔
1276
        transportPrio[ware] = GetTransportPrioFromOrdering(transport_data, ware);
80✔
1277
}
2✔
1278

1279
bool GamePlayer::IsAlly(const unsigned char playerId) const
12,228✔
1280
{
1281
    // Der Spieler ist ja auch zu sich selber verbündet
1282
    if(GetPlayerId() == playerId)
12,228✔
1283
        return true;
3,917✔
1284
    else
1285
        return GetPactState(PactType::TreatyOfAlliance, playerId) == PactState::Accepted;
8,311✔
1286
}
1287

1288
bool GamePlayer::IsAttackable(const unsigned char playerId) const
897✔
1289
{
1290
    // Verbündete dürfen nicht angegriffen werden
1291
    if(IsAlly(playerId))
897✔
1292
        return false;
44✔
1293
    else
1294
        // Ansonsten darf bei bestehendem Nichtangriffspakt ebenfalls nicht angegriffen werden
1295
        return GetPactState(PactType::NonAgressionPact, playerId) != PactState::Accepted;
853✔
1296
}
1297

1298
void GamePlayer::OrderTroops(nobMilitary& goal, std::array<unsigned, NUM_SOLDIER_RANKS> counts,
33✔
1299
                             unsigned total_max) const
1300
{
1301
    // Solange Lagerhäuser nach Soldaten absuchen, bis entweder keins mehr übrig ist oder alle Soldaten bestellt sind
1302
    nobBaseWarehouse* wh;
1303
    unsigned sum = 0;
33✔
1304
    do
3✔
1305
    {
1306
        std::array<bool, NUM_SOLDIER_RANKS> desiredRanks;
1307
        for(unsigned i = 0; i < NUM_SOLDIER_RANKS; i++)
216✔
1308
            desiredRanks[i] = counts[i] > 0;
180✔
1309

1310
        wh = FindWarehouse(goal, FW::HasAnyMatchingSoldier(desiredRanks), false, false);
36✔
1311
        if(wh)
36✔
1312
        {
1313
            wh->OrderTroops(goal, counts, total_max);
19✔
1314
            sum = std::accumulate(counts.begin(), counts.end(), 0u);
19✔
1315
        }
1316
    } while(total_max && sum && wh);
36✔
1317
}
33✔
1318

1319
void GamePlayer::RegulateAllTroops()
89✔
1320
{
1321
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
92✔
1322
        milBld->RegulateTroops();
3✔
1323
}
89✔
1324

1325
/// Prüft von allen Militärgebäuden die Fahnen neu
1326
void GamePlayer::RecalcMilitaryFlags()
48✔
1327
{
1328
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
72✔
1329
        milBld->LookForEnemyBuildings(nullptr);
24✔
1330
}
48✔
1331

1332
/// Sucht für Soldaten ein neues Militärgebäude, als Argument wird Referenz auf die
1333
/// entsprechende Soldatenanzahl im Lagerhaus verlangt
1334
void GamePlayer::NewSoldiersAvailable(const unsigned& soldier_count)
152✔
1335
{
1336
    RTTR_Assert(soldier_count > 0);
152✔
1337
    // solange laufen lassen, bis soldier_count = 0, d.h. der Soldat irgendwohin geschickt wurde
1338
    // Zuerst nach unbesetzten Militärgebäude schauen
1339
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1340
    {
1341
        if(milBld->IsNewBuilt())
17✔
1342
        {
1343
            milBld->RegulateTroops();
×
1344
            // Used that soldier? Go out
1345
            if(!soldier_count)
×
1346
                return;
×
1347
        }
1348
    }
1349

1350
    // Als nächstes Gebäude in Grenznähe
1351
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1352
    {
1353
        if(milBld->GetFrontierDistance() == FrontierDistance::Near)
17✔
1354
        {
1355
            milBld->RegulateTroops();
17✔
1356
            // Used that soldier? Go out
1357
            if(!soldier_count)
17✔
1358
                return;
×
1359
        }
1360
    }
1361

1362
    // Und den Rest ggf.
1363
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1364
    {
1365
        // already checked? -> skip
1366
        if(milBld->GetFrontierDistance() == FrontierDistance::Near || milBld->IsNewBuilt())
17✔
1367
            continue;
17✔
1368
        milBld->RegulateTroops();
×
1369
        if(!soldier_count) // used the soldier?
×
1370
            return;
×
1371
    }
1372
}
1373

1374
void GamePlayer::CallFlagWorker(const MapPoint pt, const Job job)
32✔
1375
{
1376
    auto* flag = world.GetSpecObj<noFlag>(pt);
32✔
1377
    if(!flag)
32✔
1378
        return;
2✔
1379
    /// Find wh with given job type (e.g. geologist, scout, ...)
1380
    nobBaseWarehouse* wh = FindWarehouse(*flag, FW::HasFigure(job, true), false, false);
30✔
1381

1382
    if(wh)
30✔
1383
        wh->OrderJob(job, *flag, true);
26✔
1384
}
1385

1386
bool GamePlayer::IsFlagWorker(const nofFlagWorker* flagworker)
×
1387
{
1388
    return helpers::contains(flagworkers, flagworker);
×
1389
}
1390

1391
void GamePlayer::FlagDestroyed(noFlag* flag)
775✔
1392
{
1393
    // Alle durchgehen und ggf. sagen, dass sie keine Flagge mehr haben, wenn das ihre Flagge war, die zerstört wurde
1394
    for(auto it = flagworkers.begin(); it != flagworkers.end();)
775✔
1395
    {
1396
        if((*it)->GetFlag() == flag)
×
1397
        {
1398
            (*it)->LostWork();
×
1399
            it = flagworkers.erase(it);
×
1400
        } else
1401
            ++it;
×
1402
    }
1403
}
775✔
1404

1405
void GamePlayer::RefreshDefenderList()
65✔
1406
{
1407
    shouldSendDefenderList.clear();
65✔
1408
    // Add as many true values as set in the settings, the rest will be false
1409
    for(unsigned i = 0; i < MILITARY_SETTINGS_SCALE[2]; ++i)
390✔
1410
        shouldSendDefenderList.push_back(i < militarySettings_[2]);
325✔
1411
    // und ordentlich schütteln
1412
    RANDOM_SHUFFLE2(shouldSendDefenderList, 0);
65✔
1413
}
65✔
1414

1415
void GamePlayer::ChangeMilitarySettings(const MilitarySettings& military_settings)
65✔
1416
{
1417
    for(unsigned i = 0; i < military_settings.size(); ++i)
585✔
1418
    {
1419
        // Sicherstellen, dass im validen Bereich
1420
        RTTR_Assert(military_settings[i] <= MILITARY_SETTINGS_SCALE[i]);
520✔
1421
        this->militarySettings_[i] = military_settings[i];
520✔
1422
    }
1423
    /// Truppen müssen neu kalkuliert werden
1424
    RegulateAllTroops();
65✔
1425
    /// Die Verteidigungsliste muss erneuert werden
1426
    RefreshDefenderList();
65✔
1427
}
65✔
1428

1429
/// Setzt neue Werkzeugeinstellungen
1430
void GamePlayer::ChangeToolsSettings(const ToolSettings& tools_settings,
6✔
1431
                                     const helpers::EnumArray<int8_t, Tool>& orderChanges)
1432
{
1433
    const bool settingsChanged = toolsSettings_ != tools_settings;
6✔
1434
    toolsSettings_ = tools_settings;
6✔
1435
    if(settingsChanged)
6✔
1436
        world.GetNotifications().publish(ToolNote(ToolNote::SettingsChanged, GetPlayerId()));
4✔
1437

1438
    for(const auto tool : helpers::enumRange<Tool>())
168✔
1439
    {
1440
        tools_ordered[tool] = helpers::clamp(tools_ordered[tool] + orderChanges[tool], 0, 100);
72✔
1441
        tools_ordered_delta[tool] -= orderChanges[tool];
72✔
1442

1443
        if(orderChanges[tool] != 0)
72✔
1444
        {
1445
            LOG.write(">> Committing an order of %1% for tool #%2%(%3%)\n", LogTarget::File) % (int)orderChanges[tool]
8✔
1446
              % static_cast<unsigned>(tool) % _(WARE_NAMES[TOOL_TO_GOOD[tool]]);
8✔
1447
            world.GetNotifications().publish(ToolNote(ToolNote::OrderPlaced, GetPlayerId()));
4✔
1448
        }
1449
    }
1450
}
6✔
1451

1452
/// Setzt neue Verteilungseinstellungen
1453
void GamePlayer::ChangeDistribution(const Distributions& distribution_settings)
6✔
1454
{
1455
    unsigned idx = 0;
6✔
1456
    for(const DistributionMapping& mapping : distributionMap)
180✔
1457
    {
1458
        distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)] = distribution_settings[idx++];
174✔
1459
    }
1460

1461
    RecalcDistribution();
6✔
1462
}
6✔
1463

1464
/// Setzt neue Baureihenfolge-Einstellungen
1465
void GamePlayer::ChangeBuildOrder(bool useCustomBuildOrder, const BuildOrders& order_data)
2✔
1466
{
1467
    this->useCustomBuildOrder_ = useCustomBuildOrder;
2✔
1468
    this->build_order = order_data;
2✔
1469
}
2✔
1470

1471
bool GamePlayer::ShouldSendDefender()
35✔
1472
{
1473
    // Wenn wir schon am Ende sind, muss die Verteidgungsliste erneuert werden
1474
    if(shouldSendDefenderList.empty())
35✔
1475
        RefreshDefenderList();
×
1476

1477
    bool result = shouldSendDefenderList.back();
35✔
1478
    shouldSendDefenderList.pop_back();
35✔
1479
    return result;
35✔
1480
}
1481

1482
void GamePlayer::TestDefeat()
82✔
1483
{
1484
    // Nicht schon besiegt?
1485
    // Keine Militärgebäude, keine Lagerhäuser (HQ,Häfen) -> kein Land --> verloren
1486
    if(!isDefeated && buildings.GetMilitaryBuildings().empty() && buildings.GetStorehouses().empty())
82✔
1487
        Surrender();
29✔
1488
}
82✔
1489

1490
nobHQ* GamePlayer::GetHQ() const
14✔
1491
{
1492
    const MapPoint& hqPos = GetHQPos();
14✔
1493
    return const_cast<nobHQ*>(hqPos.isValid() ? GetGameWorld().GetSpecObj<nobHQ>(hqPos) : nullptr);
14✔
1494
}
1495

1496
void GamePlayer::Surrender()
32✔
1497
{
1498
    if(isDefeated)
32✔
1499
        return;
1✔
1500

1501
    isDefeated = true;
31✔
1502

1503
    // GUI Bescheid sagen
1504
    if(world.GetGameInterface())
31✔
1505
        world.GetGameInterface()->GI_PlayerDefeated(GetPlayerId());
×
1506
}
1507

1508
void GamePlayer::SetStatisticValue(StatisticType type, unsigned value)
×
1509
{
1510
    statisticCurrentData[type] = value;
×
1511
}
×
1512

1513
void GamePlayer::ChangeStatisticValue(StatisticType type, int change)
2,065✔
1514
{
1515
    RTTR_Assert(change >= 0 || statisticCurrentData[type] >= static_cast<unsigned>(-change));
2,065✔
1516
    statisticCurrentData[type] += change;
2,065✔
1517
}
2,065✔
1518

1519
void GamePlayer::IncreaseMerchandiseStatistic(GoodType type)
4✔
1520
{
1521
    // Einsortieren...
1522
    switch(type)
4✔
1523
    {
1524
        case GoodType::Wood: statisticCurrentMerchandiseData[0]++; break;
×
1525
        case GoodType::Boards: statisticCurrentMerchandiseData[1]++; break;
×
1526
        case GoodType::Stones: statisticCurrentMerchandiseData[2]++; break;
×
1527
        case GoodType::Fish:
×
1528
        case GoodType::Bread:
1529
        case GoodType::Meat: statisticCurrentMerchandiseData[3]++; break;
×
1530
        case GoodType::Water: statisticCurrentMerchandiseData[4]++; break;
×
1531
        case GoodType::Beer: statisticCurrentMerchandiseData[5]++; break;
×
1532
        case GoodType::Coal: statisticCurrentMerchandiseData[6]++; break;
×
1533
        case GoodType::IronOre: statisticCurrentMerchandiseData[7]++; break;
×
1534
        case GoodType::Gold: statisticCurrentMerchandiseData[8]++; break;
×
1535
        case GoodType::Iron: statisticCurrentMerchandiseData[9]++; break;
×
1536
        case GoodType::Coins: statisticCurrentMerchandiseData[10]++; break;
×
1537
        case GoodType::Tongs:
3✔
1538
        case GoodType::Axe:
1539
        case GoodType::Saw:
1540
        case GoodType::PickAxe:
1541
        case GoodType::Hammer:
1542
        case GoodType::Shovel:
1543
        case GoodType::Crucible:
1544
        case GoodType::RodAndLine:
1545
        case GoodType::Scythe:
1546
        case GoodType::Cleaver:
1547
        case GoodType::Rollingpin:
1548
        case GoodType::Bow: statisticCurrentMerchandiseData[11]++; break;
3✔
1549
        case GoodType::ShieldVikings:
×
1550
        case GoodType::ShieldAfricans:
1551
        case GoodType::ShieldRomans:
1552
        case GoodType::ShieldJapanese:
1553
        case GoodType::Sword: statisticCurrentMerchandiseData[12]++; break;
×
1554
        case GoodType::Boat: statisticCurrentMerchandiseData[13]++; break;
×
1555
        default: break;
1✔
1556
    }
1557
}
4✔
1558

1559
/// Calculates current statistics
1560
void GamePlayer::CalcStatistics()
6✔
1561
{
1562
    // Waren aus der Inventur zählen
1563
    statisticCurrentData[StatisticType::Merchandise] = 0;
6✔
1564
    for(const auto i : helpers::enumRange<GoodType>())
504✔
1565
        statisticCurrentData[StatisticType::Merchandise] += global_inventory[i];
240✔
1566

1567
    // Bevölkerung aus der Inventur zählen
1568
    statisticCurrentData[StatisticType::Inhabitants] = 0;
6✔
1569
    for(const auto i : helpers::enumRange<Job>())
480✔
1570
        statisticCurrentData[StatisticType::Inhabitants] += global_inventory[i];
228✔
1571

1572
    // Militär aus der Inventur zählen
1573
    statisticCurrentData[StatisticType::Military] =
12✔
1574
      global_inventory.people[Job::Private] + global_inventory.people[Job::PrivateFirstClass] * 2
6✔
1575
      + global_inventory.people[Job::Sergeant] * 3 + global_inventory.people[Job::Officer] * 4
6✔
1576
      + global_inventory.people[Job::General] * 5;
6✔
1577

1578
    // Produktivität berechnen
1579
    statisticCurrentData[StatisticType::Productivity] = buildings.CalcAverageProductivity();
6✔
1580

1581
    // Total points for tournament games
1582
    statisticCurrentData[StatisticType::Tournament] =
12✔
1583
      statisticCurrentData[StatisticType::Military] + 3 * statisticCurrentData[StatisticType::Vanquished];
6✔
1584
}
6✔
1585

1586
void GamePlayer::StatisticStep()
6✔
1587
{
1588
    CalcStatistics();
6✔
1589

1590
    // 15-min-Statistik ein Feld weiterschieben
1591
    for(const auto i : helpers::enumRange<StatisticType>())
132✔
1592
    {
1593
        statistic[StatisticTime::T15Minutes].data[i][incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex)] =
54✔
1594
          statisticCurrentData[i];
54✔
1595
    }
1596
    for(unsigned i = 0; i < NUM_STAT_MERCHANDISE_TYPES; ++i)
90✔
1597
    {
1598
        statistic[StatisticTime::T15Minutes]
84✔
1599
          .merchandiseData[i][incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex)] =
168✔
1600
          statisticCurrentMerchandiseData[i];
84✔
1601
    }
1602
    statistic[StatisticTime::T15Minutes].currentIndex =
6✔
1603
      incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex);
6✔
1604

1605
    statistic[StatisticTime::T15Minutes].counter++;
6✔
1606

1607
    // Prüfen ob 4mal 15-min-Statistik weitergeschoben wurde, wenn ja: 1-h-Statistik weiterschieben
1608
    // und aktuellen Wert der 15min-Statistik benutzen
1609
    // gleiches für die 4h und 16h Statistik
1610
    for(const auto t : helpers::enumRange<StatisticTime>())
60✔
1611
    {
1612
        if(t == StatisticTime(helpers::MaxEnumValue_v<StatisticTime>))
24✔
1613
            break;
6✔
1614
        const auto nextT = StatisticTime(rttr::enum_cast(t) + 1);
18✔
1615
        if(statistic[t].counter == 4)
18✔
1616
        {
1617
            statistic[t].counter = 0;
×
1618
            for(const auto i : helpers::enumRange<StatisticType>())
×
1619
            {
1620
                statistic[nextT].data[i][incrStatIndex(statistic[nextT].currentIndex)] = statisticCurrentData[i];
×
1621
            }
1622

1623
            // Summe für den Zeitraum berechnen (immer 4 Zeitschritte der jeweils kleineren Statistik)
1624
            for(unsigned i = 0; i < NUM_STAT_MERCHANDISE_TYPES; ++i)
×
1625
            {
1626
                statistic[nextT].merchandiseData[i][incrStatIndex(statistic[nextT].currentIndex)] =
×
1627
                  statisticCurrentMerchandiseData[i]
×
1628
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 1)]
×
1629
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 2)]
×
1630
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 3)];
×
1631
            }
1632

1633
            statistic[nextT].currentIndex = incrStatIndex(statistic[nextT].currentIndex);
×
1634
            statistic[nextT].counter++;
×
1635
        }
1636
    }
1637

1638
    // Warenstatistikzähler nullen
1639
    statisticCurrentMerchandiseData.fill(0);
6✔
1640
}
6✔
1641

1642
GamePlayer::Pact::Pact(SerializedGameData& sgd)
112✔
1643
    : duration(sgd.PopUnsignedInt()), start(sgd.PopUnsignedInt()), accepted(sgd.PopBool()), want_cancel(sgd.PopBool())
112✔
1644
{}
112✔
1645

1646
void GamePlayer::Pact::Serialize(SerializedGameData& sgd) const
224✔
1647
{
1648
    sgd.PushUnsignedInt(duration);
224✔
1649
    sgd.PushUnsignedInt(start);
224✔
1650
    sgd.PushBool(accepted);
224✔
1651
    sgd.PushBool(want_cancel);
224✔
1652
}
224✔
1653

1654
void GamePlayer::PactChanged(const PactType pt)
24✔
1655
{
1656
    // Recheck military flags as the border (to an enemy) might have changed
1657
    RecalcMilitaryFlags();
24✔
1658

1659
    // Ggf. den GUI Bescheid sagen, um Sichtbarkeiten etc. neu zu berechnen
1660
    if(pt == PactType::TreatyOfAlliance)
24✔
1661
    {
1662
        if(world.GetGameInterface())
6✔
1663
            world.GetGameInterface()->GI_TreatyOfAllianceChanged(GetPlayerId());
×
1664
    }
1665
}
24✔
1666

1667
void GamePlayer::SuggestPact(const unsigned char targetPlayerId, const PactType pt, const unsigned duration)
10✔
1668
{
1669
    // Don't try to make pact with self
1670
    if(targetPlayerId == GetPlayerId())
10✔
1671
        return;
1✔
1672

1673
    if(!pacts[targetPlayerId][pt].accepted && duration > 0)
9✔
1674
    {
1675
        pacts[targetPlayerId][pt].duration = duration;
8✔
1676
        pacts[targetPlayerId][pt].start = world.GetEvMgr().GetCurrentGF();
8✔
1677
        GamePlayer targetPlayer = world.GetPlayer(targetPlayerId);
16✔
1678
        if(targetPlayer.isHuman())
8✔
1679
            targetPlayer.SendPostMessage(std::make_unique<DiplomacyPostQuestion>(
6✔
1680
              world.GetEvMgr().GetCurrentGF(), pt, pacts[targetPlayerId][pt].start, *this, duration));
12✔
1681
        else if(world.HasLua())
2✔
1682
            world.GetLua().EventSuggestPact(pt, GetPlayerId(), targetPlayerId, duration);
2✔
1683
    }
1684
}
1685

1686
void GamePlayer::AcceptPact(const unsigned id, const PactType pt, const unsigned char targetPlayer)
21✔
1687
{
1688
    if(!pacts[targetPlayer][pt].accepted && pacts[targetPlayer][pt].duration > 0 && pacts[targetPlayer][pt].start == id)
21✔
1689
    {
1690
        MakePact(pt, targetPlayer, pacts[targetPlayer][pt].duration);
8✔
1691
        world.GetPlayer(targetPlayer).MakePact(pt, GetPlayerId(), pacts[targetPlayer][pt].duration);
8✔
1692
        PactChanged(pt);
8✔
1693
        world.GetPlayer(targetPlayer).PactChanged(pt);
8✔
1694
        if(world.HasLua())
8✔
1695
            world.GetLua().EventPactCreated(pt, GetPlayerId(), targetPlayer, pacts[targetPlayer][pt].duration);
3✔
1696
    }
1697
}
21✔
1698

1699
/// Bündnis (real, d.h. spielentscheidend) abschließen
1700
void GamePlayer::MakePact(const PactType pt, const unsigned char other_player, const unsigned duration)
16✔
1701
{
1702
    pacts[other_player][pt].accepted = true;
16✔
1703
    pacts[other_player][pt].start = world.GetEvMgr().GetCurrentGF();
16✔
1704
    pacts[other_player][pt].duration = duration;
16✔
1705
    pacts[other_player][pt].want_cancel = false;
16✔
1706

1707
    SendPostMessage(
16✔
1708
      std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, world.GetPlayer(other_player), true));
32✔
1709
}
16✔
1710

1711
/// Zeigt an, ob ein Pakt besteht
1712
PactState GamePlayer::GetPactState(const PactType pt, const unsigned char other_player) const
9,314✔
1713
{
1714
    // Prüfen, ob Bündnis in Kraft ist
1715
    if(pacts[other_player][pt].duration)
9,314✔
1716
    {
1717
        if(!pacts[other_player][pt].accepted)
5,053✔
1718
            return PactState::InProgress;
16✔
1719

1720
        if(pacts[other_player][pt].duration == DURATION_INFINITE
5,037✔
1721
           || world.GetEvMgr().GetCurrentGF() < pacts[other_player][pt].start + pacts[other_player][pt].duration)
5,037✔
1722
            return PactState::Accepted;
5,035✔
1723
    }
1724

1725
    return PactState::None;
4,263✔
1726
}
1727

1728
/// all allied players get a letter with the location
1729
void GamePlayer::NotifyAlliesOfLocation(const MapPoint pt)
6✔
1730
{
1731
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
24✔
1732
    {
1733
        if(i != GetPlayerId() && IsAlly(i))
18✔
1734
            world.GetPlayer(i).SendPostMessage(std::make_unique<PostMsg>(
10✔
1735
              world.GetEvMgr().GetCurrentGF(), _("Your ally wishes to notify you of this location"),
5✔
1736
              PostCategory::Diplomacy, pt));
10✔
1737
    }
1738
}
6✔
1739

1740
/// Gibt die verbleibende Dauer zurück, die ein Bündnis noch laufen wird (DURATION_INFINITE = für immer)
1741
unsigned GamePlayer::GetRemainingPactTime(const PactType pt, const unsigned char other_player) const
125✔
1742
{
1743
    if(pacts[other_player][pt].duration)
125✔
1744
    {
1745
        if(pacts[other_player][pt].accepted)
88✔
1746
        {
1747
            if(pacts[other_player][pt].duration == DURATION_INFINITE)
76✔
1748
                return DURATION_INFINITE;
×
1749
            else if(world.GetEvMgr().GetCurrentGF() <= pacts[other_player][pt].start + pacts[other_player][pt].duration)
76✔
1750
                return ((pacts[other_player][pt].start + pacts[other_player][pt].duration)
76✔
1751
                        - world.GetEvMgr().GetCurrentGF());
76✔
1752
        }
1753
    }
1754

1755
    return 0;
49✔
1756
}
1757

1758
/// Gibt Einverständnis, dass dieser Spieler den Pakt auflösen will
1759
/// Falls dieser Spieler einen Bündnisvorschlag gemacht hat, wird dieser dagegen zurückgenommen
1760
void GamePlayer::CancelPact(const PactType pt, const unsigned char otherPlayerIdx)
8✔
1761
{
1762
    // Don't try to cancel pact with self
1763
    if(otherPlayerIdx == GetPlayerId())
8✔
1764
        return;
2✔
1765

1766
    // Besteht bereits ein Bündnis?
1767
    if(pacts[otherPlayerIdx][pt].accepted)
6✔
1768
    {
1769
        // Vermerken, dass der Spieler das Bündnis auflösen will
1770
        pacts[otherPlayerIdx][pt].want_cancel = true;
6✔
1771

1772
        // Will der andere Spieler das Bündnis auch auflösen?
1773
        GamePlayer& otherPlayer = world.GetPlayer(otherPlayerIdx);
6✔
1774
        if(otherPlayer.pacts[GetPlayerId()][pt].want_cancel)
6✔
1775
        {
1776
            // Dann wird das Bündnis aufgelöst
1777
            pacts[otherPlayerIdx][pt].accepted = false;
2✔
1778
            pacts[otherPlayerIdx][pt].duration = 0;
2✔
1779
            pacts[otherPlayerIdx][pt].want_cancel = false;
2✔
1780

1781
            otherPlayer.pacts[GetPlayerId()][pt].accepted = false;
2✔
1782
            otherPlayer.pacts[GetPlayerId()][pt].duration = 0;
2✔
1783
            otherPlayer.pacts[GetPlayerId()][pt].want_cancel = false;
2✔
1784

1785
            // Den Spielern eine Informationsnachricht schicken
1786
            world.GetPlayer(otherPlayerIdx)
2✔
1787
              .SendPostMessage(std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, *this, false));
2✔
1788
            SendPostMessage(
2✔
1789
              std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, world.GetPlayer(otherPlayerIdx), false));
4✔
1790
            PactChanged(pt);
2✔
1791
            otherPlayer.PactChanged(pt);
2✔
1792
            if(world.HasLua())
2✔
1793
                world.GetLua().EventPactCanceled(pt, GetPlayerId(), otherPlayerIdx);
1✔
1794
        } else
1795
        {
1796
            // Ansonsten den anderen Spieler fragen, ob der das auch so sieht
1797
            if(otherPlayer.isHuman())
4✔
1798
                otherPlayer.SendPostMessage(std::make_unique<DiplomacyPostQuestion>(
3✔
1799
                  world.GetEvMgr().GetCurrentGF(), pt, pacts[otherPlayerIdx][pt].start, *this));
6✔
1800
            else if(!world.HasLua() || world.GetLua().EventCancelPactRequest(pt, GetPlayerId(), otherPlayerIdx))
1✔
1801
            {
1802
                // AI accepts cancels, if there is no lua-interace
1803
                pacts[otherPlayerIdx][pt].accepted = false;
1✔
1804
                pacts[otherPlayerIdx][pt].duration = 0;
1✔
1805
                pacts[otherPlayerIdx][pt].want_cancel = false;
1✔
1806

1807
                otherPlayer.pacts[GetPlayerId()][pt].accepted = false;
1✔
1808
                otherPlayer.pacts[GetPlayerId()][pt].duration = 0;
1✔
1809
                otherPlayer.pacts[GetPlayerId()][pt].want_cancel = false;
1✔
1810

1811
                if(world.HasLua())
1✔
1812
                    world.GetLua().EventPactCanceled(pt, GetPlayerId(), otherPlayerIdx);
1✔
1813
            }
1814
        }
1815
    } else
1816
    {
1817
        // Es besteht kein Bündnis, also unseren Bündnisvorschlag wieder zurücknehmen
1818
        pacts[otherPlayerIdx][pt].duration = 0;
×
1819
    }
1820
}
1821

1822
void GamePlayer::MakeStartPacts()
66✔
1823
{
1824
    // Reset pacts
1825
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
262✔
1826
    {
1827
        for(const auto z : helpers::enumRange<PactType>())
1,568✔
1828
            pacts[i][z] = Pact();
392✔
1829
    }
1830

1831
    // No team -> No pacts
1832
    if(team == Team::None)
66✔
1833
        return;
4✔
1834
    RTTR_Assert(isTeam(team));
62✔
1835

1836
    // Create ally- and non-aggression-pact for all players of same team
1837
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
245✔
1838
    {
1839
        if(team != world.GetPlayer(i).team)
183✔
1840
            continue;
75✔
1841
        for(const auto z : helpers::enumRange<PactType>())
864✔
1842
        {
1843
            pacts[i][z].duration = DURATION_INFINITE;
216✔
1844
            pacts[i][z].start = 0;
216✔
1845
            pacts[i][z].accepted = true;
216✔
1846
            pacts[i][z].want_cancel = false;
216✔
1847
        }
1848
    }
1849
}
1850

1851
bool GamePlayer::IsWareRegistred(const Ware& ware)
165✔
1852
{
1853
    return helpers::contains(ware_list, &ware);
165✔
1854
}
1855

1856
bool GamePlayer::IsWareDependent(const Ware& ware)
14✔
1857
{
1858
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
41✔
1859
    {
1860
        if(wh->IsWareDependent(ware))
27✔
1861
            return true;
×
1862
    }
1863

1864
    return false;
14✔
1865
}
1866

1867
void GamePlayer::IncreaseInventoryWare(const GoodType ware, const unsigned count)
16,367✔
1868
{
1869
    global_inventory.Add(ConvertShields(ware), count);
16,367✔
1870
}
16,367✔
1871

1872
void GamePlayer::DecreaseInventoryWare(const GoodType ware, const unsigned count)
2,533✔
1873
{
1874
    global_inventory.Remove(ConvertShields(ware), count);
2,533✔
1875
}
2,533✔
1876

1877
/// Registriert ein Schiff beim Einwohnermeldeamt
1878
void GamePlayer::RegisterShip(noShip& ship)
21✔
1879
{
1880
    ships.push_back(&ship);
21✔
1881
    // Evtl bekommt das Schiffchen gleich was zu tun?
1882
    GetJobForShip(ship);
21✔
1883
}
21✔
1884

1885
struct ShipForHarbor
1886
{
1887
    noShip* ship;
1888
    uint32_t estimate;
1889

1890
    ShipForHarbor(noShip* ship, uint32_t estimate) : ship(ship), estimate(estimate) {}
18✔
1891

1892
    bool operator<(const ShipForHarbor& b) const
×
1893
    {
1894
        return (estimate < b.estimate) || (estimate == b.estimate && ship->GetObjId() < b.ship->GetObjId());
×
1895
    }
1896
};
1897

1898
/// Schiff für Hafen bestellen
1899
bool GamePlayer::OrderShip(nobHarborBuilding& hb)
32✔
1900
{
1901
    std::vector<ShipForHarbor> sfh;
64✔
1902

1903
    // we need more ships than those that are already on their way? limit search to idle ships
1904
    if(GetShipsToHarbor(hb) < hb.GetNumNeededShips())
32✔
1905
    {
1906
        for(noShip* ship : ships)
64✔
1907
        {
1908
            if(ship->IsIdling() && world.IsHarborAtSea(world.GetHarborPointID(hb.GetPos()), ship->GetSeaID()))
32✔
1909
                sfh.push_back(ShipForHarbor(ship, world.CalcDistance(hb.GetPos(), ship->GetPos())));
18✔
1910
        }
1911
    } else
1912
    {
1913
        for(noShip* ship : ships)
×
1914
        {
1915
            if((ship->IsIdling() && world.IsHarborAtSea(world.GetHarborPointID(hb.GetPos()), ship->GetSeaID()))
×
1916
               || ship->IsGoingToHarbor(hb))
×
1917
            {
1918
                sfh.push_back(ShipForHarbor(ship, world.CalcDistance(hb.GetPos(), ship->GetPos())));
×
1919
            }
1920
        }
1921
    }
1922

1923
    std::sort(sfh.begin(), sfh.end());
32✔
1924

1925
    noShip* best_ship = nullptr;
32✔
1926
    uint32_t best_distance = std::numeric_limits<uint32_t>::max();
32✔
1927
    std::vector<Direction> best_route;
64✔
1928

1929
    for(auto& it : sfh)
41✔
1930
    {
1931
        uint32_t distance;
1932
        std::vector<Direction> route;
18✔
1933

1934
        // the estimate (air-line distance) for this and all other ships in the list is already worse than what we
1935
        // found? disregard the rest
1936
        if(it.estimate >= best_distance)
18✔
1937
            break;
×
1938

1939
        noShip& ship = *it.ship;
18✔
1940

1941
        MapPoint dest = world.GetCoastalPoint(hb.GetHarborPosID(), ship.GetSeaID());
18✔
1942

1943
        // ship already there?
1944
        if(ship.GetPos() == dest)
18✔
1945
        {
1946
            hb.ShipArrived(ship);
9✔
1947
            return (true);
9✔
1948
        }
1949

1950
        if(world.FindShipPathToHarbor(ship.GetPos(), hb.GetHarborPosID(), ship.GetSeaID(), &route, &distance))
9✔
1951
        {
1952
            if(distance < best_distance)
9✔
1953
            {
1954
                best_ship = &ship;
9✔
1955
                best_distance = distance;
9✔
1956
                best_route = route;
9✔
1957
            }
1958
        }
1959
    }
1960

1961
    // only order ships not already on their way
1962
    if(best_ship && best_ship->IsIdling())
23✔
1963
    {
1964
        best_ship->GoToHarbor(hb, best_route);
9✔
1965

1966
        return (true);
9✔
1967
    }
1968

1969
    return (false);
14✔
1970
}
1971

1972
/// Meldet das Schiff wieder ab
1973
void GamePlayer::RemoveShip(noShip* ship)
×
1974
{
1975
    for(unsigned i = 0; i < ships.size(); ++i)
×
1976
    {
1977
        if(ships[i] == ship)
×
1978
        {
1979
            ships.erase(ships.begin() + i);
×
1980
            return;
×
1981
        }
1982
    }
1983
}
1984

1985
/// Versucht, für ein untätiges Schiff eine Arbeit zu suchen
1986
void GamePlayer::GetJobForShip(noShip& ship)
31✔
1987
{
1988
    // Evtl. steht irgendwo eine Expedition an und das Schiff kann diese übernehmen
1989
    nobHarborBuilding* best = nullptr;
31✔
1990
    int best_points = 0;
31✔
1991
    std::vector<Direction> best_route;
31✔
1992

1993
    // Beste Weglänge, die ein Schiff zurücklegen muss, welches gerade nichts zu tun hat
1994
    for(nobHarborBuilding* harbor : buildings.GetHarbors())
64✔
1995
    {
1996
        // Braucht der Hafen noch Schiffe?
1997
        if(harbor->GetNumNeededShips() == 0)
33✔
1998
            continue;
33✔
1999

2000
        // Anzahl der Schiffe ermitteln, die diesen Hafen bereits anfahren
2001
        unsigned ships_coming = GetShipsToHarbor(*harbor);
×
2002

2003
        // Evtl. kommen schon genug?
2004
        if(harbor->GetNumNeededShips() <= ships_coming)
×
2005
            continue;
×
2006

2007
        // liegen wir am gleichen Meer?
2008
        if(world.IsHarborAtSea(harbor->GetHarborPosID(), ship.GetSeaID()))
×
2009
        {
2010
            const MapPoint coastPt = world.GetCoastalPoint(harbor->GetHarborPosID(), ship.GetSeaID());
×
2011

2012
            // Evtl. sind wir schon da?
2013
            if(ship.GetPos() == coastPt)
×
2014
            {
2015
                harbor->ShipArrived(ship);
×
2016
                return;
×
2017
            }
2018

2019
            unsigned length;
2020
            std::vector<Direction> route;
×
2021

2022
            if(world.FindShipPathToHarbor(ship.GetPos(), harbor->GetHarborPosID(), ship.GetSeaID(), &route, &length))
×
2023
            {
2024
                // Punkte ausrechnen
2025
                int points = harbor->GetNeedForShip(ships_coming) - length;
×
2026
                if(points > best_points || !best)
×
2027
                {
2028
                    best = harbor;
×
2029
                    best_points = points;
×
2030
                    best_route = route;
×
2031
                }
2032
            }
2033
        }
2034
    }
2035

2036
    // Einen Hafen gefunden?
2037
    if(best)
31✔
2038
        // Dann bekommt das gleich der Hafen
2039
        ship.GoToHarbor(*best, best_route);
×
2040
}
2041

2042
/// Gibt die ID eines Schiffes zurück
2043
unsigned GamePlayer::GetShipID(const noShip* const ship) const
13✔
2044
{
2045
    for(unsigned i = 0; i < ships.size(); ++i)
13✔
2046
        if(ships[i] == ship)
13✔
2047
            return i;
13✔
2048

2049
    return 0xFFFFFFFF;
×
2050
}
2051

2052
/// Gibt ein Schiff anhand der ID zurück bzw. nullptr, wenn keines mit der ID existiert
2053
noShip* GamePlayer::GetShipByID(const unsigned ship_id) const
20✔
2054
{
2055
    if(ship_id >= ships.size())
20✔
2056
        return nullptr;
×
2057
    else
2058
        return ships[ship_id];
20✔
2059
}
2060

2061
/// Gibt eine Liste mit allen Häfen dieses Spieler zurück, die an ein bestimmtes Meer angrenzen
2062
void GamePlayer::GetHarborsAtSea(std::vector<nobHarborBuilding*>& harbor_buildings, const unsigned short seaId) const
198✔
2063
{
2064
    for(nobHarborBuilding* harbor : buildings.GetHarbors())
642✔
2065
    {
2066
        if(helpers::contains(harbor_buildings, harbor))
444✔
2067
            continue;
216✔
2068

2069
        if(world.IsHarborAtSea(harbor->GetHarborPosID(), seaId))
228✔
2070
            harbor_buildings.push_back(harbor);
228✔
2071
    }
2072
}
198✔
2073

2074
/// Gibt die Anzahl der Schiffe, die einen bestimmten Hafen ansteuern, zurück
2075
unsigned GamePlayer::GetShipsToHarbor(const nobHarborBuilding& hb) const
71✔
2076
{
2077
    unsigned count = 0;
71✔
2078
    for(const auto* ship : ships)
142✔
2079
    {
2080
        if(ship->IsGoingToHarbor(hb))
71✔
2081
            ++count;
5✔
2082
    }
2083

2084
    return count;
71✔
2085
}
2086

2087
/// Sucht einen Hafen in der Nähe, wo dieses Schiff seine Waren abladen kann
2088
/// gibt true zurück, falls erfolgreich
2089
bool GamePlayer::FindHarborForUnloading(noShip* ship, const MapPoint start, unsigned* goal_harborId,
5✔
2090
                                        std::vector<Direction>* route, nobHarborBuilding* exception)
2091
{
2092
    nobHarborBuilding* best = nullptr;
5✔
2093
    unsigned best_distance = 0xffffffff;
5✔
2094

2095
    for(nobHarborBuilding* hb : buildings.GetHarbors())
8✔
2096
    {
2097
        // Bestimmten Hafen ausschließen
2098
        if(hb == exception)
3✔
2099
            continue;
×
2100

2101
        // Prüfen, ob Hafen an das Meer, wo sich das Schiff gerade befindet, angrenzt
2102
        if(!world.IsHarborAtSea(hb->GetHarborPosID(), ship->GetSeaID()))
3✔
2103
            continue;
×
2104

2105
        // Distanz ermitteln zwischen Schiff und Hafen, Schiff kann natürlich auch über Kartenränder fahren
2106
        unsigned distance = world.CalcDistance(ship->GetPos(), hb->GetPos());
3✔
2107

2108
        // Kürzerer Weg als bisher bestes Ziel?
2109
        if(distance < best_distance)
3✔
2110
        {
2111
            best_distance = distance;
3✔
2112
            best = hb;
3✔
2113
        }
2114
    }
2115

2116
    // Hafen gefunden?
2117
    if(best)
5✔
2118
    {
2119
        // Weg dorthin suchen
2120
        route->clear();
3✔
2121
        *goal_harborId = best->GetHarborPosID();
3✔
2122
        const MapPoint coastPt = world.GetCoastalPoint(best->GetHarborPosID(), ship->GetSeaID());
3✔
2123
        if(start == coastPt
3✔
2124
           || world.FindShipPathToHarbor(start, best->GetHarborPosID(), ship->GetSeaID(), route, nullptr))
3✔
2125
            return true;
3✔
2126
    }
2127

2128
    return false;
2✔
2129
}
2130

2131
void GamePlayer::TestForEmergencyProgramm()
×
2132
{
2133
    // we are already defeated, do not even think about an emergency program - it's too late :-(
2134
    if(isDefeated)
×
2135
        return;
×
2136

2137
    // In Lagern vorhandene Bretter und Steine zählen
2138
    unsigned boards = 0;
×
2139
    unsigned stones = 0;
×
2140
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
×
2141
    {
2142
        boards += wh->GetInventory().goods[GoodType::Boards];
×
2143
        stones += wh->GetInventory().goods[GoodType::Stones];
×
2144
    }
2145

2146
    // Emergency happens, if we have less than 10 boards or stones...
2147
    bool isNewEmergency = boards <= 10 || stones <= 10;
×
2148
    // ...and no woddcutter or sawmill
2149
    isNewEmergency &=
×
2150
      buildings.GetBuildings(BuildingType::Woodcutter).empty() || buildings.GetBuildings(BuildingType::Sawmill).empty();
×
2151

2152
    // Wenn nötig, Notfallprogramm auslösen
2153
    if(isNewEmergency)
×
2154
    {
2155
        if(!emergency)
×
2156
        {
2157
            emergency = true;
×
2158
            SendPostMessage(std::make_unique<PostMsg>(
×
2159
              world.GetEvMgr().GetCurrentGF(), _("The emergency program has been activated."), PostCategory::Economy));
×
2160
        }
2161
    } else
2162
    {
2163
        // Sobald Notfall vorbei, Notfallprogramm beenden, evtl. Baustellen wieder mit Kram versorgen
2164
        if(emergency)
×
2165
        {
2166
            emergency = false;
×
2167
            SendPostMessage(std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(),
×
2168
                                                      _("The emergency program has been deactivated."),
×
2169
                                                      PostCategory::Economy));
×
2170
            FindMaterialForBuildingSites();
×
2171
        }
2172
    }
2173
}
2174

2175
/// Testet die Bündnisse, ob sie nicht schon abgelaufen sind
2176
void GamePlayer::TestPacts()
20✔
2177
{
2178
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
80✔
2179
    {
2180
        if(i == GetPlayerId())
60✔
2181
            continue;
20✔
2182

2183
        for(const auto pact : helpers::enumRange<PactType>())
320✔
2184
        {
2185
            // Pact not running
2186
            if(pacts[i][pact].duration == 0)
80✔
2187
                continue;
60✔
2188
            if(GetPactState(pact, i) == PactState::None)
20✔
2189
            {
2190
                // Pact was running but is expired -> Cancel for both players
2191
                pacts[i][pact].duration = 0;
2✔
2192
                pacts[i][pact].accepted = false;
2✔
2193
                GamePlayer& otherPlayer = world.GetPlayer(i);
2✔
2194
                RTTR_Assert(otherPlayer.pacts[GetPlayerId()][pact].duration);
2✔
2195
                RTTR_Assert(otherPlayer.pacts[GetPlayerId()][pact].accepted);
2✔
2196
                otherPlayer.pacts[GetPlayerId()][pact].duration = 0;
2✔
2197
                otherPlayer.pacts[GetPlayerId()][pact].accepted = false;
2✔
2198
                // And notify
2199
                PactChanged(pact);
2✔
2200
                otherPlayer.PactChanged(pact);
2✔
2201
            }
2202
        }
2203
    }
2204
}
20✔
2205

2206
bool GamePlayer::CanBuildCatapult() const
1✔
2207
{
2208
    // Wenn AddonId::LIMIT_CATAPULTS nicht aktiv ist, bauen immer erlaubt
2209
    if(!world.GetGGS().isEnabled(AddonId::LIMIT_CATAPULTS)) //-V807
1✔
2210
        return true;
1✔
2211

2212
    BuildingCount bc = buildings.GetBuildingNums();
×
2213

2214
    unsigned max = 0;
×
2215
    // proportional?
2216
    if(world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) == 1)
×
2217
    {
2218
        max = int(bc.buildings[BuildingType::Barracks] * 0.125 + bc.buildings[BuildingType::Guardhouse] * 0.25
×
2219
                  + bc.buildings[BuildingType::Watchtower] * 0.5 + bc.buildings[BuildingType::Fortress]
×
2220
                  + 0.111); // to avoid rounding errors
×
2221
    } else if(world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) < 8)
×
2222
    {
2223
        const std::array<unsigned, 6> limits = {{0, 3, 5, 10, 20, 30}};
×
2224
        max = limits[world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) - 2];
×
2225
    }
2226

2227
    return bc.buildings[BuildingType::Catapult] + bc.buildingSites[BuildingType::Catapult] < max;
×
2228
}
2229

2230
/// A ship has discovered new hostile territory --> determines if this is new
2231
/// i.e. there is a sufficient distance to older locations
2232
/// Returns true if yes and false if not
2233
bool GamePlayer::ShipDiscoveredHostileTerritory(const MapPoint location)
25✔
2234
{
2235
    // Prüfen, ob Abstand zu bisherigen Punkten nicht zu klein
2236
    for(const auto& enemies_discovered_by_ship : enemies_discovered_by_ships)
25✔
2237
    {
2238
        if(world.CalcDistance(enemies_discovered_by_ship, location) < 30)
24✔
2239
            return false;
24✔
2240
    }
2241

2242
    // Nein? Dann haben wir ein neues Territorium gefunden
2243
    enemies_discovered_by_ships.push_back(location);
1✔
2244

2245
    return true;
1✔
2246
}
2247

2248
/// For debug only
2249
bool GamePlayer::IsDependentFigure(const noFigure& fig)
236✔
2250
{
2251
    for(const nobBaseWarehouse* wh : buildings.GetStorehouses())
580✔
2252
    {
2253
        if(wh->IsDependentFigure(fig))
344✔
2254
            return true;
×
2255
    }
2256
    return false;
236✔
2257
}
2258

2259
std::vector<nobBaseWarehouse*> GamePlayer::GetWarehousesForTrading(const nobBaseWarehouse& goalWh) const
18✔
2260
{
2261
    std::vector<nobBaseWarehouse*> result;
18✔
2262

2263
    // Don't try to trade with us!
2264
    if(goalWh.GetPlayer() == GetPlayerId())
18✔
2265
        return result;
6✔
2266

2267
    const MapPoint goalFlagPos = goalWh.GetFlagPos();
12✔
2268

2269
    TradePathCache& tradePathCache = world.GetTradePathCache();
12✔
2270
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
24✔
2271
    {
2272
        // Is there a trade path from this warehouse to wh? (flag to flag)
2273
        if(tradePathCache.pathExists(wh->GetFlagPos(), goalFlagPos, GetPlayerId()))
12✔
2274
            result.push_back(wh);
4✔
2275
    }
2276

2277
    return result;
12✔
2278
}
2279

2280
struct WarehouseDistanceComparator
2281
{
2282
    // Reference warehouse position, to which we want to calc the distance
2283
    const MapPoint refWareHousePos_;
2284
    /// GameWorld
2285
    const GameWorld& gwg_;
2286

2287
    WarehouseDistanceComparator(const nobBaseWarehouse& refWareHouse, const GameWorld& world)
15✔
2288
        : refWareHousePos_(refWareHouse.GetPos()), gwg_(world)
15✔
2289
    {}
15✔
2290

2291
    bool operator()(nobBaseWarehouse* const wh1, nobBaseWarehouse* const wh2) const
×
2292
    {
2293
        unsigned dist1 = gwg_.CalcDistance(wh1->GetPos(), refWareHousePos_);
×
2294
        unsigned dist2 = gwg_.CalcDistance(wh2->GetPos(), refWareHousePos_);
×
2295
        return (dist1 < dist2) || (dist1 == dist2 && wh1->GetObjId() < wh2->GetObjId());
×
2296
    }
2297
};
2298

2299
/// Send wares to warehouse wh
2300
void GamePlayer::Trade(nobBaseWarehouse* goalWh, const boost_variant2<GoodType, Job>& what, unsigned count) const
23✔
2301
{
2302
    if(!world.GetGGS().isEnabled(AddonId::TRADE))
23✔
2303
        return;
11✔
2304

2305
    if(count == 0)
20✔
2306
        return;
3✔
2307

2308
    // Don't try to trade with us!
2309
    if(goalWh->GetPlayer() == GetPlayerId())
17✔
2310
        return;
1✔
2311

2312
    // No trades with enemies
2313
    if(!IsAlly(goalWh->GetPlayer()))
16✔
2314
        return;
1✔
2315

2316
    const MapPoint goalFlagPos = goalWh->GetFlagPos();
15✔
2317

2318
    std::vector<nobBaseWarehouse*> whs(buildings.GetStorehouses().begin(), buildings.GetStorehouses().end());
15✔
2319
    std::sort(whs.begin(), whs.end(), WarehouseDistanceComparator(*goalWh, world));
15✔
2320
    TradePathCache& tradePathCache = world.GetTradePathCache();
15✔
2321
    for(nobBaseWarehouse* wh : whs)
27✔
2322
    {
2323
        // Get available wares
2324
        const unsigned available =
2325
          boost::variant2::visit(composeVisitor([wh](GoodType gt) { return wh->GetAvailableWaresForTrading(gt); },
22✔
2326
                                                [wh](Job job) { return wh->GetAvailableFiguresForTrading(job); }),
23✔
2327
                                 what);
15✔
2328
        if(available == 0)
15✔
2329
            continue;
×
2330

2331
        const unsigned actualCount = std::min(available, count);
15✔
2332

2333
        // Find a trade path from flag to flag
2334
        TradeRoute tr(world, GetPlayerId(), wh->GetFlagPos(), goalFlagPos);
15✔
2335

2336
        // Found a path?
2337
        if(tr.IsValid())
15✔
2338
        {
2339
            // Add to cache for future searches
2340
            tradePathCache.addEntry(tr.GetTradePath(), GetPlayerId());
14✔
2341

2342
            wh->StartTradeCaravane(what, actualCount, tr, goalWh);
14✔
2343
            count -= available;
14✔
2344
            if(count == 0)
14✔
2345
                return;
3✔
2346
        }
2347
    }
2348
}
2349

2350
bool GamePlayer::IsBuildingEnabled(BuildingType type) const
955✔
2351
{
2352
    return building_enabled[type] || (isHuman() && world.GetGameInterface()->GI_GetCheats().areAllBuildingsEnabled());
955✔
2353
}
2354

2355
void GamePlayer::FillVisualSettings(VisualSettings& visualSettings) const
2✔
2356
{
2357
    Distributions& visDistribution = visualSettings.distribution;
2✔
2358
    unsigned visIdx = 0;
2✔
2359
    for(const DistributionMapping& mapping : distributionMap)
60✔
2360
    {
2361
        visDistribution[visIdx++] = distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)];
58✔
2362
    }
2363

2364
    visualSettings.useCustomBuildOrder = useCustomBuildOrder_;
2✔
2365
    visualSettings.build_order = build_order;
2✔
2366

2367
    visualSettings.transport_order = GetOrderingFromTransportPrio(transportPrio);
2✔
2368

2369
    visualSettings.military_settings = militarySettings_;
2✔
2370
    visualSettings.tools_settings = toolsSettings_;
2✔
2371
}
2✔
2372

2373
#define INSTANTIATE_FINDWH(Cond)                                                                                \
2374
    template nobBaseWarehouse* GamePlayer::FindWarehouse(const noRoadNode&, const Cond&, bool, bool, unsigned*, \
2375
                                                         const RoadSegment*) const
2376

2377
INSTANTIATE_FINDWH(FW::HasMinWares);
2378
INSTANTIATE_FINDWH(FW::HasFigure);
2379
INSTANTIATE_FINDWH(FW::HasWareAndFigure);
2380
INSTANTIATE_FINDWH(FW::HasAnyMatchingSoldier);
2381
INSTANTIATE_FINDWH(FW::AcceptsWare);
2382
INSTANTIATE_FINDWH(FW::AcceptsFigure);
2383
INSTANTIATE_FINDWH(FW::CollectsWare);
2384
INSTANTIATE_FINDWH(FW::CollectsFigure);
2385
INSTANTIATE_FINDWH(FW::HasWareButNoCollect);
2386
INSTANTIATE_FINDWH(FW::HasFigureButNoCollect);
2387
INSTANTIATE_FINDWH(FW::AcceptsFigureButNoSend);
2388
INSTANTIATE_FINDWH(FW::NoCondition);
2389

2390
#undef INSTANTIATE_FINDWH
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc