SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
ShaderHotReload.cpp
Go to the documentation of this file.
2
3#ifdef SLEAK_HOT_RELOAD
6#include <Core/Logger.hpp>
7#include <Core/Timer.hpp>
9#include <algorithm>
10#include <cstdio>
11#include <filesystem>
12#include <set>
13#include <string>
14#include <string_view>
15
16#ifdef PLATFORM_WIN
17#include <process.h>
18#else
19#include <unistd.h>
20#endif
21#endif
22
23namespace Sleak {
24namespace Debug {
25
26#ifdef SLEAK_HOT_RELOAD
27namespace {
28
29namespace fs = std::filesystem;
30
31constexpr float DEBOUNCE_SECONDS = 0.15f;
32constexpr float MS_PER_SECOND = 1000.0f;
33constexpr size_t PROCESS_LINE_SIZE = 512;
34constexpr const char* RUNTIME_SHADER_DIR = "assets/shaders";
35constexpr const char* SPIRV_EXTENSION = ".spv";
36constexpr const char* TEMP_EXTENSION = ".tmp";
37constexpr std::string_view GL_SUFFIX = "_gl";
38constexpr std::string_view DX12_SUFFIX = "_dx12";
39
40struct State {
41 FileWatcher watcher;
42 std::vector<fs::path> directories;
43 std::set<fs::path> pending;
44 Timer quietTimer;
45};
46
47/// Lazily created hot reload state shared by all calls.
48State& GetState() {
49 static State state;
50 return state;
51}
52
53/// Per-process temp name next to a target, so two running games never clash.
54fs::path TempPathFor(const fs::path& target) {
55#ifdef PLATFORM_WIN
56 const int pid = _getpid();
57#else
58 const int pid = static_cast<int>(getpid());
59#endif
60 fs::path tmp = target;
61 tmp += "." + std::to_string(pid) + TEMP_EXTENSION;
62 return tmp;
63}
64
65/// Atomically replaces a target with a finished temp file.
66bool ReplaceWith(const fs::path& tmp, const fs::path& target) {
67 std::error_code ec;
68 fs::rename(tmp, target, ec);
69 if (!ec) return true;
70 SLEAK_ERROR("Hot reload: can't replace {}: {}", target.filename().string(),
71 ec.message());
72 fs::remove(tmp, ec);
73 return false;
74}
75
76/// True for shader sources the watcher reacts to.
77bool IsShaderSource(const fs::path& file) {
78 const fs::path ext = file.extension();
79 return ext == ".vert" || ext == ".frag" || ext == ".hlsl";
80}
81
82/// True for GLSL that glslc compiles to SPIR-V for Vulkan.
83bool IsVulkanSource(const fs::path& file) {
84 const fs::path ext = file.extension();
85 if (ext != ".vert" && ext != ".frag") return false;
86 return !file.stem().string().ends_with(GL_SUFFIX);
87}
88
89/// Stem shared by all backend variants, e.g. lighting_pass_gl.frag.
90std::string StemOf(const fs::path& file) {
91 std::string name = file.filename().string();
92 name = name.substr(0, name.find('.'));
93 for (std::string_view suffix : {GL_SUFFIX, DX12_SUFFIX}) {
94 if (name.ends_with(suffix)) {
95 name.resize(name.size() - suffix.size());
96 break;
97 }
98 }
99 return name;
100}
101
102/// Backend that loads this source file, picked from its suffix.
103RenderEngine::RendererType BackendOf(const fs::path& file) {
105 const std::string stem = file.stem().string();
106 if (file.extension() == ".hlsl")
107 return stem.ends_with(DX12_SUFFIX) ? RendererType::DirectX12
108 : RendererType::DirectX11;
109 return stem.ends_with(GL_SUFFIX) ? RendererType::OpenGL
110 : RendererType::Vulkan;
111}
112
113/// File name pattern a backend loads for a stem.
114std::string VariantFor(const std::string& stem,
117 switch (type) {
118 case RendererType::Vulkan:
119 return stem + ".vert / " + stem + ".frag";
120 case RendererType::OpenGL:
121 return stem + "_gl.vert / " + stem + "_gl.frag";
122 case RendererType::DirectX11:
123 return stem + ".hlsl";
124 case RendererType::DirectX12:
125 return stem + "_dx12.hlsl";
126 }
127 return stem;
128}
129
130/// True when a later source folder has a file with the same name.
131bool IsOverridden(const fs::path& file, const State& state) {
132 const auto dir = std::find(state.directories.begin(),
133 state.directories.end(), file.parent_path());
134 if (dir == state.directories.end()) return false;
135 for (auto later = dir + 1; later != state.directories.end(); ++later) {
136 std::error_code ec;
137 if (fs::exists(*later / file.filename(), ec)) return true;
138 }
139 return false;
140}
141
142/// Compiles GLSL to SPIR-V next to the source. Keeps the old .spv on error.
143bool CompileSpirv(const fs::path& src, const fs::path& spv) {
144#ifndef SLEAK_GLSLC_PATH
145 (void)spv;
146 SLEAK_WARN("Hot reload: glslc was not found at configure time, {} skipped",
147 src.filename().string());
148 return false;
149#else
150 const fs::path tmp = TempPathFor(spv);
151 std::string cmd = "\"" SLEAK_GLSLC_PATH "\" \"" + src.string() +
152 "\" -o \"" + tmp.string() + "\" 2>&1";
153#ifdef PLATFORM_WIN
154 cmd = "\"" + cmd + "\"";
155 FILE* pipe = _popen(cmd.c_str(), "r");
156#else
157 FILE* pipe = popen(cmd.c_str(), "r");
158#endif
159 if (!pipe) {
160 SLEAK_ERROR("Hot reload: can't run glslc for {}",
161 src.filename().string());
162 return false;
163 }
164 std::string output;
165 char line[PROCESS_LINE_SIZE];
166 while (std::fgets(line, sizeof(line), pipe)) output += line;
167#ifdef PLATFORM_WIN
168 const int status = _pclose(pipe);
169#else
170 const int status = pclose(pipe);
171#endif
172 if (status != 0) {
173 std::error_code ec;
174 fs::remove(tmp, ec);
176 "Hot reload: {} failed to compile, keeping the old "
177 "shader\n{}",
178 src.filename().string(), output);
179 return false;
180 }
181 return ReplaceWith(tmp, spv);
182#endif
183}
184
185/// Copies a file into the runtime shader folder the backends load from.
186bool CopyToRuntime(const fs::path& file) {
187 const fs::path target = fs::path(RUNTIME_SHADER_DIR) / file.filename();
188 const fs::path tmp = TempPathFor(target);
189 std::error_code ec;
190 fs::copy_file(file, tmp, fs::copy_options::overwrite_existing, ec);
191 if (ec) {
192 SLEAK_ERROR("Hot reload: can't copy {}: {}", file.filename().string(),
193 ec.message());
194 return false;
195 }
196 return ReplaceWith(tmp, target);
197}
198
199/// Compiles and stages one saved file. Returns its stem, or empty to skip.
200std::string ProcessFile(const fs::path& file, const State& state) {
201 std::error_code ec;
202 if (!fs::exists(file, ec)) return {};
203 if (IsOverridden(file, state)) {
205 "Hot reload: {} is overridden by a later shader folder, "
206 "edit that copy instead",
207 file.filename().string());
208 return {};
209 }
210 if (IsVulkanSource(file)) {
211 fs::path spv = file;
212 spv += SPIRV_EXTENSION;
213 if (!CompileSpirv(file, spv) || !CopyToRuntime(spv)) return {};
214 }
215 if (!CopyToRuntime(file)) return {};
216 return StemOf(file);
217}
218
219} // namespace
220#endif
221
222void ShaderHotReload::AddSourceDirectory(const std::string& dir) {
223#ifdef SLEAK_HOT_RELOAD
224 std::error_code ec;
225 const fs::path path = fs::canonical(dir, ec);
226 if (ec) {
227 SLEAK_WARN("Hot reload: shader folder {} not found", dir);
228 return;
229 }
230 State& state = GetState();
231 if (std::find(state.directories.begin(), state.directories.end(), path) !=
232 state.directories.end())
233 return;
234 if (!state.watcher.AddDirectory(path.string())) return;
235 state.directories.push_back(path);
236 SLEAK_INFO("Hot reload: watching {}", path.string());
237#else
238 (void)dir;
239#endif
240}
241
243#ifdef SLEAK_HOT_RELOAD
244 State& state = GetState();
245 if (state.directories.empty()) return;
246
247 std::vector<std::string> changed;
248 state.watcher.Poll(changed);
249 for (const std::string& path : changed) {
250 const fs::path file(path);
251 if (!IsShaderSource(file)) continue;
252 state.pending.insert(file);
253 state.quietTimer.Reset();
254 }
255 if (state.pending.empty() || state.quietTimer.Elapsed() < DEBOUNCE_SECONDS)
256 return;
257
259 RenderEngine::Renderer* renderer = app ? app->GetRenderer() : nullptr;
260 if (!renderer) return;
261 const RenderEngine::RendererType active = renderer->GetType();
262
263 Timer reloadTimer;
264 std::vector<std::string> stems;
265 for (const fs::path& file : state.pending) {
266 std::string stem = ProcessFile(file, state);
267 if (stem.empty()) continue;
268 if (BackendOf(file) != active) {
270 "Hot reload: {} is not used by the {} renderer, edit {} "
271 "instead",
272 file.filename().string(), app->GetRendererTypeStr(),
273 VariantFor(stem, active));
274 continue;
275 }
276 if (std::find(stems.begin(), stems.end(), stem) == stems.end())
277 stems.push_back(std::move(stem));
278 }
279 state.pending.clear();
280 if (stems.empty()) return;
281
282 app->WaitGPUIdle();
283 if (!renderer->ReloadShaders(stems)) {
284 SLEAK_WARN("Hot reload: the {} backend can't reload shaders yet",
285 app->GetRendererTypeStr());
286 return;
287 }
288
289 std::string names;
290 for (const std::string& stem : stems)
291 names += (names.empty() ? "" : ", ") + stem;
292 SLEAK_INFO("Hot reload: reloaded {} in {:.0f} ms", names,
293 reloadTimer.Elapsed() * MS_PER_SECOND);
294#endif
295}
296
297} // namespace Debug
298} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
const char * GetRendererTypeStr() const
Human-readable name of the active backend (e.g. "Vulkan").
void WaitGPUIdle()
Blocks until the GPU finishes all in-flight work. Call before tearing down scene resources.
static Application * GetInstance()
The one Application for this process, or null before construction.
RenderEngine::Renderer * GetRenderer()
Active renderer backend, or null before Run() initializes it.
static void AddSourceDirectory(const std::string &dir)
Watches a shader source folder. Later folders override earlier ones.
static void Poll()
Rebuilds changed shaders. Called once per frame by Application.
Abstract render backend: swapchain, frame lifecycle, and post-effect toggles.
Definition Renderer.hpp:41
RendererType GetType() const
Definition Renderer.hpp:88
virtual bool ReloadShaders(const std::vector< std::string > &stems)
Definition Renderer.hpp:56
float Elapsed() const
Seconds since construction or the last Reset().
Definition Timer.cpp:13
RendererType
Selects which graphics API a Renderer instance targets.
Definition Renderer.hpp:17
Root namespace for everything the engine exposes.
Definition Camera.hpp:10