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

Return-To-The-Roots / s25client / 26276677540

22 May 2026 08:17AM UTC coverage: 50.362% (+0.07%) from 50.29%
26276677540

push

github

web-flow
Merge pull request #1925 from DevOpsOfChaos/sidequest/ignore-isolated-fish-resources

Ignore isolated fish resources for fisheries

36 of 63 new or added lines in 4 files covered. (57.14%)

5 existing lines in 2 files now uncovered.

23180 of 46027 relevant lines covered (50.36%)

43873.39 hits per line

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

76.1
/libs/s25main/world/MapLoader.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 "world/MapLoader.h"
6
#include "Game.h"
7
#include "GamePlayer.h"
8
#include "GameWorldBase.h"
9
#include "GlobalGameSettings.h"
10
#include "PointOutput.h"
11
#include "RttrForeachPt.h"
12
#include "addons/const_addons.h"
13
#include "buildings/nobHQ.h"
14
#include "factories/BuildingFactory.h"
15
#include "helpers/IdRange.h"
16
#include "helpers/Range.h"
17
#include "helpers/containerUtils.h"
18
#include "helpers/mathFuncs.h"
19
#include "lua/GameDataLoader.h"
20
#include "pathfinding/PathConditionShip.h"
21
#include "random/Random.h"
22
#include "world/World.h"
23
#include "nodeObjs/noAnimal.h"
24
#include "nodeObjs/noEnvObject.h"
25
#include "nodeObjs/noGranite.h"
26
#include "nodeObjs/noStaticObject.h"
27
#include "nodeObjs/noTree.h"
28
#include "gameTypes/ShipDirection.h"
29
#include "gameData/MaxPlayers.h"
30
#include "gameData/TerrainDesc.h"
31
#include "libsiedler2/Archiv.h"
32
#include "libsiedler2/ArchivItem_Map.h"
33
#include "libsiedler2/ArchivItem_Map_Header.h"
34
#include "libsiedler2/prototypen.h"
35
#include "s25util/Log.h"
36
#include <boost/filesystem/operations.hpp>
37
#include <algorithm>
38
#include <map>
39
#include <queue>
40

41
class noBase;
42

43
MapLoader::MapLoader(GameWorldBase& world) : world_(world) {}
7✔
44

45
bool MapLoader::Load(const libsiedler2::ArchivItem_Map& map, Exploration exploration)
5✔
46
{
47
    GameDataLoader gdLoader(world_.GetDescriptionWriteable());
10✔
48
    if(!gdLoader.Load())
5✔
49
        return false;
×
50

51
    uint8_t gfxSet = map.getHeader().getGfxSet();
5✔
52
    DescIdx<LandscapeDesc> lt =
53
      world_.GetDescription().landscapes.find([gfxSet](const LandscapeDesc& l) { return l.s2Id == gfxSet; });
10✔
54
    world_.Init(MapExtent(map.getHeader().getWidth(), map.getHeader().getHeight()), lt); //-V807
5✔
55

56
    if(!InitNodes(map, exploration))
5✔
57
        return false;
×
58
    PlaceObjects(map);
5✔
59
    PlaceAnimals(map);
5✔
60
    if(!InitSeasAndHarbors(world_))
5✔
61
        return false;
×
62

63
    /// Schatten
64
    InitShadows(world_);
5✔
65

66
    // If we have explored FoW, create the FoW objects
67
    if(exploration == Exploration::FogOfWarExplored)
5✔
68
        SetMapExplored(world_);
×
69

70
    return true;
5✔
71
}
72

73
bool MapLoader::Load(const boost::filesystem::path& mapFilePath)
3✔
74
{
75
    // Map laden
76
    libsiedler2::Archiv mapArchiv;
6✔
77

78
    // Karteninformationen laden
79
    if(libsiedler2::loader::LoadMAP(mapFilePath, mapArchiv) != 0)
3✔
80
        return false;
×
81

82
    const libsiedler2::ArchivItem_Map& map = *static_cast<libsiedler2::ArchivItem_Map*>(mapArchiv[0]);
3✔
83

84
    if(!Load(map, world_.GetGGS().exploration))
3✔
85
        return false;
×
86
    if(!PlaceHQs())
3✔
87
        return false;
×
88

89
    world_.CreateTradeGraphs();
3✔
90

91
    return true;
3✔
92
}
93

94
bool MapLoader::LoadLuaScript(Game& game, ILocalGameState& localgameState, const boost::filesystem::path& luaFilePath)
3✔
95
{
96
    if(!bfs::exists(luaFilePath))
3✔
97
        return false;
×
98
    auto lua = std::make_unique<LuaInterfaceGame>(game, localgameState);
6✔
99
    if(!lua->loadScript(luaFilePath) || !lua->CheckScriptVersion())
3✔
100
        return false;
1✔
101
    game.SetLua(std::move(lua));
2✔
102
    return true;
2✔
103
}
104

105
bool MapLoader::PlaceHQs(bool addStartWares)
3✔
106
{
107
    std::vector<MapPoint> hqPositions = hqPositions_;
6✔
108
    if(world_.GetGGS().randomStartPosition)
3✔
109
        RANDOM_SHUFFLE2(hqPositions, 0);
1✔
110
    return PlaceHQs(world_, hqPositions, addStartWares);
6✔
111
}
112

113
void MapLoader::SetupResources(GameWorldBase& world, const bool fixFish)
3✔
114
{
115
    ResourceType target;
116
    switch(world.GetGGS().getSelection(AddonId::CHANGE_GOLD_DEPOSITS))
3✔
117
    {
118
        case 0:
3✔
119
        default: target = ResourceType::Gold; break;
3✔
NEW
120
        case 1: target = ResourceType::Nothing; break;
×
NEW
121
        case 2: target = ResourceType::Iron; break;
×
NEW
122
        case 3: target = ResourceType::Coal; break;
×
NEW
123
        case 4: target = ResourceType::Granite; break;
×
124
    }
125
    ConvertMineResourceTypes(world, ResourceType::Gold, target);
3✔
126
    PlaceAndFixWater(world);
3✔
127
    if(fixFish)
3✔
128
        RemoveUnusableFishResources(world);
3✔
129
}
3✔
130

131
void MapLoader::ConvertMineResourceTypes(GameWorldBase& world, ResourceType from, ResourceType to)
3✔
132
{
133
    // LOG.write(("Convert map resources from %i to %i\n", from, to);
134
    if(from == to)
3✔
135
        return;
3✔
136

NEW
137
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
×
138
    {
NEW
139
        Resource resources = world.GetNode(pt).resources;
×
140
        // Gibt es Ressourcen dieses Typs?
141
        // Wenn ja, dann umwandeln bzw löschen
NEW
142
        if(resources.getType() == from)
×
143
        {
NEW
144
            resources.setType(to);
×
NEW
145
            world.SetResource(pt, resources);
×
146
        }
147
    }
148
}
149

150
void MapLoader::PlaceAndFixWater(GameWorldBase& world)
3✔
151
{
152
    const bool waterEverywhere = world.GetGGS().getSelection(AddonId::EXHAUSTIBLE_WATER) == 1;
3✔
153

154
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
1,383✔
155
    {
156
        Resource curNodeResource = world.GetNode(pt).resources;
1,320✔
157

158
        if(curNodeResource.getType() == ResourceType::Nothing)
1,320✔
159
        {
160
            if(!waterEverywhere)
1,313✔
161
                continue;
1,320✔
162
        } else if(curNodeResource.getType() != ResourceType::Water)
7✔
163
            continue; // do not override maps resource.
7✔
164

NEW
165
        uint8_t minHumidity = 100;
×
NEW
166
        for(const DescIdx<TerrainDesc> tIdx : world.GetTerrainsAround(pt))
×
167
        {
NEW
168
            const uint8_t curHumidity = world.GetDescription().get(tIdx).humidity;
×
NEW
169
            if(curHumidity < minHumidity)
×
170
            {
NEW
171
                minHumidity = curHumidity;
×
NEW
172
                if(minHumidity == 0)
×
NEW
173
                    break;
×
174
            }
175
        }
NEW
176
        if(minHumidity)
×
177
        {
NEW
178
            curNodeResource =
×
NEW
179
              Resource(ResourceType::Water, waterEverywhere ? 7 : helpers::iround<uint8_t>(minHumidity * 7. / 100.));
×
180
        } else
NEW
181
            curNodeResource = Resource(ResourceType::Nothing, 0);
×
182

NEW
183
        world.SetResource(pt, curNodeResource);
×
184
    }
185
}
3✔
186

187
void MapLoader::RemoveUnusableFishResources(GameWorldBase& world)
3✔
188
{
189
    const auto isWaterPoint = [&world](const MapPoint nb) { return world.IsWaterPoint(nb); };
28✔
190
    for(const MapCoord y : helpers::range(world.GetHeight()))
132✔
191
    {
192
        // Optimization: When there was fish on the previous node (in the same row)
193
        // we do not need to check for isolated water points, as there is at least that water point
194
        bool previousHasFish = false;
60✔
195
        for(const MapCoord x : helpers::range(world.GetWidth()))
2,880✔
196
        {
197
            const MapPoint pt(x, y);
1,320✔
198
            bool hasFish = false;
1,320✔
199

200
            if(world.GetNode(pt).resources.has(ResourceType::Fish))
1,320✔
201
            {
202
                if(isWaterPoint(pt) && (previousHasFish || helpers::contains_if(world.GetNeighbours(pt), isWaterPoint)))
7✔
203
                    hasFish = true;
5✔
204
                else
205
                    world.SetResource(pt, Resource(ResourceType::Nothing, 0));
2✔
206
            }
207
            previousHasFish = hasFish;
1,320✔
208
        }
209
    }
210
}
3✔
211

212
void MapLoader::InitShadows(World& world)
5✔
213
{
214
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
70,805✔
215
        world.RecalcShadow(pt);
70,400✔
216
}
5✔
217

218
void MapLoader::SetMapExplored(World& world)
×
219
{
220
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
×
221
    {
222
        // For every player
NEW
223
        for(const auto i : helpers::range(MAX_PLAYERS))
×
224
        {
225
            // If we have FoW here, save it
226
            if(world.GetNode(pt).fow[i].visibility == Visibility::FogOfWar)
×
227
                world.SaveFOWNode(pt, i, 0);
×
228
        }
229
    }
230
}
×
231

232
DescIdx<TerrainDesc> MapLoader::getTerrainFromS2(uint8_t s2Id) const
140,800✔
233
{
234
    return world_.GetDescription().terrain.find([s2Id, landscape = world_.GetLandscapeType()](const TerrainDesc& t) {
140,800✔
235
        return t.s2Id == s2Id && t.landscape == landscape;
1,442,160✔
236
    });
140,800✔
237
}
238

239
bool MapLoader::InitNodes(const libsiedler2::ArchivItem_Map& map, Exploration exploration)
5✔
240
{
241
    using libsiedler2::MapLayer;
242
    // Init node data (everything except the objects, figures and BQ)
243
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
244
    {
245
        MapNode& node = world_.GetNodeInt(pt);
70,400✔
246

247
        std::fill(node.roads.begin(), node.roads.end(), PointRoad::None);
70,400✔
248
        node.altitude = map.getMapDataAt(MapLayer::Altitude, pt.x, pt.y);
70,400✔
249
        unsigned char t1 = map.getMapDataAt(MapLayer::Terrain1, pt.x, pt.y),
70,400✔
250
                      t2 = map.getMapDataAt(MapLayer::Terrain2, pt.x, pt.y);
70,400✔
251

252
        // Hafenplatz?
253
        if((t1 & libsiedler2::HARBOR_MASK) != 0)
70,400✔
254
            world_.harborData.push_back(HarborPos(pt));
×
255

256
        // Will be set later
257
        node.harborId.reset();
70,400✔
258

259
        node.t1 = getTerrainFromS2(t1 & 0x3F); // Only lower 6 bits
70,400✔
260
        node.t2 = getTerrainFromS2(t2 & 0x3F); // Only lower 6 bits
70,400✔
261
        if(!node.t1 || !node.t2)
70,400✔
262
            return false;
×
263

264
        unsigned char mapResource = map.getMapDataAt(MapLayer::Resources, pt.x, pt.y);
70,400✔
265
        Resource resource;
70,400✔
266
        // Wasser?
267
        if(mapResource == 0x20 || mapResource == 0x21)
70,400✔
268
            resource = Resource(ResourceType::Water, 7);
36,625✔
269
        else if(mapResource > 0x40 && mapResource < 0x48)
33,775✔
270
            resource = Resource(ResourceType::Coal, mapResource - 0x40);
9,815✔
271
        else if(mapResource > 0x48 && mapResource < 0x50)
23,960✔
272
            resource = Resource(ResourceType::Iron, mapResource - 0x48);
2,525✔
273
        else if(mapResource > 0x50 && mapResource < 0x58)
21,435✔
274
            resource = Resource(ResourceType::Gold, mapResource - 0x50);
1,660✔
275
        else if(mapResource > 0x58 && mapResource < 0x60)
19,775✔
276
            resource = Resource(ResourceType::Granite, mapResource - 0x58);
550✔
277
        else if(mapResource > 0x80 && mapResource < 0x90) // fish
19,225✔
278
            resource = Resource(ResourceType::Fish, 4);   // Use 4 fish
2,420✔
279
        node.resources = resource;
70,400✔
280

281
        node.reserved = false;
70,400✔
282
        node.owner = 0;
70,400✔
283
        std::fill(node.boundary_stones.begin(), node.boundary_stones.end(), 0);
70,400✔
284
        node.seaId.reset();
70,400✔
285

286
        Visibility fowVisibility;
287
        switch(exploration)
70,400✔
288
        {
289
            case Exploration::Disabled: fowVisibility = Visibility::Visible; break;
×
290
            case Exploration::Classic:
70,400✔
291
            case Exploration::FogOfWar: fowVisibility = Visibility::Invisible; break;
70,400✔
292
            case Exploration::FogOfWarExplored: fowVisibility = Visibility::FogOfWar; break;
×
293
            default: throw std::invalid_argument("Visibility for FoW");
×
294
        }
295

296
        // FOW-Zeug initialisieren
297
        for(auto& fow : node.fow)
633,600✔
298
        {
299
            fow = FoWNode();
563,200✔
300
            fow.visibility = fowVisibility;
563,200✔
301
        }
302

303
        RTTR_Assert(node.figures.empty());
70,400✔
304
    }
305
    return true;
5✔
306
}
307

308
void MapLoader::PlaceObjects(const libsiedler2::ArchivItem_Map& map)
5✔
309
{
310
    hqPositions_.clear();
5✔
311

312
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
313
    {
314
        using libsiedler2::MapLayer;
315
        unsigned char lc = map.getMapDataAt(MapLayer::ObjectIndex, pt.x, pt.y);
70,400✔
316
        noBase* obj = nullptr;
70,400✔
317

318
        switch(map.getMapDataAt(MapLayer::ObjectType, pt.x, pt.y))
70,400✔
319
        {
320
            // Player Startpos (provisorisch)
321
            case 0x80:
20✔
322
            {
323
                if(lc < MAX_PLAYERS)
20✔
324
                {
325
                    while(hqPositions_.size() <= lc)
40✔
326
                        hqPositions_.push_back(MapPoint::Invalid());
20✔
327
                    hqPositions_[lc] = pt;
20✔
328
                }
329
            }
330
            break;
20✔
331

332
            // Baum 1-4
333
            case 0xC4:
17,640✔
334
            {
335
                if(lc >= 0x30 && lc <= 0x3D)
17,640✔
336
                    obj = new noTree(pt, 0, 3);
5,610✔
337
                else if(lc >= 0x70 && lc <= 0x7D)
12,030✔
338
                    obj = new noTree(pt, 1, 3);
5,860✔
339
                else if(lc >= 0xB0 && lc <= 0xBD)
6,170✔
340
                    obj = new noTree(pt, 2, 3);
5,555✔
341
                else if(lc >= 0xF0 && lc <= 0xFD)
615✔
342
                    obj = new noTree(pt, 3, 3);
615✔
343
                else
344
                    LOG.write(_("Unknown tree1-4 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
345
            }
346
            break;
17,640✔
347

348
            // Baum 5-8
349
            case 0xC5:
×
350
            {
351
                if(lc >= 0x30 && lc <= 0x3D)
×
352
                    obj = new noTree(pt, 4, 3);
×
353
                else if(lc >= 0x70 && lc <= 0x7D)
×
354
                    obj = new noTree(pt, 5, 3);
×
355
                else if(lc >= 0xB0 && lc <= 0xBD)
×
356
                    obj = new noTree(pt, 6, 3);
×
357
                else if(lc >= 0xF0 && lc <= 0xFD)
×
358
                    obj = new noTree(pt, 7, 3);
×
359
                else
360
                    LOG.write(_("Unknown tree5-8 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
361
            }
362
            break;
×
363

364
            // Baum 9
365
            case 0xC6:
×
366
            {
367
                if(lc >= 0x30 && lc <= 0x3D)
×
368
                    obj = new noTree(pt, 8, 3);
×
369
                else
370
                    LOG.write(_("Unknown tree9 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
371
            }
372
            break;
×
373

374
            // Sonstiges Naturzeug ohne Funktion, nur zur Dekoration
375
            case 0xC8:
3,740✔
376
            case 0xC9: // Note: 0xC9 is actually a bug and should be 0xC8. But the random map generator produced that...
377
            {
378
                // "wasserstein" aus der map_?_z.lst
379
                if(lc == 0x0B)
3,740✔
380
                    obj = new noStaticObject(pt, 500 + lc);
×
381
                // Objekte aus der map_?_z.lst
382
                else if(lc <= 0x0F)
3,740✔
383
                    obj = new noEnvObject(pt, 500 + lc);
1,615✔
384
                // Objekte aus der map.lst
385
                else if(lc <= 0x14)
2,125✔
386
                    obj = new noEnvObject(pt, 542 + lc - 0x10);
1,580✔
387
                // exists in mis0bobs-mis5bobs -> take stranded ship
388
                else if(lc == 0x15)
545✔
389
                    obj = new noStaticObject(pt, 0, 0);
×
390
                // gate
391
                else if(lc == 0x16)
545✔
392
                    obj = new noStaticObject(pt, 560);
×
393
                // open gate
394
                else if(lc == 0x17)
545✔
395
                    obj = new noStaticObject(pt, 561);
×
396
                // Stalagmiten (mis1bobs)
397
                else if(lc <= 0x1E)
545✔
398
                    obj = new noStaticObject(pt, (lc - 0x18) * 2, 1);
×
399
                // toter Baum (mis1bobs)
400
                else if(lc <= 0x20)
545✔
401
                    obj = new noStaticObject(pt, 20 + (lc - 0x1F) * 2, 1);
×
402
                // Gerippe (mis1bobs)
403
                else if(lc == 0x21)
545✔
404
                    obj = new noStaticObject(pt, 30, 1);
×
405
                // Objekte aus der map.lst
406
                else if(lc <= 0x2B)
545✔
407
                    obj = new noEnvObject(pt, 550 + lc - 0x22);
545✔
408
                // tent, ruin of guardhouse, tower ruin, cross
409
                else if(lc <= 0x2E || lc == 0x30)
×
410
                    obj = new noStaticObject(pt, (lc - 0x2C) * 2, 2);
×
411
                // castle ruin
412
                else if(lc == 0x2F)
×
413
                    obj = new noStaticObject(pt, (lc - 0x2C) * 2, 2, 2);
×
414
                // small wiking with boat
415
                else if(lc == 0x31)
×
416
                    obj = new noStaticObject(pt, 0, 3);
×
417
                // Pile of wood
418
                else if(lc == 0x32)
×
419
                    obj = new noStaticObject(pt, 0, 4);
×
420
                // whale skeleton (head right)
421
                else if(lc == 0x33)
×
422
                    obj = new noStaticObject(pt, 0, 5);
×
423
                // The next 2 are non standard and only for access in RTTR (replaced in original by
424
                // whale skeleton (head left)
425
                else if(lc == 0x34)
×
426
                    obj = new noStaticObject(pt, 2, 5);
×
427
                // Cave
428
                else if(lc == 0x35)
×
429
                    obj = new noStaticObject(pt, 4, 5);
×
430
                else
431
                    LOG.write(_("Unknown nature object at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
432
            }
433
            break;
3,740✔
434

435
            // Granit Typ 1
436
            case 0xCC:
1,370✔
437
            {
438
                if(lc >= 0x01 && lc <= 0x06)
1,370✔
439
                    obj = new noGranite(GraniteType::One, lc - 1);
1,370✔
440
                else
441
                    LOG.write(_("Unknown granite type2 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
442
            }
443
            break;
1,370✔
444

445
            // Granit Typ 2
446
            case 0xCD:
1,395✔
447
            {
448
                if(lc >= 0x01 && lc <= 0x06)
1,395✔
449
                    obj = new noGranite(GraniteType::Two, lc - 1);
1,395✔
450
                else
451
                    LOG.write(_("Unknown granite type2 at %1%: (0x%2$x)\n")) % pt % unsigned(lc);
×
452
            }
453
            break;
1,395✔
454

455
            // Nichts
456
            case 0: break;
46,235✔
457

458
            default:
×
459
#ifndef NDEBUG
460
                unsigned unknownObj = map.getMapDataAt(MapLayer::ObjectType, pt.x, pt.y);
×
461
                LOG.write(_("Unknown object at %1%: (0x%2$x: 0x%3$x)\n")) % pt % unknownObj % unsigned(lc);
×
462
#endif // !NDEBUG
463
                break;
×
464
        }
465

466
        world_.GetNodeInt(pt).obj = obj;
70,400✔
467
    }
468
}
5✔
469

470
void MapLoader::PlaceAnimals(const libsiedler2::ArchivItem_Map& map)
5✔
471
{
472
    // Tiere auslesen
473
    RTTR_FOREACH_PT(MapPoint, world_.GetSize())
70,805✔
474
    {
475
        Species species;
476
        using libsiedler2::MapLayer;
477
        switch(map.getMapDataAt(MapLayer::Animals, pt.x, pt.y))
70,400✔
478
        {
479
            // TODO: Which id is the polar bear?
480
            case 1:
175✔
481
                species = (RANDOM.Rand(RANDOM_CONTEXT2(0), 2) == 0) ? Species::RabbitWhite : Species::RabbitGrey;
175✔
482
                break; // Random rabbit
175✔
483
            case 2: species = Species::Fox; break;
140✔
484
            case 3: species = Species::Stag; break;
×
485
            case 4: species = Species::Deer; break;
140✔
486
            case 5: species = Species::Duck; break;
×
487
            case 6: species = Species::Sheep; break;
70✔
488
            case 0:
69,875✔
489
            case 0xFF: // 0xFF is for (really) old S2 maps
490
                continue;
69,875✔
491
            default:
×
492
#ifndef NDEBUG
493
                unsigned unknownAnimal = map.getMapDataAt(MapLayer::Animals, pt.x, pt.y);
×
494
                LOG.write(_("Unknown animal species at %1%: (0x%2$x)\n")) % pt % unknownAnimal;
×
495
#endif // !NDEBUG
496
                continue;
69,875✔
497
        }
498

499
        world_.AddFigure(pt, std::make_unique<noAnimal>(species, pt)).StartLiving();
525✔
500
    }
501
}
5✔
502

503
bool MapLoader::PlaceHQs(GameWorldBase& world, const std::vector<MapPoint>& hqPositions, const bool addStartWares)
179✔
504
{
505
    for(unsigned i = 0; i < world.GetNumPlayers(); ++i)
558✔
506
    {
507
        // Skip unused slots
508
        if(!world.GetPlayer(i).isUsed())
379✔
509
            continue;
13✔
510

511
        // Does the HQ have a position?
512
        if(i >= hqPositions.size() || !hqPositions[i].isValid())
366✔
513
        {
514
            LOG.write(_("Player %u does not have a valid start position!")) % i;
×
515
            return false;
×
516
        }
517

518
        auto* hq = checkedCast<nobHQ*>(BuildingFactory::CreateBuilding(world, BuildingType::Headquarters,
366✔
519
                                                                       hqPositions[i], i, world.GetPlayer(i).nation));
366✔
520
        if(addStartWares)
366✔
521
            hq->addStartWares();
8✔
522
    }
523
    return true;
179✔
524
}
525

526
bool MapLoader::InitSeasAndHarbors(World& world, const std::vector<MapPoint>& additionalHarbors)
27✔
527
{
528
    for(MapPoint pt : additionalHarbors)
185✔
529
        world.harborData.push_back(HarborPos(pt));
158✔
530
    // Clear current harbors and seas
531
    RTTR_FOREACH_PT(MapPoint, world.GetSize()) //-V807
192,697✔
532
    {
533
        MapNode& node = world.GetNodeInt(pt);
190,284✔
534
        node.seaId.reset();
190,284✔
535
        node.harborId.reset();
190,284✔
536
    }
537

538
    /// Determine all seas
539
    world.seas.clear();
27✔
540
    SeaId curSeaId(1);
27✔
541
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
192,697✔
542
    {
543
        // Point is not yet assigned a sea but should be
544
        if(!world.GetNode(pt).seaId && world.IsSeaPoint(pt))
190,284✔
545
        {
546
            const auto seaSize = MeasureSea(world, pt, curSeaId);
46✔
547
            world.seas.push_back(World::Sea(seaSize));
46✔
548
            curSeaId = curSeaId.next();
46✔
549
        }
550
    }
551

552
    /// Determine seas adjacent to the harbor places
553
    HarborId curHarborId(1);
27✔
554
    for(auto it = world.harborData.begin(); it != world.harborData.end();)
201✔
555
    {
556
        helpers::StrongIdVector<bool, SeaId> hasCoastAtSea(world.seas.size(), false);
348✔
557
        bool foundCoast = false;
174✔
558
        for(const auto dir : helpers::EnumRange<Direction>{})
2,784✔
559
        {
560
            SeaId seaId;
1,044✔
561
            // Skip point at NW as often there is no path from it if the harbor is north of an island
562
            if(dir != Direction::NorthWest)
1,044✔
563
            {
564
                seaId = world.GetSeaFromCoastalPoint(world.GetNeighbour(it->pos, dir));
870✔
565
                if(seaId)
870✔
566
                {
567
                    foundCoast = true;
226✔
568
                    // Only 1 coastal point per sea
569
                    if(hasCoastAtSea[seaId])
226✔
570
                        seaId.reset();
52✔
571
                    else
572
                        hasCoastAtSea[seaId] = true;
174✔
573
                }
574
            }
575
            it->seaIds[dir] = seaId;
1,044✔
576
        }
577
        if(!foundCoast)
174✔
578
        {
579
            LOG.write("Map Bug: Found harbor without coast at %1%. Removing!\n") % it->pos;
×
580
            it = world.harborData.erase(it);
×
581
        } else
582
        {
583
            world.GetNodeInt(it->pos).harborId = curHarborId;
174✔
584
            curHarborId = curHarborId.next();
174✔
585
            ++it;
174✔
586
        }
587
    }
588

589
    // Calculate the neighbors and distances
590
    CalcHarborPosNeighbors(world);
27✔
591

592
    // Validate
593
    for(const auto startHbId : helpers::idRange<HarborId>(world.harborData.size()))
201✔
594
    {
595
        const HarborPos& startHbPos = world.harborData[startHbId];
174✔
596
        for(const std::vector<HarborPos::Neighbor>& neighbors : startHbPos.neighbors)
1,218✔
597
        {
598
            for(const HarborPos::Neighbor& neighbor : neighbors)
1,664✔
599
            {
600
                if(world.CalcHarborDistance(neighbor.id, startHbId) != neighbor.distance)
620✔
601
                {
602
                    LOG.write("Bug: Harbor distance mismatch for harbors %1%->%2%: %3% != %4%\n") % startHbId
×
603
                      % neighbor.id % world.CalcHarborDistance(neighbor.id, startHbId) % neighbor.distance;
×
604
                    return false;
×
605
                }
606
            }
607
        }
608
    }
609
    return true;
27✔
610
}
611

612
// class for finding harbor neighbors
613
struct CalcHarborPosNeighborsNode
614
{
615
    CalcHarborPosNeighborsNode() = default; //-V730
616
    CalcHarborPosNeighborsNode(const MapPoint pt, unsigned distance) : pos(pt), distance(distance) {}
232,032✔
617

618
    MapPoint pos;
619
    unsigned distance;
620
};
621

622
/// Calculate the distance from each harbor to the others
623
void MapLoader::CalcHarborPosNeighbors(World& world)
27✔
624
{
625
    for(HarborPos& harbor : world.harborData)
201✔
626
    {
627
        for(const auto dir : helpers::EnumRange<ShipDirection>{})
2,784✔
628
            harbor.neighbors[dir].clear();
1,044✔
629
    }
630
    PathConditionShip shipPathChecker(world);
27✔
631

632
    // pre-calculate sea-points, as IsSeaPoint is rather expensive
633
    std::vector<int8_t> ptIsSeaPt(world.nodes.size()); //-V656
54✔
634

635
    RTTR_FOREACH_PT(MapPoint, world.GetSize())
192,697✔
636
    {
637
        if(shipPathChecker.IsNodeOk(pt))
190,284✔
638
            ptIsSeaPt[world.GetIdx(pt)] = -1;
64,106✔
639
    }
640

641
    // FIFO queue used for a BFS
642
    std::queue<CalcHarborPosNeighborsNode> todo_list;
54✔
643

644
    for(const auto startHbId : helpers::idRange<HarborId>(world.harborData.size()))
201✔
645
    {
646
        RTTR_Assert(todo_list.empty());
174✔
647

648
        // Copy sea points to working flags. Possible values are
649
        // -1 - sea point, not already visited
650
        // 0 - visited or no sea point
651
        // 1 - Coast to a harbor
652
        std::vector<int8_t> ptToVisitOrHb(ptIsSeaPt);
348✔
653

654
        helpers::StrongIdVector<bool, HarborId> hbFound(world.harborData.size(), false);
348✔
655
        // For each sea, store the coastal point indices and their harbor
656
        helpers::StrongIdVector<std::multimap<unsigned, HarborId>, SeaId> coastToHarborPerSea(world.seas.size());
348✔
657
        std::vector<MapPoint> ownCoastalPoints;
348✔
658

659
        // mark coastal points around harbors
660
        for(const auto otherHbId : helpers::idRange<HarborId>(world.harborData.size()))
1,600✔
661
        {
662
            for(const auto dir : helpers::EnumRange<Direction>{})
22,816✔
663
            {
664
                SeaId seaId = world.GetSeaId(otherHbId, dir);
8,556✔
665
                // No sea? -> Next
666
                if(!seaId)
8,556✔
667
                    continue;
7,130✔
668
                const MapPoint coastPt = world.GetNeighbour(world.GetHarborPoint(otherHbId), dir);
1,426✔
669
                // This should not be marked for visit
670
                unsigned idx = world.GetIdx(coastPt);
1,426✔
671
                RTTR_Assert(ptToVisitOrHb[idx] != -1);
1,426✔
672
                if(otherHbId == startHbId)
1,426✔
673
                {
674
                    // This is our start harbor. Add the coast points around it to our todo list.
675
                    ownCoastalPoints.push_back(coastPt);
174✔
676
                } else
677
                {
678
                    ptToVisitOrHb[idx] = 1;
1,252✔
679
                    coastToHarborPerSea[seaId].insert(std::make_pair(idx, otherHbId));
1,252✔
680
                }
681
            }
682
        }
683

684
        for(const MapPoint& ownCoastPt : ownCoastalPoints)
348✔
685
        {
686
            // Special case: Get all harbors that share the coast point with us
687
            SeaId seaId = world.GetSeaFromCoastalPoint(ownCoastPt);
174✔
688
            auto const coastToHbs = coastToHarborPerSea[seaId].equal_range(world.GetIdx(ownCoastPt));
174✔
689
            for(auto it = coastToHbs.first; it != coastToHbs.second; ++it)
180✔
690
            {
691
                ShipDirection shipDir = world.GetShipDir(ownCoastPt, ownCoastPt);
6✔
692
                world.harborData[startHbId].neighbors[shipDir].push_back(HarborPos::Neighbor(it->second, 0));
6✔
693
                hbFound[it->second] = true;
6✔
694
            }
695
            todo_list.push(CalcHarborPosNeighborsNode(ownCoastPt, 0));
174✔
696
        }
697

698
        while(!todo_list.empty()) // as long as there are sea points on our todo list...
232,206✔
699
        {
700
            CalcHarborPosNeighborsNode curNode = todo_list.front();
232,032✔
701
            todo_list.pop();
232,032✔
702

703
            for(const auto dir : helpers::EnumRange<Direction>{})
3,712,512✔
704
            {
705
                MapPoint curPt = world.GetNeighbour(curNode.pos, dir);
1,392,192✔
706
                unsigned idx = world.GetIdx(curPt);
1,392,192✔
707

708
                const int8_t ptValue = ptToVisitOrHb[idx];
1,392,192✔
709
                // Already visited
710
                if(ptValue == 0)
1,392,192✔
711
                    continue;
1,160,334✔
712
                // Not reachable
713
                if(!shipPathChecker.IsEdgeOk(curNode.pos, dir))
231,874✔
714
                    continue;
16✔
715

716
                if(ptValue > 0) // found harbor(s)
231,858✔
717
                {
718
                    ShipDirection shipDir = world.GetShipDir(world.harborData[startHbId].pos, curPt);
597✔
719
                    SeaId seaId = world.GetSeaFromCoastalPoint(curPt);
597✔
720
                    auto const coastToHbs = coastToHarborPerSea[seaId].equal_range(idx);
597✔
721
                    for(auto it = coastToHbs.first; it != coastToHbs.second; ++it)
1,217✔
722
                    {
723
                        const HarborId otherHbId = it->second;
620✔
724
                        if(hbFound[otherHbId])
620✔
725
                            continue;
6✔
726

727
                        hbFound[otherHbId] = true;
614✔
728
                        world.harborData[startHbId].neighbors[shipDir].push_back(
1,228✔
729
                          HarborPos::Neighbor(otherHbId, curNode.distance + 1));
614✔
730

731
                        // Make this the only coastal point of this harbor for this sea
732
                        HarborPos& otherHb = world.harborData[otherHbId];
614✔
733
                        RTTR_Assert(seaId);
614✔
734
                        for(const auto hbDir : helpers::EnumRange<Direction>{})
9,824✔
735
                        {
736
                            if(otherHb.seaIds[hbDir] == seaId && world.GetNeighbour(otherHb.pos, hbDir) != curPt)
3,684✔
737
                                otherHb.seaIds[hbDir].reset();
×
738
                        }
739
                    }
740
                }
741
                todo_list.push(CalcHarborPosNeighborsNode(curPt, curNode.distance + 1));
231,858✔
742
                ptToVisitOrHb[idx] = 0; // mark as visited, so we do not go here again
231,858✔
743
            }
744
        }
745
    }
746
}
27✔
747

748
/// Vermisst ein neues Weltmeer von einem Punkt aus, indem es alle mit diesem Punkt verbundenen
749
/// Wasserpunkte mit der gleichen ID belegt und die Anzahl zur�ckgibt
750
unsigned MapLoader::MeasureSea(World& world, const MapPoint start, SeaId seaId)
46✔
751
{
752
    // Breitensuche von diesem Punkt aus durchf�hren
753
    std::vector<bool> visited(world.GetWidth() * world.GetHeight(), false);
92✔
754
    std::queue<MapPoint> todo;
46✔
755

756
    todo.push(start);
46✔
757
    visited[world.GetIdx(start)] = true;
46✔
758

759
    // Count of nodes (including start node)
760
    unsigned count = 0;
46✔
761

762
    while(!todo.empty())
64,152✔
763
    {
764
        MapPoint p = todo.front();
64,106✔
765
        todo.pop();
64,106✔
766

767
        RTTR_Assert(visited[world.GetIdx(p)]);
64,106✔
768
        world.GetNodeInt(p).seaId = seaId;
64,106✔
769

770
        for(const MapPoint neighbourPt : world.GetNeighbours(p))
448,742✔
771
        {
772
            if(visited[world.GetIdx(neighbourPt)])
384,636✔
773
                continue;
310,153✔
774
            visited[world.GetIdx(neighbourPt)] = true;
74,483✔
775

776
            // Ist das dort auch ein Meerespunkt?
777
            if(world.IsSeaPoint(neighbourPt))
74,483✔
778
                todo.push(neighbourPt);
64,060✔
779
        }
780

781
        ++count;
64,106✔
782
    }
783

784
    return count;
92✔
785
}
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