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

Return-To-The-Roots / s25client / 22239234288

20 Feb 2026 08:04PM UTC coverage: 50.316% (-0.5%) from 50.79%
22239234288

Pull #1720

github

web-flow
Merge 2f74b463f into ed1e143dc
Pull Request #1720: Add leather addon

282 of 1072 new or added lines in 65 files covered. (26.31%)

47 existing lines in 28 files now uncovered.

23027 of 45765 relevant lines covered (50.32%)

42926.09 hits per line

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

72.32
/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✔
NEW
282
            dist.percent_buildings[BuildingType::Slaughterhouse] = 8;
×
283

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

298
    useCustomBuildOrder_ = sgd.PopBool();
7✔
299

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

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

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

UNCOV
319
        std::copy(build_order_raw.begin(), build_order_raw.end(), build_order.begin());
×
320

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

335
    helpers::popContainer(sgd, militarySettings_);
7✔
336
    helpers::popContainer(sgd, toolsSettings_);
7✔
337

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

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

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

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

367
    // Visuelle Einstellungen festlegen
368

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

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

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

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

393
    emergency = sgd.PopBool();
7✔
394
}
395

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

403
    unsigned best_length = std::numeric_limits<unsigned>::max();
4,318✔
404

405
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
14,817✔
406
    {
407
        // Lagerhaus geeignet?
408
        RTTR_Assert(wh);
10,504✔
409
        if(!isWarehouseGood(*wh))
10,504✔
410
            continue;
8,045✔
411

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

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

438
    if(length)
4,313✔
439
        *length = best_length;
378✔
440

441
    return best;
4,313✔
442
}
443

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

653
        ++it;
10✔
654
    }
655

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

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

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

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

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

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

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

719
    // 1. Anteile der einzelnen Waren ausrechnen
720

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

725
    unsigned goal_count = 0;
3,240✔
726

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

738
    // TODO: evtl noch die counts miteinander kürzen (ggt berechnen)
739

740
    // Array für die Gebäudtypen erstellen
741

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

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

754
    distribution[ware].selected_goal = 0;
3,240✔
755
}
3,240✔
756

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

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

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

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

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

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

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

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

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

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

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

845
bool GamePlayer::FindWarehouseForJob(const Job job, noRoadNode& goal) const
166✔
846
{
847
    // Optimization: return early if building is isolated
848
    if(goal.GetType() == NodalObjectType::Building || goal.GetType() == NodalObjectType::Buildingsite)
166✔
849
    {
850
        if(!static_cast<noBaseBuilding&>(goal).IsConnected())
166✔
851
            return false;
134✔
852
    }
853

854
    nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasFigure(job, true), false, false);
32✔
855

856
    if(wh)
32✔
857
    {
858
        // Es wurde ein Lagerhaus gefunden, wo es den geforderten Beruf gibt, also den Typen zur Arbeit rufen
859
        wh->OrderJob(job, goal, true);
32✔
860
        return true;
32✔
861
    }
862

863
    return false;
×
864
}
865

866
void GamePlayer::FindWarehouseForAllJobs()
179✔
867
{
868
    for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
198✔
869
    {
870
        if(FindWarehouseForJob(it->job, *it->workplace))
19✔
871
            it = jobs_wanted.erase(it);
19✔
872
        else
873
            ++it;
×
874
    }
875
}
179✔
876

877
void GamePlayer::FindWarehouseForAllJobs(const Job job)
340✔
878
{
879
    for(auto it = jobs_wanted.begin(); it != jobs_wanted.end();)
340✔
880
    {
881
        if(it->job == job)
×
882
        {
883
            if(FindWarehouseForJob(it->job, *it->workplace))
×
884
                it = jobs_wanted.erase(it);
×
885
            else
886
                ++it;
×
887
        } else
888
            ++it;
×
889
    }
890
}
340✔
891

892
Ware* GamePlayer::OrderWare(const GoodType ware, noBaseBuilding& goal)
113✔
893
{
894
    /// Gibt es ein Lagerhaus mit dieser Ware?
895
    nobBaseWarehouse* wh = FindWarehouse(goal, FW::HasMinWares(ware, 1), false, true);
113✔
896

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

937
nofCarrier* GamePlayer::OrderDonkey(RoadSegment& road) const
3✔
938
{
939
    std::array<unsigned, 2> length;
940
    std::array<nobBaseWarehouse*, 2> best;
941

942
    // 1. Flagge des Weges
943
    best[0] = FindWarehouse(*road.GetF1(), FW::HasFigure(Job::PackDonkey, false), false, false, length.data(), &road);
3✔
944
    // 2. Flagge des Weges
945
    best[1] = FindWarehouse(*road.GetF2(), FW::HasFigure(Job::PackDonkey, false), false, false, &length[1], &road);
3✔
946

947
    // überhaupt nen Weg gefunden?
948
    // Welche Flagge benutzen?
949
    if(best[0] && (!best[1] || length[0] < length[1]))
3✔
950
        return best[0]->OrderDonkey(road, *road.GetF1());
2✔
951
    else if(best[1])
1✔
952
        return best[1]->OrderDonkey(road, *road.GetF2());
×
953
    else
954
        return nullptr;
1✔
955
}
956

957
RoadSegment* GamePlayer::FindRoadForDonkey(noRoadNode& start, noRoadNode** goal)
10✔
958
{
959
    // Bisher höchste Trägerproduktivität und die entsprechende Straße dazu
960
    unsigned best_productivity = 0;
10✔
961
    RoadSegment* best_road = nullptr;
10✔
962
    // Beste Flagge dieser Straße
963
    *goal = nullptr;
10✔
964

965
    for(RoadSegment* roadSeg : roads)
12✔
966
    {
967
        // Braucht die Straße einen Esel?
968
        if(roadSeg->NeedDonkey())
2✔
969
        {
970
            // Beste Flagge von diesem Weg, und beste Wegstrecke
971
            noRoadNode* current_best_goal = nullptr;
×
972
            // Weg zu beiden Flaggen berechnen
973
            unsigned length1, length2;
974
            bool isF1Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF1(), &length1, nullptr, roadSeg)
×
975
                                 != RoadPathDirection::None;
×
976
            bool isF2Reachable = world.FindHumanPathOnRoads(start, *roadSeg->GetF2(), &length2, nullptr, roadSeg)
×
977
                                 != RoadPathDirection::None;
×
978

979
            // Wenn man zu einer Flagge nich kommt, die jeweils andere nehmen
980
            if(!isF1Reachable)
×
981
                current_best_goal = (isF2Reachable) ? roadSeg->GetF2() : nullptr;
×
982
            else if(!isF2Reachable)
×
983
                current_best_goal = roadSeg->GetF1();
×
984
            else
985
            {
986
                // ansonsten die kürzeste von beiden
987
                current_best_goal = (length1 < length2) ? roadSeg->GetF1() : roadSeg->GetF2();
×
988
            }
989

990
            // Kein Weg führt hin, nächste Straße bitte
991
            if(!current_best_goal)
×
992
                continue;
×
993

994
            // Jeweiligen Weg bestimmen
995
            unsigned current_best_way = (roadSeg->GetF1() == current_best_goal) ? length1 : length2;
×
996

997
            // Produktivität ausrechnen, *10 die Produktivität + die Wegstrecke, damit die
998
            // auch noch mit einberechnet wird
999
            unsigned current_productivity = 10 * roadSeg->getCarrier(0)->GetProductivity() + current_best_way;
×
1000

1001
            // Besser als der bisher beste?
1002
            if(current_productivity > best_productivity)
×
1003
            {
1004
                // Dann wird der vom Thron gestoßen
1005
                best_productivity = current_productivity;
×
1006
                best_road = roadSeg;
×
1007
                *goal = current_best_goal;
×
1008
            }
1009
        }
1010
    }
1011

1012
    return best_road;
10✔
1013
}
1014

1015
struct ClientForWare
1016
{
1017
    noBaseBuilding* bld;
1018
    unsigned estimate; // points minus half the optimal distance
1019
    unsigned points;
1020

1021
    ClientForWare(noBaseBuilding* bld, unsigned estimate, unsigned points)
×
1022
        : bld(bld), estimate(estimate), points(points)
×
1023
    {}
×
1024

1025
    bool operator<(const ClientForWare& b) const
×
1026
    {
1027
        // use estimate, points and object id (as tie breaker) for sorting
1028
        if(estimate != b.estimate)
×
1029
            return estimate > b.estimate;
×
1030
        else if(points != b.points)
×
1031
            return points > b.points;
×
1032
        else
1033
            return bld->GetObjId() > b.bld->GetObjId();
×
1034
    }
1035
};
1036

1037
noBaseBuilding* GamePlayer::FindClientForWare(const Ware& ware)
12✔
1038
{
1039
    // If the ware is a coin or an armor, the goal is determined by another logic
1040
    if(ware.type == GoodType::Coins)
12✔
1041
        return FindClientForCoin(ware);
×
1042
    else if(ware.type == GoodType::Armor)
12✔
NEW
1043
        return FindClientForArmor(ware);
×
1044

1045
    // Warentyp herausfinden
1046
    GoodType gt = ware.type;
12✔
1047
    // All food is considered fish in the distribution table
1048
    Distribution& wareDistribution =
1049
      (gt == GoodType::Bread || gt == GoodType::Meat) ? distribution[GoodType::Fish] : distribution[gt];
12✔
1050

1051
    std::vector<ClientForWare> possibleClients;
12✔
1052

1053
    const noRoadNode* start = ware.GetLocation();
12✔
1054

1055
    // Bretter und Steine können evtl. auch Häfen für Expeditionen gebrauchen
1056
    if(gt == GoodType::Stones || gt == GoodType::Boards)
12✔
1057
    {
1058
        for(nobHarborBuilding* harbor : buildings.GetHarbors())
8✔
1059
        {
1060
            unsigned points = harbor->CalcDistributionPoints(gt);
×
1061
            if(!points)
×
1062
                continue;
×
1063

1064
            points += 10 * 30; // Verteilung existiert nicht, Expeditionen haben allerdings hohe Priorität
×
1065
            unsigned distance = world.CalcDistance(start->GetPos(), harbor->GetPos()) / 2;
×
1066
            possibleClients.push_back(ClientForWare(harbor, points > distance ? points - distance : 0, points));
×
1067
        }
1068
    }
1069

1070
    for(const auto bldType : wareDistribution.client_buildings)
49✔
1071
    {
1072
        // BuildingType::Headquarters sind Baustellen!!, da HQs ja sowieso nicht gebaut werden können
1073
        if(bldType == BuildingType::Headquarters)
37✔
1074
        {
1075
            // Bei Baustellen die Extraliste abfragen
1076
            for(noBuildingSite* bldSite : buildings.GetBuildingSites())
8✔
1077
            {
1078
                // Optimization: Ignore if unconnected
1079
                if(!bldSite->IsConnected())
×
1080
                    continue;
×
1081

1082
                unsigned points = bldSite->CalcDistributionPoints(gt);
×
1083
                if(!points)
×
1084
                    continue;
×
1085

1086
                points += wareDistribution.percent_buildings[BuildingType::Headquarters] * 30;
×
1087
                unsigned distance = world.CalcDistance(start->GetPos(), bldSite->GetPos()) / 2;
×
1088
                possibleClients.push_back(ClientForWare(bldSite, points > distance ? points - distance : 0, points));
×
1089
            }
1090
        } else
1091
        {
1092
            // Für übrige Gebäude
1093
            for(nobUsual* bld : buildings.GetBuildings(bldType))
29✔
1094
            {
1095
                // Optimization: Ignore if unconnected
1096
                if(!bld->IsConnected())
×
1097
                    continue;
×
1098

1099
                unsigned points = bld->CalcDistributionPoints(gt);
×
1100
                if(!points)
×
1101
                    continue; // Ware not needed
×
1102

1103
                if(!wareDistribution.goals.empty())
×
1104
                {
1105
                    if(bld->GetBuildingType()
×
1106
                       == static_cast<BuildingType>(wareDistribution.goals[wareDistribution.selected_goal]))
×
1107
                        points += 300;
×
1108
                    else if(points >= 300) // avoid overflows (async!)
×
1109
                        points -= 300;
×
1110
                    else
1111
                        points = 0;
×
1112
                }
1113

1114
                unsigned distance = world.CalcDistance(start->GetPos(), bld->GetPos()) / 2;
×
1115
                possibleClients.push_back(ClientForWare(bld, points > distance ? points - distance : 0, points));
×
1116
            }
1117
        }
1118
    }
1119

1120
    // sort our clients, highest score first
1121
    std::sort(possibleClients.begin(), possibleClients.end());
12✔
1122

1123
    noBaseBuilding* lastBld = nullptr;
12✔
1124
    noBaseBuilding* bestBld = nullptr;
12✔
1125
    unsigned best_points = 0;
12✔
1126
    for(auto& possibleClient : possibleClients)
12✔
1127
    {
1128
        unsigned path_length;
1129

1130
        // If our estimate is worse (or equal) best_points, the real value cannot be better.
1131
        // As our list is sorted, further entries cannot be better either, so stop searching.
1132
        if(possibleClient.estimate <= best_points)
×
1133
            break;
×
1134

1135
        // get rid of double building entries. TODO: why are there double entries!?
1136
        if(possibleClient.bld == lastBld)
×
1137
            continue;
×
1138

1139
        lastBld = possibleClient.bld;
×
1140

1141
        // Just to be sure no underflow happens...
1142
        if(possibleClient.points < best_points + 1)
×
1143
            continue;
×
1144

1145
        // Find path ONLY if it may be better. Pathfinding is limited to the worst path score that would lead to a
1146
        // better score. This eliminates the worst case scenario where all nodes in a split road network would be hit by
1147
        // the pathfinding only to conclude that there is no possible path.
1148
        if(world.FindPathForWareOnRoads(*start, *possibleClient.bld, &path_length, nullptr,
×
1149
                                        (possibleClient.points - best_points) * 2 - 1)
×
1150
           != RoadPathDirection::None)
×
1151
        {
1152
            unsigned score = possibleClient.points - (path_length / 2);
×
1153

1154
            // As we have limited our pathfinding to take a maximum of (points - best_points) * 2 - 1 steps,
1155
            // path_length / 2 can at most be points - best_points - 1, so the score will be greater than best_points.
1156
            // :)
1157
            RTTR_Assert(score > best_points);
×
1158

1159
            best_points = score;
×
1160
            bestBld = possibleClient.bld;
×
1161
        }
1162
    }
1163

1164
    if(bestBld && !wareDistribution.goals.empty())
12✔
1165
        wareDistribution.selected_goal =
×
1166
          (wareDistribution.selected_goal + 907) % unsigned(wareDistribution.goals.size());
×
1167

1168
    // Wenn kein Abnehmer gefunden wurde, muss es halt in ein Lagerhaus
1169
    if(!bestBld)
12✔
1170
        bestBld = FindWarehouseForWare(ware);
12✔
1171

1172
    return bestBld;
12✔
1173
}
1174

1175
nobBaseWarehouse* GamePlayer::FindWarehouseForWare(const Ware& ware) const
16✔
1176
{
1177
    // Check whs that collect this ware
1178
    nobBaseWarehouse* wh = FindWarehouse(*ware.GetLocation(), FW::CollectsWare(ware.type), true, true);
16✔
1179
    // If there is none, check those that accept it
1180
    if(!wh)
16✔
1181
    {
1182
        // First find the ones, that do not send it right away (IMPORTANT: This avoids sending a ware to the wh that is
1183
        // sending the ware out)
1184
        wh = FindWarehouse(*ware.GetLocation(), FW::AcceptsWareButNoSend(ware.type), true, true);
16✔
1185
        // The others only if this fails
1186
        if(!wh)
16✔
1187
            wh = FindWarehouse(*ware.GetLocation(), FW::AcceptsWare(ware.type), true, true);
5✔
1188
    }
1189
    return wh;
16✔
1190
}
1191

1192
nobBaseMilitary* GamePlayer::FindClientForCoin(const Ware& ware) const
×
1193
{
1194
    nobBaseMilitary* bb = nullptr;
×
1195
    unsigned best_points = 0, points;
×
1196

1197
    // Militärgebäude durchgehen
1198
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
×
1199
    {
1200
        // Optimization: Ignore if unconnected
1201
        if(!milBld->IsConnected())
×
1202
            continue;
×
1203

1204
        points = milBld->CalcCoinsPoints();
×
NEW
1205
        if(points > best_points)
×
1206
        {
1207
            // Find the nearest building
1208
            unsigned way_points;
NEW
1209
            if(world.FindPathForWareOnRoads(*ware.GetLocation(), *milBld, &way_points, nullptr,
×
NEW
1210
                                            points - best_points - 1)
×
NEW
1211
               != RoadPathDirection::None)
×
1212
            {
NEW
1213
                best_points = points - way_points;
×
NEW
1214
                bb = milBld;
×
1215
            }
1216
        }
1217
    }
1218

1219
    // Wenn kein Abnehmer gefunden wurde, muss es halt in ein Lagerhaus
1220
    if(!bb)
×
1221
        bb = FindWarehouseForWare(ware);
×
1222

1223
    return bb;
×
1224
}
1225

NEW
1226
nobBaseMilitary* GamePlayer::FindClientForArmor(const Ware& ware) const
×
1227
{
NEW
1228
    nobBaseMilitary* bb = nullptr;
×
NEW
1229
    unsigned best_points = 0, points;
×
1230

NEW
1231
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
×
1232
    {
1233
        // Optimization: Ignore if unconnected
NEW
1234
        if(!milBld->IsConnected())
×
NEW
1235
            continue;
×
1236

NEW
1237
        points = milBld->CalcArmorPoints();
×
NEW
1238
        if(points > best_points)
×
1239
        {
1240
            // Find the nearest building
1241
            unsigned way_points;
NEW
1242
            if(world.FindPathForWareOnRoads(*ware.GetLocation(), *milBld, &way_points, nullptr,
×
NEW
1243
                                            points - best_points - 1)
×
NEW
1244
               != RoadPathDirection::None)
×
1245
            {
NEW
1246
                best_points = points - way_points;
×
NEW
1247
                bb = milBld;
×
1248
            }
1249
        }
1250
    }
1251

NEW
1252
    if(!bb)
×
NEW
1253
        bb = FindWarehouseForWare(ware);
×
1254

NEW
1255
    return bb;
×
1256
}
1257

UNCOV
1258
unsigned GamePlayer::GetBuidingSitePriority(const noBuildingSite* building_site)
×
1259
{
1260
    if(useCustomBuildOrder_)
×
1261
    {
1262
        // Spezielle Reihenfolge
1263

1264
        // Typ in der Reihenfolge suchen und Position als Priorität zurückgeben
1265
        for(unsigned i = 0; i < build_order.size(); ++i)
×
1266
        {
1267
            if(building_site->GetBuildingType() == build_order[i])
×
1268
                return i;
×
1269
        }
1270
    } else
1271
    {
1272
        // Reihenfolge der Bauaufträge, also was zuerst in Auftrag gegeben wurde, wird zuerst gebaut
1273
        unsigned i = 0;
×
1274
        for(noBuildingSite* bldSite : buildings.GetBuildingSites())
×
1275
        {
1276
            if(building_site == bldSite)
×
1277
                return i;
×
1278
            i++;
×
1279
        }
1280
    }
1281

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

1288
void GamePlayer::ConvertTransportData(const TransportOrders& transport_data)
2✔
1289
{
1290
    for(const auto ware : helpers::EnumRange<GoodType>{})
168✔
1291
        transportPrio[ware] = GetTransportPrioFromOrdering(transport_data, ware);
80✔
1292
}
2✔
1293

1294
bool GamePlayer::IsAlly(const unsigned char playerId) const
12,228✔
1295
{
1296
    // Der Spieler ist ja auch zu sich selber verbündet
1297
    if(GetPlayerId() == playerId)
12,228✔
1298
        return true;
3,917✔
1299
    else
1300
        return GetPactState(PactType::TreatyOfAlliance, playerId) == PactState::Accepted;
8,311✔
1301
}
1302

1303
bool GamePlayer::IsAttackable(const unsigned char playerId) const
897✔
1304
{
1305
    // Verbündete dürfen nicht angegriffen werden
1306
    if(IsAlly(playerId))
897✔
1307
        return false;
44✔
1308
    else
1309
        // Ansonsten darf bei bestehendem Nichtangriffspakt ebenfalls nicht angegriffen werden
1310
        return GetPactState(PactType::NonAgressionPact, playerId) != PactState::Accepted;
853✔
1311
}
1312

1313
void GamePlayer::OrderTroops(nobMilitary& goal, std::array<unsigned, NUM_SOLDIER_RANKS> counts,
33✔
1314
                             unsigned total_max) const
1315
{
1316
    // Solange Lagerhäuser nach Soldaten absuchen, bis entweder keins mehr übrig ist oder alle Soldaten bestellt sind
1317
    nobBaseWarehouse* wh;
1318
    unsigned sum = 0;
33✔
1319
    do
3✔
1320
    {
1321
        std::array<bool, NUM_SOLDIER_RANKS> desiredRanks;
1322
        for(unsigned i = 0; i < NUM_SOLDIER_RANKS; i++)
216✔
1323
            desiredRanks[i] = counts[i] > 0;
180✔
1324

1325
        wh = FindWarehouse(goal, FW::HasAnyMatchingSoldier(desiredRanks), false, false);
36✔
1326
        if(wh)
36✔
1327
        {
1328
            wh->OrderTroops(goal, counts, total_max);
19✔
1329
            sum = std::accumulate(counts.begin(), counts.end(), 0u);
19✔
1330
        }
1331
    } while(total_max && sum && wh);
36✔
1332
}
33✔
1333

1334
void GamePlayer::RegulateAllTroops()
89✔
1335
{
1336
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
92✔
1337
        milBld->RegulateTroops();
3✔
1338
}
89✔
1339

1340
/// Prüft von allen Militärgebäuden die Fahnen neu
1341
void GamePlayer::RecalcMilitaryFlags()
48✔
1342
{
1343
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
72✔
1344
        milBld->LookForEnemyBuildings(nullptr);
24✔
1345
}
48✔
1346

1347
/// Sucht für Soldaten ein neues Militärgebäude, als Argument wird Referenz auf die
1348
/// entsprechende Soldatenanzahl im Lagerhaus verlangt
1349
void GamePlayer::NewSoldiersAvailable(const unsigned& soldier_count)
152✔
1350
{
1351
    RTTR_Assert(soldier_count > 0);
152✔
1352
    // solange laufen lassen, bis soldier_count = 0, d.h. der Soldat irgendwohin geschickt wurde
1353
    // Zuerst nach unbesetzten Militärgebäude schauen
1354
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1355
    {
1356
        if(milBld->IsNewBuilt())
17✔
1357
        {
1358
            milBld->RegulateTroops();
×
1359
            // Used that soldier? Go out
1360
            if(!soldier_count)
×
1361
                return;
×
1362
        }
1363
    }
1364

1365
    // Als nächstes Gebäude in Grenznähe
1366
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1367
    {
1368
        if(milBld->GetFrontierDistance() == FrontierDistance::Near)
17✔
1369
        {
1370
            milBld->RegulateTroops();
17✔
1371
            // Used that soldier? Go out
1372
            if(!soldier_count)
17✔
1373
                return;
×
1374
        }
1375
    }
1376

1377
    // Und den Rest ggf.
1378
    for(nobMilitary* milBld : buildings.GetMilitaryBuildings())
169✔
1379
    {
1380
        // already checked? -> skip
1381
        if(milBld->GetFrontierDistance() == FrontierDistance::Near || milBld->IsNewBuilt())
17✔
1382
            continue;
17✔
1383
        milBld->RegulateTroops();
×
1384
        if(!soldier_count) // used the soldier?
×
1385
            return;
×
1386
    }
1387
}
1388

1389
void GamePlayer::CallFlagWorker(const MapPoint pt, const Job job)
32✔
1390
{
1391
    auto* flag = world.GetSpecObj<noFlag>(pt);
32✔
1392
    if(!flag)
32✔
1393
        return;
2✔
1394
    /// Find wh with given job type (e.g. geologist, scout, ...)
1395
    nobBaseWarehouse* wh = FindWarehouse(*flag, FW::HasFigure(job, true), false, false);
30✔
1396

1397
    if(wh)
30✔
1398
        wh->OrderJob(job, *flag, true);
26✔
1399
}
1400

1401
bool GamePlayer::IsFlagWorker(const nofFlagWorker* flagworker)
×
1402
{
1403
    return helpers::contains(flagworkers, flagworker);
×
1404
}
1405

1406
void GamePlayer::FlagDestroyed(noFlag* flag)
775✔
1407
{
1408
    // Alle durchgehen und ggf. sagen, dass sie keine Flagge mehr haben, wenn das ihre Flagge war, die zerstört wurde
1409
    for(auto it = flagworkers.begin(); it != flagworkers.end();)
775✔
1410
    {
1411
        if((*it)->GetFlag() == flag)
×
1412
        {
1413
            (*it)->LostWork();
×
1414
            it = flagworkers.erase(it);
×
1415
        } else
1416
            ++it;
×
1417
    }
1418
}
775✔
1419

1420
void GamePlayer::RefreshDefenderList()
65✔
1421
{
1422
    shouldSendDefenderList.clear();
65✔
1423
    // Add as many true values as set in the settings, the rest will be false
1424
    for(unsigned i = 0; i < MILITARY_SETTINGS_SCALE[2]; ++i)
390✔
1425
        shouldSendDefenderList.push_back(i < militarySettings_[2]);
325✔
1426
    // und ordentlich schütteln
1427
    RANDOM_SHUFFLE2(shouldSendDefenderList, 0);
65✔
1428
}
65✔
1429

1430
void GamePlayer::ChangeMilitarySettings(const MilitarySettings& military_settings)
65✔
1431
{
1432
    for(unsigned i = 0; i < military_settings.size(); ++i)
585✔
1433
    {
1434
        // Sicherstellen, dass im validen Bereich
1435
        RTTR_Assert(military_settings[i] <= MILITARY_SETTINGS_SCALE[i]);
520✔
1436
        this->militarySettings_[i] = military_settings[i];
520✔
1437
    }
1438
    /// Truppen müssen neu kalkuliert werden
1439
    RegulateAllTroops();
65✔
1440
    /// Die Verteidigungsliste muss erneuert werden
1441
    RefreshDefenderList();
65✔
1442
}
65✔
1443

1444
/// Setzt neue Werkzeugeinstellungen
1445
void GamePlayer::ChangeToolsSettings(const ToolSettings& tools_settings,
6✔
1446
                                     const helpers::EnumArray<int8_t, Tool>& orderChanges)
1447
{
1448
    const bool settingsChanged = toolsSettings_ != tools_settings;
6✔
1449
    toolsSettings_ = tools_settings;
6✔
1450
    if(settingsChanged)
6✔
1451
        world.GetNotifications().publish(ToolNote(ToolNote::SettingsChanged, GetPlayerId()));
4✔
1452

1453
    for(const auto tool : helpers::enumRange<Tool>())
168✔
1454
    {
1455
        tools_ordered[tool] = helpers::clamp(tools_ordered[tool] + orderChanges[tool], 0, 100);
72✔
1456
        tools_ordered_delta[tool] -= orderChanges[tool];
72✔
1457

1458
        if(orderChanges[tool] != 0)
72✔
1459
        {
1460
            LOG.write(">> Committing an order of %1% for tool #%2%(%3%)\n", LogTarget::File) % (int)orderChanges[tool]
8✔
1461
              % static_cast<unsigned>(tool) % _(WARE_NAMES[TOOL_TO_GOOD[tool]]);
8✔
1462
            world.GetNotifications().publish(ToolNote(ToolNote::OrderPlaced, GetPlayerId()));
4✔
1463
        }
1464
    }
1465
}
6✔
1466

1467
/// Setzt neue Verteilungseinstellungen
1468
void GamePlayer::ChangeDistribution(const Distributions& distribution_settings)
6✔
1469
{
1470
    unsigned idx = 0;
6✔
1471
    for(const DistributionMapping& mapping : distributionMap)
180✔
1472
    {
1473
        distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)] = distribution_settings[idx++];
174✔
1474
    }
1475

1476
    RecalcDistribution();
6✔
1477
}
6✔
1478

1479
/// Setzt neue Baureihenfolge-Einstellungen
1480
void GamePlayer::ChangeBuildOrder(bool useCustomBuildOrder, const BuildOrders& order_data)
2✔
1481
{
1482
    this->useCustomBuildOrder_ = useCustomBuildOrder;
2✔
1483
    this->build_order = order_data;
2✔
1484
}
2✔
1485

1486
bool GamePlayer::ShouldSendDefender()
35✔
1487
{
1488
    // Wenn wir schon am Ende sind, muss die Verteidgungsliste erneuert werden
1489
    if(shouldSendDefenderList.empty())
35✔
1490
        RefreshDefenderList();
×
1491

1492
    bool result = shouldSendDefenderList.back();
35✔
1493
    shouldSendDefenderList.pop_back();
35✔
1494
    return result;
35✔
1495
}
1496

1497
void GamePlayer::TestDefeat()
82✔
1498
{
1499
    // Nicht schon besiegt?
1500
    // Keine Militärgebäude, keine Lagerhäuser (HQ,Häfen) -> kein Land --> verloren
1501
    if(!isDefeated && buildings.GetMilitaryBuildings().empty() && buildings.GetStorehouses().empty())
82✔
1502
        Surrender();
29✔
1503
}
82✔
1504

1505
nobHQ* GamePlayer::GetHQ() const
14✔
1506
{
1507
    const MapPoint& hqPos = GetHQPos();
14✔
1508
    return const_cast<nobHQ*>(hqPos.isValid() ? GetGameWorld().GetSpecObj<nobHQ>(hqPos) : nullptr);
14✔
1509
}
1510

1511
void GamePlayer::Surrender()
32✔
1512
{
1513
    if(isDefeated)
32✔
1514
        return;
1✔
1515

1516
    isDefeated = true;
31✔
1517

1518
    // GUI Bescheid sagen
1519
    if(world.GetGameInterface())
31✔
1520
        world.GetGameInterface()->GI_PlayerDefeated(GetPlayerId());
×
1521
}
1522

1523
void GamePlayer::SetStatisticValue(StatisticType type, unsigned value)
×
1524
{
1525
    statisticCurrentData[type] = value;
×
1526
}
×
1527

1528
void GamePlayer::ChangeStatisticValue(StatisticType type, int change)
2,065✔
1529
{
1530
    RTTR_Assert(change >= 0 || statisticCurrentData[type] >= static_cast<unsigned>(-change));
2,065✔
1531
    statisticCurrentData[type] += change;
2,065✔
1532
}
2,065✔
1533

1534
void GamePlayer::IncreaseMerchandiseStatistic(GoodType type)
4✔
1535
{
1536
    // Einsortieren...
1537
    switch(type)
4✔
1538
    {
1539
        case GoodType::Wood: statisticCurrentMerchandiseData[0]++; break;
×
1540
        case GoodType::Boards: statisticCurrentMerchandiseData[1]++; break;
×
1541
        case GoodType::Stones: statisticCurrentMerchandiseData[2]++; break;
×
1542
        case GoodType::Fish:
×
1543
        case GoodType::Bread:
1544
        case GoodType::Meat: statisticCurrentMerchandiseData[3]++; break;
×
1545
        case GoodType::Water: statisticCurrentMerchandiseData[4]++; break;
×
1546
        case GoodType::Beer: statisticCurrentMerchandiseData[5]++; break;
×
1547
        case GoodType::Coal: statisticCurrentMerchandiseData[6]++; break;
×
1548
        case GoodType::IronOre: statisticCurrentMerchandiseData[7]++; break;
×
1549
        case GoodType::Gold: statisticCurrentMerchandiseData[8]++; break;
×
1550
        case GoodType::Iron: statisticCurrentMerchandiseData[9]++; break;
×
1551
        case GoodType::Coins: statisticCurrentMerchandiseData[10]++; break;
×
1552
        case GoodType::Tongs:
3✔
1553
        case GoodType::Axe:
1554
        case GoodType::Saw:
1555
        case GoodType::PickAxe:
1556
        case GoodType::Hammer:
1557
        case GoodType::Shovel:
1558
        case GoodType::Crucible:
1559
        case GoodType::RodAndLine:
1560
        case GoodType::Scythe:
1561
        case GoodType::Cleaver:
1562
        case GoodType::Rollingpin:
1563
        case GoodType::Bow: statisticCurrentMerchandiseData[11]++; break;
3✔
1564
        case GoodType::ShieldVikings:
×
1565
        case GoodType::ShieldAfricans:
1566
        case GoodType::ShieldRomans:
1567
        case GoodType::ShieldJapanese:
1568
        case GoodType::Sword: statisticCurrentMerchandiseData[12]++; break;
×
1569
        case GoodType::Boat: statisticCurrentMerchandiseData[13]++; break;
×
1570
        default: break;
1✔
1571
    }
1572
}
4✔
1573

1574
/// Calculates current statistics
1575
void GamePlayer::CalcStatistics()
6✔
1576
{
1577
    // Waren aus der Inventur zählen
1578
    statisticCurrentData[StatisticType::Merchandise] = 0;
6✔
1579
    for(const auto i : helpers::enumRange<GoodType>())
504✔
1580
        statisticCurrentData[StatisticType::Merchandise] += global_inventory[i];
240✔
1581

1582
    // Bevölkerung aus der Inventur zählen
1583
    statisticCurrentData[StatisticType::Inhabitants] = 0;
6✔
1584
    for(const auto i : helpers::enumRange<Job>())
480✔
1585
        statisticCurrentData[StatisticType::Inhabitants] += global_inventory[i];
228✔
1586

1587
    // Militär aus der Inventur zählen
1588
    statisticCurrentData[StatisticType::Military] =
12✔
1589
      global_inventory.people[Job::Private] + global_inventory.people[Job::PrivateFirstClass] * 2
6✔
1590
      + global_inventory.people[Job::Sergeant] * 3 + global_inventory.people[Job::Officer] * 4
6✔
1591
      + global_inventory.people[Job::General] * 5;
6✔
1592

1593
    // Produktivität berechnen
1594
    statisticCurrentData[StatisticType::Productivity] = buildings.CalcAverageProductivity();
6✔
1595

1596
    // Total points for tournament games
1597
    statisticCurrentData[StatisticType::Tournament] =
12✔
1598
      statisticCurrentData[StatisticType::Military] + 3 * statisticCurrentData[StatisticType::Vanquished];
6✔
1599
}
6✔
1600

1601
void GamePlayer::StatisticStep()
6✔
1602
{
1603
    CalcStatistics();
6✔
1604

1605
    // 15-min-Statistik ein Feld weiterschieben
1606
    for(const auto i : helpers::enumRange<StatisticType>())
132✔
1607
    {
1608
        statistic[StatisticTime::T15Minutes].data[i][incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex)] =
54✔
1609
          statisticCurrentData[i];
54✔
1610
    }
1611
    for(unsigned i = 0; i < NUM_STAT_MERCHANDISE_TYPES; ++i)
90✔
1612
    {
1613
        statistic[StatisticTime::T15Minutes]
84✔
1614
          .merchandiseData[i][incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex)] =
168✔
1615
          statisticCurrentMerchandiseData[i];
84✔
1616
    }
1617
    statistic[StatisticTime::T15Minutes].currentIndex =
6✔
1618
      incrStatIndex(statistic[StatisticTime::T15Minutes].currentIndex);
6✔
1619

1620
    statistic[StatisticTime::T15Minutes].counter++;
6✔
1621

1622
    // Prüfen ob 4mal 15-min-Statistik weitergeschoben wurde, wenn ja: 1-h-Statistik weiterschieben
1623
    // und aktuellen Wert der 15min-Statistik benutzen
1624
    // gleiches für die 4h und 16h Statistik
1625
    for(const auto t : helpers::enumRange<StatisticTime>())
60✔
1626
    {
1627
        if(t == StatisticTime(helpers::MaxEnumValue_v<StatisticTime>))
24✔
1628
            break;
6✔
1629
        const auto nextT = StatisticTime(rttr::enum_cast(t) + 1);
18✔
1630
        if(statistic[t].counter == 4)
18✔
1631
        {
1632
            statistic[t].counter = 0;
×
1633
            for(const auto i : helpers::enumRange<StatisticType>())
×
1634
            {
1635
                statistic[nextT].data[i][incrStatIndex(statistic[nextT].currentIndex)] = statisticCurrentData[i];
×
1636
            }
1637

1638
            // Summe für den Zeitraum berechnen (immer 4 Zeitschritte der jeweils kleineren Statistik)
1639
            for(unsigned i = 0; i < NUM_STAT_MERCHANDISE_TYPES; ++i)
×
1640
            {
1641
                statistic[nextT].merchandiseData[i][incrStatIndex(statistic[nextT].currentIndex)] =
×
1642
                  statisticCurrentMerchandiseData[i]
×
1643
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 1)]
×
1644
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 2)]
×
1645
                  + statistic[t].merchandiseData[i][decrStatIndex(statistic[t].currentIndex, 3)];
×
1646
            }
1647

1648
            statistic[nextT].currentIndex = incrStatIndex(statistic[nextT].currentIndex);
×
1649
            statistic[nextT].counter++;
×
1650
        }
1651
    }
1652

1653
    // Warenstatistikzähler nullen
1654
    statisticCurrentMerchandiseData.fill(0);
6✔
1655
}
6✔
1656

1657
GamePlayer::Pact::Pact(SerializedGameData& sgd)
112✔
1658
    : duration(sgd.PopUnsignedInt()), start(sgd.PopUnsignedInt()), accepted(sgd.PopBool()), want_cancel(sgd.PopBool())
112✔
1659
{}
112✔
1660

1661
void GamePlayer::Pact::Serialize(SerializedGameData& sgd) const
224✔
1662
{
1663
    sgd.PushUnsignedInt(duration);
224✔
1664
    sgd.PushUnsignedInt(start);
224✔
1665
    sgd.PushBool(accepted);
224✔
1666
    sgd.PushBool(want_cancel);
224✔
1667
}
224✔
1668

1669
void GamePlayer::PactChanged(const PactType pt)
24✔
1670
{
1671
    // Recheck military flags as the border (to an enemy) might have changed
1672
    RecalcMilitaryFlags();
24✔
1673

1674
    // Ggf. den GUI Bescheid sagen, um Sichtbarkeiten etc. neu zu berechnen
1675
    if(pt == PactType::TreatyOfAlliance)
24✔
1676
    {
1677
        if(world.GetGameInterface())
6✔
1678
            world.GetGameInterface()->GI_TreatyOfAllianceChanged(GetPlayerId());
×
1679
    }
1680
}
24✔
1681

1682
void GamePlayer::SuggestPact(const unsigned char targetPlayerId, const PactType pt, const unsigned duration)
10✔
1683
{
1684
    // Don't try to make pact with self
1685
    if(targetPlayerId == GetPlayerId())
10✔
1686
        return;
1✔
1687

1688
    if(!pacts[targetPlayerId][pt].accepted && duration > 0)
9✔
1689
    {
1690
        pacts[targetPlayerId][pt].duration = duration;
8✔
1691
        pacts[targetPlayerId][pt].start = world.GetEvMgr().GetCurrentGF();
8✔
1692
        GamePlayer targetPlayer = world.GetPlayer(targetPlayerId);
16✔
1693
        if(targetPlayer.isHuman())
8✔
1694
            targetPlayer.SendPostMessage(std::make_unique<DiplomacyPostQuestion>(
6✔
1695
              world.GetEvMgr().GetCurrentGF(), pt, pacts[targetPlayerId][pt].start, *this, duration));
12✔
1696
        else if(world.HasLua())
2✔
1697
            world.GetLua().EventSuggestPact(pt, GetPlayerId(), targetPlayerId, duration);
2✔
1698
    }
1699
}
1700

1701
void GamePlayer::AcceptPact(const unsigned id, const PactType pt, const unsigned char targetPlayer)
21✔
1702
{
1703
    if(!pacts[targetPlayer][pt].accepted && pacts[targetPlayer][pt].duration > 0 && pacts[targetPlayer][pt].start == id)
21✔
1704
    {
1705
        MakePact(pt, targetPlayer, pacts[targetPlayer][pt].duration);
8✔
1706
        world.GetPlayer(targetPlayer).MakePact(pt, GetPlayerId(), pacts[targetPlayer][pt].duration);
8✔
1707
        PactChanged(pt);
8✔
1708
        world.GetPlayer(targetPlayer).PactChanged(pt);
8✔
1709
        if(world.HasLua())
8✔
1710
            world.GetLua().EventPactCreated(pt, GetPlayerId(), targetPlayer, pacts[targetPlayer][pt].duration);
3✔
1711
    }
1712
}
21✔
1713

1714
/// Bündnis (real, d.h. spielentscheidend) abschließen
1715
void GamePlayer::MakePact(const PactType pt, const unsigned char other_player, const unsigned duration)
16✔
1716
{
1717
    pacts[other_player][pt].accepted = true;
16✔
1718
    pacts[other_player][pt].start = world.GetEvMgr().GetCurrentGF();
16✔
1719
    pacts[other_player][pt].duration = duration;
16✔
1720
    pacts[other_player][pt].want_cancel = false;
16✔
1721

1722
    SendPostMessage(
16✔
1723
      std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, world.GetPlayer(other_player), true));
32✔
1724
}
16✔
1725

1726
/// Zeigt an, ob ein Pakt besteht
1727
PactState GamePlayer::GetPactState(const PactType pt, const unsigned char other_player) const
9,314✔
1728
{
1729
    // Prüfen, ob Bündnis in Kraft ist
1730
    if(pacts[other_player][pt].duration)
9,314✔
1731
    {
1732
        if(!pacts[other_player][pt].accepted)
5,053✔
1733
            return PactState::InProgress;
16✔
1734

1735
        if(pacts[other_player][pt].duration == DURATION_INFINITE
5,037✔
1736
           || world.GetEvMgr().GetCurrentGF() < pacts[other_player][pt].start + pacts[other_player][pt].duration)
5,037✔
1737
            return PactState::Accepted;
5,035✔
1738
    }
1739

1740
    return PactState::None;
4,263✔
1741
}
1742

1743
/// all allied players get a letter with the location
1744
void GamePlayer::NotifyAlliesOfLocation(const MapPoint pt)
6✔
1745
{
1746
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
24✔
1747
    {
1748
        if(i != GetPlayerId() && IsAlly(i))
18✔
1749
            world.GetPlayer(i).SendPostMessage(std::make_unique<PostMsg>(
10✔
1750
              world.GetEvMgr().GetCurrentGF(), _("Your ally wishes to notify you of this location"),
5✔
1751
              PostCategory::Diplomacy, pt));
10✔
1752
    }
1753
}
6✔
1754

1755
/// Gibt die verbleibende Dauer zurück, die ein Bündnis noch laufen wird (DURATION_INFINITE = für immer)
1756
unsigned GamePlayer::GetRemainingPactTime(const PactType pt, const unsigned char other_player) const
125✔
1757
{
1758
    if(pacts[other_player][pt].duration)
125✔
1759
    {
1760
        if(pacts[other_player][pt].accepted)
88✔
1761
        {
1762
            if(pacts[other_player][pt].duration == DURATION_INFINITE)
76✔
1763
                return DURATION_INFINITE;
×
1764
            else if(world.GetEvMgr().GetCurrentGF() <= pacts[other_player][pt].start + pacts[other_player][pt].duration)
76✔
1765
                return ((pacts[other_player][pt].start + pacts[other_player][pt].duration)
76✔
1766
                        - world.GetEvMgr().GetCurrentGF());
76✔
1767
        }
1768
    }
1769

1770
    return 0;
49✔
1771
}
1772

1773
/// Gibt Einverständnis, dass dieser Spieler den Pakt auflösen will
1774
/// Falls dieser Spieler einen Bündnisvorschlag gemacht hat, wird dieser dagegen zurückgenommen
1775
void GamePlayer::CancelPact(const PactType pt, const unsigned char otherPlayerIdx)
8✔
1776
{
1777
    // Don't try to cancel pact with self
1778
    if(otherPlayerIdx == GetPlayerId())
8✔
1779
        return;
2✔
1780

1781
    // Besteht bereits ein Bündnis?
1782
    if(pacts[otherPlayerIdx][pt].accepted)
6✔
1783
    {
1784
        // Vermerken, dass der Spieler das Bündnis auflösen will
1785
        pacts[otherPlayerIdx][pt].want_cancel = true;
6✔
1786

1787
        // Will der andere Spieler das Bündnis auch auflösen?
1788
        GamePlayer& otherPlayer = world.GetPlayer(otherPlayerIdx);
6✔
1789
        if(otherPlayer.pacts[GetPlayerId()][pt].want_cancel)
6✔
1790
        {
1791
            // Dann wird das Bündnis aufgelöst
1792
            pacts[otherPlayerIdx][pt].accepted = false;
2✔
1793
            pacts[otherPlayerIdx][pt].duration = 0;
2✔
1794
            pacts[otherPlayerIdx][pt].want_cancel = false;
2✔
1795

1796
            otherPlayer.pacts[GetPlayerId()][pt].accepted = false;
2✔
1797
            otherPlayer.pacts[GetPlayerId()][pt].duration = 0;
2✔
1798
            otherPlayer.pacts[GetPlayerId()][pt].want_cancel = false;
2✔
1799

1800
            // Den Spielern eine Informationsnachricht schicken
1801
            world.GetPlayer(otherPlayerIdx)
2✔
1802
              .SendPostMessage(std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, *this, false));
2✔
1803
            SendPostMessage(
2✔
1804
              std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(), pt, world.GetPlayer(otherPlayerIdx), false));
4✔
1805
            PactChanged(pt);
2✔
1806
            otherPlayer.PactChanged(pt);
2✔
1807
            if(world.HasLua())
2✔
1808
                world.GetLua().EventPactCanceled(pt, GetPlayerId(), otherPlayerIdx);
1✔
1809
        } else
1810
        {
1811
            // Ansonsten den anderen Spieler fragen, ob der das auch so sieht
1812
            if(otherPlayer.isHuman())
4✔
1813
                otherPlayer.SendPostMessage(std::make_unique<DiplomacyPostQuestion>(
3✔
1814
                  world.GetEvMgr().GetCurrentGF(), pt, pacts[otherPlayerIdx][pt].start, *this));
6✔
1815
            else if(!world.HasLua() || world.GetLua().EventCancelPactRequest(pt, GetPlayerId(), otherPlayerIdx))
1✔
1816
            {
1817
                // AI accepts cancels, if there is no lua-interace
1818
                pacts[otherPlayerIdx][pt].accepted = false;
1✔
1819
                pacts[otherPlayerIdx][pt].duration = 0;
1✔
1820
                pacts[otherPlayerIdx][pt].want_cancel = false;
1✔
1821

1822
                otherPlayer.pacts[GetPlayerId()][pt].accepted = false;
1✔
1823
                otherPlayer.pacts[GetPlayerId()][pt].duration = 0;
1✔
1824
                otherPlayer.pacts[GetPlayerId()][pt].want_cancel = false;
1✔
1825

1826
                if(world.HasLua())
1✔
1827
                    world.GetLua().EventPactCanceled(pt, GetPlayerId(), otherPlayerIdx);
1✔
1828
            }
1829
        }
1830
    } else
1831
    {
1832
        // Es besteht kein Bündnis, also unseren Bündnisvorschlag wieder zurücknehmen
1833
        pacts[otherPlayerIdx][pt].duration = 0;
×
1834
    }
1835
}
1836

1837
void GamePlayer::MakeStartPacts()
66✔
1838
{
1839
    // Reset pacts
1840
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
262✔
1841
    {
1842
        for(const auto z : helpers::enumRange<PactType>())
1,568✔
1843
            pacts[i][z] = Pact();
392✔
1844
    }
1845

1846
    // No team -> No pacts
1847
    if(team == Team::None)
66✔
1848
        return;
4✔
1849
    RTTR_Assert(isTeam(team));
62✔
1850

1851
    // Create ally- and non-aggression-pact for all players of same team
1852
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
245✔
1853
    {
1854
        if(team != world.GetPlayer(i).team)
183✔
1855
            continue;
75✔
1856
        for(const auto z : helpers::enumRange<PactType>())
864✔
1857
        {
1858
            pacts[i][z].duration = DURATION_INFINITE;
216✔
1859
            pacts[i][z].start = 0;
216✔
1860
            pacts[i][z].accepted = true;
216✔
1861
            pacts[i][z].want_cancel = false;
216✔
1862
        }
1863
    }
1864
}
1865

1866
bool GamePlayer::IsWareRegistred(const Ware& ware)
165✔
1867
{
1868
    return helpers::contains(ware_list, &ware);
165✔
1869
}
1870

1871
bool GamePlayer::IsWareDependent(const Ware& ware)
14✔
1872
{
1873
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
41✔
1874
    {
1875
        if(wh->IsWareDependent(ware))
27✔
1876
            return true;
×
1877
    }
1878

1879
    return false;
14✔
1880
}
1881

1882
void GamePlayer::IncreaseInventoryWare(const GoodType ware, const unsigned count)
16,367✔
1883
{
1884
    global_inventory.Add(ConvertShields(ware), count);
16,367✔
1885
}
16,367✔
1886

1887
void GamePlayer::DecreaseInventoryWare(const GoodType ware, const unsigned count)
2,533✔
1888
{
1889
    global_inventory.Remove(ConvertShields(ware), count);
2,533✔
1890
}
2,533✔
1891

1892
/// Registriert ein Schiff beim Einwohnermeldeamt
1893
void GamePlayer::RegisterShip(noShip& ship)
21✔
1894
{
1895
    ships.push_back(&ship);
21✔
1896
    // Evtl bekommt das Schiffchen gleich was zu tun?
1897
    GetJobForShip(ship);
21✔
1898
}
21✔
1899

1900
struct ShipForHarbor
1901
{
1902
    noShip* ship;
1903
    uint32_t estimate;
1904

1905
    ShipForHarbor(noShip* ship, uint32_t estimate) : ship(ship), estimate(estimate) {}
18✔
1906

1907
    bool operator<(const ShipForHarbor& b) const
×
1908
    {
1909
        return (estimate < b.estimate) || (estimate == b.estimate && ship->GetObjId() < b.ship->GetObjId());
×
1910
    }
1911
};
1912

1913
/// Schiff für Hafen bestellen
1914
bool GamePlayer::OrderShip(nobHarborBuilding& hb)
32✔
1915
{
1916
    std::vector<ShipForHarbor> sfh;
64✔
1917

1918
    // we need more ships than those that are already on their way? limit search to idle ships
1919
    if(GetShipsToHarbor(hb) < hb.GetNumNeededShips())
32✔
1920
    {
1921
        for(noShip* ship : ships)
64✔
1922
        {
1923
            if(ship->IsIdling() && world.IsHarborAtSea(world.GetHarborPointID(hb.GetPos()), ship->GetSeaID()))
32✔
1924
                sfh.push_back(ShipForHarbor(ship, world.CalcDistance(hb.GetPos(), ship->GetPos())));
18✔
1925
        }
1926
    } else
1927
    {
1928
        for(noShip* ship : ships)
×
1929
        {
1930
            if((ship->IsIdling() && world.IsHarborAtSea(world.GetHarborPointID(hb.GetPos()), ship->GetSeaID()))
×
1931
               || ship->IsGoingToHarbor(hb))
×
1932
            {
1933
                sfh.push_back(ShipForHarbor(ship, world.CalcDistance(hb.GetPos(), ship->GetPos())));
×
1934
            }
1935
        }
1936
    }
1937

1938
    std::sort(sfh.begin(), sfh.end());
32✔
1939

1940
    noShip* best_ship = nullptr;
32✔
1941
    uint32_t best_distance = std::numeric_limits<uint32_t>::max();
32✔
1942
    std::vector<Direction> best_route;
64✔
1943

1944
    for(auto& it : sfh)
41✔
1945
    {
1946
        uint32_t distance;
1947
        std::vector<Direction> route;
18✔
1948

1949
        // the estimate (air-line distance) for this and all other ships in the list is already worse than what we
1950
        // found? disregard the rest
1951
        if(it.estimate >= best_distance)
18✔
1952
            break;
×
1953

1954
        noShip& ship = *it.ship;
18✔
1955

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

1958
        // ship already there?
1959
        if(ship.GetPos() == dest)
18✔
1960
        {
1961
            hb.ShipArrived(ship);
9✔
1962
            return (true);
9✔
1963
        }
1964

1965
        if(world.FindShipPathToHarbor(ship.GetPos(), hb.GetHarborPosID(), ship.GetSeaID(), &route, &distance))
9✔
1966
        {
1967
            if(distance < best_distance)
9✔
1968
            {
1969
                best_ship = &ship;
9✔
1970
                best_distance = distance;
9✔
1971
                best_route = route;
9✔
1972
            }
1973
        }
1974
    }
1975

1976
    // only order ships not already on their way
1977
    if(best_ship && best_ship->IsIdling())
23✔
1978
    {
1979
        best_ship->GoToHarbor(hb, best_route);
9✔
1980

1981
        return (true);
9✔
1982
    }
1983

1984
    return (false);
14✔
1985
}
1986

1987
/// Meldet das Schiff wieder ab
1988
void GamePlayer::RemoveShip(noShip* ship)
×
1989
{
1990
    for(unsigned i = 0; i < ships.size(); ++i)
×
1991
    {
1992
        if(ships[i] == ship)
×
1993
        {
1994
            ships.erase(ships.begin() + i);
×
1995
            return;
×
1996
        }
1997
    }
1998
}
1999

2000
/// Versucht, für ein untätiges Schiff eine Arbeit zu suchen
2001
void GamePlayer::GetJobForShip(noShip& ship)
31✔
2002
{
2003
    // Evtl. steht irgendwo eine Expedition an und das Schiff kann diese übernehmen
2004
    nobHarborBuilding* best = nullptr;
31✔
2005
    int best_points = 0;
31✔
2006
    std::vector<Direction> best_route;
31✔
2007

2008
    // Beste Weglänge, die ein Schiff zurücklegen muss, welches gerade nichts zu tun hat
2009
    for(nobHarborBuilding* harbor : buildings.GetHarbors())
64✔
2010
    {
2011
        // Braucht der Hafen noch Schiffe?
2012
        if(harbor->GetNumNeededShips() == 0)
33✔
2013
            continue;
33✔
2014

2015
        // Anzahl der Schiffe ermitteln, die diesen Hafen bereits anfahren
2016
        unsigned ships_coming = GetShipsToHarbor(*harbor);
×
2017

2018
        // Evtl. kommen schon genug?
2019
        if(harbor->GetNumNeededShips() <= ships_coming)
×
2020
            continue;
×
2021

2022
        // liegen wir am gleichen Meer?
2023
        if(world.IsHarborAtSea(harbor->GetHarborPosID(), ship.GetSeaID()))
×
2024
        {
2025
            const MapPoint coastPt = world.GetCoastalPoint(harbor->GetHarborPosID(), ship.GetSeaID());
×
2026

2027
            // Evtl. sind wir schon da?
2028
            if(ship.GetPos() == coastPt)
×
2029
            {
2030
                harbor->ShipArrived(ship);
×
2031
                return;
×
2032
            }
2033

2034
            unsigned length;
2035
            std::vector<Direction> route;
×
2036

2037
            if(world.FindShipPathToHarbor(ship.GetPos(), harbor->GetHarborPosID(), ship.GetSeaID(), &route, &length))
×
2038
            {
2039
                // Punkte ausrechnen
2040
                int points = harbor->GetNeedForShip(ships_coming) - length;
×
2041
                if(points > best_points || !best)
×
2042
                {
2043
                    best = harbor;
×
2044
                    best_points = points;
×
2045
                    best_route = route;
×
2046
                }
2047
            }
2048
        }
2049
    }
2050

2051
    // Einen Hafen gefunden?
2052
    if(best)
31✔
2053
        // Dann bekommt das gleich der Hafen
2054
        ship.GoToHarbor(*best, best_route);
×
2055
}
2056

2057
/// Gibt die ID eines Schiffes zurück
2058
unsigned GamePlayer::GetShipID(const noShip* const ship) const
13✔
2059
{
2060
    for(unsigned i = 0; i < ships.size(); ++i)
13✔
2061
        if(ships[i] == ship)
13✔
2062
            return i;
13✔
2063

2064
    return 0xFFFFFFFF;
×
2065
}
2066

2067
/// Gibt ein Schiff anhand der ID zurück bzw. nullptr, wenn keines mit der ID existiert
2068
noShip* GamePlayer::GetShipByID(const unsigned ship_id) const
20✔
2069
{
2070
    if(ship_id >= ships.size())
20✔
2071
        return nullptr;
×
2072
    else
2073
        return ships[ship_id];
20✔
2074
}
2075

2076
/// Gibt eine Liste mit allen Häfen dieses Spieler zurück, die an ein bestimmtes Meer angrenzen
2077
void GamePlayer::GetHarborsAtSea(std::vector<nobHarborBuilding*>& harbor_buildings, const unsigned short seaId) const
196✔
2078
{
2079
    for(nobHarborBuilding* harbor : buildings.GetHarbors())
638✔
2080
    {
2081
        if(helpers::contains(harbor_buildings, harbor))
442✔
2082
            continue;
215✔
2083

2084
        if(world.IsHarborAtSea(harbor->GetHarborPosID(), seaId))
227✔
2085
            harbor_buildings.push_back(harbor);
227✔
2086
    }
2087
}
196✔
2088

2089
/// Gibt die Anzahl der Schiffe, die einen bestimmten Hafen ansteuern, zurück
2090
unsigned GamePlayer::GetShipsToHarbor(const nobHarborBuilding& hb) const
71✔
2091
{
2092
    unsigned count = 0;
71✔
2093
    for(const auto* ship : ships)
142✔
2094
    {
2095
        if(ship->IsGoingToHarbor(hb))
71✔
2096
            ++count;
5✔
2097
    }
2098

2099
    return count;
71✔
2100
}
2101

2102
/// Sucht einen Hafen in der Nähe, wo dieses Schiff seine Waren abladen kann
2103
/// gibt true zurück, falls erfolgreich
2104
bool GamePlayer::FindHarborForUnloading(noShip* ship, const MapPoint start, unsigned* goal_harborId,
5✔
2105
                                        std::vector<Direction>* route, nobHarborBuilding* exception)
2106
{
2107
    nobHarborBuilding* best = nullptr;
5✔
2108
    unsigned best_distance = 0xffffffff;
5✔
2109

2110
    for(nobHarborBuilding* hb : buildings.GetHarbors())
8✔
2111
    {
2112
        // Bestimmten Hafen ausschließen
2113
        if(hb == exception)
3✔
2114
            continue;
×
2115

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

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

2123
        // Kürzerer Weg als bisher bestes Ziel?
2124
        if(distance < best_distance)
3✔
2125
        {
2126
            best_distance = distance;
3✔
2127
            best = hb;
3✔
2128
        }
2129
    }
2130

2131
    // Hafen gefunden?
2132
    if(best)
5✔
2133
    {
2134
        // Weg dorthin suchen
2135
        route->clear();
3✔
2136
        *goal_harborId = best->GetHarborPosID();
3✔
2137
        const MapPoint coastPt = world.GetCoastalPoint(best->GetHarborPosID(), ship->GetSeaID());
3✔
2138
        if(start == coastPt
3✔
2139
           || world.FindShipPathToHarbor(start, best->GetHarborPosID(), ship->GetSeaID(), route, nullptr))
3✔
2140
            return true;
3✔
2141
    }
2142

2143
    return false;
2✔
2144
}
2145

2146
void GamePlayer::TestForEmergencyProgramm()
×
2147
{
2148
    // we are already defeated, do not even think about an emergency program - it's too late :-(
2149
    if(isDefeated)
×
2150
        return;
×
2151

2152
    // In Lagern vorhandene Bretter und Steine zählen
2153
    unsigned boards = 0;
×
2154
    unsigned stones = 0;
×
2155
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
×
2156
    {
2157
        boards += wh->GetInventory().goods[GoodType::Boards];
×
2158
        stones += wh->GetInventory().goods[GoodType::Stones];
×
2159
    }
2160

2161
    // Emergency happens, if we have less than 10 boards or stones...
2162
    bool isNewEmergency = boards <= 10 || stones <= 10;
×
2163
    // ...and no woddcutter or sawmill
2164
    isNewEmergency &=
×
2165
      buildings.GetBuildings(BuildingType::Woodcutter).empty() || buildings.GetBuildings(BuildingType::Sawmill).empty();
×
2166

2167
    // Wenn nötig, Notfallprogramm auslösen
2168
    if(isNewEmergency)
×
2169
    {
2170
        if(!emergency)
×
2171
        {
2172
            emergency = true;
×
2173
            SendPostMessage(std::make_unique<PostMsg>(
×
2174
              world.GetEvMgr().GetCurrentGF(), _("The emergency program has been activated."), PostCategory::Economy));
×
2175
        }
2176
    } else
2177
    {
2178
        // Sobald Notfall vorbei, Notfallprogramm beenden, evtl. Baustellen wieder mit Kram versorgen
2179
        if(emergency)
×
2180
        {
2181
            emergency = false;
×
2182
            SendPostMessage(std::make_unique<PostMsg>(world.GetEvMgr().GetCurrentGF(),
×
2183
                                                      _("The emergency program has been deactivated."),
×
2184
                                                      PostCategory::Economy));
×
2185
            FindMaterialForBuildingSites();
×
2186
        }
2187
    }
2188
}
2189

2190
/// Testet die Bündnisse, ob sie nicht schon abgelaufen sind
2191
void GamePlayer::TestPacts()
20✔
2192
{
2193
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
80✔
2194
    {
2195
        if(i == GetPlayerId())
60✔
2196
            continue;
20✔
2197

2198
        for(const auto pact : helpers::enumRange<PactType>())
320✔
2199
        {
2200
            // Pact not running
2201
            if(pacts[i][pact].duration == 0)
80✔
2202
                continue;
60✔
2203
            if(GetPactState(pact, i) == PactState::None)
20✔
2204
            {
2205
                // Pact was running but is expired -> Cancel for both players
2206
                pacts[i][pact].duration = 0;
2✔
2207
                pacts[i][pact].accepted = false;
2✔
2208
                GamePlayer& otherPlayer = world.GetPlayer(i);
2✔
2209
                RTTR_Assert(otherPlayer.pacts[GetPlayerId()][pact].duration);
2✔
2210
                RTTR_Assert(otherPlayer.pacts[GetPlayerId()][pact].accepted);
2✔
2211
                otherPlayer.pacts[GetPlayerId()][pact].duration = 0;
2✔
2212
                otherPlayer.pacts[GetPlayerId()][pact].accepted = false;
2✔
2213
                // And notify
2214
                PactChanged(pact);
2✔
2215
                otherPlayer.PactChanged(pact);
2✔
2216
            }
2217
        }
2218
    }
2219
}
20✔
2220

2221
bool GamePlayer::CanBuildCatapult() const
1✔
2222
{
2223
    // Wenn AddonId::LIMIT_CATAPULTS nicht aktiv ist, bauen immer erlaubt
2224
    if(!world.GetGGS().isEnabled(AddonId::LIMIT_CATAPULTS)) //-V807
1✔
2225
        return true;
1✔
2226

2227
    BuildingCount bc = buildings.GetBuildingNums();
×
2228

2229
    unsigned max = 0;
×
2230
    // proportional?
2231
    if(world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) == 1)
×
2232
    {
2233
        max = int(bc.buildings[BuildingType::Barracks] * 0.125 + bc.buildings[BuildingType::Guardhouse] * 0.25
×
2234
                  + bc.buildings[BuildingType::Watchtower] * 0.5 + bc.buildings[BuildingType::Fortress]
×
2235
                  + 0.111); // to avoid rounding errors
×
2236
    } else if(world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) < 8)
×
2237
    {
2238
        const std::array<unsigned, 6> limits = {{0, 3, 5, 10, 20, 30}};
×
2239
        max = limits[world.GetGGS().getSelection(AddonId::LIMIT_CATAPULTS) - 2];
×
2240
    }
2241

2242
    return bc.buildings[BuildingType::Catapult] + bc.buildingSites[BuildingType::Catapult] < max;
×
2243
}
2244

2245
/// A ship has discovered new hostile territory --> determines if this is new
2246
/// i.e. there is a sufficient distance to older locations
2247
/// Returns true if yes and false if not
2248
bool GamePlayer::ShipDiscoveredHostileTerritory(const MapPoint location)
25✔
2249
{
2250
    // Prüfen, ob Abstand zu bisherigen Punkten nicht zu klein
2251
    for(const auto& enemies_discovered_by_ship : enemies_discovered_by_ships)
25✔
2252
    {
2253
        if(world.CalcDistance(enemies_discovered_by_ship, location) < 30)
24✔
2254
            return false;
24✔
2255
    }
2256

2257
    // Nein? Dann haben wir ein neues Territorium gefunden
2258
    enemies_discovered_by_ships.push_back(location);
1✔
2259

2260
    return true;
1✔
2261
}
2262

2263
/// For debug only
2264
bool GamePlayer::IsDependentFigure(const noFigure& fig)
236✔
2265
{
2266
    for(const nobBaseWarehouse* wh : buildings.GetStorehouses())
580✔
2267
    {
2268
        if(wh->IsDependentFigure(fig))
344✔
2269
            return true;
×
2270
    }
2271
    return false;
236✔
2272
}
2273

2274
std::vector<nobBaseWarehouse*> GamePlayer::GetWarehousesForTrading(const nobBaseWarehouse& goalWh) const
18✔
2275
{
2276
    std::vector<nobBaseWarehouse*> result;
18✔
2277

2278
    // Don't try to trade with us!
2279
    if(goalWh.GetPlayer() == GetPlayerId())
18✔
2280
        return result;
6✔
2281

2282
    const MapPoint goalFlagPos = goalWh.GetFlagPos();
12✔
2283

2284
    TradePathCache& tradePathCache = world.GetTradePathCache();
12✔
2285
    for(nobBaseWarehouse* wh : buildings.GetStorehouses())
24✔
2286
    {
2287
        // Is there a trade path from this warehouse to wh? (flag to flag)
2288
        if(tradePathCache.pathExists(wh->GetFlagPos(), goalFlagPos, GetPlayerId()))
12✔
2289
            result.push_back(wh);
4✔
2290
    }
2291

2292
    return result;
12✔
2293
}
2294

2295
struct WarehouseDistanceComparator
2296
{
2297
    // Reference warehouse position, to which we want to calc the distance
2298
    const MapPoint refWareHousePos_;
2299
    /// GameWorld
2300
    const GameWorld& gwg_;
2301

2302
    WarehouseDistanceComparator(const nobBaseWarehouse& refWareHouse, const GameWorld& world)
15✔
2303
        : refWareHousePos_(refWareHouse.GetPos()), gwg_(world)
15✔
2304
    {}
15✔
2305

2306
    bool operator()(nobBaseWarehouse* const wh1, nobBaseWarehouse* const wh2) const
×
2307
    {
2308
        unsigned dist1 = gwg_.CalcDistance(wh1->GetPos(), refWareHousePos_);
×
2309
        unsigned dist2 = gwg_.CalcDistance(wh2->GetPos(), refWareHousePos_);
×
2310
        return (dist1 < dist2) || (dist1 == dist2 && wh1->GetObjId() < wh2->GetObjId());
×
2311
    }
2312
};
2313

2314
/// Send wares to warehouse wh
2315
void GamePlayer::Trade(nobBaseWarehouse* goalWh, const boost_variant2<GoodType, Job>& what, unsigned count) const
23✔
2316
{
2317
    if(!world.GetGGS().isEnabled(AddonId::TRADE))
23✔
2318
        return;
11✔
2319

2320
    if(count == 0)
20✔
2321
        return;
3✔
2322

2323
    // Don't try to trade with us!
2324
    if(goalWh->GetPlayer() == GetPlayerId())
17✔
2325
        return;
1✔
2326

2327
    // No trades with enemies
2328
    if(!IsAlly(goalWh->GetPlayer()))
16✔
2329
        return;
1✔
2330

2331
    const MapPoint goalFlagPos = goalWh->GetFlagPos();
15✔
2332

2333
    std::vector<nobBaseWarehouse*> whs(buildings.GetStorehouses().begin(), buildings.GetStorehouses().end());
15✔
2334
    std::sort(whs.begin(), whs.end(), WarehouseDistanceComparator(*goalWh, world));
15✔
2335
    TradePathCache& tradePathCache = world.GetTradePathCache();
15✔
2336
    for(nobBaseWarehouse* wh : whs)
27✔
2337
    {
2338
        // Get available wares
2339
        const unsigned available =
2340
          boost::variant2::visit(composeVisitor([wh](GoodType gt) { return wh->GetAvailableWaresForTrading(gt); },
22✔
2341
                                                [wh](Job job) { return wh->GetAvailableFiguresForTrading(job); }),
23✔
2342
                                 what);
15✔
2343
        if(available == 0)
15✔
2344
            continue;
×
2345

2346
        const unsigned actualCount = std::min(available, count);
15✔
2347

2348
        // Find a trade path from flag to flag
2349
        TradeRoute tr(world, GetPlayerId(), wh->GetFlagPos(), goalFlagPos);
15✔
2350

2351
        // Found a path?
2352
        if(tr.IsValid())
15✔
2353
        {
2354
            // Add to cache for future searches
2355
            tradePathCache.addEntry(tr.GetTradePath(), GetPlayerId());
14✔
2356

2357
            wh->StartTradeCaravane(what, actualCount, tr, goalWh);
14✔
2358
            count -= available;
14✔
2359
            if(count == 0)
14✔
2360
                return;
3✔
2361
        }
2362
    }
2363
}
2364

2365
bool GamePlayer::IsBuildingEnabled(BuildingType type) const
955✔
2366
{
2367
    return building_enabled[type] || (isHuman() && world.GetGameInterface()->GI_GetCheats().areAllBuildingsEnabled());
955✔
2368
}
2369

2370
void GamePlayer::FillVisualSettings(VisualSettings& visualSettings) const
2✔
2371
{
2372
    Distributions& visDistribution = visualSettings.distribution;
2✔
2373
    unsigned visIdx = 0;
2✔
2374
    for(const DistributionMapping& mapping : distributionMap)
60✔
2375
    {
2376
        visDistribution[visIdx++] = distribution[std::get<0>(mapping)].percent_buildings[std::get<1>(mapping)];
58✔
2377
    }
2378

2379
    visualSettings.useCustomBuildOrder = useCustomBuildOrder_;
2✔
2380
    visualSettings.build_order = build_order;
2✔
2381

2382
    visualSettings.transport_order = GetOrderingFromTransportPrio(transportPrio);
2✔
2383

2384
    visualSettings.military_settings = militarySettings_;
2✔
2385
    visualSettings.tools_settings = toolsSettings_;
2✔
2386
}
2✔
2387

2388
#define INSTANTIATE_FINDWH(Cond)                                                                                \
2389
    template nobBaseWarehouse* GamePlayer::FindWarehouse(const noRoadNode&, const Cond&, bool, bool, unsigned*, \
2390
                                                         const RoadSegment*) const
2391

2392
INSTANTIATE_FINDWH(FW::HasMinWares);
2393
INSTANTIATE_FINDWH(FW::HasFigure);
2394
INSTANTIATE_FINDWH(FW::HasWareAndFigure);
2395
INSTANTIATE_FINDWH(FW::HasAnyMatchingSoldier);
2396
INSTANTIATE_FINDWH(FW::AcceptsWare);
2397
INSTANTIATE_FINDWH(FW::AcceptsFigure);
2398
INSTANTIATE_FINDWH(FW::CollectsWare);
2399
INSTANTIATE_FINDWH(FW::CollectsFigure);
2400
INSTANTIATE_FINDWH(FW::HasWareButNoCollect);
2401
INSTANTIATE_FINDWH(FW::HasFigureButNoCollect);
2402
INSTANTIATE_FINDWH(FW::AcceptsFigureButNoSend);
2403
INSTANTIATE_FINDWH(FW::NoCondition);
2404

2405
#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