ACMX 2.139.0
Dual-Backend Real-Time GPU Video Synthesis
Loading...
Searching...
No Matches
shader_library.cpp
Go to the documentation of this file.
1#include "shader_library.hpp"
2
4
5#include <mxvk/mxvk.hpp>
6#include <opencv2/core.hpp>
7
8#include <algorithm>
9#include <atomic>
10#include <cctype>
11#include <chrono>
12#include <cstring>
13#include <exception>
14#include <fstream>
15#include <iomanip>
16#include <iostream>
17#include <limits>
18#include <mutex>
19#if defined(__linux__) || defined(__APPLE__)
20#include <cerrno>
21#include <spawn.h>
22#include <sys/wait.h>
23#include <unistd.h>
24#endif
25#include <stdexcept>
26#include <thread>
27#include <unordered_set>
28
29#ifdef _WIN32
30#ifndef NOMINMAX
31#define NOMINMAX
32#endif
33#include <windows.h>
34#endif
35
36#if defined(__linux__) || defined(__APPLE__)
37extern char **environ;
38#endif
39
40namespace acmxvk {
41 [[nodiscard]] bool isValidCustomUniformName(const std::string &name) {
42 if (name.starts_with("gl_")) {
43 return false;
44 }
45 try {
46 input::validate_string(name, input::StringKind::Identifier, "custom uniform name");
47 return true;
48 } catch (const std::runtime_error &) {
49 return false;
50 }
51 }
52
53 [[nodiscard]] ShaderManifest loadShaderManifest(const fs::path &directory) {
54 ShaderManifest manifest;
55 const fs::path json_path = directory / "library.json";
56 const fs::path text_path = directory / "index.txt";
57 if (fs::is_regular_file(json_path)) {
58 manifest.path = json_path;
59 input::validate_text_file(json_path, "shader library.json");
60 try {
61 cv::FileStorage storage(json_path.string(), cv::FileStorage::READ | cv::FileStorage::FORMAT_JSON);
62 if (!storage.isOpened()) {
63 throw std::runtime_error("unable to open shader manifest: " + json_path.string());
64 }
65 const cv::FileNode shader_entries = storage["shaders"];
66 if (shader_entries.type() == cv::FileNode::NONE || !shader_entries.isSeq()) {
67 throw std::runtime_error(json_path.string() + " must contain a 'shaders' array");
68 }
69 for (const cv::FileNode &entry : shader_entries) {
70 if (manifest.entries.size() >= input::MAX_SHADER_ENTRIES) {
71 throw std::runtime_error(json_path.string() + " contains too many shader entries");
72 }
73 std::string filename;
74 if (entry.isString()) {
75 entry >> filename;
76 } else if (entry.isMap() && !entry["file"].empty()) {
77 entry["file"] >> filename;
78 } else {
79 throw std::runtime_error(json_path.string() + " contains a shader entry without a file name");
80 }
81 filename = trim(std::move(filename));
82 if (filename.empty()) {
83 throw std::runtime_error(json_path.string() + " contains a shader entry without a file name");
84 }
85 input::validate_string(filename, input::StringKind::Path, json_path.string() + " shader file");
86 manifest.entries.push_back(std::move(filename));
87 }
88
89 const cv::FileNode custom_uniforms = storage["custom_uniforms"];
90 if (!custom_uniforms.empty()) {
91 if (!custom_uniforms.isMap()) {
92 throw std::runtime_error(json_path.string() + " field 'custom_uniforms' must be an object");
93 }
94 bool has_explicit_slots = false;
95 bool has_implicit_slots = false;
96 std::unordered_set<std::size_t> occupied_slots;
97 for (auto iterator = custom_uniforms.begin(); iterator != custom_uniforms.end(); ++iterator) {
98 if (manifest.custom_uniforms.size() >= mxvk::VK_Sprite::MAX_CUSTOM_UNIFORMS) {
99 throw std::runtime_error(json_path.string() + " contains more than " + std::to_string(mxvk::VK_Sprite::MAX_CUSTOM_UNIFORMS) + " custom uniforms");
100 }
101
102 const cv::FileNode entry = *iterator;
104 uniform.name = entry.name();
105 if (!entry.isMap() || !isValidCustomUniformName(uniform.name)) {
106 throw std::runtime_error(json_path.string() + " contains an invalid custom uniform: " + uniform.name);
107 }
108 uniform.slot = manifest.custom_uniforms.size();
109 if (!entry["slot"].empty()) {
110 int slot = -1;
111 entry["slot"] >> slot;
112 if (slot < 0 || slot >= static_cast<int>(mxvk::VK_Sprite::MAX_CUSTOM_UNIFORMS)) {
113 throw std::runtime_error(json_path.string() + " contains an invalid slot for custom uniform: " + uniform.name);
114 }
115 uniform.slot = static_cast<std::size_t>(slot);
116 if (!occupied_slots.insert(uniform.slot).second) {
117 throw std::runtime_error(json_path.string() + " assigns more than one custom uniform to slot " + std::to_string(slot));
118 }
119 has_explicit_slots = true;
120 } else {
121 has_implicit_slots = true;
122 }
123 if (!entry["minimum"].empty()) {
124 entry["minimum"] >> uniform.minimum;
125 }
126 if (!entry["maximum"].empty()) {
127 entry["maximum"] >> uniform.maximum;
128 }
129 if (!entry["step"].empty()) {
130 entry["step"] >> uniform.step;
131 }
132 uniform.value = uniform.minimum;
133 if (!entry["value"].empty()) {
134 entry["value"] >> uniform.value;
135 }
136 if (!std::isfinite(uniform.minimum) || !std::isfinite(uniform.maximum) || !std::isfinite(uniform.step) || !std::isfinite(uniform.value) || uniform.maximum <= uniform.minimum || uniform.step <= 0.0 || std::abs(uniform.minimum) > std::numeric_limits<float>::max() || std::abs(uniform.maximum) > std::numeric_limits<float>::max() || std::abs(uniform.step) > std::numeric_limits<float>::max() || std::abs(uniform.value) > std::numeric_limits<float>::max()) {
137 throw std::runtime_error(json_path.string() + " contains an invalid range for custom uniform: " + uniform.name);
138 }
139 uniform.value = std::clamp(uniform.value, uniform.minimum, uniform.maximum);
140 manifest.custom_uniforms.push_back(std::move(uniform));
141 }
142 if (has_explicit_slots && has_implicit_slots) {
143 throw std::runtime_error(json_path.string() + " must specify a slot for every custom uniform or none");
144 }
145 if (has_explicit_slots) {
146 std::sort(manifest.custom_uniforms.begin(), manifest.custom_uniforms.end(), [](const ShaderManifest::CustomUniform &left, const ShaderManifest::CustomUniform &right) { return left.slot < right.slot; });
147 for (std::size_t slot = 0; slot < manifest.custom_uniforms.size(); ++slot) {
148 if (manifest.custom_uniforms[slot].slot != slot) {
149 throw std::runtime_error(json_path.string() + " custom uniform slots must be contiguous from zero");
150 }
151 }
152 }
153 }
154 } catch (const cv::Exception &error) {
155 throw std::runtime_error("unable to parse shader manifest " + json_path.string() + ": " + error.what());
156 }
157 return manifest;
158 }
159
160 if (!fs::is_regular_file(text_path)) {
161 throw std::runtime_error("no library.json or index.txt found in shader library: " + directory.string());
162 }
163 manifest.path = text_path;
164 input::validate_file_size(text_path, "shader index.txt");
165 std::ifstream manifest_input(text_path);
166 if (!manifest_input) {
167 throw std::runtime_error("unable to open shader manifest: " + text_path.string());
168 }
169 std::string line;
170 std::size_t line_number = 1;
171 while (input::read_bounded_line(manifest_input, line, "shader index.txt", line_number++)) {
172 line = trim(std::move(line));
173 if (!line.empty() && line.front() != '#') {
174 if (manifest.entries.size() >= input::MAX_SHADER_ENTRIES) {
175 throw std::runtime_error(text_path.string() + " contains too many shader entries");
176 }
177 input::validate_string(line, input::StringKind::Path, text_path.string() + " shader file");
178 manifest.entries.push_back(std::move(line));
179 }
180 }
181 return manifest;
182 }
183
184 [[nodiscard]] fs::path resolveShaderManifestEntry(const fs::path &directory, std::string entry) {
185 std::replace(entry.begin(), entry.end(), '\\', '/');
186 const fs::path relative_path(entry);
187 if (relative_path.is_absolute()) {
188 return {};
189 }
190
191 const fs::path normalized = relative_path.lexically_normal();
192 const std::string normalized_text = normalized.generic_string();
193 if (normalized_text.empty() || normalized_text == "." || normalized_text == ".." || normalized_text.starts_with("../") || normalized_text.find("/../") != std::string::npos || normalized.extension() != ".spv") {
194 return {};
195 }
196
197 std::error_code error;
198 const fs::path root = fs::weakly_canonical(directory, error);
199 if (error) {
200 return {};
201 }
202 const fs::path shader = fs::weakly_canonical(root / normalized, error);
203 if (error || !fs::is_regular_file(shader)) {
204 return {};
205 }
206 const std::string resolved_relative = shader.lexically_relative(root).generic_string();
207 if (resolved_relative.empty() || resolved_relative == ".." || resolved_relative.starts_with("../")) {
208 return {};
209 }
210 return shader;
211 }
212
213 [[nodiscard]] fs::path resolveShaderBuildEntry(const fs::path &directory, std::string entry) {
214 std::replace(entry.begin(), entry.end(), '\\', '/');
215 const fs::path relative_path(entry);
216 if (relative_path.is_absolute()) {
217 return {};
218 }
219
220 const fs::path normalized = relative_path.lexically_normal();
221 const std::string normalized_text = normalized.generic_string();
222 const std::string extension = normalized.extension().string();
223 if (normalized_text.empty() || normalized_text == "." || normalized_text == ".." || normalized_text.starts_with("../") || normalized_text.find("/../") != std::string::npos || (extension != ".frag" && extension != ".comp" && extension != ".spv")) {
224 return {};
225 }
226
227 std::error_code error;
228 const fs::path root = fs::weakly_canonical(directory, error);
229 if (error) {
230 return {};
231 }
232 const fs::path source = fs::weakly_canonical(root / normalized, error);
233 if (error || !fs::is_regular_file(source)) {
234 return {};
235 }
236 const std::string resolved_relative = source.lexically_relative(root).generic_string();
237 if (resolved_relative.empty() || resolved_relative == ".." || resolved_relative.starts_with("../")) {
238 return {};
239 }
240 return source;
241 }
242
243 [[nodiscard]] std::string escapeJson(std::string_view value) {
244 std::ostringstream escaped;
245 for (const unsigned char character : value) {
246 switch (character) {
247 case '"':
248 escaped << "\\\"";
249 break;
250 case '\\':
251 escaped << "\\\\";
252 break;
253 case '\b':
254 escaped << "\\b";
255 break;
256 case '\f':
257 escaped << "\\f";
258 break;
259 case '\n':
260 escaped << "\\n";
261 break;
262 case '\r':
263 escaped << "\\r";
264 break;
265 case '\t':
266 escaped << "\\t";
267 break;
268 default:
269 if (character < 0x20U) {
270 escaped << "\\u" << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << static_cast<unsigned int>(character) << std::dec << std::nouppercase;
271 } else {
272 escaped << static_cast<char>(character);
273 }
274 break;
275 }
276 }
277 return escaped.str();
278 }
279
280 [[nodiscard]] fs::path temporaryBuildPath(const fs::path &destination) {
281 static std::atomic<std::uint64_t> sequence{0};
282 for (int attempt = 0; attempt < 100; ++attempt) {
283 fs::path temporary = destination;
284 temporary += ".acmxvk-tmp-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + "-" + std::to_string(sequence.fetch_add(1U) + 1U);
285 if (!fs::exists(temporary)) {
286 return temporary;
287 }
288 }
289 throw std::runtime_error("unable to allocate a temporary shader build path for: " + destination.string());
290 }
291
292 void replaceBuiltFile(const fs::path &temporary, const fs::path &destination) {
293 std::error_code error;
294 fs::rename(temporary, destination, error);
295 if (error) {
296 fs::remove(temporary);
297 throw std::runtime_error("unable to install built file " + destination.string() + ": " + error.message());
298 }
299 }
300
301 class ShaderCompilationError : public std::runtime_error {
302 public:
303 using std::runtime_error::runtime_error;
304 };
305
306#ifdef _WIN32
307 [[nodiscard]] std::wstring utf8_to_wide(const std::string &value) {
308 if (value.empty()) {
309 return {};
310 }
311 const int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), nullptr, 0);
312 if (length <= 0) {
313 throw std::runtime_error("invalid UTF-8 in Windows command argument");
314 }
315 std::wstring result(static_cast<std::size_t>(length), L'\0');
316 if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), result.data(), length) != length) {
317 throw std::runtime_error("unable to convert Windows command argument");
318 }
319 return result;
320 }
321
322 [[nodiscard]] std::wstring quote_windows_argument(const std::wstring &value) {
323 std::wstring quoted{L"\""};
324 std::size_t backslash_count = 0;
325 for (const wchar_t character : value) {
326 if (character == L'\\') {
327 ++backslash_count;
328 continue;
329 }
330 if (character == L'"') {
331 quoted.append(backslash_count * 2U + 1U, L'\\');
332 quoted += character;
333 backslash_count = 0;
334 continue;
335 }
336 quoted.append(backslash_count, L'\\');
337 backslash_count = 0;
338 quoted += character;
339 }
340 quoted.append(backslash_count * 2U, L'\\');
341 quoted += L'"';
342 return quoted;
343 }
344
345 [[nodiscard]] DWORD run_windows_process(const std::vector<std::wstring> &arguments) {
346 std::wstring command_line;
347 for (const std::wstring &argument : arguments) {
348 if (!command_line.empty()) {
349 command_line += L' ';
350 }
351 command_line += quote_windows_argument(argument);
352 }
353
354 STARTUPINFOW startup_info{};
355 startup_info.cb = sizeof(startup_info);
356 PROCESS_INFORMATION process_info{};
357 if (CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup_info, &process_info) == FALSE) {
358 const DWORD process_error = GetLastError();
359 throw std::runtime_error("unable to execute glslc (Windows error " + std::to_string(process_error) + ")");
360 }
361
362 CloseHandle(process_info.hThread);
363 const DWORD wait_result = WaitForSingleObject(process_info.hProcess, INFINITE);
364 DWORD exit_code = 1;
365 if (wait_result != WAIT_OBJECT_0 || GetExitCodeProcess(process_info.hProcess, &exit_code) == FALSE) {
366 const DWORD process_error = GetLastError();
367 CloseHandle(process_info.hProcess);
368 throw std::runtime_error("unable to wait for glslc (Windows error " + std::to_string(process_error) + ")");
369 }
370 CloseHandle(process_info.hProcess);
371 return exit_code;
372 }
373#endif
374
375 void runGlslc(const std::string &executable, const fs::path &source_root, const fs::path &source, const fs::path &output) {
376#if defined(__linux__) || defined(__APPLE__)
377 std::vector<std::string> arguments{executable, "-I", source_root.string(), source.string(), "-o", output.string()};
378 std::vector<char *> argument_pointers;
379 argument_pointers.reserve(arguments.size() + 1U);
380 for (std::string &argument : arguments) {
381 argument_pointers.push_back(argument.data());
382 }
383 argument_pointers.push_back(nullptr);
384
385 pid_t process = 0;
386 const int spawn_result = posix_spawnp(&process, executable.c_str(), nullptr, nullptr, argument_pointers.data(), environ);
387 if (spawn_result != 0) {
388 throw std::runtime_error("unable to execute glslc '" + executable + "': " + std::strerror(spawn_result));
389 }
390
391 int status = 0;
392 while (::waitpid(process, &status, 0) < 0) {
393 if (errno != EINTR) {
394 throw std::runtime_error("unable to wait for glslc: " + std::string(std::strerror(errno)));
395 }
396 }
397 if (!WIFEXITED(status)) {
398 throw std::runtime_error("glslc terminated by a signal for " + source.string());
399 }
400 if (WEXITSTATUS(status) != 0) {
401 throw ShaderCompilationError("glslc failed for " + source.string() + " (exit status " + std::to_string(WEXITSTATUS(status)) + ")");
402 }
403#elif defined(_WIN32)
404 const DWORD result = run_windows_process({utf8_to_wide(executable), L"-I", source_root.wstring(), source.wstring(), L"-o", output.wstring()});
405 if (result != 0U) {
406 throw ShaderCompilationError("glslc failed for " + source.string() + " (exit status " + std::to_string(result) + ")");
407 }
408#else
409#error Unsupported platform
410#endif
411 }
412
413 [[nodiscard]] int buildShaderLibrary(const Options &options) {
414 const fs::path requested_manifest = fs::absolute(options.build_manifest).lexically_normal();
415 if (requested_manifest.filename() != "library.json") {
416 throw std::runtime_error("--build must name a file called library.json");
417 }
418 input::validate_text_file(requested_manifest, "source shader library.json");
419
420 std::error_code error;
421 const fs::path source_root = fs::weakly_canonical(requested_manifest.parent_path(), error);
422 if (error || source_root.empty()) {
423 throw std::runtime_error("unable to resolve source shader library: " + requested_manifest.string());
424 }
425 fs::create_directories(options.build_directory, error);
426 if (error) {
427 throw std::runtime_error("unable to create shader build directory: " + error.message());
428 }
429 const fs::path output_root = fs::weakly_canonical(options.build_directory, error);
430 if (error || output_root.empty()) {
431 throw std::runtime_error("unable to resolve shader build directory: " + options.build_directory);
432 }
433 if (source_root == output_root) {
434 throw std::runtime_error("the shader output directory must differ from the source "
435 "library directory");
436 }
437
438 const ShaderManifest manifest = loadShaderManifest(source_root);
439 if (manifest.entries.empty()) {
440 throw std::runtime_error("source library.json contains no shader entries");
441 }
442
443 struct PreparedEntry {
444 fs::path relative;
445 std::string output_entry;
446 bool ready = false;
447 };
448
449 std::vector<PreparedEntry> prepared_entries(manifest.entries.size());
450 std::vector<std::string> output_entries_by_index(manifest.entries.size());
451 std::unordered_set<std::string> unique_outputs;
452 std::atomic<std::size_t> compiled{0};
453 std::atomic<std::size_t> copied{0};
454 std::atomic<std::size_t> current{0};
455 std::atomic<std::size_t> failed{0};
456 std::atomic<std::size_t> pruned{0};
457 std::atomic<std::size_t> processed{0};
458 int next_progress = 5;
459 std::mutex progress_mutex;
460 std::mutex error_mutex;
461 std::mutex failure_mutex;
462 std::exception_ptr first_failure;
463
464 const auto report_progress = [&] {
465 const std::size_t completed = processed.fetch_add(1U) + 1U;
466 const int percentage = static_cast<int>(completed * 100U / manifest.entries.size());
467 const std::lock_guard lock(progress_mutex);
468 while (next_progress <= 100 && percentage >= next_progress) {
469 std::cout << "acmxvk: build progress: " << next_progress << "% (" << completed << '/' << manifest.entries.size() << ")\n" << std::flush;
470 next_progress += 5;
471 }
472 };
473
474 const auto store_failure = [&](std::exception_ptr failure) {
475 const std::lock_guard lock(failure_mutex);
476 if (!first_failure) {
477 first_failure = std::move(failure);
478 }
479 };
480
481 for (std::size_t index = 0; index < manifest.entries.size(); ++index) {
482 const std::string &entry = manifest.entries[index];
483 try {
484 std::string normalized_entry = entry;
485 std::replace(normalized_entry.begin(), normalized_entry.end(), '\\', '/');
486 fs::path relative(normalized_entry);
487 relative = relative.lexically_normal();
488 if (relative.extension() != ".spv") {
489 relative += ".spv";
490 }
491 const std::string output_entry = relative.generic_string();
492 std::string output_key = output_entry;
493 std::transform(output_key.begin(), output_key.end(), output_key.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); });
494 if (!unique_outputs.insert(output_key).second) {
495 throw std::runtime_error("source library produces a duplicate output path: " + output_entry);
496 }
497 prepared_entries[index] = PreparedEntry{relative, output_entry, true};
498 } catch (const std::exception &failure_value) {
499 if (!options.build_fix) {
500 throw;
501 }
502 ++failed;
503 std::cerr << "acmxvk: fix omitted '" << entry << "': " << failure_value.what() << '\n';
504 report_progress();
505 }
506 }
507
508 const auto process_entry = [&](std::size_t index) {
509 const PreparedEntry &prepared = prepared_entries[index];
510 if (!prepared.ready) {
511 return;
512 }
513 const std::string &entry = manifest.entries[index];
514 fs::path source;
515 fs::path destination;
516 try {
517 source = resolveShaderBuildEntry(source_root, entry);
518 if (source.empty()) {
519 throw std::runtime_error("source library contains an unavailable or unsafe shader: " + entry);
520 }
521
522 destination = output_root / prepared.relative;
523 std::error_code entry_error;
524 fs::create_directories(destination.parent_path(), entry_error);
525 if (entry_error) {
526 throw std::runtime_error("unable to create shader output directory: " + entry_error.message());
527 }
528 const fs::path destination_parent = fs::weakly_canonical(destination.parent_path(), entry_error);
529 const std::string parent_relative = entry_error ? std::string{} : destination_parent.lexically_relative(output_root).generic_string();
530 if (entry_error || parent_relative == ".." || parent_relative.starts_with("../") || fs::is_symlink(destination)) {
531 throw std::runtime_error("shader output resolves outside the output directory: " + prepared.output_entry);
532 }
533
534 bool needs_build = !fs::is_regular_file(destination);
535 if (!needs_build) {
536 needs_build = fs::last_write_time(destination, entry_error) < fs::last_write_time(source);
537 if (entry_error) {
538 needs_build = true;
539 entry_error.clear();
540 }
541 }
542 if (!needs_build) {
543 try {
544 input::validate_spirv_file(destination, "built shader module");
545 } catch (const std::runtime_error &) {
546 needs_build = true;
547 }
548 }
549
550 if (needs_build) {
551 const fs::path temporary = temporaryBuildPath(destination);
552 const bool copy_source = source.extension() == ".spv";
553 try {
554 if (copy_source) {
555 input::validate_spirv_file(source, "source shader module");
556 fs::copy_file(source, temporary, fs::copy_options::overwrite_existing);
557 } else {
558 input::validate_text_file(source, "GLSL shader source");
559 runGlslc(options.glslc_executable, source_root, source, temporary);
560 }
561 input::validate_spirv_file(temporary, "compiled shader module");
562 replaceBuiltFile(temporary, destination);
563 } catch (...) {
564 fs::remove(temporary);
565 throw;
566 }
567 if (copy_source) {
568 ++copied;
569 } else {
570 ++compiled;
571 }
572 } else {
573 ++current;
574 }
575 output_entries_by_index[index] = prepared.output_entry;
576 } catch (const std::exception &failure_value) {
577 if (!options.build_fix) {
578 store_failure(std::current_exception());
579 } else {
580 try {
581 const bool compilation_failed = dynamic_cast<const ShaderCompilationError *>(&failure_value) != nullptr;
582 if (!destination.empty()) {
583 std::error_code remove_error;
584 fs::remove(destination, remove_error);
585 if (remove_error) {
586 throw std::runtime_error("unable to remove failed shader output " + destination.string() + ": " + remove_error.message());
587 }
588 }
589 if (options.build_prune && compilation_failed && !source.empty() && (source.extension() == ".frag" || source.extension() == ".comp")) {
590 std::error_code remove_error;
591 const bool removed = fs::remove(source, remove_error);
592 if (remove_error || !removed) {
593 throw std::runtime_error("unable to prune failed shader source " + source.string() + (remove_error ? ": " + remove_error.message() : ": file was not removed"));
594 }
595 ++pruned;
596 const std::lock_guard lock(error_mutex);
597 std::cerr << "acmxvk: pruned failed source '" << source.string() << "'\n";
598 }
599 ++failed;
600 const std::lock_guard lock(error_mutex);
601 std::cerr << "acmxvk: fix omitted '" << entry << "': " << failure_value.what() << '\n';
602 } catch (...) {
603 store_failure(std::current_exception());
604 }
605 }
606 }
607 report_progress();
608 };
609
610 const std::size_t worker_count = std::min(static_cast<std::size_t>(options.build_parallel), manifest.entries.size());
611 if (worker_count > 1U) {
612 std::cout << "acmxvk: building shader library with " << worker_count << " parallel jobs\n";
613 }
614 std::atomic<std::size_t> next_entry{0};
615 const auto worker = [&] {
616 while (true) {
617 const std::size_t index = next_entry.fetch_add(1U);
618 if (index >= manifest.entries.size()) {
619 return;
620 }
621 process_entry(index);
622 }
623 };
624 std::vector<std::thread> workers;
625 workers.reserve(worker_count);
626 for (std::size_t index = 0; index < worker_count; ++index) {
627 workers.emplace_back(worker);
628 }
629 for (std::thread &thread : workers) {
630 thread.join();
631 }
632 if (first_failure) {
633 std::rethrow_exception(first_failure);
634 }
635
636 std::vector<std::string> output_entries;
637 output_entries.reserve(manifest.entries.size());
638 for (std::string &entry : output_entries_by_index) {
639 if (!entry.empty()) {
640 output_entries.push_back(std::move(entry));
641 }
642 }
643
644 const fs::path output_manifest = output_root / "library.json";
645 if (fs::is_symlink(output_manifest)) {
646 throw std::runtime_error("refusing to replace a symbolic-link output library.json");
647 }
648 const fs::path temporary_manifest = temporaryBuildPath(output_manifest);
649 {
650 std::ofstream output(temporary_manifest, std::ios::out | std::ios::trunc);
651 if (!output) {
652 throw std::runtime_error("unable to create output library.json");
653 }
654 output << "{\n \"version\": 1"
655 << ",\n \"backend\": \"acmxvk\""
656 << ",\n \"library_type\": \"runtime\"";
657 if (!manifest.custom_uniforms.empty()) {
658 output << ",\n \"custom_uniforms\": {\n";
659 for (std::size_t index = 0; index < manifest.custom_uniforms.size(); ++index) {
660 const ShaderManifest::CustomUniform &uniform = manifest.custom_uniforms[index];
661 output << " \"" << escapeJson(uniform.name) << "\": {\n" << std::setprecision(15) << " \"slot\": " << uniform.slot << ",\n \"minimum\": " << uniform.minimum << ",\n \"maximum\": " << uniform.maximum << ",\n \"step\": " << uniform.step << ",\n \"value\": " << uniform.value << "\n }";
662 output << (index + 1U < manifest.custom_uniforms.size() ? ",\n" : "\n");
663 }
664 output << " }";
665 }
666 output << ",\n \"shaders\": [\n";
667 for (std::size_t index = 0; index < output_entries.size(); ++index) {
668 output << " \"" << escapeJson(output_entries[index]) << '"' << (index + 1U < output_entries.size() ? ",\n" : "\n");
669 }
670 output << " ]\n}\n";
671 if (!output) {
672 fs::remove(temporary_manifest);
673 throw std::runtime_error("unable to write output library.json");
674 }
675 }
676 try {
677 input::validate_text_file(temporary_manifest, "built shader library.json");
678 replaceBuiltFile(temporary_manifest, output_manifest);
679 } catch (...) {
680 fs::remove(temporary_manifest);
681 throw;
682 }
683
684 std::cout << "acmxvk: shader library built in " << output_root << '\n' << "acmxvk: " << compiled << " compiled, " << copied << " copied, " << current << " up to date, " << failed << " failed, " << pruned << " pruned, " << output_entries.size() << " included\n";
685 return EXIT_SUCCESS;
686 }
687} // namespace acmxvk
GLsizei GLsizei * length
bool read_bounded_line(std::istream &input, std::string &line, std::string_view context, std::size_t line_number, std::size_t maximum_bytes)
constexpr std::size_t MAX_SHADER_ENTRIES
void validate_file_size(const std::filesystem::path &path, std::string_view context, std::uintmax_t maximum_bytes)
void validate_spirv_file(const std::filesystem::path &path, std::string_view context)
void validate_text_file(const std::filesystem::path &path, std::string_view context, std::uintmax_t maximum_bytes, std::size_t maximum_line_bytes)
void validate_string(std::string_view value, StringKind kind, std::string_view context, bool allow_empty)
fs::path resolveShaderManifestEntry(const fs::path &directory, std::string entry)
std::string escapeJson(std::string_view value)
void runGlslc(const std::string &executable, const fs::path &source_root, const fs::path &source, const fs::path &output)
std::string trim(std::string text)
Definition options.cpp:1454
ShaderManifest loadShaderManifest(const fs::path &directory)
fs::path resolveShaderBuildEntry(const fs::path &directory, std::string entry)
int buildShaderLibrary(const Options &options)
fs::path temporaryBuildPath(const fs::path &destination)
bool isValidCustomUniformName(const std::string &name)
void replaceBuiltFile(const fs::path &temporary, const fs::path &destination)
char ** environ
std::string glslc_executable
Definition options.hpp:179
std::string build_manifest
Definition options.hpp:177
std::string build_directory
Definition options.hpp:178
std::vector< std::string > entries
std::vector< CustomUniform > custom_uniforms