Torch
Loading...
Searching...
No Matches
ExportUtils.h
1#pragma once
2
3#ifdef BUILD_UI
4
5#include <cstdint>
6#include <cstdio>
7#include <filesystem>
8#include <string>
9#include <unordered_map>
10
11#include "imgui.h"
12
13namespace UI {
14
15// Exports land under torch-exports/ mirroring the asset path.
16inline std::filesystem::path ExportFilePath(const std::string& assetName, const char* ext) {
17 std::filesystem::path path = std::filesystem::path("torch-exports") / (assetName + "." + ext);
18 std::error_code ec;
19 std::filesystem::create_directories(path.parent_path(), ec);
20 return path;
21}
22
23inline bool WriteWavFile(const std::filesystem::path& path, const int16_t* samples, size_t frames, int channels,
24 int rate) {
25 FILE* f = fopen(path.string().c_str(), "wb");
26 if (f == nullptr) {
27 return false;
28 }
29 const uint32_t dataSize = (uint32_t)(frames * channels * 2);
30 const uint32_t riffSize = 36 + dataSize;
31 const uint16_t fmt = 1, ch = (uint16_t)channels, bits = 16;
32 const uint16_t align = (uint16_t)(channels * 2);
33 const uint32_t rate32 = (uint32_t)rate, byteRate = rate32 * align, fmtSize = 16;
34 fwrite("RIFF", 1, 4, f);
35 fwrite(&riffSize, 4, 1, f);
36 fwrite("WAVE", 1, 4, f);
37 fwrite("fmt ", 1, 4, f);
38 fwrite(&fmtSize, 4, 1, f);
39 fwrite(&fmt, 2, 1, f);
40 fwrite(&ch, 2, 1, f);
41 fwrite(&rate32, 4, 1, f);
42 fwrite(&byteRate, 4, 1, f);
43 fwrite(&align, 2, 1, f);
44 fwrite(&bits, 2, 1, f);
45 fwrite("data", 1, 4, f);
46 fwrite(&dataSize, 4, 1, f);
47 fwrite(samples, 2, frames * channels, f);
48 fclose(f);
49 return true;
50}
51
52// Last export result per asset; shown as a "saved" marker with the full
53// path in the tooltip.
54inline std::unordered_map<std::string, std::string>& ExportResults() {
55 static std::unordered_map<std::string, std::string> results;
56 return results;
57}
58
59inline void NoteExport(const std::string& assetName, const std::string& result) {
60 ExportResults()[assetName] = result;
61}
62
63inline void DrawExportMarker(const std::string& assetName) {
64 const auto it = ExportResults().find(assetName);
65 if (it == ExportResults().end()) {
66 return;
67 }
68 ImGui::SameLine();
69 ImGui::TextDisabled("saved");
70 if (ImGui::IsItemHovered()) {
71 ImGui::SetTooltip("%s", it->second.c_str());
72 }
73}
74
75} // namespace UI
76
77#endif // BUILD_UI