summaryrefslogtreecommitdiffhomepage
path: root/Stars45/CampaignSaveGame.cpp
blob: 29f87f82a88d305f89449e5d2a9704b656c603e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2022, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.

    AUTHOR:       John DiCamillo


    OVERVIEW
    ========
    CampaignSaveGame contains the logic needed to save and load
    campaign games in progress.
*/

#include "MemDebug.h"
#include "CampaignSaveGame.h"
#include "Campaign.h"
#include "Combatant.h"
#include "CombatAction.h"
#include "CombatEvent.h"
#include "CombatGroup.h"
#include "CombatUnit.h"
#include "CombatZone.h"
#include "Galaxy.h"
#include "Mission.h"
#include "StarSystem.h"
#include "Player.h"

#include "Game.h"
#include "DataLoader.h"
#include "ParseUtil.h"
#include "FormatUtil.h"

static const char* SAVE_DIR = "SaveGame";

// +--------------------------------------------------------------------+

CampaignSaveGame::CampaignSaveGame(Campaign* c)
    : campaign(c)
{ }

// +--------------------------------------------------------------------+

CampaignSaveGame::~CampaignSaveGame()
{ }

// +--------------------------------------------------------------------+

Text
CampaignSaveGame::GetSaveDirectory()
{
    return GetSaveDirectory(Player::GetCurrentPlayer());
}

Text
CampaignSaveGame::GetSaveDirectory(Player* player)
{
    if (player) {
        char save_dir[32];
        sprintf_s(save_dir, "%s/%02d", SAVE_DIR, player->Identity());

        return save_dir;
    }

    return SAVE_DIR;
}

void
CampaignSaveGame::CreateSaveDirectory()
{
    HANDLE hDir = CreateFile(SAVE_DIR, 0, 0, 0, OPEN_EXISTING, 0, 0);

    if (hDir == INVALID_HANDLE_VALUE)
    CreateDirectory(SAVE_DIR, NULL);
    else
    CloseHandle(hDir);

    hDir = CreateFile(GetSaveDirectory(), 0, 0, 0, OPEN_EXISTING, 0, 0);

    if (hDir == INVALID_HANDLE_VALUE)
    CreateDirectory(GetSaveDirectory(), NULL);
    else
    CloseHandle(hDir);
}

// +--------------------------------------------------------------------+

static char multiline[4096];
static char* FormatMultiLine(const char* s)
{
    int   i = 4095;
    char* p = multiline;

    while (*s && i > 0) {
        if (*s == '\n') {
            *p++ = '\\';
            *p++ = 'n';
            s++;
            i -= 2;
        }
        else if (*s == '"') {
            *p++ = '\\';
            *p++ = '"';
            s++;
            i -= 2;
        }
        else {
            *p++ = *s++;
            i--;
        }
    }

    *p = 0;
    return multiline;
}

static char* ParseMultiLine(const char* s)
{
    int   i = 4095;
    char* p = multiline;

    while (*s && i > 0) {
        if (*s == '\\') {
            s++;
            if (*s == 'n') {
                *p++ = '\n';
#pragma warning(suppress: 6269)
                *s++;
                i--;
            }
            else if (*s == '"') {
                *p++ = '"';
#pragma warning(suppress: 6269)
                *s++;
                i--;
            }
            else {
                *p++ = *s++;
                i--;
            }
        }
        else {
            *p++ = *s++;
            i--;
        }
    }

    *p = 0;
    return multiline;
}

void
CampaignSaveGame::Load(const char* filename)
{
    Print("-------------------------\nLOADING SAVEGAME (%s).\n", filename);
    campaign = 0;

    if (!filename || !filename[0]) return;

    DataLoader* loader = DataLoader::GetLoader();
    bool use_file_sys = loader->IsFileSystemEnabled();
    loader->UseFileSystem(true);
    loader->SetDataPath(GetSaveDirectory() + "/");

    BYTE* block;
    loader->LoadBuffer(filename, block, true);
    loader->UseFileSystem(use_file_sys);

    Sleep(10);

    Parser parser(new(__FILE__,__LINE__) BlockReader((const char*) block));
    Term*  term = parser.ParseTerm();

    if (!term) {
        Print("ERROR: could not parse save game '%s'\n", filename);
        loader->SetDataPath(0);
        return;
    }
    else {
        TermText* file_type = term->isText();
        if (!file_type || file_type->value() != "SAVEGAME") {
            Print("ERROR: invalid save game file '%s'\n", filename);
            term->print(10);
            loader->SetDataPath(0);
            delete term;
            return;
        }
    }

    int    grp_iff  = 0;
    int    grp_type = 0;
    int    grp_id   = 0;
    int    status   = 0;
    double baseTime = 0;
    double time     = 0;
    Text   unit;
    Text   sitrep;
    Text   orders;

    do {
        Sleep(5);
        delete term; term = 0;
        term = parser.ParseTerm();

        if (term) {
            TermDef* def = term->isDef();
            if (def) {
                if (def->name()->value() == "campaign") {
                    Text cname;
                    int  cid=0;

                    if (def->term()) {
                        if (def->term()->isText())
                        cname = def->term()->isText()->value();
                        else if (def->term()->isNumber())
                        cid   = (int) def->term()->isNumber()->value();
                    }

                    if (!campaign) {
                        List<Campaign>& list = Campaign::GetAllCampaigns();

                        for (int i = 0; i < list.size() && !campaign; i++) {
                            Campaign* c = list.at(i);

                            if (cname == c->Name() || cid == c->GetCampaignId()) {
                                campaign = c;
                                campaign->Load();
                                campaign->Prep(); // restore campaign to pristine state

                                loader->SetDataPath(GetSaveDirectory() + "/");
                            }
                        }
                    }
                }

                else if (def->name()->value() == "grp_iff") {
                    GetDefNumber(grp_iff, def, filename);
                }

                else if (def->name()->value() == "grp_type") {
                    GetDefNumber(grp_type, def, filename);
                }

                else if (def->name()->value() == "grp_id") {
                    GetDefNumber(grp_id, def, filename);
                }

                else if (def->name()->value() == "unit") {
                    GetDefText(unit, def, filename);
                }

                else if (def->name()->value() == "status") {
                    GetDefNumber(status, def, filename);
                }

                else if (def->name()->value() == "basetime") {
                    GetDefNumber(baseTime, def, filename);
                }

                else if (def->name()->value() == "time") {
                    GetDefNumber(time, def, filename);
                }

                else if (def->name()->value() == "sitrep") {
                    GetDefText(sitrep, def, filename);
                }

                else if (def->name()->value() == "orders") {
                    GetDefText(orders, def, filename);
                }

                else if (def->name()->value() == "combatant") {
                    if (!def->term() || !def->term()->isStruct()) {
                        ::Print("WARNING: combatant struct missing in '%s/%s'\n", loader->GetDataPath(), filename);
                    }
                    else {
                        TermStruct* val = def->term()->isStruct();

                        char  name[64];
                        int   iff   = 0;
                        int   score = 0;

                        ZeroMemory(name,  sizeof(name));

                        for (int i = 0; i < val->elements()->size(); i++) {
                            TermDef* pdef = val->elements()->at(i)->isDef();
                            if (pdef) {
                                if (pdef->name()->value() == "name")
                                GetDefText(name, pdef, filename);

                                else if (pdef->name()->value() == "iff") {
                                    GetDefNumber(iff, pdef, filename);
                                }

                                else if (pdef->name()->value() == "score") {
                                    GetDefNumber(score, pdef, filename);
                                }
                            }
                        }

                        if (campaign && name[0]) {
                            Combatant* combatant = campaign->GetCombatant(name);

                            if (combatant) {
                                CombatGroup::MergeOrderOfBattle(block, filename, iff, combatant, campaign);
                                combatant->SetScore(score);
                            }
                            else {
                                ::Print("WARNING: could not find combatant '%s' in campaign.\n", name);
                            }
                        }
                    }
                }
                else if (def->name()->value() == "event") {
                    if (!def->term() || !def->term()->isStruct()) {
                        ::Print("WARNING: event struct missing in '%s/%s'\n", loader->GetDataPath(), filename);
                    }
                    else {
                        TermStruct* val = def->term()->isStruct();

                        char  type[64];
                        char  source[64];
                        char  region[64];
                        char  title[256];
                        char  file[256];
                        char  image[256];
                        char  scene[256];
                        char  info[4096];
                        int   time = 0;
                        int   team = 0;
                        int   points = 0;

                        type[0]   = 0;
                        info[0]   = 0;
                        file[0]   = 0;
                        image[0]  = 0;
                        scene[0]  = 0;
                        title[0]  = 0;
                        region[0] = 0;
                        source[0] = 0;

                        for (int i = 0; i < val->elements()->size(); i++) {
                            TermDef* pdef = val->elements()->at(i)->isDef();
                            if (pdef) {
                                if (pdef->name()->value() == "type")
                                GetDefText(type, pdef, filename);

                                else if (pdef->name()->value() == "source")
                                GetDefText(source, pdef, filename);

                                else if (pdef->name()->value() == "region")
                                GetDefText(region, pdef, filename);

                                else if (pdef->name()->value() == "title")
                                GetDefText(title, pdef, filename);

                                else if (pdef->name()->value() == "file")
                                GetDefText(file, pdef, filename);

                                else if (pdef->name()->value() == "image")
                                GetDefText(image, pdef, filename);

                                else if (pdef->name()->value() == "scene")
                                GetDefText(scene, pdef, filename);

                                else if (pdef->name()->value() == "info")
                                GetDefText(info, pdef, filename);

                                else if (pdef->name()->value() == "time")
                                GetDefNumber(time, pdef, filename);

                                else if (pdef->name()->value() == "team")
                                GetDefNumber(team, pdef, filename);

                                else if (pdef->name()->value() == "points")
                                GetDefNumber(points, pdef, filename);
                            }
                        }

                        if (campaign && type[0]) {
                            loader->SetDataPath(campaign->Path());

                            CombatEvent* event = new(__FILE__,__LINE__)
                            CombatEvent(campaign,
                            CombatEvent::TypeFromName(type),
                            time,
                            team,
                            CombatEvent::SourceFromName(source),
                            region);

                            if (event) {
                                event->SetTitle(title);
                                event->SetFilename(file);
                                event->SetImageFile(image);
                                event->SetSceneFile(scene);
                                event->Load();

                                if (info[0])
                                event->SetInformation(ParseMultiLine(info));

                                event->SetVisited(true);
                                campaign->GetEvents().append(event);
                            }
                        }
                    }
                }
                else if (def->name()->value() == "action") {
                    if (!def->term() || !def->term()->isStruct()) {
                        ::Print("WARNING: action struct missing in '%s/%s'\n", loader->GetDataPath(), filename);
                    }
                    else {
                        TermStruct* val = def->term()->isStruct();

                        int   id    = -1;
                        int   stat  = 0;
                        int   count = 0;
                        int   after = 0;

                        for (int i = 0; i < val->elements()->size(); i++) {
                            TermDef* pdef = val->elements()->at(i)->isDef();
                            if (pdef) {
                                if (pdef->name()->value() == "id")
                                GetDefNumber(id, pdef, filename);

                                else if (pdef->name()->value() == "stat")
                                GetDefNumber(stat, pdef, filename);

                                else if (pdef->name()->value() == "count")
                                GetDefNumber(count, pdef, filename);

                                else if (pdef->name()->value().contains("after"))
                                GetDefNumber(after, pdef, filename);
                            }
                        }

                        if (campaign && id >= 0) {
                            ListIter<CombatAction> a_iter = campaign->GetActions();
                            while (++a_iter) {
                                CombatAction* a = a_iter.value();
                                if (a->Identity() == id) {
                                    a->SetStatus(stat);

                                    if (count)
                                    a->SetCount(count);

                                    if (after)
                                    a->SetStartAfter(after);

                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    while (term);

    if (term) {
        delete term;
        term = 0;
    }

    if (campaign) {
        campaign->SetSaveGame(true);

        List<Campaign>& list = Campaign::GetAllCampaigns();

        if (status < Campaign::CAMPAIGN_SUCCESS) {
            campaign->SetStatus(status);
            if (sitrep.length()) campaign->SetSituation(sitrep);
            if (orders.length()) campaign->SetOrders(orders);
            campaign->SetStartTime(baseTime);
            campaign->SetLoadTime(baseTime + time);
            campaign->LockoutEvents(3600);
            campaign->Start();

            if (grp_type >= CombatGroup::FLEET && grp_type <= CombatGroup::PRIVATE) {
                CombatGroup* player_group = campaign->FindGroup(grp_iff, grp_type, grp_id);
                if (player_group) {
                    CombatUnit* player_unit = 0;

                    if (unit.length())
                    player_unit = player_group->FindUnit(unit);

                    if (player_unit)
                    campaign->SetPlayerUnit(player_unit);
                    else
                    campaign->SetPlayerGroup(player_group);
                }
            }
        }

        // failed - restart current campaign:
        else if (status == Campaign::CAMPAIGN_FAILED) {
            Print("CampaignSaveGame: Loading FAILED campaign, restarting '%s'\n",
            campaign->Name());

            campaign->Load();
            campaign->Prep(); // restore campaign to pristine state
            campaign->SetSaveGame(false);

            loader->SetDataPath(GetSaveDirectory() + "/");
        }

        // start next campaign:
        else if (status == Campaign::CAMPAIGN_SUCCESS) {
            Print("CampaignSaveGame: Loading COMPLETED campaign '%s', searching for next campaign...\n",
            campaign->Name());

            bool found = false;

            for (int i = 0; i < list.size() && !found; i++) {
                Campaign* c = list.at(i);

                if (c->GetCampaignId() == campaign->GetCampaignId()+1) {
                    campaign = c;
                    campaign->Load();
                    campaign->Prep(); // restore campaign to pristine state

                    Print("Advanced to campaign %d '%s'\n",
                    campaign->GetCampaignId(),
                    campaign->Name());

                    loader->SetDataPath(GetSaveDirectory() + "/");
                    found = true;
                }
            }

            // if no next campaign found, start over from the beginning:
            for (int i = 0; i < list.size() && !found; i++) {
                Campaign* c = list.at(i);

                if (c->IsDynamic()) {
                    campaign = c;
                    campaign->Load();
                    campaign->Prep(); // restore campaign to pristine state

                    Print("Completed full series, restarting at %d '%s'\n",
                    campaign->GetCampaignId(),
                    campaign->Name());

                    loader->SetDataPath(GetSaveDirectory() + "/");
                    found = true;
                }
            }
        }
    }

    loader->ReleaseBuffer(block);
    loader->SetDataPath(0);
    Print("SAVEGAME LOADED (%s).\n\n", filename);
}

// +--------------------------------------------------------------------+

void
CampaignSaveGame::Save(const char* name)
{
    if (!campaign) return;

    CreateSaveDirectory();

    Text s = GetSaveDirectory() + Text("/") + Text(name);

    FILE* f;
    fopen_s(&f, s, "wb");

    if (f) {
        char timestr[32];
        FormatDayTime(timestr, campaign->GetTime());

        CombatGroup* player_group = campaign->GetPlayerGroup();
        CombatUnit*  player_unit  = campaign->GetPlayerUnit();

        fprintf(f, "SAVEGAME\n\n");
        fprintf(f, "campaign: \"%s\"\n\n",  campaign->Name());
        fprintf(f, "grp_iff:  %d\n",        (int) player_group->GetIFF());
        fprintf(f, "grp_type: %d\n",        (int) player_group->Type());
        fprintf(f, "grp_id:   %d\n",        (int) player_group->GetID());
        if (player_unit)
        fprintf(f, "unit:     \"%s\"\n", player_unit->Name().data());

        fprintf(f, "status:   %d\n",        (int) campaign->GetStatus());
        fprintf(f, "basetime: %f\n",        campaign->GetStartTime());
        fprintf(f, "time:     %f // %s\n\n",
        campaign->GetTime(),
        timestr);

        fprintf(f, "sitrep:   \"%s\"\n",    campaign->Situation());
        fprintf(f, "orders:   \"%s\"\n\n",  campaign->Orders());

        ListIter<Combatant> c_iter = campaign->GetCombatants();
        while (++c_iter) {
            Combatant*   c = c_iter.value();

            fprintf(f, "combatant: {");
            fprintf(f, " name:\"%s\",", c->Name());
            fprintf(f, " iff:%d,", c->GetIFF());
            fprintf(f, " score:%d,", c->Score());
            fprintf(f, " }\n");
        }

        fprintf(f, "\n");

        ListIter<CombatAction> a_iter = campaign->GetActions();
        while (++a_iter) {
            CombatAction* a = a_iter.value();
            fprintf(f, "action: { id:%4d, stat:%d", a->Identity(), a->Status());

            if (a->Status() == CombatAction::PENDING) {
                if (a->Count())
                fprintf(f, ", count:%d", a->Count());

                if (a->StartAfter())
                fprintf(f, ", after:%d", a->StartAfter());
            }

            fprintf(f, " }\n");
        }

        fprintf(f, "\n");

        ListIter<CombatEvent> e_iter = campaign->GetEvents();
        while (++e_iter) {
            CombatEvent* e = e_iter.value();

            fprintf(f, "event: {");
            fprintf(f, " type:%-18s,",      e->TypeName());
            fprintf(f, " time:0x%08x,",     e->Time());
            fprintf(f, " team:%d,",         e->GetIFF());
            fprintf(f, " points:%d,",       e->Points());
            fprintf(f, " source:\"%s\",",   e->SourceName());
            fprintf(f, " region:\"%s\",",   e->Region());
            fprintf(f, " title:\"%s\",",    e->Title());
            if (e->Filename())
            fprintf(f, " file:\"%s\",",     e->Filename());
            if (e->ImageFile())
            fprintf(f, " image:\"%s\",",    e->ImageFile());
            if (e->SceneFile())
            fprintf(f, " scene:\"%s\",",    e->SceneFile());
            if (!e->Filename() || *e->Filename() == 0)
            fprintf(f, " info:\"%s\"",      FormatMultiLine(e->Information()));
            fprintf(f, " }\n");
        }

        fprintf(f, "\n// ORDER OF BATTLE:\n\n");
        fclose(f);

        c_iter.reset();
        while (++c_iter) {
            Combatant*   c = c_iter.value();
            CombatGroup* g = c->GetForce();
            CombatGroup::SaveOrderOfBattle(s, g);
        }
    }
}

void
CampaignSaveGame::Delete(const char* name)
{
    DeleteFile(GetSaveDirectory() + "/" + name);
}

void
CampaignSaveGame::RemovePlayer(Player* p)
{
    List<Text> save_list;
    Text       save_dir = GetSaveDirectory(p) + "/";

    DataLoader* loader = DataLoader::GetLoader();
    bool use_file_sys = loader->IsFileSystemEnabled();
    loader->UseFileSystem(true);
    loader->SetDataPath(save_dir);
    loader->ListFiles("*.*", save_list);
    loader->SetDataPath(0);
    loader->UseFileSystem(use_file_sys);

    for (int i = 0; i < save_list.size(); i++) {
        Text* filename = save_list[i];
        DeleteFile(save_dir + filename->data());
    }

    save_list.destroy();

    RemoveDirectory(GetSaveDirectory(p));
}

// +--------------------------------------------------------------------+

void
CampaignSaveGame::SaveAuto()
{
    Save("AutoSave");
}

void
CampaignSaveGame::LoadAuto()
{
    Load("AutoSave");
}

// +--------------------------------------------------------------------+

Text
CampaignSaveGame::GetResumeFile()
{
    // check for auto save game:
    FILE* f;
    ::fopen_s(&f, GetSaveDirectory() + "/AutoSave", "rb");

    if (f) {
        ::fclose(f);

        return "AutoSave";
    }

    return Text();
}

int
CampaignSaveGame::GetSaveGameList(List<Text>& save_list)
{
    DataLoader* loader = DataLoader::GetLoader();
    bool use_file_sys = loader->IsFileSystemEnabled();
    loader->UseFileSystem(true);
    loader->SetDataPath(GetSaveDirectory() + "/");
    loader->ListFiles("*.*", save_list);
    loader->SetDataPath(0);
    loader->UseFileSystem(use_file_sys);

    return save_list.size();
}