diff --git a/README.md b/README.md index 0cd208b..b6cd385 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,13 @@ restores the default). and one row of keyframes per camera, song, bone and morph track. Click a bone row to select that bone. Ctrl+wheel zooms, Shift+wheel or middle drag pans. While the song plays its clock drives the timeline. Untick **Camera follow** to orbit freely. + **Camera fit...** adapts a camera motion made for a different model: set **Made for height** (about + 20 for standard MMD models, or **Measure model...** to read it from the model the motion came + with), then **Fit to model** scales the camera's heights to the selected model. **Distance** moves + every shot closer or farther and **Offset X/Y/Z** shifts the whole camera. With **Follow model + placement** on, moving, turning or scaling the model carries the camera with it. Saved in the scene; + `--camera-made-for H --camera-fit`, `--camera-height S`, `--camera-distance S` and + `--camera-offset x,y,z` do the same from the command line. * **Pop out** (top-left of the 3D view, or **View > Viewport in separate window**) moves the 3D view into its own OS window, e.g. for a second monitor; close it or press **Dock viewport back**. * **File > Render...** writes a PNG frame sequence at any resolution (presets up to 4K and diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 86eed30..a42860b 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -188,6 +188,7 @@ void App::updatePlacement(SceneItem& item) { item.node->setMatrix(osg::Matrix::scale(item.scale, item.scale, item.scale) * osg::Matrix::rotate(osg::DegreesToRadians(item.rotationY), osg::Y_AXIS) * osg::Matrix::translate(item.position) * item.base); + if (camera_ && useMotionCamera_ && cameraFit_.followModel) applyCamera(); } void App::applyViewSettings() { @@ -318,13 +319,81 @@ void App::applyFrame() { } void App::applyCamera() { - const CameraPose pose = evaluateCamera(camera_->cameraKeys, motionFrame_); - const osg::Matrixd toWorld = osg::Matrixd::rotate(osg::PI_2, osg::X_AXIS); // as ModelNode - manipulator_->setTransformation(osg::Vec3d(pose.eye) * toWorld, osg::Vec3d(pose.center) * toWorld, - osg::Vec3d(pose.up) * toWorld); + CameraPose pose = evaluateCamera(camera_->cameraKeys, motionFrame_); + const auto fit = [&](osg::Vec3f p) { return osg::Vec3f(p.x(), p.y() * cameraFit_.heightScale, p.z()); }; + const osg::Vec3f center = fit(pose.center); + const osg::Vec3f eye = center + (fit(pose.eye) - center) * cameraFit_.distance + cameraFit_.offset; + // Camera motions are relative to the dancer: moving, turning or scaling the model carries the camera along. + osg::Matrixd toWorld = osg::Matrixd::rotate(osg::PI_2, osg::X_AXIS); // as ModelNode + if (const SceneItem* item = cameraFit_.followModel ? followedItem() : nullptr) toWorld = item->node->getMatrix(); + const osg::Vec3d worldEye = osg::Vec3d(eye) * toWorld, worldCenter = osg::Vec3d(center + cameraFit_.offset) * toWorld; + const osg::Vec3d worldUp = osg::Vec3d(pose.up + center) * toWorld - osg::Vec3d(center) * toWorld; + manipulator_->setTransformation(worldEye, worldCenter, worldUp); fov_ = pose.fov; } +void App::setCameraFit(const CameraFit& fit) { + cameraFit_ = fit; + if (camera_ && useMotionCamera_) applyCamera(); +} + +// The selected model, or the first visible non-stage model when a stage is selected. +const App::SceneItem* App::followedItem() const { + if (active_ >= 0 && active_ < static_cast(items_.size()) && !items_[active_]->stage) return items_[active_].get(); + for (const auto& item : items_) + if (!item->stage && item->visible) return item.get(); + return nullptr; +} + +// In the model's own units: its Scale already scales the camera through followModel. +float App::followedModelHeight() const { + const SceneItem* item = followedItem(); + if (!item) return 0.f; + osg::Vec3f lo, hi; + item->node->model().computeBounds(lo, hi); + return hi.y() - lo.y(); +} + +void App::fitCameraToModel() { + const float height = followedModelHeight(); + if (height > 0.f && cameraFit_.madeFor > 0.f) cameraFit_.heightScale = height / cameraFit_.madeFor; + if (camera_ && useMotionCamera_) applyCamera(); +} + +void App::drawCameraFit() { + bool changed = false; + ImGui::TextUnformatted("Fit the camera motion to your model"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f); + ImGui::DragFloat("Made for height", &cameraFit_.madeFor, 0.1f, 1.f, 1000.f, "%.1f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Height of the model the camera motion was made for.\nStandard MMD models are about 20."); + ImGui::SameLine(); + if (ImGui::Button("Measure model...")) { + measuringModel_ = true; + fileBrowser_.open(); + } + const float height = followedModelHeight(); + ImGui::BeginDisabled(height <= 0.f); + if (ImGui::Button("Fit to model")) fitCameraToModel(); + ImGui::EndDisabled(); + ImGui::SameLine(); + ImGui::TextDisabled(height > 0.f ? "your model: %.1f" : "no model", height); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f); + changed |= ImGui::DragFloat("Height scale", &cameraFit_.heightScale, 0.005f, 0.05f, 20.f, "%.3fx"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f); + changed |= ImGui::DragFloat("Distance", &cameraFit_.distance, 0.005f, 0.05f, 20.f, "%.3fx"); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12.f); + changed |= ImGui::DragFloat3("Offset X/Y/Z", cameraFit_.offset.ptr(), 0.05f); + changed |= ImGui::Checkbox("Follow model placement", &cameraFit_.followModel); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Moving, turning or scaling the model moves the camera with it."); + if (ImGui::Button("Reset")) { + cameraFit_ = CameraFit(); + changed = true; + } + if (changed && camera_ && useMotionCamera_) applyCamera(); +} + void App::restoreCamera() { fov_ = 30.0; } @@ -548,9 +617,21 @@ void App::drawUi() { else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S)) requestSaveScene(false); else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene"); } + if (!fileBrowser_.isOpen()) measuringModel_ = false; if (fileBrowser_.draw()) { if (fileBrowser_.mode() == FileBrowser::Mode::Save) saveScene(fileBrowser_.selectedPath()); - else openFile(fileBrowser_.selectedPath()); + else if (measuringModel_) { + std::string error; + auto model = mr::loadModel(fileBrowser_.selectedPath(), error); + if (model) { + osg::Vec3f lo, hi; + model->computeBounds(lo, hi); + cameraFit_.madeFor = hi.y() - lo.y(); + fitCameraToModel(); + } else { + loadError_ = error; + } + } else openFile(fileBrowser_.selectedPath()); } drawModelWindow(); if (modelNode_) { diff --git a/src/app/AppUi.h b/src/app/AppUi.h index 4008eec..5a19546 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -45,6 +45,19 @@ public: const LookSettings& look() const { return look_; } void setLook(const LookSettings& look); + // Adapts a camera motion made for another model: see Scene::cameraHeightScale. + struct CameraFit { + float madeFor = 20.f; // height of the model the camera motion was made for + float heightScale = 1.f, distance = 1.f; + osg::Vec3f offset; + bool followModel = true; // apply the followed model's position, rotation and scale + }; + const CameraFit& cameraFit() const { return cameraFit_; } + void setCameraFit(const CameraFit& fit); + // Sets the height scale from the followed model's height and madeFor. + void fitCameraToModel(); + float followedModelHeight() const; + bool loadMotion(const std::string& path); void unloadMotion(); void setMotionFrame(float frame); @@ -108,6 +121,7 @@ private: std::unique_ptr player; std::string motionName; }; + const SceneItem* followedItem() const; SceneItem* activeItem() { return active_ >= 0 ? items_[active_].get() : nullptr; } void updatePlacement(SceneItem& item); void drawSceneList(); @@ -138,6 +152,9 @@ private: std::shared_ptr camera_; std::string cameraName_; bool useMotionCamera_ = true; + CameraFit cameraFit_; + bool measuringModel_ = false; // the file browser picks a model to read madeFor from + void drawCameraFit(); double fov_ = 30.0; osg::Vec4f viewRect_; // 3D view area in UI pixels (x, y from top-left, w, h) bool resetLayout_ = false; diff --git a/src/app/FileBrowser.cpp b/src/app/FileBrowser.cpp index 094d9d0..bdc6b53 100644 --- a/src/app/FileBrowser.cpp +++ b/src/app/FileBrowser.cpp @@ -70,7 +70,9 @@ bool FileBrowser::draw() { bool chosen = false; ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver); const bool saving = mode_ == Mode::Save; - if (ImGui::BeginPopupModal(saving ? "Save scene###filebrowser" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr)) { + visible_ = ImGui::BeginPopupModal( + saving ? "Save scene###filebrowser" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr); + if (visible_) { if (ImGui::Button("Up")) { currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path()); refresh(); diff --git a/src/app/FileBrowser.h b/src/app/FileBrowser.h index 8d541af..92dcd14 100644 --- a/src/app/FileBrowser.h +++ b/src/app/FileBrowser.h @@ -17,6 +17,7 @@ public: // Draws the popup; returns true when a file was chosen (see selectedPath()). bool draw(); const std::string& selectedPath() const { return selected_; } + bool isOpen() const { return openRequested_ || visible_; } private: void refresh(); @@ -26,7 +27,7 @@ private: std::vector> entries_; // name, isDirectory std::string selected_; std::string error_; - bool openRequested_ = false; + bool openRequested_ = false, visible_ = false; Mode mode_ = Mode::Open; char nameBuffer_[256] = {}; std::string extension_, highlighted_; diff --git a/src/app/SceneIo.cpp b/src/app/SceneIo.cpp index 7faf43d..387bdea 100644 --- a/src/app/SceneIo.cpp +++ b/src/app/SceneIo.cpp @@ -64,6 +64,11 @@ bool App::saveScene(const std::string& path) { scene.frame = motionFrame_; scene.loop = loopMotion_; scene.followCamera = useMotionCamera_; + scene.cameraMadeFor = cameraFit_.madeFor; + scene.cameraHeightScale = cameraFit_.heightScale; + scene.cameraDistance = cameraFit_.distance; + scene.cameraOffset = cameraFit_.offset; + scene.cameraFollowModel = cameraFit_.followModel; scene.volume = volume_; scene.view.valid = true; manipulator_->getTransformation(scene.view.eye, scene.view.center, scene.view.up); @@ -142,6 +147,11 @@ bool App::openScene(const std::string& path) { look_ = scene.look; loopMotion_ = scene.loop; useMotionCamera_ = scene.followCamera; + cameraFit_.madeFor = scene.cameraMadeFor; + cameraFit_.heightScale = scene.cameraHeightScale; + cameraFit_.distance = scene.cameraDistance; + cameraFit_.offset = scene.cameraOffset; + cameraFit_.followModel = scene.cameraFollowModel; volume_ = scene.volume; audio_.setVolume(volume_); render_.width = scene.renderWidth; diff --git a/src/app/Timeline.cpp b/src/app/Timeline.cpp index 106e406..0d7608e 100644 --- a/src/app/Timeline.cpp +++ b/src/app/Timeline.cpp @@ -75,6 +75,12 @@ void App::drawTimelineWindow() { if (useMotionCamera_) applyCamera(); else restoreCamera(); } + ImGui::SameLine(); + if (ImGui::Button("Camera fit...")) ImGui::OpenPopup("Camera fit"); + if (ImGui::BeginPopup("Camera fit")) { + drawCameraFit(); + ImGui::EndPopup(); + } } if (audio_.loaded() && audio_.hasDevice()) { ImGui::SameLine(); diff --git a/src/app/main.cpp b/src/app/main.cpp index 15cf4b2..ff78c6c 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #if defined(_WIN32) #define NOMINMAX @@ -178,6 +179,9 @@ int main(int argc, char** argv) { bool physics = true, grid = true; std::vector stagePaths, extraModels; float modelScale = 1.f, stageScale = 1.f; + std::optional cameraMadeFor, cameraHeight, cameraDistance; + std::optional cameraOffset; + bool cameraFitToModel = false; std::string saveScenePath; bool orbitSet = false, physicsSet = false; int shading = -1, shadows = -1, outlines = -1; @@ -248,6 +252,18 @@ int main(int argc, char** argv) { extraModels.push_back(next()); } else if (a == "--scale") { modelScale = std::strtof(next().c_str(), nullptr); + } else if (a == "--camera-made-for") { + cameraMadeFor = std::strtof(next().c_str(), nullptr); + } else if (a == "--camera-fit") { + cameraFitToModel = true; + } else if (a == "--camera-height") { + cameraHeight = std::strtof(next().c_str(), nullptr); + } else if (a == "--camera-distance") { + cameraDistance = std::strtof(next().c_str(), nullptr); + } else if (a == "--camera-offset") { + osg::Vec3f o; + std::sscanf(next().c_str(), "%f,%f,%f", &o.x(), &o.y(), &o.z()); + cameraOffset = o; } else if (a == "--stage-scale") { stageScale = std::strtof(next().c_str(), nullptr); } else if (a == "--no-grid") { @@ -385,6 +401,15 @@ int main(int argc, char** argv) { if (skeleton || !isScene) app.setShowSkeleton(skeleton); if (orbitSet || !isScene) app.frameModel(azimuth, elevation); } + if (cameraMadeFor || cameraHeight || cameraDistance || cameraOffset || cameraFitToModel) { + mr::App::CameraFit fit = app.cameraFit(); + if (cameraMadeFor) fit.madeFor = *cameraMadeFor; + if (cameraHeight) fit.heightScale = *cameraHeight; + if (cameraDistance) fit.distance = *cameraDistance; + if (cameraOffset) fit.offset = *cameraOffset; + app.setCameraFit(fit); + if (cameraFitToModel) app.fitCameraToModel(); + } app.setViewportPoppedOut(popOut); if (physicsSet || !isScene) app.setPhysicsEnabled(physics); if (!saveScenePath.empty() && !app.saveScene(saveScenePath)) std::cerr << app.loadError() << "\n"; diff --git a/src/scene/SceneFile.cpp b/src/scene/SceneFile.cpp index 9c9974c..9c2e8d3 100644 --- a/src/scene/SceneFile.cpp +++ b/src/scene/SceneFile.cpp @@ -91,6 +91,11 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error) 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) @@ -211,6 +216,13 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) { 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); } diff --git a/src/scene/SceneFile.h b/src/scene/SceneFile.h index 426391d..51e0646 100644 --- a/src/scene/SceneFile.h +++ b/src/scene/SceneFile.h @@ -36,6 +36,11 @@ struct Scene { std::string cameraMotionPath, audioPath; float frame = 0.f; bool loop = true, followCamera = true; + // Camera motion fit: heights scale by cameraHeightScale, shots move closer/farther by + // cameraDistance, then everything shifts by cameraOffset (model space, Y up). + float cameraMadeFor = 20.f, cameraHeightScale = 1.f, cameraDistance = 1.f; + osg::Vec3d cameraOffset; + bool cameraFollowModel = true; float volume = 1.f; SceneView view; diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 8066415..5569bf2 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -382,6 +382,9 @@ void testSceneFile() { scene.look.toneMapping = 1; scene.look.vignette = 0.3f; scene.renderWidth = 1280; + scene.cameraMadeFor = 18.5f; + scene.cameraHeightScale = 1.25f; + scene.cameraOffset = osg::Vec3d(1, 2, 3); const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene"); std::string error; CHECK(mr::saveScene(scene, file, error)); @@ -394,6 +397,8 @@ void testSceneFile() { mr::Scene loaded; CHECK(mr::loadScene(file, loaded, error)); CHECK(loaded.models.size() == 1); + CHECK(near(loaded.cameraMadeFor, 18.5f) && near(loaded.cameraHeightScale, 1.25f) && near(loaded.cameraDistance, 1.f)); + CHECK(loaded.cameraOffset == osg::Vec3d(1, 2, 3)); if (loaded.models.size() == 1) { const mr::SceneModel& l = loaded.models[0]; CHECK(fs::equivalent(mr::pathFromUtf8(l.path).parent_path(), dir / "project" / "models"));