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

Return-To-The-Roots / s25client / 22140547164

18 Feb 2026 12:54PM UTC coverage: 50.804% (-0.005%) from 50.809%
22140547164

Pull #1895

github

web-flow
Merge 2294b7ca4 into 7a79bd216
Pull Request #1895: Ships: Fix crash when doing expedition between adjacent harbor places

120 of 169 new or added lines in 20 files covered. (71.01%)

129 existing lines in 5 files now uncovered.

22810 of 44898 relevant lines covered (50.8%)

42709.3 hits per line

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

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

5
#include "noShip.h"
6
#include "EventManager.h"
7
#include "GameEvent.h"
8
#include "GamePlayer.h"
9
#include "GlobalGameSettings.h"
10
#include "Loader.h"
11
#include "SerializedGameData.h"
12
#include "Ware.h"
13
#include "addons/const_addons.h"
14
#include "buildings/nobHarborBuilding.h"
15
#include "figures/noFigure.h"
16
#include "figures/nofAttacker.h"
17
#include "helpers/EnumArray.h"
18
#include "helpers/containerUtils.h"
19
#include "helpers/pointerContainerUtils.h"
20
#include "network/GameClient.h"
21
#include "notifications/ExpeditionNote.h"
22
#include "notifications/ShipNote.h"
23
#include "ogl/glArchivItem_Bitmap.h"
24
#include "ogl/glArchivItem_Bitmap_Player.h"
25
#include "postSystem/ShipPostMsg.h"
26
#include "random/Random.h"
27
#include "world/GameWorld.h"
28
#include "gameData/BuildingConsts.h"
29
#include "gameData/ShipNames.h"
30
#include "s25util/Log.h"
31
#include <array>
32

33
/// Zeit zum Beladen des Schiffes
34
const unsigned LOADING_TIME = 200;
35
/// Zeit zum Entladen des Schiffes
36
const unsigned UNLOADING_TIME = 200;
37

38
/// Maximaler Weg, der zurückgelegt werden kann bei einem Erkundungsschiff
39
const unsigned MAX_EXPLORATION_EXPEDITION_DISTANCE = 100;
40
/// Zeit (in GF), die das Schiff bei der Erkundungs-Expedition jeweils an einem Punkt ankert
41
const unsigned EXPLORATION_EXPEDITION_WAITING_TIME = 300;
42

43
/// Positionen der Flaggen am Schiff für die 6 unterschiedlichen Richtungen jeweils
44
constexpr std::array<helpers::EnumArray<DrawPoint, Direction>, 2> SHIPS_FLAG_POS = {{
45
  {{{-3, -77}, {-6, -71}, {-3, -71}, {-1, -71}, {5, -63}, {-1, -70}}}, // Standing (sails down)
46
  {{{3, -70}, {0, -64}, {3, -64}, {-1, -70}, {5, -63}, {5, -63}}}      // Driving
47
}};
48

49
noShip::noShip(const MapPoint pos, const unsigned char player)
21✔
50
    : noMovable(NodalObjectType::Ship, pos), ownerId_(player), state(State::Idle), seaId_(0), goal_harborId(0),
51
      goal_dir(0), name(RANDOM_ELEMENT(ship_names[world->GetPlayer(player).nation])), curRouteIdx(0), lost(false),
21✔
52
      remaining_sea_attackers(0), home_harbor(0), covered_distance(0)
42✔
53
{
54
    // Meer ermitteln, auf dem dieses Schiff fährt
55
    for(const auto dir : helpers::EnumRange<Direction>{})
336✔
56
    {
57
        unsigned short seaId = world->GetNeighbourNode(pos, dir).seaId;
126✔
58
        if(seaId)
126✔
59
            this->seaId_ = seaId;
118✔
60
    }
61

62
    // Auf irgendeinem Meer müssen wir ja sein
63
    RTTR_Assert(seaId_ > 0);
21✔
64
}
21✔
65

66
noShip::~noShip() = default;
42✔
67

68
void noShip::Serialize(SerializedGameData& sgd) const
×
69
{
70
    noMovable::Serialize(sgd);
×
71

72
    sgd.PushUnsignedChar(ownerId_);
×
73
    sgd.PushEnum<uint8_t>(state);
×
NEW
74
    sgd.PushUnsignedShort(seaId_);
×
NEW
75
    sgd.PushUnsignedInt(goal_harborId);
×
76
    sgd.PushUnsignedChar(goal_dir);
×
77
    sgd.PushString(name);
×
78
    sgd.PushUnsignedInt(curRouteIdx);
×
79
    sgd.PushBool(lost);
×
80
    sgd.PushUnsignedInt(remaining_sea_attackers);
×
NEW
81
    sgd.PushUnsignedInt(home_harbor);
×
82
    sgd.PushUnsignedInt(covered_distance);
×
83
    helpers::pushContainer(sgd, route_);
×
84
    sgd.PushObjectContainer(figures);
×
85
    sgd.PushObjectContainer(wares, true);
×
86
}
×
87

88
noShip::noShip(SerializedGameData& sgd, const unsigned obj_id)
×
89
    : noMovable(sgd, obj_id), ownerId_(sgd.PopUnsignedChar()), state(sgd.Pop<State>()), seaId_(sgd.PopUnsignedShort()),
×
NEW
90
      goal_harborId(sgd.PopUnsignedInt()), goal_dir(sgd.PopUnsignedChar()),
×
91
      name(sgd.GetGameDataVersion() < 2 ? sgd.PopLongString() : sgd.PopString()), curRouteIdx(sgd.PopUnsignedInt()),
×
92
      route_(sgd.GetGameDataVersion() < 7 ? sgd.PopUnsignedInt() : 0), lost(sgd.PopBool()),
×
NEW
93
      remaining_sea_attackers(sgd.PopUnsignedInt()), home_harbor(sgd.PopUnsignedInt()),
×
94
      covered_distance(sgd.PopUnsignedInt())
×
95
{
96
    helpers::popContainer(sgd, route_, sgd.GetGameDataVersion() < 7);
×
97
    sgd.PopObjectContainer(figures);
×
98
    sgd.PopObjectContainer(wares, GO_Type::Ware);
×
99
}
×
100

101
void noShip::Destroy()
×
102
{
103
    RTTR_Assert(figures.empty());
×
104
    RTTR_Assert(wares.empty());
×
105
    world->GetNotifications().publish(ShipNote(ShipNote::Destroyed, ownerId_, pos));
×
106
    // Schiff wieder abmelden
107
    world->GetPlayer(ownerId_).RemoveShip(this);
×
108
}
×
109

110
void noShip::Draw(DrawPoint drawPt)
×
111
{
112
    unsigned flag_drawing_type = 1;
×
113

114
    // Sind wir verloren? Dann immer stehend zeichnen
115
    if(lost)
×
116
    {
117
        DrawFixed(drawPt, true);
×
118
        return;
×
119
    }
120

121
    switch(state)
×
122
    {
123
        default: break;
×
124
        case State::Idle:
×
125
        case State::SeaattackWaiting:
126
        {
127
            DrawFixed(drawPt, false);
×
128
            flag_drawing_type = 0;
×
129
        }
130
        break;
×
131

132
        case State::Gotoharbor:
×
133
        {
134
            DrawDriving(drawPt);
×
135
        }
136
        break;
×
137
        case State::ExpeditionLoading:
×
138
        case State::ExpeditionUnloading:
139
        case State::TransportLoading:
140
        case State::TransportUnloading:
141
        case State::SeaattackLoading:
142
        case State::SeaattackUnloading:
143
        case State::ExplorationexpeditionLoading:
144
        case State::ExplorationexpeditionUnloading:
145
        {
146
            DrawFixed(drawPt, false);
×
147
        }
148
        break;
×
149
        case State::ExplorationexpeditionWaiting:
×
150
        case State::ExpeditionWaiting:
151
        {
152
            DrawFixed(drawPt, true);
×
153
        }
154
        break;
×
155
        case State::ExpeditionDriving:
×
156
        case State::TransportDriving:
157
        case State::SeaattackDrivingToDestination:
158
        case State::ExplorationexpeditionDriving:
159
        {
160
            DrawDrivingWithWares(drawPt);
×
161
        }
162
        break;
×
163
        case State::SeaattackReturnDriving:
×
164
        {
165
            if(!figures.empty() || !wares.empty())
×
166
                DrawDrivingWithWares(drawPt);
×
167
            else
168
                DrawDriving(drawPt);
×
169
        }
170
        break;
×
171
    }
172

173
    LOADER.GetPlayerImage("boot_z", 40 + GAMECLIENT.GetGlobalAnimation(6, 1, 1, GetObjId()))
×
174
      ->DrawFull(drawPt + SHIPS_FLAG_POS[flag_drawing_type][GetCurMoveDir()], COLOR_WHITE,
×
175
                 world->GetPlayer(ownerId_).color);
×
176
    // Second, white flag, only when on expedition, always swinging in the opposite direction
177
    if(state >= State::ExpeditionLoading && state <= State::ExpeditionDriving)
×
178
        LOADER.GetPlayerImage("boot_z", 40 + GAMECLIENT.GetGlobalAnimation(6, 1, 1, GetObjId() + 4))
×
179
          ->DrawFull(drawPt + SHIPS_FLAG_POS[flag_drawing_type][GetCurMoveDir()]);
×
180
}
181

182
/// Zeichnet das Schiff stehend mit oder ohne Waren
183
void noShip::DrawFixed(DrawPoint drawPt, const bool draw_wares)
×
184
{
185
    LOADER.GetImageN("boot_z", rttr::enum_cast(GetCurMoveDir() + 3u) * 2 + 1)->DrawFull(drawPt, COLOR_SHADOW);
×
186
    LOADER.GetImageN("boot_z", rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt);
×
187

188
    if(draw_wares)
×
189
        /// Waren zeichnen
190
        LOADER.GetImageN("boot_z", 30 + rttr::enum_cast(GetCurMoveDir() + 3u))->DrawFull(drawPt);
×
191
}
×
192

193
/// Zeichnet normales Fahren auf dem Meer ohne irgendwelche Güter
194
void noShip::DrawDriving(DrawPoint& drawPt)
×
195
{
196
    // Interpolieren zwischen beiden Knotenpunkten
197
    drawPt += CalcWalkingRelative();
×
198

199
    LOADER.GetImageN("boot_z", 13 + rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt, COLOR_SHADOW);
×
200
    LOADER.GetImageN("boot_z", 12 + rttr::enum_cast(GetCurMoveDir() + 3u) * 2)->DrawFull(drawPt);
×
201
}
×
202

203
/// Zeichnet normales Fahren auf dem Meer mit Gütern
204
void noShip::DrawDrivingWithWares(DrawPoint& drawPt)
×
205
{
206
    DrawDriving(drawPt);
×
207
    /// Waren zeichnen
208
    LOADER.GetImageN("boot_z", 30 + rttr::enum_cast(GetCurMoveDir() + 3u))->DrawFull(drawPt);
×
209
}
×
210

211
void noShip::HandleEvent(const unsigned id)
409✔
212
{
213
    RTTR_Assert(current_ev);
409✔
214
    RTTR_Assert(current_ev->id == id);
409✔
215
    current_ev = nullptr;
409✔
216

217
    if(id == 0)
409✔
218
    {
219
        // Move event
220
        // neue Position einnehmen
221
        Walk();
378✔
222
        // entscheiden, was als nächstes zu tun ist
223
        Driven();
378✔
224
    } else
225
    {
226
        switch(state)
31✔
227
        {
228
            default:
×
229
                RTTR_Assert(false);
×
230
                LOG.write("Bug detected: Invalid state in ship event");
231
                break;
232
            case State::ExpeditionLoading:
2✔
233
                // Schiff ist nun bereit und Expedition kann beginnen
234
                state = State::ExpeditionWaiting;
2✔
235

236
                // Spieler benachrichtigen
237
                SendPostMessage(ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
2✔
238
                                                                        _("A ship is ready for an expedition."),
2✔
239
                                                                        PostCategory::Economy, *this));
2✔
240
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
2✔
241
                break;
2✔
242
            case State::ExplorationexpeditionLoading:
8✔
243
            case State::ExplorationexpeditionWaiting:
244
                // Schiff ist nun bereit und Expedition kann beginnen
245
                ContinueExplorationExpedition();
8✔
246
                break;
8✔
247
            case State::ExpeditionUnloading:
1✔
248
            {
249
                // Hafen herausfinden
250
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
1✔
251

252
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
1✔
253
                {
254
                    Inventory goods;
1✔
255
                    goods.goods[GoodType::Boards] = BUILDING_COSTS[BuildingType::HarborBuilding].boards;
1✔
256
                    goods.goods[GoodType::Stones] = BUILDING_COSTS[BuildingType::HarborBuilding].stones;
1✔
257
                    goods.people[Job::Builder] = 1;
1✔
258
                    static_cast<nobBaseWarehouse*>(hb)->AddGoods(goods, false);
1✔
259
                    // Wieder idlen und ggf. neuen Job suchen
260
                    StartIdling();
1✔
261
                    world->GetPlayer(ownerId_).GetJobForShip(*this);
1✔
262
                } else
263
                {
264
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
265
                    state = State::ExpeditionDriving;
×
266
                    HandleState_ExpeditionDriving();
×
267
                }
268
                break;
1✔
269
            }
270
            case State::ExplorationexpeditionUnloading:
3✔
271
            {
272
                // Hafen herausfinden
273
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
3✔
274

275
                unsigned old_visual_range = GetVisualRange();
3✔
276

277
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
3✔
278
                {
279
                    // Späher wieder entladen
280
                    Inventory goods;
3✔
281
                    goods.people[Job::Scout] = world->GetGGS().GetNumScoutsExpedition();
3✔
282
                    static_cast<nobBaseWarehouse*>(hb)->AddGoods(goods, false);
3✔
283
                    // Wieder idlen und ggf. neuen Job suchen
284
                    StartIdling();
3✔
285
                    world->GetPlayer(ownerId_).GetJobForShip(*this);
3✔
286
                } else
287
                {
288
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
289
                    state = State::ExplorationexpeditionDriving;
×
290
                    HandleState_ExplorationExpeditionDriving();
×
291
                }
292

293
                // Sichtbarkeiten neu berechnen
294
                world->RecalcVisibilitiesAroundPoint(pos, old_visual_range, ownerId_, nullptr);
3✔
295

296
                break;
3✔
297
            }
298
            case State::TransportLoading: StartTransport(); break;
4✔
299
            case State::TransportUnloading:
5✔
300
            case State::SeaattackUnloading:
301
            {
302
                // Hafen herausfinden
303
                RTTR_Assert(state == State::SeaattackUnloading || remaining_sea_attackers == 0);
5✔
304
                noBase* hb = goal_harborId ? world->GetNO(world->GetHarborPoint(goal_harborId)) : nullptr;
5✔
305
                if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
5✔
306
                {
307
                    static_cast<nobHarborBuilding*>(hb)->ReceiveGoodsFromShip(figures, wares);
5✔
308
                    figures.clear();
5✔
309
                    wares.clear();
5✔
310

311
                    state = State::TransportUnloading;
5✔
312
                    // Hafen bescheid sagen, dass er das Schiff nun nutzen kann
313
                    static_cast<nobHarborBuilding*>(hb)->ShipArrived(*this);
5✔
314

315
                    // Hafen hat keinen Job für uns?
316
                    if(state == State::TransportUnloading)
5✔
317
                    {
318
                        // Wieder idlen und ggf. neuen Job suchen
319
                        StartIdling();
5✔
320
                        world->GetPlayer(ownerId_).GetJobForShip(*this);
5✔
321
                    }
322
                } else
323
                {
324
                    // target harbor for unloading doesnt exist anymore -> set state to driving and handle the new state
325
                    if(state == State::TransportUnloading)
×
326
                        FindUnloadGoal(State::TransportDriving);
×
327
                    else
328
                        FindUnloadGoal(State::SeaattackReturnDriving);
×
329
                }
330
                break;
5✔
331
            }
332
            case State::SeaattackLoading: StartSeaAttack(); break;
2✔
333
            case State::SeaattackWaiting:
6✔
334
            {
335
                // Nächsten Soldaten nach draußen beordern
336
                if(figures.empty())
6✔
337
                    break;
2✔
338

339
                // Evtl. ist ein Angreifer schon fertig und wieder an Board gegangen
340
                // der darf dann natürlich nicht noch einmal raus, sonst kann die schöne Reise
341
                // böse enden
342
                if(static_cast<nofAttacker&>(*figures.front()).IsSeaAttackCompleted())
4✔
343
                    break;
×
344

345
                auto& attacker = world->AddFigure(pos, std::move(figures.front()));
4✔
346
                figures.pop_front();
4✔
347

348
                current_ev = GetEvMgr().AddEvent(this, 30, 1);
4✔
349
                static_cast<nofAttacker&>(attacker).StartAttackOnOtherIsland(pos, GetObjId());
4✔
350
                break;
4✔
351
            }
352
        }
353
    }
354
}
409✔
355

356
void noShip::StartDriving(const Direction dir)
382✔
357
{
358
    const std::array<unsigned, 5> SHIP_SPEEDS = {35, 25, 20, 10, 5};
382✔
359

360
    StartMoving(dir, SHIP_SPEEDS[world->GetGGS().getSelection(AddonId::SHIP_SPEED)]);
382✔
361
}
382✔
362

363
void noShip::Driven()
380✔
364
{
365
    MapPoint enemy_territory_discovered(MapPoint::Invalid());
380✔
366
    world->RecalcMovingVisibilities(pos, ownerId_, GetVisualRange(), GetCurMoveDir(), &enemy_territory_discovered);
380✔
367

368
    // Feindliches Territorium entdeckt?
369
    if(enemy_territory_discovered.isValid())
380✔
370
    {
371
        // Send message if necessary
372
        if(world->GetPlayer(ownerId_).ShipDiscoveredHostileTerritory(enemy_territory_discovered))
25✔
373
            SendPostMessage(ownerId_, std::make_unique<PostMsg>(GetEvMgr().GetCurrentGF(),
1✔
374
                                                                _("A ship disovered an enemy territory"),
1✔
375
                                                                PostCategory::Military, enemy_territory_discovered));
2✔
376
    }
377

378
    switch(state)
380✔
379
    {
380
        case State::Gotoharbor: HandleState_GoToHarbor(); break;
40✔
381
        case State::ExpeditionDriving: HandleState_ExpeditionDriving(); break;
42✔
382
        case State::ExplorationexpeditionDriving: HandleState_ExplorationExpeditionDriving(); break;
189✔
383
        case State::TransportDriving: HandleState_TransportDriving(); break;
64✔
384
        case State::SeaattackDrivingToDestination: HandleState_SeaAttackDriving(); break;
31✔
385
        case State::SeaattackReturnDriving: HandleState_SeaAttackReturn(); break;
14✔
386
        default: RTTR_Assert(false); break;
×
387
    }
388
}
380✔
389

390
bool noShip::IsLoading() const
11✔
391
{
392
    return state == State::ExpeditionLoading || state == State::ExplorationexpeditionLoading
11✔
393
           || state == State::TransportLoading || state == State::SeaattackLoading;
22✔
394
}
395

396
bool noShip::IsUnloading() const
100✔
397
{
398
    return state == State::ExpeditionUnloading || state == State::ExplorationexpeditionUnloading
100✔
399
           || state == State::TransportUnloading || state == State::SeaattackUnloading;
200✔
400
}
401

402
bool noShip::IsOnBoard(const noFigure& figure) const
×
403
{
404
    return helpers::containsPtr(figures, &figure);
×
405
}
406

407
/// Gibt Sichtradius dieses Schiffes zurück
408
unsigned noShip::GetVisualRange() const
4,869✔
409
{
410
    // Erkundungsschiffe haben einen größeren Sichtbereich
411
    if(state >= State::ExplorationexpeditionLoading && state <= State::ExplorationexpeditionDriving)
4,869✔
412
        return VISUALRANGE_EXPLORATION_SHIP;
3,975✔
413
    else
414
        return VISUALRANGE_SHIP;
894✔
415
}
416

417
/// Fährt zum Hafen, um dort eine Mission (Expedition) zu erledigen
418
void noShip::GoToHarbor(const nobHarborBuilding& hb, const std::vector<Direction>& route)
9✔
419
{
420
    RTTR_Assert(state == State::Idle); // otherwise we might carry wares etc
9✔
421
    RTTR_Assert(figures.empty());
9✔
422
    RTTR_Assert(wares.empty());
9✔
423
    RTTR_Assert(remaining_sea_attackers == 0);
9✔
424

425
    state = State::Gotoharbor;
9✔
426

427
    goal_harborId = world->GetNode(hb.GetPos()).harborId;
9✔
428
    RTTR_Assert(goal_harborId);
9✔
429

430
    // Route merken
431
    this->route_ = route;
9✔
432
    curRouteIdx = 1;
9✔
433

434
    // losfahren
435
    StartDriving(route[0]);
9✔
436
}
9✔
437

438
/// Startet eine Expedition
439
void noShip::StartExpedition(unsigned homeHarborId)
2✔
440
{
441
    /// Schiff wird "beladen", also kurze Zeit am Hafen stehen, bevor wir bereit sind
442
    state = State::ExpeditionLoading;
2✔
443
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
2✔
444
    RTTR_Assert(homeHarborId);
2✔
445
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
2✔
446
    home_harbor = homeHarborId;
2✔
447
    goal_harborId = homeHarborId; // This is current goal (commands are relative to current goal)
2✔
448
}
2✔
449

450
/// Startet eine Erkundungs-Expedition
451
void noShip::StartExplorationExpedition(unsigned homeHarborId)
4✔
452
{
453
    /// Schiff wird "beladen", also kurze Zeit am Hafen stehen, bevor wir bereit sind
454
    state = State::ExplorationexpeditionLoading;
4✔
455
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
4✔
456
    covered_distance = 0;
4✔
457
    RTTR_Assert(homeHarborId);
4✔
458
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
4✔
459
    home_harbor = homeHarborId;
4✔
460
    goal_harborId = homeHarborId; // This is current goal (commands are relative to current goal)
4✔
461
    // Sichtbarkeiten neu berechnen
462
    world->MakeVisibleAroundPoint(pos, GetVisualRange(), ownerId_);
4✔
463
}
4✔
464

465
/// Fährt weiter zu einem Hafen
466
noShip::Result noShip::DriveToHarbour()
242✔
467
{
468
    if(!goal_harborId)
242✔
469
        return Result::HarborDoesntExist;
3✔
470

471
    MapPoint goal(world->GetHarborPoint(goal_harborId));
239✔
472
    RTTR_Assert(goal.isValid());
239✔
473

474
    // Existiert der Hafen überhaupt noch?
475
    if(world->GetGOT(goal) != GO_Type::NobHarborbuilding)
239✔
476
        return Result::HarborDoesntExist;
×
477

478
    return DriveToHarbourPlace();
239✔
479
}
480

481
/// Fährt weiter zu Hafenbauplatz
482
noShip::Result noShip::DriveToHarbourPlace()
398✔
483
{
484
    if(goal_harborId == 0)
398✔
485
        return Result::HarborDoesntExist;
×
486

487
    // Sind wir schon da?
488
    if(curRouteIdx == route_.size())
398✔
489
        return Result::GoalReached;
25✔
490

491
    MapPoint goalRoutePos;
373✔
492

493
    // Route überprüfen
494
    if(!world->CheckShipRoute(pos, route_, curRouteIdx, &goalRoutePos))
373✔
495
    {
496
        // Route kann nicht mehr passiert werden --> neue Route suchen
497
        if(!world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr))
×
498
        {
499
            // Wieder keine gefunden -> raus
500
            return Result::NoRouteFound;
×
501
        }
502

503
        // Wir fangen bei der neuen Route wieder von vorne an
504
        curRouteIdx = 0;
×
505
    } else if(goalRoutePos != world->GetCoastalPoint(goal_harborId, seaId_))
373✔
506
    {
507
        // Our goal point of the current route has changed
508
        // If we are close to it, recalculate the route
509
        RTTR_Assert(route_.size() >= curRouteIdx);
×
NEW
510
        if(route_.size() - curRouteIdx < 10)
×
511
        {
512
            if(!world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr))
×
513
                // Keiner gefunden -> raus
514
                return Result::NoRouteFound;
×
515

516
            curRouteIdx = 0;
×
517
        }
518
    }
519

520
    RTTR_Assert(curRouteIdx < route_.size());
373✔
521
    StartDriving(route_[curRouteIdx++]);
373✔
522
    return Result::Driving;
373✔
523
}
524

525
unsigned noShip::GetCurrentHarbor() const
3✔
526
{
527
    RTTR_Assert(state == State::ExpeditionWaiting);
3✔
528
    return goal_harborId;
3✔
529
}
530

531
unsigned noShip::GetTargetHarbor() const
42✔
532
{
533
    return goal_harborId;
42✔
534
}
535

536
unsigned noShip::GetHomeHarbor() const
11✔
537
{
538
    return home_harbor;
11✔
539
}
540

541
/// Weist das Schiff an, in einer bestimmten Richtung die Expedition fortzusetzen
542
void noShip::ContinueExpedition(const ShipDirection dir)
5✔
543
{
544
    if(state != State::ExpeditionWaiting)
5✔
545
        return;
2✔
546

547
    // Nächsten Hafenpunkt in dieser Richtung suchen
548
    unsigned new_goal = world->GetNextFreeHarborPoint(pos, goal_harborId, dir, ownerId_);
3✔
549

550
    // Auch ein Ziel gefunden?
551
    if(!new_goal)
3✔
552
        return;
1✔
553

554
    // Versuchen, Weg zu finden
555
    if(!world->FindShipPathToHarbor(pos, new_goal, seaId_, &route_, nullptr))
2✔
556
        return;
×
557

558
    // Dann fahren wir da mal hin
559
    curRouteIdx = 0;
2✔
560
    goal_harborId = new_goal;
2✔
561
    state = State::ExpeditionDriving;
2✔
562

563
    HandleState_ExpeditionDriving();
2✔
564
}
565

566
/// Weist das Schiff an, eine Expedition abzubrechen (nur wenn es steht) und zum
567
/// Hafen zurückzukehren
568
void noShip::CancelExpedition()
3✔
569
{
570
    // Protect against double execution
571
    if(state != State::ExpeditionWaiting)
3✔
572
        return;
2✔
573

574
    // We are waiting. There should be no event!
575
    RTTR_Assert(!current_ev);
1✔
576

577
    // Zum Heimathafen zurückkehren
578
    // Oder sind wir schon dort?
579
    if(goal_harborId == home_harbor)
1✔
580
    {
581
        route_.clear();
×
582
        curRouteIdx = 0;
×
583
        state = State::ExpeditionDriving; // just in case the home harbor was destroyed
×
584
        HandleState_ExpeditionDriving();
×
585
    } else
586
    {
587
        state = State::ExpeditionDriving;
1✔
588
        goal_harborId = home_harbor;
1✔
589
        StartDrivingToHarborPlace();
1✔
590
        HandleState_ExpeditionDriving();
1✔
591
    }
592
}
593

594
/// Weist das Schiff an, an der aktuellen Position einen Hafen zu gründen
595
void noShip::FoundColony()
4✔
596
{
597
    if(state != State::ExpeditionWaiting)
4✔
598
        return;
2✔
599

600
    // Kolonie gründen
601
    if(world->FoundColony(goal_harborId, ownerId_, seaId_))
2✔
602
    {
603
        // For checks
604
        state = State::ExpeditionUnloading;
1✔
605
        // Dann idlen wir wieder
606
        StartIdling();
1✔
607
        // Neue Arbeit suchen
608
        world->GetPlayer(ownerId_).GetJobForShip(*this);
1✔
609
    } else // colony founding FAILED
610
        world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
1✔
611
}
612

613
void noShip::HandleState_GoToHarbor()
40✔
614
{
615
    // Hafen schon zerstört?
616
    if(goal_harborId == 0)
40✔
617
    {
618
        StartIdling();
1✔
619
        return;
1✔
620
    }
621

622
    Result res = DriveToHarbour();
39✔
623
    switch(res)
39✔
624
    {
625
        case Result::Driving: return; // Continue
32✔
626
        case Result::GoalReached:
7✔
627
        {
628
            MapPoint goal(world->GetHarborPoint(goal_harborId));
7✔
629
            RTTR_Assert(goal.isValid());
7✔
630
            // Go idle here (if harbor does not need it)
631
            StartIdling();
7✔
632
            // Hafen Bescheid sagen, dass wir da sind (falls er überhaupt noch existiert)
633
            noBase* hb = goal.isValid() ? world->GetNO(goal) : nullptr;
7✔
634
            if(hb && hb->GetGOT() == GO_Type::NobHarborbuilding)
7✔
635
                static_cast<nobHarborBuilding*>(hb)->ShipArrived(*this);
7✔
636
        }
637
        break;
7✔
638
        case Result::NoRouteFound:
×
639
        {
640
            MapPoint goal(world->GetHarborPoint(goal_harborId));
×
641
            RTTR_Assert(goal.isValid());
×
642
            // Dem Hafen Bescheid sagen
643
            world->GetSpecObj<nobHarborBuilding>(goal)->ShipLost(this);
×
644
            StartIdling();
×
645
        }
646
        break;
×
647
        case Result::HarborDoesntExist: StartIdling(); break;
×
648
    }
649
}
650

651
void noShip::HandleState_ExpeditionDriving()
45✔
652
{
653
    Result res;
654
    // Zum Heimathafen fahren?
655
    if(home_harbor == goal_harborId)
45✔
656
        res = DriveToHarbour();
15✔
657
    else
658
        res = DriveToHarbourPlace();
30✔
659

660
    switch(res)
45✔
661
    {
662
        case Result::Driving: return;
42✔
663
        case Result::GoalReached:
3✔
664
        {
665
            // Haben wir unsere Expedition beendet?
666
            if(home_harbor == goal_harborId)
3✔
667
            {
668
                // Sachen wieder in den Hafen verladen
669
                state = State::ExpeditionUnloading;
1✔
670
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
671
            } else
672
            {
673
                // Warten auf weitere Anweisungen
674
                state = State::ExpeditionWaiting;
2✔
675

676
                // Spieler benachrichtigen
677
                SendPostMessage(
4✔
678
                  ownerId_, std::make_unique<ShipPostMsg>(GetEvMgr().GetCurrentGF(),
6✔
679
                                                          _("A ship has reached the destination of its expedition."),
2✔
680
                                                          PostCategory::Economy, *this));
2✔
681
                world->GetNotifications().publish(ExpeditionNote(ExpeditionNote::Waiting, ownerId_, pos));
2✔
682
            }
683
        }
684
        break;
3✔
685
        case Result::NoRouteFound:
×
686
        case Result::HarborDoesntExist: // should only happen when an expedition is cancelled and the home harbor no
687
                                        // longer exists
688
        {
NEW
689
            if(home_harbor != goal_harborId && home_harbor != 0)
×
690
            {
691
                // Try to go back
692
                goal_harborId = home_harbor;
×
693
                HandleState_ExpeditionDriving();
×
694
            } else
695
                FindUnloadGoal(State::ExpeditionDriving); // Unload anywhere!
×
696
        }
697
        break;
×
698
    }
699
}
700

701
void noShip::HandleState_ExplorationExpeditionDriving()
197✔
702
{
703
    Result res;
704
    // Zum Heimathafen fahren?
705
    if(home_harbor == goal_harborId)
197✔
706
        res = DriveToHarbour();
101✔
707
    else
708
        res = DriveToHarbourPlace();
96✔
709

710
    switch(res)
197✔
711
    {
712
        case Result::Driving: return;
189✔
713
        case Result::GoalReached:
7✔
714
        {
715
            // Haben wir unsere Expedition beendet?
716
            if(home_harbor == goal_harborId)
7✔
717
            {
718
                // Dann sind wir fertig -> wieder entladen
719
                state = State::ExplorationexpeditionUnloading;
3✔
720
                current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
3✔
721
            } else
722
            {
723
                // Strecke, die wir gefahren sind, draufaddieren
724
                covered_distance += route_.size();
4✔
725
                // Erstmal kurz ausruhen an diesem Punkt und das Rohr ausfahren, um ein bisschen
726
                // auf der Insel zu gucken
727
                state = State::ExplorationexpeditionWaiting;
4✔
728
                current_ev = GetEvMgr().AddEvent(this, EXPLORATION_EXPEDITION_WAITING_TIME, 1);
4✔
729
            }
730
        }
731
        break;
7✔
732
        case Result::NoRouteFound:
1✔
733
        case Result::HarborDoesntExist:
734
            if(home_harbor != goal_harborId && home_harbor != 0)
1✔
735
            {
736
                // Try to go back
737
                goal_harborId = home_harbor;
×
738
                HandleState_ExplorationExpeditionDriving();
×
739
            } else
740
                FindUnloadGoal(State::ExplorationexpeditionDriving); // Unload anywhere!
1✔
741
            break;
1✔
742
    }
743
}
744

745
void noShip::HandleState_TransportDriving()
71✔
746
{
747
    Result res = DriveToHarbour();
71✔
748
    switch(res)
71✔
749
    {
750
        case Result::Driving: return;
64✔
751
        case Result::GoalReached:
5✔
752
        {
753
            // Waren abladen, dafür wieder kurze Zeit hier ankern
754
            state = State::TransportUnloading;
5✔
755
            current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
5✔
756
        }
757
        break;
5✔
758
        case Result::NoRouteFound:
2✔
759
        case Result::HarborDoesntExist:
760
        {
761
            RTTR_Assert(!remaining_sea_attackers);
2✔
762
            // Kein Hafen mehr?
763
            // Dann müssen alle Leute ihren Heimatgebäuden Bescheid geben, dass sie
764
            // nun nicht mehr kommen
765
            // Das Schiff muss einen Notlandeplatz ansteuern
766
            // LOG.write(("transport goal harbor doesnt exist player %i state %i pos %u,%u \n",player,state,x,y);
767
            for(auto& figure : figures)
2✔
768
            {
769
                figure->Abrogate();
×
770
                figure->SetGoalTonullptr();
×
771
            }
772

773
            for(auto& ware : wares)
4✔
774
            {
775
                ware->NotifyGoalAboutLostWare();
2✔
776
            }
777

778
            FindUnloadGoal(State::TransportDriving);
2✔
779
        }
780
        break;
2✔
781
    }
782
}
783

784
void noShip::HandleState_SeaAttackDriving()
33✔
785
{
786
    Result res = DriveToHarbourPlace();
33✔
787
    switch(res)
33✔
788
    {
789
        case Result::Driving: return; // OK
31✔
790
        case Result::GoalReached:
2✔
791
            // Ziel erreicht, dann stellen wir das Schiff hier hin und die Soldaten laufen nacheinander raus zum Ziel
792
            state = State::SeaattackWaiting;
2✔
793
            current_ev = GetEvMgr().AddEvent(this, 15, 1);
2✔
794
            remaining_sea_attackers = figures.size();
2✔
795
            break;
2✔
796
        case Result::NoRouteFound:
×
797
        case Result::HarborDoesntExist:
798
            RTTR_Assert(goal_harborId != home_harbor || home_harbor == 0);
×
799
            AbortSeaAttack();
×
800
            break;
×
801
    }
802
}
803

804
void noShip::HandleState_SeaAttackReturn()
16✔
805
{
806
    Result res = DriveToHarbour();
16✔
807
    switch(res)
16✔
808
    {
809
        case Result::Driving: return;
15✔
810
        case Result::GoalReached:
1✔
811
            // Entladen
812
            state = State::SeaattackUnloading;
1✔
813
            this->current_ev = GetEvMgr().AddEvent(this, UNLOADING_TIME, 1);
1✔
814
            break;
1✔
815
        case Result::HarborDoesntExist:
×
816
        case Result::NoRouteFound: AbortSeaAttack(); break;
×
817
    }
818
}
819

820
/// Gibt zurück, ob das Schiff jetzt in der Lage wäre, eine Kolonie zu gründen
821
bool noShip::IsAbleToFoundColony() const
×
822
{
823
    // Warten wir gerade?
NEW
824
    if(state == State::ExpeditionWaiting)
×
825
    {
826
        // We must always have a goal harbor
827
        RTTR_Assert(goal_harborId);
×
828
        // Ist der Punkt, an dem wir gerade ankern, noch frei?
829
        if(world->IsHarborPointFree(goal_harborId, ownerId_))
×
830
            return true;
×
831
    }
832

833
    return false;
×
834
}
835

836
/// Gibt zurück, ob das Schiff einen bestimmten Hafen ansteuert
837
bool noShip::IsGoingToHarbor(const nobHarborBuilding& hb) const
80✔
838
{
839
    if(goal_harborId != hb.GetHarborPosID())
80✔
840
        return false;
69✔
841
    // Explicit switch to check all states
842
    switch(state)
11✔
843
    {
844
        case State::Idle:
1✔
845
        case State::ExpeditionLoading:
846
        case State::ExpeditionUnloading:
847
        case State::ExpeditionWaiting:
848
        case State::ExpeditionDriving:
849
        case State::ExplorationexpeditionLoading:
850
        case State::ExplorationexpeditionUnloading:
851
        case State::ExplorationexpeditionWaiting:
852
        case State::ExplorationexpeditionDriving:
853
        case State::SeaattackLoading:
854
        case State::SeaattackDrivingToDestination:
855
        case State::SeaattackWaiting: return false;
1✔
856
        case State::Gotoharbor:
10✔
857
        case State::TransportDriving:       // Driving to this harbor
858
        case State::TransportLoading:       // Loading at home harbor and going to goal
859
        case State::TransportUnloading:     // Unloading at this harbor
860
        case State::SeaattackUnloading:     // Unloading attackers at this harbor
861
        case State::SeaattackReturnDriving: // Returning attackers to this harbor
862
            return true;
10✔
863
    }
864
    RTTR_Assert(false);
×
865
    return false;
866
}
867

868
/// Belädt das Schiff mit Waren und Figuren, um eine Transportfahrt zu starten
869
void noShip::PrepareTransport(unsigned homeHarborId, MapPoint goal, std::list<std::unique_ptr<noFigure>> figures,
5✔
870
                              std::list<std::unique_ptr<Ware>> wares)
871
{
872
    RTTR_Assert(homeHarborId);
5✔
873
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
5✔
874
    this->home_harbor = homeHarborId;
5✔
875
    // ID von Zielhafen herausfinden
876
    noBase* nb = world->GetNO(goal);
5✔
877
    RTTR_Assert(nb->GetGOT() == GO_Type::NobHarborbuilding);
5✔
878
    this->goal_harborId = static_cast<nobHarborBuilding*>(nb)->GetHarborPosID();
5✔
879

880
    this->figures = std::move(figures);
5✔
881
    this->wares = std::move(wares);
5✔
882

883
    state = State::TransportLoading;
5✔
884
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
5✔
885
}
5✔
886

887
/// Belädt das Schiff mit Schiffs-Angreifern
888
void noShip::PrepareSeaAttack(unsigned homeHarborId, MapPoint goal, std::vector<std::unique_ptr<nofAttacker>> attackers)
2✔
889
{
890
    // Heimathafen merken
891
    RTTR_Assert(homeHarborId);
2✔
892
    RTTR_Assert(pos == world->GetCoastalPoint(homeHarborId, seaId_));
2✔
893
    home_harbor = homeHarborId;
2✔
894
    goal_harborId = world->GetHarborPointID(goal);
2✔
895
    RTTR_Assert(goal_harborId);
2✔
896
    figures.clear();
2✔
897
    for(auto& attacker : attackers)
6✔
898
    {
899
        attacker->StartShipJourney();
4✔
900
        attacker->SeaAttackStarted();
4✔
901
        figures.push_back(std::move(attacker));
4✔
902
    }
903
    state = State::SeaattackLoading;
2✔
904
    current_ev = GetEvMgr().AddEvent(this, LOADING_TIME, 1);
2✔
905
}
2✔
906

907
/// Startet Schiffs-Angreiff
908
void noShip::StartSeaAttack()
2✔
909
{
910
    state = State::SeaattackDrivingToDestination;
2✔
911
    StartDrivingToHarborPlace();
2✔
912
    HandleState_SeaAttackDriving();
2✔
913
}
2✔
914

915
void noShip::AbortSeaAttack()
×
916
{
NEW
917
    RTTR_Assert(state != State::SeaattackWaiting); // figures are not aboard if this fails!
×
NEW
918
    RTTR_Assert(remaining_sea_attackers == 0);     // Some soldiers are still not aboard
×
919

920
    if((state == State::SeaattackLoading || state == State::SeaattackDrivingToDestination)
×
921
       && goal_harborId != home_harbor && home_harbor != 0)
×
922
    {
923
        // We did not start the attack yet and we can (possibly) go back to our home harbor
924
        // -> tell the soldiers we go back (like after an attack)
925
        goal_harborId = home_harbor;
×
926
        for(auto& figure : figures)
×
927
            checkedCast<nofAttacker*>(figure.get())->StartReturnViaShip(*this);
×
928
        if(state == State::SeaattackLoading)
×
929
        {
930
            // We are still loading (loading event must be active)
931
            // -> Use it to unload
932
            RTTR_Assert(current_ev);
×
933
            state = State::SeaattackUnloading;
×
934
        } else
935
        {
936
            // Else start driving back
937
            state = State::SeaattackReturnDriving;
×
938
            HandleState_SeaAttackReturn();
×
939
        }
×
940
    } else
941
    {
942
        // attack failed and we cannot go back to our home harbor
943
        // -> Tell figures that they won't go to their planned destination
944
        for(auto& figure : figures)
×
945
            checkedCast<nofAttacker*>(figure.get())->CancelSeaAttack();
×
946

947
        if(state == State::SeaattackLoading)
×
948
        {
949
            // Abort loading
950
            RTTR_Assert(current_ev);
×
951
            GetEvMgr().RemoveEvent(current_ev);
×
952
        }
953

954
        // Das Schiff muss einen Notlandeplatz ansteuern
955
        FindUnloadGoal(State::SeaattackReturnDriving);
×
956
    }
957
}
×
958

959
/// Fängt an zu einem Hafen zu fahren (berechnet Route usw.)
960
void noShip::StartDrivingToHarborPlace()
19✔
961
{
962
    if(!goal_harborId)
19✔
963
    {
964
        route_.clear();
1✔
965
        curRouteIdx = 0;
1✔
966
        return;
1✔
967
    }
968

969
    MapPoint coastalPos = world->GetCoastalPoint(goal_harborId, seaId_);
18✔
970
    if(pos == coastalPos)
18✔
971
        route_.clear();
1✔
972
    else
973
    {
974
        bool routeFound;
975
        // Use upper bound to distance by checking the distance between the harbors if we still have and are at the home
976
        // harbor
977
        if(home_harbor && pos == world->GetCoastalPoint(home_harbor, seaId_))
17✔
978
        {
979
            // Use the maximum distance between the harbors plus 6 fields
980
            unsigned maxDistance = world->CalcHarborDistance(home_harbor, goal_harborId) + 6;
8✔
981
            routeFound = world->FindShipPath(pos, coastalPos, maxDistance, &route_, nullptr);
8✔
982
        } else
983
            routeFound = world->FindShipPathToHarbor(pos, goal_harborId, seaId_, &route_, nullptr);
9✔
984
        if(!routeFound)
17✔
985
        {
986
            // todo
987
            RTTR_Assert(false);
×
988
            LOG.write("WARNING: Bug detected (GF: %u). Please report this with the savegame and "
989
                      "replay.\nnoShip::StartDrivingToHarborPlace: Schiff hat keinen Weg gefunden!\nplayer %i state %i "
990
                      "pos %u,%u goal "
991
                      "coastal %u,%u goal-id %i goalpos %u,%u \n")
992
              % GetEvMgr().GetCurrentGF() % unsigned(ownerId_) % unsigned(state) % pos.x % pos.y % coastalPos.x
993
              % coastalPos.y % goal_harborId % world->GetHarborPoint(goal_harborId).x
994
              % world->GetHarborPoint(goal_harborId).y;
995
            goal_harborId = 0;
996
            return;
997
        }
998
    }
999
    curRouteIdx = 0;
18✔
1000
}
1001

1002
/// Startet die eigentliche Transportaktion, nachdem das Schiff beladen wurde
1003
void noShip::StartTransport()
4✔
1004
{
1005
    state = State::TransportDriving;
4✔
1006

1007
    StartDrivingToHarborPlace();
4✔
1008
    // Einfach weiterfahren
1009
    HandleState_TransportDriving();
4✔
1010
}
4✔
1011

1012
void noShip::FindUnloadGoal(State newState)
5✔
1013
{
1014
    state = newState;
5✔
1015
    // Das Schiff muss einen Notlandeplatz ansteuern
1016
    // Neuen Hafen suchen
1017
    if(world->GetPlayer(ownerId_).FindHarborForUnloading(this, pos, &goal_harborId, &route_, nullptr))
5✔
1018
    {
1019
        curRouteIdx = 0;
3✔
1020
        home_harbor = goal_harborId; // To allow unloading here
3✔
1021
        if(state == State::ExpeditionDriving)
3✔
1022
            HandleState_ExpeditionDriving();
×
1023
        else if(state == State::ExplorationexpeditionDriving)
3✔
1024
            HandleState_ExplorationExpeditionDriving();
×
1025
        else if(state == State::TransportDriving)
3✔
1026
            HandleState_TransportDriving();
3✔
1027
        else if(state == State::SeaattackReturnDriving)
×
1028
            HandleState_SeaAttackReturn();
×
1029
        else
1030
        {
1031
            RTTR_Assert(false);
×
1032
            LOG.write("Bug detected: Invalid state for FindUnloadGoal");
1033
            FindUnloadGoal(State::TransportDriving);
1034
        }
1035
    } else
1036
    {
1037
        // Ansonsten als verloren markieren, damit uns später Bescheid gesagt wird
1038
        // wenn es einen neuen Hafen gibt
1039
        home_harbor = goal_harborId = 0;
2✔
1040
        lost = true;
2✔
1041
    }
1042
}
5✔
1043

1044
/// Sagt dem Schiff, das ein bestimmter Hafen zerstört wurde
1045
void noShip::HarborDestroyed(nobHarborBuilding* hb)
12✔
1046
{
1047
    const unsigned destroyedHarborId = hb->GetHarborPosID();
12✔
1048
    // Almost every case of a destroyed harbor is handled when the ships event fires (the handler detects the destroyed
1049
    // harbor) So mostly we just reset the corresponding id
1050

1051
    if(destroyedHarborId == home_harbor)
12✔
1052
        home_harbor = 0;
4✔
1053

1054
    // Ist unser Ziel betroffen?
1055
    if(destroyedHarborId != goal_harborId)
12✔
1056
    {
1057
        return;
5✔
1058
    }
1059

1060
    State oldState = state;
7✔
1061

1062
    switch(state)
7✔
1063
    {
1064
        default:
4✔
1065
            // Just reset goal, but not for expeditions
1066
            if(!IsOnExpedition() && !IsOnExplorationExpedition())
4✔
1067
            {
1068
                goal_harborId = 0;
3✔
1069
            }
1070
            return; // Skip the rest
4✔
1071
        case State::TransportLoading:
3✔
1072
        case State::TransportUnloading:
1073
            // Tell wares and figures that they won't reach their goal
1074
            for(auto& figure : figures)
3✔
1075
            {
1076
                figure->Abrogate();
×
1077
                figure->SetGoalTonullptr();
×
1078
            }
1079
            for(auto& ware : wares)
6✔
1080
            {
1081
                // Notify goal only, if it is not the destroyed harbor. It already knows about that ;)
1082
                if(ware->GetGoal() != hb)
3✔
1083
                    ware->NotifyGoalAboutLostWare();
×
1084
                else
1085
                    ware->SetGoal(nullptr);
3✔
1086
            }
1087
            break;
3✔
1088
        case State::SeaattackLoading:
×
1089
            // We could also just set the goal harbor id to 0 but this can reuse the event
1090
            AbortSeaAttack();
×
1091
            break;
×
NEW
1092
        case State::SeaattackUnloading: break;
×
1093
    }
1094

1095
    // Are we currently getting the wares?
1096
    if(oldState == State::TransportLoading)
3✔
1097
    {
1098
        RTTR_Assert(current_ev);
1✔
1099
        if(home_harbor)
1✔
1100
        {
1101
            // Then save us some time and unload immediately
1102
            // goal is now the start harbor (if it still exists)
1103
            goal_harborId = home_harbor;
1✔
1104
            state = State::TransportUnloading;
1✔
1105
        } else
1106
        {
1107
            GetEvMgr().RemoveEvent(current_ev);
×
1108
            FindUnloadGoal(State::TransportDriving);
×
1109
        }
1110
    } else if(oldState == State::TransportUnloading || oldState == State::SeaattackUnloading)
2✔
1111
    {
1112
        // Remove current unload event
1113
        GetEvMgr().RemoveEvent(current_ev);
2✔
1114

1115
        if(oldState == State::SeaattackUnloading)
2✔
1116
            AbortSeaAttack();
×
1117
        else
1118
            FindUnloadGoal(State::TransportDriving);
2✔
1119
    }
1120
}
1121

1122
/// Fängt an mit idlen und setzt nötigen Sachen auf nullptr
1123
void noShip::StartIdling()
18✔
1124
{
1125
    // If those are not empty, then we are lost, not idling!
1126
    RTTR_Assert(figures.empty());
18✔
1127
    RTTR_Assert(wares.empty());
18✔
1128
    RTTR_Assert(remaining_sea_attackers == 0);
18✔
1129
    // Implicit contained wares/figures on expeditions
1130
    RTTR_Assert(!IsOnExplorationExpedition() || state == State::ExplorationexpeditionUnloading);
18✔
1131
    RTTR_Assert(!IsOnExpedition() || state == State::ExpeditionUnloading);
18✔
1132

1133
    home_harbor = 0;
18✔
1134
    goal_harborId = 0;
18✔
1135
    state = State::Idle;
18✔
1136
}
18✔
1137

1138
/// Sagt Bescheid, dass ein Schiffsangreifer nicht mehr mit nach Hause fahren will
1139
void noShip::SeaAttackerWishesNoReturn()
4✔
1140
{
1141
    RTTR_Assert(remaining_sea_attackers);
4✔
1142
    RTTR_Assert(state == State::SeaattackWaiting);
4✔
1143

1144
    --remaining_sea_attackers;
4✔
1145
    // Alle Soldaten an Bord
1146
    if(remaining_sea_attackers == 0)
4✔
1147
    {
1148
        // Andere Events ggf. erstmal abmelden
1149
        GetEvMgr().RemoveEvent(current_ev);
2✔
1150
        if(!figures.empty())
2✔
1151
        {
1152
            // Go back home. Note: home_harbor can be 0 if it was destroyed, allow this and let the state handlers
1153
            // handle that case later
1154
            goal_harborId = home_harbor;
2✔
1155
            state = State::SeaattackReturnDriving;
2✔
1156
            StartDrivingToHarborPlace();
2✔
1157
            HandleState_SeaAttackReturn();
2✔
1158
        } else
1159
        {
1160
            // Wenn keine Soldaten mehr da sind können wir auch erstmal idlen
1161
            StartIdling();
×
1162
            world->GetPlayer(ownerId_).GetJobForShip(*this);
×
1163
        }
1164
    }
1165
}
4✔
1166

1167
/// Schiffs-Angreifer sind nach dem Angriff wieder zurückgekehrt
1168
void noShip::AddReturnedAttacker(std::unique_ptr<nofAttacker> attacker)
4✔
1169
{
1170
    RTTR_Assert(!helpers::containsPtr(figures, attacker.get()));
4✔
1171

1172
    figures.push_back(std::move(attacker));
4✔
1173
    // Nun brauchen wir quasi einen Angreifer weniger
1174
    SeaAttackerWishesNoReturn();
4✔
1175
}
4✔
1176

1177
/// Weist das Schiff an, seine Erkundungs-Expedition fortzusetzen
1178
void noShip::ContinueExplorationExpedition()
8✔
1179
{
1180
    // Sind wir schon über unserem Limit, also zu weit gefahren
1181
    if(covered_distance >= MAX_EXPLORATION_EXPEDITION_DISTANCE)
8✔
1182
    {
1183
        // Dann steuern wir unseren Heimathafen an!
1184
        goal_harborId = home_harbor;
×
1185
    } else
1186
    {
1187
        // Find the next harbor spot to explore
1188
        std::vector<unsigned> hps;
16✔
1189
        if(goal_harborId)
8✔
1190
            hps = world->GetUnexploredHarborPoints(goal_harborId, seaId_, GetPlayerId());
8✔
1191

1192
        // No possible spots? -> Go home
1193
        if(hps.empty())
8✔
1194
            goal_harborId = home_harbor;
4✔
1195
        else
1196
        {
1197
            // Choose one randomly
1198
            goal_harborId = RANDOM_ELEMENT(hps);
4✔
1199
        }
1200
    }
1201

1202
    StartDrivingToHarborPlace();
8✔
1203
    state = State::ExplorationexpeditionDriving;
8✔
1204
    HandleState_ExplorationExpeditionDriving();
8✔
1205
}
8✔
1206

1207
/// Sagt dem Schiff, dass ein neuer Hafen erbaut wurde
1208
void noShip::NewHarborBuilt(nobHarborBuilding* hb)
11✔
1209
{
1210
    if(!lost)
11✔
1211
        return;
9✔
1212
    // Liegt der Hafen auch am Meer von diesem Schiff?
1213
    if(!world->IsHarborAtSea(hb->GetHarborPosID(), seaId_))
2✔
1214
        return;
×
1215

1216
    // LOG.write(("lost ship has new goal harbor player %i state %i pos %u,%u \n",player,state,x,y);
1217
    home_harbor = goal_harborId = hb->GetHarborPosID();
2✔
1218
    lost = false;
2✔
1219

1220
    StartDrivingToHarborPlace();
2✔
1221

1222
    switch(state)
2✔
1223
    {
1224
        case State::ExplorationexpeditionDriving:
2✔
1225
        case State::ExpeditionDriving:
1226
        case State::TransportDriving:
1227
        case State::SeaattackReturnDriving: Driven(); break;
2✔
1228
        default:
×
1229
            RTTR_Assert(false); // Das darf eigentlich nicht passieren
×
1230
            LOG.write("Bug detected: Invalid state in NewHarborBuilt");
1231
            break;
1232
    }
1233
}
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