Flint Engine
Modular C++20 2D game engine powered by SDL3
Loading...
Searching...
No Matches
game-module-loader.h
1// SPDX-License-Identifier: MIT
2// SPDX-FileCopyrightText: 2025-2026 Manuel Osorio
3#pragma once
4
5#include "flint/platform/dynamic-library.h"
6
7#include <chrono>
8#include <cstdint>
9#include <filesystem>
10#include <optional>
11#include <vector>
12
13namespace Flint {
14
15 enum class MODULE_UPDATE_RESULT {
16 NoChange,
17 ReloadRequired
18 };
19
21 public:
22 explicit GameModuleLoader(std::filesystem::path modulePath);
24
25 GameModuleLoader(const GameModuleLoader &) = delete;
26 GameModuleLoader &operator=(const GameModuleLoader &) = delete;
27
28 bool load();
29
30 bool prepareReload();
31 void commitReload();
32 void rejectReload();
33
34 template <typename T>
35 T getPendingSymbol(const char *name) const {
36 if (!m_pendingLibrary.isLoaded()) {
37 return nullptr;
38 }
39
40 return m_pendingLibrary.getSymbol<T>(name);
41 }
42
43 MODULE_UPDATE_RESULT update();
44
45 void unload();
46
47 template <typename T>
48 T getSymbol(const char *name) const {
49 if (!m_library.isLoaded()) {
50 return nullptr;
51 }
52
53 return m_library.getSymbol<T>(name);
54 }
55
56 [[nodiscard]] bool isLoaded() const {
57 return m_library.isLoaded();
58 }
59
60 [[nodiscard]] const std::filesystem::path &getModulePath() const {
61 return m_modulePath;
62 }
63
64 private:
65 struct RetiredGeneration {
66 DynamicLibrary library;
67 std::filesystem::path shadowPath;
68 };
69
70 bool loadGeneration(std::filesystem::file_time_type writeTime);
71
72 void beginPendingReload(std::filesystem::file_time_type writeTime);
73
74 void clearPendingReload();
75
76 std::uint64_t getProcessId();
77
78 [[nodiscard]] std::filesystem::path createShadowPath();
79
80 DynamicLibrary m_library;
81 std::filesystem::path m_modulePath;
82 std::filesystem::path m_shadowPath;
83
84 DynamicLibrary m_pendingLibrary;
85 std::filesystem::path m_pendingShadowPath;
86 std::filesystem::file_time_type m_pendingLibraryWriteTime{};
87
88 std::filesystem::file_time_type m_lastWriteTime{};
89 std::uint32_t m_generation = 0;
90
91 std::optional<std::filesystem::file_time_type> m_pendingWriteTime;
92
93 std::chrono::steady_clock::time_point m_nextPrepareAttempt{};
94
95 bool m_prepareFailureLogged = false;
96 bool m_inspectionFailureLogged = false;
97
98 std::vector<RetiredGeneration> m_retiredGenerations;
99 };
100
101}