summaryrefslogtreecommitdiff
path: root/src/SSVOpenHexagon/Core/main.cpp
blob: b32f677fa4ac32f64f756caa3a37dd8aa9c634b9 (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
// Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: https://opensource.org/licenses/AFL-3.0

#include "SSVOpenHexagon/Core/HexagonGame.hpp"
#include "SSVOpenHexagon/Core/HexagonServer.hpp"
#include "SSVOpenHexagon/Core/HexagonClient.hpp"
#include "SSVOpenHexagon/Core/MenuGame.hpp"
#include "SSVOpenHexagon/Core/Steam.hpp"
#include "SSVOpenHexagon/Core/Discord.hpp"
#include "SSVOpenHexagon/Core/Replay.hpp"

#include "SSVOpenHexagon/Global/Assets.hpp"
#include "SSVOpenHexagon/Global/Audio.hpp"
#include "SSVOpenHexagon/Global/Assert.hpp"
#include "SSVOpenHexagon/Global/Config.hpp"
#include "SSVOpenHexagon/Global/Imgui.hpp"
#include "SSVOpenHexagon/Global/Version.hpp"

#include "SSVOpenHexagon/Utils/Concat.hpp"
#include "SSVOpenHexagon/Utils/ScopeGuard.hpp"
#include "SSVOpenHexagon/Utils/VectorToSet.hpp"

#include <sodium.h>

#include <SSVStart/GameSystem/GameWindow.hpp>

#include <SSVUtils/Core/Log/Log.hpp>
#include <SSVUtils/Core/Log/Log.inl>
#include <SSVUtils/Core/FileSystem/FileSystem.hpp>

#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <optional>
#include <string_view>
#include <string>
#include <type_traits>
#include <unordered_set>
#include <vector>

//
//
// ----------------------------------------------------------------------------
// Floating-point sanity checks
// ----------------------------------------------------------------------------

static_assert(std::numeric_limits<float>::is_iec559);
static_assert(std::numeric_limits<float>::digits == 24);

static_assert(std::numeric_limits<double>::is_iec559);
static_assert(std::numeric_limits<double>::digits == 53);

//
//
// ----------------------------------------------------------------------------
// Utilities
// ----------------------------------------------------------------------------

namespace {

void createFolderIfNonExistant(const std::string& folderName)
{
    const ssvu::FileSystem::Path path{folderName};

    if(path.exists<ssvufs::Type::Folder>())
    {
        return;
    }

    ssvu::lo("::createFolderIfNonExistant")
        << "'" << folderName << "' folder does not exist, creating\n";

    createFolder(path);
}

struct ParsedArgs
{
    std::vector<std::string> args;
    std::optional<std::string> cliLevelName;
    std::optional<std::string> cliLevelPack;
    bool printLuaDocs{false};
    bool headless{false};
    bool server{false};
};

[[nodiscard]] ParsedArgs parseArgs(const int argc, char* argv[])
{
    ParsedArgs result;

    for(int i = 0; i < argc; ++i)
    {
        // Find command-line pack name (to immediately run level)
        if(!std::strcmp(argv[i], "-p") && i + 1 < argc)
        {
            ++i;
            result.cliLevelPack = argv[i];
            continue;
        }

        // Find command-line level name (to immediately run level)
        if(!std::strcmp(argv[i], "-l") && i + 1 < argc)
        {
            ++i;
            result.cliLevelName = argv[i];
            continue;
        }

        // Find command-line argument to print Lua docs
        if(!std::strcmp(argv[i], "-printLuaDocs"))
        {
            result.printLuaDocs = true;
            continue;
        }

        // Find command-line argument to run in headless mode
        if(!std::strcmp(argv[i], "-headless"))
        {
            result.headless = true;
            continue;
        }

        // Find command-line argument to run in server mode
        if(!std::strcmp(argv[i], "-server"))
        {
            result.server = true;
            continue;
        }

        result.args.emplace_back(argv[i]);
    }

    return result;
}

[[nodiscard]] std::string makeWindowTitle()
{
    return hg::Utils::concat("Open Hexagon ", hg::GAME_VERSION_STR,
        " - by Vittorio Romeo - https://vittorioromeo.info");
}

[[nodiscard]] std::optional<std::string>
getFirstCompressedReplayFilenameFromArgs(const std::vector<std::string>& args)
{
    for(const std::string& arg : args)
    {
        if(arg.find(".ohr.z") != std::string::npos)
        {
            return arg;
        }
    }

    return std::nullopt;
}

} // namespace

//
//
// ----------------------------------------------------------------------------
// Print lua docs entrypoint
// ----------------------------------------------------------------------------

[[nodiscard]] int mainPrintLuaDocs()
{
    hg::HGAssets assets{
        nullptr, /* steamManager */ //
        true /* headless */         //
    };

    hg::HexagonGame hg{
        nullptr /* steamManager */,   //
        nullptr /* discordManager */, //
        assets,                       //
        nullptr /* audio */,          //
        nullptr /* window */,         //
        nullptr /* client */          //
    };

    std::cout << "\n\n\n\n\n";
    hg.initLuaAndPrintDocs();
    std::cout << "\n\n\n\n\n";

    ssvu::lo("::mainPrintLuaDocs") << "Finished\n";
    return 0;
}

//
//
// ----------------------------------------------------------------------------
// Server main entrypoint
// ----------------------------------------------------------------------------

[[nodiscard]] int mainServer()
{
    hg::Steam::steam_manager steamManager;

    hg::Config::loadConfig({} /* overrideIds */);

    hg::HGAssets assets{
        &steamManager,      //
        true /* headless */ //
    };

    hg::HexagonGame hg{
        nullptr /* steamManager */,   //
        nullptr /* discordManager */, //
        assets,                       //
        nullptr /* audio */,          //
        nullptr /* window */,         //
        nullptr /* client */          //
    };

    hg::HexagonServer hs{
        assets,                                                          //
        hg,                                                              //
        hg::Config::getServerIp(),                                       //
        hg::Config::getServerPort(),                                     //
        hg::Config::getServerControlPort(),                              //
        hg::Utils::toUnorderedSet(hg::Config::getServerLevelWhitelist()) //
    };

    ssvu::lo("::mainServer") << "Finished\n";
    return 0;
}

//
//
// ----------------------------------------------------------------------------
// Client main entrypoint
// ----------------------------------------------------------------------------

[[nodiscard]] int mainClient(const bool headless,
    const std::vector<std::string>& args,
    const std::optional<std::string>& cliLevelName,
    const std::optional<std::string>& cliLevelPack)
{
    // ------------------------------------------------------------------------
    // Steam integration
    hg::Steam::steam_manager steamManager;

    if(steamManager.is_initialized())
    {
        steamManager.request_encrypted_app_ticket();
        steamManager.request_stats_and_achievements();
        steamManager.run_callbacks();
    }

    //
    //
    // ------------------------------------------------------------------------
    // Discord integration
    std::optional<hg::Discord::discord_manager> discordManager;

    if(!headless)
    {
        discordManager.emplace();
    }

    //
    //
    // ------------------------------------------------------------------------
    // Create game folders if needed
    createFolderIfNonExistant("Profiles/");
    createFolderIfNonExistant("Replays/");

    //
    //
    // ------------------------------------------------------------------------
    // Load configuration (and overrides)
    hg::Config::loadConfig(args);
    hg::Config::reapplyResolution();

    HG_SCOPE_GUARD({
        ssvu::lo("::main") << "Saving config...\n";
        hg::Config::saveConfig();
        ssvu::lo("::main") << "Done saving config\n";
    });

    //
    //
    // ------------------------------------------------------------------------
    // Create the game window
    std::optional<ssvs::GameWindow> window;

    if(!headless)
    {
        window.emplace();

        window->setTitle(makeWindowTitle());
        window->setSize(hg::Config::getWidth(), hg::Config::getHeight());
        window->setPixelMult(hg::Config::getPixelMultiplier());
        window->setFullscreen(hg::Config::getFullscreen());
        window->setAntialiasingLevel(hg::Config::getAntialiasingLevel());
        window->setVsync(hg::Config::getVsync());
        window->setFPSLimited(hg::Config::getLimitFPS());
        window->setMaxFPS(hg::Config::getMaxFPS());

        {
            const auto resetIcon = [&window]
            {
                sf::Image icon;
                if(!icon.loadFromFile("Assets/icon.png"))
                {
                    ssvu::lo("::main") << "Failed to load icon image\n";
                }

                window->getRenderWindow().setIcon(
                    icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
            };

            window->onRecreation += resetIcon;
            resetIcon();
        }

        // 240 ticks per second.
        window->setTimer<ssvs::TimerStatic>(
            hg::Config::TIME_STEP, hg::Config::TIME_SLICE);

        // Signal handling: exit gracefully on CTRL-C
        {
            SSVOH_ASSERT(window.has_value());
            static ssvs::GameWindow& globalWindow = *window;

            // TODO (P2): UB
            std::signal(SIGINT,
                [](int s)
                {
                    ssvu::lo("::main") << "Caught signal '" << s
                                       << "' with game window open\n";

                    ssvu::lo("::main") << "Stopping game window...\n";
                    globalWindow.stop();
                    ssvu::lo("::main") << "Done stopping game window\n";
                });
        }
    }

    //
    //
    // ------------------------------------------------------------------------
    // Initialize IMGUI
    if(!headless)
    {
        SSVOH_ASSERT(window.has_value());
        hg::Imgui::initialize(*window);
    }

    HG_SCOPE_GUARD({
        ssvu::lo("::main") << "Shutting down ImGui...\n";

        if(!headless)
        {
            hg::Imgui::shutdown();
        }

        ssvu::lo("::main") << "Done shutting down ImGui...\n";
    });

    //
    //
    // ------------------------------------------------------------------------
    // Initialize assets
    hg::HGAssets assets{&steamManager, headless};
    HG_SCOPE_GUARD({
        ssvu::lo("::main") << "Saving all local profiles...\n";
        assets.pSaveAll();
        ssvu::lo("::main") << "Done saving all local profiles\n";
    });

    //
    //
    // ------------------------------------------------------------------------
    // Initialize audio
    hg::Audio audio{
        //
        [&assets](const std::string& assetId) -> sf::SoundBuffer*
        { return assets.getSoundBuffer(assetId); }, //
        [&assets](const std::string& assetId) -> const std::string*
        { return assets.getMusicPath(assetId); } //
    };

    audio.setSoundVolume(hg::Config::getSoundVolume());
    audio.setMusicVolume(hg::Config::getMusicVolume());

    // ------------------------------------------------------------------------
    // Initialize hexagon client
    hg::HexagonClient hc{
        steamManager, hg::Config::getServerIp(), hg::Config::getServerPort()};

    //
    //
    // ------------------------------------------------------------------------
    // Initialize hexagon game
    hg::HexagonGame hg{
        &steamManager,                                             //
        (discordManager.has_value() ? &*discordManager : nullptr), //
        assets,                                                    //
        &audio,                                                    //
        (window.has_value() ? &*window : nullptr),                 //
        &hc                                                        //
    };

    //
    //
    // ------------------------------------------------------------------------
    // Initialize menu game and link to hexagon game
    std::optional<hg::MenuGame> mg;

    if(!headless)
    {
        SSVOH_ASSERT(window.has_value());
        SSVOH_ASSERT(discordManager.has_value());

        mg.emplace(steamManager, *discordManager, assets, audio, *window, hc);

        mg->fnHGTriggerRefresh = [&](const ssvs::Input::Trigger& trigger,
                                     int bindId) //
        {
            hg.refreshTrigger(trigger, bindId); //
        };

        mg->fnHGNewGame = [&](const std::string& packId,
                              const std::string& levelId, bool firstPlay,
                              float diffMult, bool executeLastReplay)
        {
            hg.newGame(packId, levelId, firstPlay, diffMult, executeLastReplay);

            window->setGameState(hg.getGame());
        };

        mg->fnHGUpdateRichPresenceCallbacks = [&] //
        {                                         //
            hg.updateRichPresenceCallbacks();
        };

        hg.fnGoToMenu = [&](const bool error)
        {
            mg->returnToLevelSelection();
            mg->init(error);

            window->setGameState(mg->getGame());
        };
    }

    //
    //
    // ------------------------------------------------------------------------
    // Load drag & drop replay, if any -- otherwise run game as normal
    const std::optional<std::string> compressedReplayFilename =
        getFirstCompressedReplayFilenameFromArgs(args);

    if(!headless)
    {
        SSVOH_ASSERT(window.has_value());

        const auto gotoMenu = [&]
        {
            mg->init(false /* mError */);
            window->setGameState(mg->getGame());
        };

        const auto gotoGameCompressedReplay =
            [&](const hg::compressed_replay_file& compressedReplayFile)
        {
            std::optional<hg::replay_file> replayFileOpt =
                hg::decompress_replay_file(compressedReplayFile);

            if(!replayFileOpt.has_value())
            {
                std::cerr << "Could not decompress replay file\n";
                return;
            }

            hg::replay_file& replayFile = replayFileOpt.value();

            hg.setLastReplay(replayFile);

            hg.newGame(replayFile._pack_id, replayFile._level_id,
                replayFile._first_play, replayFile._difficulty_mult,
                /* mExecuteLastReplay */ true);

            window->setGameState(hg.getGame());
        };

        if(!compressedReplayFilename.has_value())
        {
            if(cliLevelPack.has_value() && cliLevelName.has_value())
            {
                // Load pack and levels specified via command line args.
                mg->init(false /* mError */, *cliLevelPack, *cliLevelName);
            }
            else
            {
                // Start game as normal.
                gotoMenu();
            }
        }
        else
        {
            if(hg::compressed_replay_file crf;
                crf.deserialize_from_file(*compressedReplayFilename))
            {
                ssvu::lo("Replay") << "Playing compressed replay file '"
                                   << *compressedReplayFilename << "'\n";

                gotoGameCompressedReplay(crf);
            }
            else
            {
                ssvu::lo("Replay") << "Failed to read compressed replay file '"
                                   << compressedReplayFilename.value() << "'\n";

                gotoMenu();
            }
        }
    }
    else
    {
        SSVOH_ASSERT(headless);

        // TODO (P2): code repetition, cleanup
        if(!compressedReplayFilename.has_value())
        {
            std::cout << "Running in headless mode without replay...?\n";
            return 1;
        }

        if(hg::compressed_replay_file crf;
            crf.deserialize_from_file(*compressedReplayFilename))
        {
            std::optional<hg::replay_file> replayFileOpt =
                hg::decompress_replay_file(crf);

            if(!replayFileOpt.has_value())
            {
                std::cerr << "Could not decompress replay file\n";
                return 1;
            }

            hg::replay_file& replayFile = replayFileOpt.value();

            ssvu::lo("Replay")
                << "Playing compressed replay file in headless mode '"
                << *compressedReplayFilename << "'\n";

            // TODO (P2): check level validity

            std::cout << "Player died.\nFinal time: "
                      << hg.runReplayUntilDeathAndGetScore(replayFile,
                               1 /* maxProcessingSeconds */,
                               1.f /* timescale */)
                             .value()
                             .playedTimeSeconds
                      << '\n';
        }
        else
        {
            ssvu::lo("Replay")
                << "Failed to read compressed replay file in headless mode '"
                << compressedReplayFilename.value() << "'\n";
        }
    }

    //
    //
    // ------------------------------------------------------------------------
    // Run the game!
    if(!headless)
    {
        SSVOH_ASSERT(window.has_value());
        window->run();
    }

    ssvu::lo("::mainClient") << "Finished\n";
    return 0;
}

//
//
// ----------------------------------------------------------------------------
// Program main entrypoint
// ----------------------------------------------------------------------------

int main(int argc, char* argv[])
{
    if(argc < 1)
    {
        std::cerr << "Fatal error: no executable specified" << std::endl;
        return -1;
    }

    //
    //
    // ------------------------------------------------------------------------
    // libsodium initialization
    if(sodium_init() < 0)
    {
        ssvu::lo("::main") << "Failed initializing libsodium\n";
        return 1;
    }

    //
    //
    // ------------------------------------------------------------------------
    // Basic signal handling
    // TODO (P2): UB
    std::signal(SIGINT,
        [](int s)
        {
            ssvu::lo("::main") << "Caught signal '" << s
                               << "' without game window open, exiting...\n";

            std::exit(1);
        });

    //
    //
    // ------------------------------------------------------------------------
    // Flush and save log (at the end of the scope)
    HG_SCOPE_GUARD({
        ssvu::lo("::main") << "Saving log to 'log.txt'...\n";

        ssvu::lo().flush();
        ssvu::saveLogToFile("log.txt");

        ssvu::lo("::main") << "Done saving log to 'log.txt'\n";
    });

    //
    //
    // ------------------------------------------------------------------------
    // Set working directory to current executable location
    std::filesystem::current_path(std::filesystem::path{argv[0]}.parent_path());

    //
    //
    // ------------------------------------------------------------------------
    // Parse command line arguments
    const auto [args, cliLevelName, cliLevelPack, printLuaDocs, headlessB,
        server] = parseArgs(argc, argv);
    const auto headless = headlessB; // Workaround binding capture

    //
    //
    // ------------------------------------------------------------------------
    // Print Lua docs mode
    if(printLuaDocs)
    {
        return mainPrintLuaDocs();
    }

    //
    //
    // ------------------------------------------------------------------------
    // Server mode
    if(server)
    {
        return mainServer();
    }

    //
    //
    // ------------------------------------------------------------------------
    // Client mode
    SSVOH_ASSERT(!printLuaDocs);
    SSVOH_ASSERT(!server);
    return mainClient(headless, args, cliLevelName, cliLevelPack);
}