Repository navigation
Expand file tree
/
Copy pathScene.cpp
More file actions
367 lines (337 loc) · 16.2 KB
/
Copy pathScene.cpp
File metadata and controls
367 lines (337 loc) · 16.2 KB
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
#include "Scene.h"
#include "file_dialog.h"
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <optional>
#include <system_error>
#include <nlohmann/json.hpp>
#include <imgui.h>
#include "glm/gtc/type_ptr.hpp"
void Scene::makeThisSceneRendered() {
NRE::bindScene(scene);
}
namespace {
// The model files in folder, sorted, or nothing when it isn't a folder that can be read.
// Uses the error_code overloads, so a bad path never throws.
std::optional<std::vector<std::filesystem::path>> scanModels(const std::string& folder) {
std::error_code ec;
std::filesystem::directory_iterator it(folder, ec);
if (ec) return std::nullopt;
std::vector<std::filesystem::path> files;
for (; !ec && it != std::filesystem::directory_iterator(); it.increment(ec)) {
const auto ext = it->path().extension();
if (it->is_regular_file(ec) && (ext == ".glb" || ext == ".gltf" || ext == ".obj"))
files.push_back(it->path());
}
std::ranges::sort(files);
return files;
}
}
void Scene::setAssetsFolder(const std::string& path) {
modelFiles = scanModels(path).value_or(std::vector<std::filesystem::path>{});
assetsPath = path;
}
// Creates the (empty) NRE scene and shows the Create scene screen, with assetsPath filled in.
void Scene::createScene(std::string assetsPath) {
auto scene = NRE::createScene().value();
this->scene = scene;
isAlive = true;
this->assetsPath = assetsPath;
enterSetup(assetsPath, false);
}
void Scene::enterSetup(const std::string& startFolder, bool fromEditor) {
std::snprintf(folderField, sizeof folderField, "%s", startFolder.c_str());
refreshFolderField();
selected = -1;
canGoBack = fromEditor;
setup = true;
}
void Scene::refreshFolderField() {
auto files = scanModels(folderField);
folderModelCount = files ? static_cast<int>(files->size()) : -1;
}
// The Create scene screen: pick the assets folder for a new scene, or open a saved one.
void Scene::renderSetupScreen() {
const ImGuiIO& io = ImGui::GetIO();
ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::Begin("Create scene", nullptr,
ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove);
// The dialogs block until closed, so they're opened after the window is finished, not from inside it.
bool pickFolder = false, create = false, open = false, back = false;
ImGui::TextUnformatted("Assets folder");
ImGui::SetNextItemWidth(400.0f);
if (ImGui::InputText("##folder", folderField, sizeof folderField)) refreshFolderField();
ImGui::SameLine();
if (ImGui::Button("...")) pickFolder = true;
if (folderModelCount < 0) ImGui::TextDisabled("Folder not found");
else ImGui::TextDisabled("%d model%s found", folderModelCount, folderModelCount == 1 ? "" : "s");
ImGui::Spacing();
ImGui::BeginDisabled(folderModelCount < 0);
if (ImGui::Button("Create")) create = true;
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button("Open scene...")) open = true;
if (canGoBack) {
ImGui::SameLine();
if (ImGui::Button("Back")) back = true; // to the scene that was open, unchanged
}
ImGui::End();
if (pickFolder)
if (auto folder = FileDialog::pickFolder(folderField)) {
std::snprintf(folderField, sizeof folderField, "%s", folder->c_str());
refreshFolderField();
}
if (create) {
clearInstances();
scenePath.clear();
// Absolute, so the saved scene finds the folder whatever directory NSC is started from.
std::error_code ec;
std::filesystem::path folder = std::filesystem::absolute(folderField, ec);
setAssetsFolder(ec ? std::string(folderField) : folder.lexically_normal().string());
makeThisSceneRendered(); // instances are added to the bound scene
setup = false;
}
if (open) openSceneDialog(folderField);
if (back) setup = false;
}
void Scene::openSceneDialog(const std::string& startDir) {
if (auto path = FileDialog::openFile("NSC scene", "nsc", startDir))
if (!loadScene(*path)) std::cerr << "Can't open " << *path << " (not a scene?)\n";
}
// Removes every instance and model, leaving an empty scene.
void Scene::clearInstances() {
for (auto& instance : instances) (void)NRE::destroyInstance(instance.instance);
for (auto& model : models) (void)NRE::destroyModel(model);
instances.clear();
models.clear();
missingEntries.clear();
selected = -1;
}
// Replaces this scene's instances with the ones saved in path (by saveScene). Returns false without
// changing anything if the file doesn't exist or isn't valid JSON.
bool Scene::loadScene(std::string_view path) {
std::ifstream file(std::string{path}); // fstreams don't take string_view
if (!file) return false;
nlohmann::json j = nlohmann::json::parse(file, nullptr, false); // false: no exception on bad JSON
if (j.is_discarded()) {
std::cerr << "loadScene: " << path << " is not valid JSON\n";
return false;
}
scenePath = path;
// Missing fields fall back to defaults instead of throwing, so older or hand-edited files still load.
auto readVec3 = [](const nlohmann::json& parent, const char* key, glm::vec3 fallback) {
if (!parent.contains(key)) return fallback;
const nlohmann::json& v = parent[key];
return glm::vec3(v.value("x", fallback.x), v.value("y", fallback.y), v.value("z", fallback.z));
};
clearInstances();
setAssetsFolder(j.value("assets", assetsPath)); // the Models list follows the scene's folder
setup = false;
(void)NRE::bindScene(scene); // addInstanceToScene adds to the bound scene
if (!j.contains("scene")) return true;
for (const nlohmann::json& item : j["scene"]) {
std::string name = item.value("name", "");
std::filesystem::path file = std::filesystem::path(assetsPath) / name;
// Checked first: with RenderErrorPolicy::Panic, createModel aborts the app on a file it can't load.
std::error_code ec;
if (!std::filesystem::is_regular_file(file, ec)) {
std::cerr << "loadScene: model " << file << " not found, kept in the file but not shown\n";
missingEntries.push_back(item);
continue;
}
auto model = NRE::createModel(file.string());
if (!model) {
std::cerr << "loadScene: can't load model " << name << '\n';
continue;
}
models.push_back(*model);
auto instance = NRE::createInstance(*model).value();
(void)NRE::addInstanceToScene(instance);
NRE::Transform t;
t.position = readVec3(item, "position", glm::vec3(0.0f));
if (item.contains("rotation")) {
const nlohmann::json& r = item["rotation"];
t.rotation = glm::normalize(glm::quat(r.value("w", 1.0f), r.value("x", 0.0f),
r.value("y", 0.0f), r.value("z", 0.0f))); // glm::quat is (w, x, y, z)
}
t.scale = readVec3(item, "scale", glm::vec3(1.0f));
(void)NRE::setInstanceTransform(instance, t);
instances.push_back(InstancWithName{name, instance, glm::degrees(glm::eulerAngles(t.rotation))});
}
return true;
}
bool Scene::saveScene(std::string_view path) {
nlohmann::json j;
j["assets"] = assetsPath;
nlohmann::json& scene = j["scene"];
for (int i = 0; i < instances.size(); i++) {
scene[i]["name"] = instances[i].name;
auto transform = NRE::getInstanceTransform(instances[i].instance);
scene[i]["position"]["x"] = transform->position.x;
scene[i]["position"]["y"] = transform->position.y;
scene[i]["position"]["z"] = transform->position.z;
scene[i]["rotation"]["x"] = transform->rotation.x;
scene[i]["rotation"]["y"] = transform->rotation.y;
scene[i]["rotation"]["z"] = transform->rotation.z;
scene[i]["rotation"]["w"] = transform->rotation.w;
scene[i]["scale"]["x"] = transform->scale.x;
scene[i]["scale"]["y"] = transform->scale.y;
scene[i]["scale"]["z"] = transform->scale.z;
}
for (const nlohmann::json& entry : missingEntries) scene.push_back(entry);
if (scene.is_null()) scene = nlohmann::json::array(); // an empty scene saves as [] rather than null
std::ofstream file(std::string{path});
file << j.dump(2);
if (!file) return false;
scenePath = path;
return true;
}
// The bar across the top of the window: File > New / Open... / Save / Save As..., and Ctrl+S.
void Scene::renderMenuBar() {
// The dialogs block until closed, so they're opened after the menu is finished, not from inside it.
enum class FileAction { None, Open, Save, SaveAs };
FileAction action = FileAction::None;
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New")) enterSetup(assetsPath, true); // the instances stay until Create
if (ImGui::MenuItem("Open...")) action = FileAction::Open;
if (ImGui::MenuItem("Save", "Ctrl+S")) action = FileAction::Save;
if (ImGui::MenuItem("Save As...")) action = FileAction::SaveAs;
ImGui::EndMenu();
}
ImGui::TextDisabled("%s", scenePath.empty() ? "(unsaved scene)" : scenePath.c_str());
ImGui::EndMainMenuBar();
}
// RouteGlobal: works whichever ImGui window has focus, or none.
if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_S, ImGuiInputFlags_RouteGlobal)) action = FileAction::Save;
if (action == FileAction::Save && scenePath.empty()) action = FileAction::SaveAs; // never saved: ask where
// The dialogs start in the current scene's folder, or the assets folder for a new scene.
std::filesystem::path current = scenePath;
std::string startDir = scenePath.empty() ? assetsPath : current.parent_path().string();
switch (action) {
case FileAction::None:
break;
case FileAction::Open:
openSceneDialog(startDir);
break;
case FileAction::Save:
if (!saveScene(scenePath)) std::cerr << "Can't write " << scenePath << '\n';
break;
case FileAction::SaveAs: {
std::string name = scenePath.empty() ? "scene.nsc" : current.filename().string();
if (auto path = FileDialog::saveFile("NSC scene", "nsc", startDir, name)) {
std::filesystem::path chosen = *path;
if (!chosen.has_extension()) chosen += ".nsc"; // not every dialog adds it
if (!saveScene(chosen.string())) std::cerr << "Can't write " << chosen << '\n';
}
break;
}
}
}
void Scene::renderUIForScene() {
if (setup) {
renderSetupScreen();
return;
}
renderMenuBar();
ImGui::Begin("Models");
for (const auto& file : modelFiles) {
if (ImGui::Button(file.filename().string().c_str())) {
std::error_code ec;
if (!std::filesystem::is_regular_file(file, ec)) { // deleted since the scan; createModel would abort
std::cerr << "Model " << file << " no longer exists\n";
continue;
}
if (auto model = NRE::createModel(file.string())) {
models.push_back(*model);
auto instance = NRE::createInstance(*model).value();
(void) NRE::addInstanceToScene(instance);
instances.push_back(InstancWithName{file.filename().string(),instance});
}
}
}
ImGui::End();
ImGui::Begin("Instances", nullptr, ImGuiWindowFlags_MenuBar);
if (ImGui::BeginMenuBar()) {
if (ImGui::RadioButton("Move", gizmoOp == ImGuizmo::TRANSLATE)) gizmoOp = ImGuizmo::TRANSLATE;
if (ImGui::RadioButton("Rotate", gizmoOp == ImGuizmo::ROTATE)) gizmoOp = ImGuizmo::ROTATE;
if (ImGui::RadioButton("Scale", gizmoOp == ImGuizmo::SCALE)) gizmoOp = ImGuizmo::SCALE;
ImGui::Separator();
// Scale is always along the object's own axes, so the toggle only affects move and rotate.
if (ImGui::RadioButton("World", gizmoMode == ImGuizmo::WORLD)) gizmoMode = ImGuizmo::WORLD;
if (ImGui::RadioButton("Local", gizmoMode == ImGuizmo::LOCAL)) gizmoMode = ImGuizmo::LOCAL;
ImGui::EndMenuBar();
}
int toDelete = -1; // erased after the loops, not while iterating
int i = 0;
for (auto& instance : instances) {
ImGui::PushID(i);
if (ImGui::SmallButton("x")) toDelete = i;
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Remove %s", instance.name.c_str());
ImGui::SameLine();
// Click the name to put the gizmo on this instance (again to take it off).
if (ImGui::Selectable(instance.name.c_str(), selected == i)) selected = selected == i ? -1 : i;
auto transform = getInstanceTransform(instance.instance).value();
bool changed = false;
changed |= ImGui::InputFloat3("Position", &transform.position.x, "%.1f");
if (ImGui::InputFloat3("Rotation", &instance.rotationDegrees.x, "%.1f")) {
transform.rotation = glm::quat(glm::radians(instance.rotationDegrees)); // pitch, yaw, roll -> quat
changed = true;
}
changed |= ImGui::InputFloat3("Scale", &transform.scale.x, "%.2f");
if (changed) (void)setInstanceTransform(instance.instance, transform);
ImGui::Separator();
ImGui::PopID();
i++;
}
ImGui::End();
if (toDelete != -1) {
(void)destroyInstance(instances[toDelete].instance); // also removes it from the scene
instances.erase(instances.begin() + toDelete);
if (selected == toDelete) selected = -1;
else if (selected > toDelete) selected--;
}
if (selected != -1) {
auto& sel = instances[selected];
const ImGuiIO& io = ImGui::GetIO();
ImGuizmo::SetOrthographic(false);
ImGuizmo::SetDrawlist(ImGui::GetBackgroundDrawList()); // over the 3D view, under the ImGui windows
ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);
glm::mat4 view = NRE::getViewMatrix().value();
// NRE has no projection getter: this copies the one in its renderer.cpp (updateProjection),
// minus the Vulkan Y flip, because ImGuizmo expects an OpenGL-style projection.
glm::mat4 proj = glm::perspective(glm::radians(60.0f), io.DisplaySize.x / io.DisplaySize.y, 0.1f, 1000.0f);
glm::mat4 model = getInstanceMatrix(sel.instance).value();
if (ImGuizmo::Manipulate(glm::value_ptr(view), glm::value_ptr(proj), gizmoOp, gizmoMode,
glm::value_ptr(model))) {
// Back to position / rotation / scale. The matrix is translate * rotate * scale, so no skew.
NRE::Transform t;
t.position = glm::vec3(model[3]);
t.scale = {glm::length(glm::vec3(model[0])), glm::length(glm::vec3(model[1])),
glm::length(glm::vec3(model[2]))};
t.rotation = glm::normalize(glm::quat_cast(glm::mat3(glm::vec3(model[0]) / t.scale.x,
glm::vec3(model[1]) / t.scale.y,
glm::vec3(model[2]) / t.scale.z)));
if (gizmoOp == ImGuizmo::ROTATE) // keep the Rotation fields in sync with the gizmo
sel.rotationDegrees = glm::degrees(glm::eulerAngles(t.rotation));
(void)setInstanceTransform(sel.instance, t);
}
}
}
void Scene::destroyScene() {
for (auto& instance : instances) {
NRE::destroyInstance(instance.instance);
}
for (auto& model: models) {
NRE::destroyModel(model);
}
NRE::destroyScene(scene);
isAlive = false;
}
Scene::~Scene() {
if (isAlive) {
destroyScene();
}
}