Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
292 lines
13 KiB
C++
292 lines
13 KiB
C++
#include "scene/SceneFile.h"
|
|
|
|
#include "model/PathUtil.h"
|
|
|
|
#include <nlohmann/json.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
|
|
namespace fs = std::filesystem;
|
|
using json = nlohmann::ordered_json;
|
|
|
|
namespace mr {
|
|
|
|
namespace {
|
|
|
|
json vec(const osg::Vec3f& v) { return json::array({v.x(), v.y(), v.z()}); }
|
|
json vec(const osg::Vec3d& v) { return json::array({v.x(), v.y(), v.z()}); }
|
|
|
|
const char* const kShadingNames[] = {"toon", "lambert", "cel", "soft"};
|
|
|
|
int shadingFromName(const std::string& name) {
|
|
for (int i = 0; i < 4; ++i)
|
|
if (name == kShadingNames[i]) return i;
|
|
return 0;
|
|
}
|
|
|
|
template <typename V>
|
|
void readVec(const json& j, const char* key, V& out) {
|
|
auto it = j.find(key);
|
|
if (it == j.end() || !it->is_array() || it->size() != 3) return;
|
|
for (int i = 0; i < 3; ++i) out[i] = (*it)[i].get<typename V::value_type>();
|
|
}
|
|
|
|
template <typename T>
|
|
void read(const json& j, const char* key, T& out) {
|
|
auto it = j.find(key);
|
|
if (it != j.end() && !it->is_null()) out = it->get<T>();
|
|
}
|
|
|
|
// Relative to the scene's folder when possible, always with forward slashes.
|
|
std::string relativePath(const std::string& path, const fs::path& baseDir) {
|
|
if (path.empty()) return {};
|
|
std::error_code ec;
|
|
const fs::path p = pathFromUtf8(path);
|
|
fs::path rel = fs::relative(p, baseDir, ec);
|
|
if (ec || rel.empty() || p.root_name() != baseDir.root_name()) rel = p;
|
|
std::string out = pathToUtf8(rel);
|
|
std::replace(out.begin(), out.end(), '\\', '/');
|
|
return out;
|
|
}
|
|
|
|
std::string absolutePath(const std::string& stored, const fs::path& baseDir) {
|
|
if (stored.empty()) return {};
|
|
fs::path p = pathFromUtf8(stored);
|
|
if (p.is_relative()) p = baseDir / p;
|
|
return pathToUtf8(p.lexically_normal().make_preferred());
|
|
}
|
|
|
|
} // namespace
|
|
|
|
bool saveScene(const Scene& scene, const std::string& path, std::string& error) {
|
|
std::error_code ec;
|
|
const fs::path file = fs::absolute(pathFromUtf8(path), ec);
|
|
const fs::path dir = file.parent_path();
|
|
json j;
|
|
j["format"] = "mr-scene";
|
|
j["version"] = kSceneFormatVersion;
|
|
json models = json::array();
|
|
for (const SceneModel& m : scene.models) {
|
|
json jm;
|
|
jm["path"] = relativePath(m.path, dir);
|
|
jm["stage"] = m.stage;
|
|
jm["visible"] = m.visible;
|
|
jm["position"] = vec(m.position);
|
|
jm["rotationY"] = m.rotationY;
|
|
jm["scale"] = m.scale;
|
|
if (!m.motionPath.empty()) jm["motion"] = relativePath(m.motionPath, dir);
|
|
json poses = json::object();
|
|
for (const auto& [name, pose] : m.bonePoses)
|
|
poses[name] = {{"rotation", vec(pose.eulerDegrees)}, {"translation", vec(pose.translation)}};
|
|
if (!poses.empty()) jm["bones"] = poses;
|
|
json morphs = json::object();
|
|
for (const auto& [name, weight] : m.morphWeights) morphs[name] = weight;
|
|
if (!morphs.empty()) jm["morphs"] = morphs;
|
|
models.push_back(jm);
|
|
}
|
|
j["models"] = models;
|
|
j["activeModel"] = scene.activeModel;
|
|
j["timeline"] = {{"frame", scene.frame}, {"loop", scene.loop}};
|
|
if (!scene.cameraMotionPath.empty()) j["timeline"]["camera"] = relativePath(scene.cameraMotionPath, dir);
|
|
j["timeline"]["followCamera"] = scene.followCamera;
|
|
j["timeline"]["cameraFit"] = {{"madeForHeight", scene.cameraMadeFor},
|
|
{"heightScale", scene.cameraHeightScale},
|
|
{"distance", scene.cameraDistance},
|
|
{"offset", vec(scene.cameraOffset)},
|
|
{"followModel", scene.cameraFollowModel}};
|
|
if (!scene.audioPath.empty()) j["timeline"]["audio"] = relativePath(scene.audioPath, dir);
|
|
j["timeline"]["volume"] = scene.volume;
|
|
if (scene.view.valid)
|
|
j["view"] = {{"eye", vec(scene.view.eye)}, {"center", vec(scene.view.center)}, {"up", vec(scene.view.up)}};
|
|
j["settings"] = {{"grid", scene.showGrid},
|
|
{"physics", scene.physics},
|
|
{"ik", scene.ik},
|
|
{"gpuSkinning", scene.gpuSkinning},
|
|
{"skeleton", scene.skeleton},
|
|
{"wireframe", scene.wireframe},
|
|
{"backfaceCulling", scene.backfaceCulling},
|
|
{"lightFollowsCamera", scene.look.lightFollowsCamera},
|
|
{"shading", kShadingNames[std::clamp(scene.look.shading, 0, 3)]}};
|
|
const LookSettings& look = scene.look;
|
|
j["look"] = {{"lightColor", vec(look.lightColor)},
|
|
{"lightAzimuth", look.lightAzimuth},
|
|
{"lightElevation", look.lightElevation},
|
|
{"outlines", look.outlines},
|
|
{"outlineWidth", look.outlineWidth},
|
|
{"shadows", look.shadows},
|
|
{"shadowQuality", look.shadowQuality},
|
|
{"shadowSoftness", look.shadowSoftness},
|
|
{"shadowStrength", look.shadowStrength},
|
|
{"stageShadows", look.stageShadows},
|
|
{"groundShadow", look.groundShadow},
|
|
{"groundShadowOpacity", look.groundShadowOpacity},
|
|
{"rimStrength", look.rimStrength},
|
|
{"rimColor", vec(look.rimColor)},
|
|
{"bloom", look.bloom},
|
|
{"bloomStrength", look.bloomStrength},
|
|
{"bloomThreshold", look.bloomThreshold},
|
|
{"bloomRadius", look.bloomRadius},
|
|
{"ambientOcclusion", look.ambientOcclusion},
|
|
{"aoStrength", look.aoStrength},
|
|
{"aoRadius", look.aoRadius},
|
|
{"toneMapping", look.toneMapping == 1 ? "filmic" : "off"},
|
|
{"exposure", look.exposure},
|
|
{"contrast", look.contrast},
|
|
{"saturation", look.saturation},
|
|
{"temperature", look.temperature},
|
|
{"vignette", look.vignette},
|
|
{"fxaa", look.fxaa}};
|
|
j["render"] = {{"width", scene.renderWidth},
|
|
{"height", scene.renderHeight},
|
|
{"transparent", scene.renderTransparent},
|
|
{"mp4", scene.renderMp4},
|
|
{"audio", scene.renderAudio}};
|
|
|
|
const fs::path tmp = fs::path(file).concat(".tmp");
|
|
{
|
|
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
|
|
if (!out) {
|
|
error = "Cannot write " + path;
|
|
return false;
|
|
}
|
|
out << j.dump(2) << "\n";
|
|
if (!out) {
|
|
error = "Failed writing " + path;
|
|
return false;
|
|
}
|
|
}
|
|
fs::rename(tmp, file, ec); // replace atomically so a failed save never truncates the old scene
|
|
if (ec) {
|
|
fs::remove(tmp, ec);
|
|
error = "Cannot replace " + path + ": " + ec.message();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool loadScene(const std::string& path, Scene& scene, std::string& error) {
|
|
std::vector<uint8_t> bytes;
|
|
if (!readFileBytes(path, bytes)) {
|
|
error = "Cannot read " + path;
|
|
return false;
|
|
}
|
|
json j = json::parse(bytes.begin(), bytes.end(), nullptr, false);
|
|
if (j.is_discarded() || !j.is_object()) {
|
|
error = path + " is not a valid scene file";
|
|
return false;
|
|
}
|
|
if (j.value("format", std::string()) != "mr-scene") {
|
|
error = path + " is not a model renderer scene";
|
|
return false;
|
|
}
|
|
if (j.value("version", 0) > kSceneFormatVersion) {
|
|
error = path + " was saved by a newer version of the program";
|
|
return false;
|
|
}
|
|
std::error_code ec;
|
|
const fs::path dir = fs::absolute(pathFromUtf8(path), ec).parent_path();
|
|
try {
|
|
scene = Scene();
|
|
for (const json& jm : j.value("models", json::array())) {
|
|
SceneModel m;
|
|
m.path = absolutePath(jm.value("path", std::string()), dir);
|
|
read(jm, "stage", m.stage);
|
|
read(jm, "visible", m.visible);
|
|
readVec(jm, "position", m.position);
|
|
read(jm, "rotationY", m.rotationY);
|
|
read(jm, "scale", m.scale);
|
|
if (!(m.scale > 0.f)) m.scale = 1.f;
|
|
m.motionPath = absolutePath(jm.value("motion", std::string()), dir);
|
|
if (auto it = jm.find("bones"); it != jm.end() && it->is_object())
|
|
for (const auto& [name, jp] : it->items()) {
|
|
BonePose pose;
|
|
readVec(jp, "rotation", pose.eulerDegrees);
|
|
readVec(jp, "translation", pose.translation);
|
|
m.bonePoses.emplace_back(name, pose);
|
|
}
|
|
if (auto it = jm.find("morphs"); it != jm.end() && it->is_object())
|
|
for (const auto& [name, w] : it->items()) m.morphWeights.emplace_back(name, w.get<float>());
|
|
if (!m.path.empty()) scene.models.push_back(std::move(m));
|
|
}
|
|
read(j, "activeModel", scene.activeModel);
|
|
if (auto it = j.find("timeline"); it != j.end() && it->is_object()) {
|
|
read(*it, "frame", scene.frame);
|
|
read(*it, "loop", scene.loop);
|
|
scene.cameraMotionPath = absolutePath(it->value("camera", std::string()), dir);
|
|
read(*it, "followCamera", scene.followCamera);
|
|
if (auto fit = it->find("cameraFit"); fit != it->end() && fit->is_object()) {
|
|
read(*fit, "madeForHeight", scene.cameraMadeFor);
|
|
read(*fit, "heightScale", scene.cameraHeightScale);
|
|
read(*fit, "distance", scene.cameraDistance);
|
|
readVec(*fit, "offset", scene.cameraOffset);
|
|
read(*fit, "followModel", scene.cameraFollowModel);
|
|
}
|
|
scene.audioPath = absolutePath(it->value("audio", std::string()), dir);
|
|
read(*it, "volume", scene.volume);
|
|
}
|
|
if (auto it = j.find("view"); it != j.end() && it->is_object()) {
|
|
readVec(*it, "eye", scene.view.eye);
|
|
readVec(*it, "center", scene.view.center);
|
|
readVec(*it, "up", scene.view.up);
|
|
scene.view.valid = true;
|
|
}
|
|
if (auto it = j.find("settings"); it != j.end() && it->is_object()) {
|
|
read(*it, "grid", scene.showGrid);
|
|
read(*it, "physics", scene.physics);
|
|
read(*it, "ik", scene.ik);
|
|
read(*it, "gpuSkinning", scene.gpuSkinning);
|
|
read(*it, "skeleton", scene.skeleton);
|
|
read(*it, "wireframe", scene.wireframe);
|
|
read(*it, "backfaceCulling", scene.backfaceCulling);
|
|
read(*it, "lightFollowsCamera", scene.look.lightFollowsCamera);
|
|
scene.look.shading = shadingFromName(it->value("shading", std::string("toon")));
|
|
}
|
|
if (auto it = j.find("look"); it != j.end() && it->is_object()) {
|
|
LookSettings& look = scene.look;
|
|
readVec(*it, "lightColor", look.lightColor);
|
|
read(*it, "lightAzimuth", look.lightAzimuth);
|
|
read(*it, "lightElevation", look.lightElevation);
|
|
read(*it, "outlines", look.outlines);
|
|
read(*it, "outlineWidth", look.outlineWidth);
|
|
read(*it, "shadows", look.shadows);
|
|
read(*it, "shadowQuality", look.shadowQuality);
|
|
read(*it, "shadowSoftness", look.shadowSoftness);
|
|
read(*it, "shadowStrength", look.shadowStrength);
|
|
read(*it, "stageShadows", look.stageShadows);
|
|
read(*it, "groundShadow", look.groundShadow);
|
|
read(*it, "groundShadowOpacity", look.groundShadowOpacity);
|
|
read(*it, "rimStrength", look.rimStrength);
|
|
readVec(*it, "rimColor", look.rimColor);
|
|
read(*it, "bloom", look.bloom);
|
|
read(*it, "bloomStrength", look.bloomStrength);
|
|
read(*it, "bloomThreshold", look.bloomThreshold);
|
|
read(*it, "bloomRadius", look.bloomRadius);
|
|
read(*it, "ambientOcclusion", look.ambientOcclusion);
|
|
read(*it, "aoStrength", look.aoStrength);
|
|
read(*it, "aoRadius", look.aoRadius);
|
|
look.toneMapping = it->value("toneMapping", std::string("off")) == "filmic" ? 1 : 0;
|
|
read(*it, "exposure", look.exposure);
|
|
read(*it, "contrast", look.contrast);
|
|
read(*it, "saturation", look.saturation);
|
|
read(*it, "temperature", look.temperature);
|
|
read(*it, "vignette", look.vignette);
|
|
read(*it, "fxaa", look.fxaa);
|
|
}
|
|
if (auto it = j.find("render"); it != j.end() && it->is_object()) {
|
|
read(*it, "width", scene.renderWidth);
|
|
read(*it, "height", scene.renderHeight);
|
|
read(*it, "transparent", scene.renderTransparent);
|
|
read(*it, "mp4", scene.renderMp4);
|
|
read(*it, "audio", scene.renderAudio);
|
|
}
|
|
} catch (const json::exception& e) {
|
|
error = path + ": " + e.what();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
} // namespace mr
|