IK, VMD motion and camera playback, synced audio #4
No files matched your search
+20
-4
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(ModelRenderer VERSION 0.1.0 LANGUAGES CXX)
|
||||
project(ModelRenderer VERSION 0.1.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -76,7 +76,8 @@ add_library(mr_core STATIC
|
||||
src/model/PmdLoader.cpp
|
||||
src/model/AssimpLoader.cpp
|
||||
src/model/ModelLoader.cpp
|
||||
src/model/Poser.cpp)
|
||||
src/model/Poser.cpp
|
||||
src/model/Motion.cpp)
|
||||
target_include_directories(mr_core PUBLIC src ${OPENSCENEGRAPH_INCLUDE_DIRS})
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(mr_core PUBLIC ${OPENSCENEGRAPH_LIBRARIES} assimp::assimp Threads::Threads)
|
||||
@@ -84,6 +85,21 @@ if(NOT WIN32)
|
||||
target_link_libraries(mr_core PRIVATE Iconv::Iconv)
|
||||
endif()
|
||||
|
||||
# --- miniaudio (audio playback) ---------------------------------------------------
|
||||
FetchContent_Declare(miniaudio
|
||||
URL https://github.com/mackron/miniaudio/archive/refs/tags/0.11.21.tar.gz
|
||||
URL_HASH SHA256=6afb5c231613d2fab4f1c668b7243ff9a7d6d78a7f5a2692c133f026fe508506)
|
||||
FetchContent_GetProperties(miniaudio)
|
||||
if(NOT miniaudio_POPULATED)
|
||||
FetchContent_Populate(miniaudio)
|
||||
endif()
|
||||
add_library(mr_audio STATIC src/audio/AudioPlayer.cpp src/audio/miniaudio_impl.c)
|
||||
target_include_directories(mr_audio PUBLIC src SYSTEM PRIVATE ${miniaudio_SOURCE_DIR})
|
||||
target_link_libraries(mr_audio PRIVATE Threads::Threads ${CMAKE_DL_LIBS})
|
||||
if(UNIX AND NOT APPLE)
|
||||
target_link_libraries(mr_audio PRIVATE m)
|
||||
endif()
|
||||
|
||||
# --- Viewer application ----------------------------------------------------------
|
||||
add_executable(model_renderer
|
||||
src/app/main.cpp
|
||||
@@ -94,7 +110,7 @@ add_executable(model_renderer
|
||||
src/render/Shaders.cpp
|
||||
src/render/GpuCaps.cpp
|
||||
src/ui/ImGuiOsg.cpp)
|
||||
target_link_libraries(model_renderer PRIVATE mr_core imgui OpenGL::GL)
|
||||
target_link_libraries(model_renderer PRIVATE mr_core mr_audio imgui OpenGL::GL)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(mr_core PRIVATE /W3 /utf-8)
|
||||
@@ -108,7 +124,7 @@ endif()
|
||||
if(MR_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_executable(mr_tests tests/test_main.cpp)
|
||||
target_link_libraries(mr_tests PRIVATE mr_core)
|
||||
target_link_libraries(mr_tests PRIVATE mr_core mr_audio)
|
||||
target_compile_definitions(mr_tests PRIVATE MR_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/data")
|
||||
add_test(NAME mr_tests COMMAND mr_tests)
|
||||
endif()
|
||||
@@ -27,8 +27,10 @@ Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGr
|
||||
Morphs are applied on the CPU in both modes and only re-uploaded when morph weights change.
|
||||
|
||||
Supported: textures (incl. MMD sphere `.sph`/`.spa` and toon maps), vertex/group/bone/flip morphs,
|
||||
BDEF1/2/4 weights (SDEF/QDEF approximated as linear blend). Not yet: IK solving, physics, UV and
|
||||
material morphs, edge outlines, animation playback (VMD).
|
||||
BDEF1/2/4 weights (SDEF/QDEF approximated as linear blend), IK (CCD with MMD-style knee limits),
|
||||
VMD bone/morph/IK-switch and camera playback with MMD's Bezier easing, and song playback
|
||||
(.wav/.mp3/.flac via [miniaudio](https://miniaud.io)) kept in sync with the timeline. Not yet:
|
||||
physics, VMD light/self-shadow, UV and material morphs, edge outlines.
|
||||
|
||||
## Building
|
||||
|
||||
@@ -108,6 +110,11 @@ Linux) so MMD bone and morph names display correctly.
|
||||
* **File > Open** picks a model; you can also pass the path on the command line.
|
||||
* **Bones**: select a bone, then use the rotation sliders / move fields. `*` marks posed bones.
|
||||
* **Morphs**: sliders grouped as Eye / Mouth / Eyebrow / Other, as in MMD.
|
||||
* **Motion**: open a dance `.vmd`, a camera `.vmd` and a song with File > Open (camera files are
|
||||
detected automatically); play/pause, rewind, loop and scrub the timeline. While the song plays
|
||||
its clock drives the timeline, so motion stays in sync. Untick **Follow** to orbit freely.
|
||||
Bones the motion drives can still be offset with the Bones panel. Bones in an IK chain (thighs,
|
||||
knees) follow their IK bone while **View > Solve IK** is on.
|
||||
* **View**: skeleton overlay, wireframe, culling, MMD toon vs Lambert shading, GPU vs CPU skinning,
|
||||
UI scale (use 2 on Retina).
|
||||
* Camera: left drag orbits, middle drag pans, right drag or wheel zooms, Space resets.
|
||||
@@ -119,7 +126,9 @@ Command-line options (`--help`) allow scripted renders, e.g.
|
||||
--orbit 20,10 --hide-ui --screenshot out.png
|
||||
```
|
||||
|
||||
`--skinning gpu|cpu` picks the skinning path; `--bench N` prints load, frame and deformation times.
|
||||
`--motion dance.vmd --camera camera.vmd --audio song.wav --play` plays a full MMD scene
|
||||
(`--frame N` jumps to a frame);
|
||||
`tools/make_test_vmd.py --demo out.vmd` writes a short demo motion. `--skinning gpu|cpu` picks the skinning path; `--bench N` prints load, frame and deformation times.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+216
-2
@@ -4,8 +4,10 @@
|
||||
#include "render/GpuCaps.h"
|
||||
|
||||
#include <imgui.h>
|
||||
#include <osg/NodeCallback>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
@@ -37,9 +39,26 @@ const char* panelName(MorphPanel p) {
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace {
|
||||
|
||||
class TickCallback : public osg::NodeCallback {
|
||||
public:
|
||||
explicit TickCallback(App* app) : app_(app) {}
|
||||
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
|
||||
if (nv->getFrameStamp()) app_->tick(nv->getFrameStamp()->getReferenceTime());
|
||||
traverse(node, nv);
|
||||
}
|
||||
|
||||
private:
|
||||
App* app_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator)
|
||||
: viewer_(viewer), root_(root), manipulator_(manipulator) {
|
||||
imgui_ = new ImGuiOsg([this]() { drawUi(); });
|
||||
root_->addUpdateCallback(new TickCallback(this));
|
||||
imgui_->attach(viewer_);
|
||||
}
|
||||
|
||||
@@ -59,6 +78,7 @@ bool App::loadModel(const std::string& path) {
|
||||
imgui_->addGlyphs(glyphs);
|
||||
modelNode_ = new ModelNode(model);
|
||||
root_->addChild(modelNode_);
|
||||
player_.reset(motion_ ? new MotionPlayer(motion_, *model) : nullptr);
|
||||
selectedBone_ = -1;
|
||||
boneFilter_[0] = '\0';
|
||||
morphFilter_[0] = '\0';
|
||||
@@ -84,6 +104,198 @@ void App::setGpuSkinning(bool enabled) {
|
||||
applyViewSettings();
|
||||
}
|
||||
|
||||
bool App::loadMotion(const std::string& path) {
|
||||
std::string error;
|
||||
auto motion = loadVmd(path, error);
|
||||
if (!motion) {
|
||||
loadError_ = "Failed to load motion " + path + ": " + error;
|
||||
return false;
|
||||
}
|
||||
const std::string name = path.substr(path.find_last_of("/\\") + 1);
|
||||
if (!motion->cameraKeys.empty()) {
|
||||
camera_ = motion;
|
||||
cameraName_ = name;
|
||||
}
|
||||
if (!motion->boneTracks.empty() || !motion->morphTracks.empty() || motion->cameraKeys.empty()) {
|
||||
motion_ = motion;
|
||||
motionName_ = name;
|
||||
if (modelNode_) {
|
||||
modelNode_->poser().resetMotion();
|
||||
player_.reset(new MotionPlayer(motion_, modelNode_->model()));
|
||||
}
|
||||
}
|
||||
setPlaying(false);
|
||||
setMotionFrame(0.f);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool App::loadAudio(const std::string& path) {
|
||||
std::string error;
|
||||
if (!audio_.load(path, error)) {
|
||||
loadError_ = "Failed to load audio " + path + ": " + error;
|
||||
return false;
|
||||
}
|
||||
audio_.setVolume(volume_);
|
||||
audioName_ = path.substr(path.find_last_of("/\\") + 1);
|
||||
setPlaying(false);
|
||||
setMotionFrame(0.f);
|
||||
return true;
|
||||
}
|
||||
|
||||
void App::unloadMotion() {
|
||||
setPlaying(false);
|
||||
player_.reset();
|
||||
motion_.reset();
|
||||
camera_.reset();
|
||||
restoreCamera();
|
||||
audio_.unload();
|
||||
motionFrame_ = 0.f;
|
||||
if (modelNode_) modelNode_->poser().resetMotion();
|
||||
}
|
||||
|
||||
float App::timelineEnd() const {
|
||||
float end = 0.f;
|
||||
if (motion_) end = std::max(end, static_cast<float>(motion_->lastFrame));
|
||||
if (camera_) end = std::max(end, static_cast<float>(camera_->lastFrame));
|
||||
if (audio_.loaded()) end = std::max(end, static_cast<float>(audio_.length()) * kMotionFps);
|
||||
return end;
|
||||
}
|
||||
|
||||
void App::setPlaying(bool playing) {
|
||||
playing_ = playing;
|
||||
if (playing && motionFrame_ / kMotionFps < audio_.length()) {
|
||||
audio_.seek(motionFrame_ / kMotionFps);
|
||||
audio_.play();
|
||||
} else {
|
||||
audio_.pause();
|
||||
}
|
||||
}
|
||||
|
||||
void App::setMotionFrame(float frame) {
|
||||
motionFrame_ = std::max(0.f, frame);
|
||||
if (playing_) setPlaying(true);
|
||||
else audio_.seek(motionFrame_ / kMotionFps);
|
||||
applyFrame();
|
||||
}
|
||||
|
||||
void App::applyFrame() {
|
||||
if (player_ && modelNode_) player_->apply(motionFrame_, modelNode_->poser());
|
||||
if (camera_ && useMotionCamera_) applyCamera();
|
||||
}
|
||||
|
||||
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);
|
||||
osg::Camera* camera = viewer_.getCamera();
|
||||
double fovy, aspect, zNear, zFar;
|
||||
if (!camera->getProjectionMatrixAsPerspective(fovy, aspect, zNear, zFar)) return;
|
||||
if (defaultFov_ <= 0.0) defaultFov_ = fovy;
|
||||
camera->setProjectionMatrixAsPerspective(pose.fov, aspect, zNear, zFar);
|
||||
}
|
||||
|
||||
void App::restoreCamera() {
|
||||
if (defaultFov_ <= 0.0) return;
|
||||
osg::Camera* camera = viewer_.getCamera();
|
||||
double fovy, aspect, zNear, zFar;
|
||||
if (camera->getProjectionMatrixAsPerspective(fovy, aspect, zNear, zFar))
|
||||
camera->setProjectionMatrixAsPerspective(defaultFov_, aspect, zNear, zFar);
|
||||
defaultFov_ = 0.0;
|
||||
}
|
||||
|
||||
void App::tick(double time) {
|
||||
const double dt = lastTick_ < 0.0 ? 0.0 : time - lastTick_;
|
||||
lastTick_ = time;
|
||||
if (modelNode_) modelNode_->poser().setIkEnabled(ikEnabled_);
|
||||
if (!player_ && !camera_ && !audio_.loaded()) return;
|
||||
if (playing_) {
|
||||
// The sound card's clock drives playback while the song plays, so motion stays in sync.
|
||||
if (audio_.playing()) motionFrame_ = static_cast<float>(audio_.position()) * kMotionFps;
|
||||
else motionFrame_ += static_cast<float>(dt) * kMotionFps;
|
||||
const float end = timelineEnd();
|
||||
if (motionFrame_ >= end) {
|
||||
if (loopMotion_ && end > 0.f) {
|
||||
motionFrame_ = 0.f;
|
||||
setPlaying(true);
|
||||
} else {
|
||||
motionFrame_ = end;
|
||||
setPlaying(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
applyFrame();
|
||||
}
|
||||
|
||||
void App::openFile(const std::string& path) {
|
||||
std::string lower = path;
|
||||
std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
auto endsWith = [&](const char* ext) {
|
||||
const size_t n = std::strlen(ext);
|
||||
return lower.size() > n && lower.compare(lower.size() - n, n, ext) == 0;
|
||||
};
|
||||
if (endsWith(".vmd")) {
|
||||
loadMotion(path);
|
||||
} else if (endsWith(".wav") || endsWith(".mp3") || endsWith(".flac")) {
|
||||
loadAudio(path);
|
||||
} else {
|
||||
loadModel(path);
|
||||
}
|
||||
}
|
||||
|
||||
void App::drawMotionWindow() {
|
||||
const ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y - 10.f), ImGuiCond_FirstUseEver,
|
||||
ImVec2(0.5f, 1.f));
|
||||
ImGui::SetNextWindowSize(ImVec2(520.f, 0.f), ImGuiCond_FirstUseEver);
|
||||
ImGui::Begin("Motion");
|
||||
if (!player_ && !camera_ && !audio_.loaded()) {
|
||||
ImGui::TextDisabled("Open a motion .vmd, camera .vmd or song (.wav .mp3 .flac).");
|
||||
if (ImGui::Button("Open...")) fileBrowser_.open();
|
||||
} else {
|
||||
const float last = timelineEnd();
|
||||
if (player_) {
|
||||
ImGui::Text("Motion: %s", motionName_.c_str());
|
||||
ImGui::SameLine();
|
||||
ImGui::TextDisabled("(bones %zu/%zu, morphs %zu/%zu matched)", player_->boundBones(),
|
||||
player_->boneTrackCount(), player_->boundMorphs(), player_->morphTrackCount());
|
||||
}
|
||||
if (camera_) {
|
||||
ImGui::Text("Camera: %s", cameraName_.c_str());
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Checkbox("Follow##camera", &useMotionCamera_)) {
|
||||
if (useMotionCamera_) applyCamera();
|
||||
else restoreCamera();
|
||||
}
|
||||
}
|
||||
if (audio_.loaded()) {
|
||||
ImGui::Text("Audio: %s", audioName_.c_str());
|
||||
ImGui::SameLine();
|
||||
if (!audio_.hasDevice()) {
|
||||
ImGui::TextDisabled("(no output device)");
|
||||
} else {
|
||||
ImGui::SetNextItemWidth(120.f);
|
||||
if (ImGui::SliderFloat("Volume", &volume_, 0.f, 1.f, "%.2f")) audio_.setVolume(volume_);
|
||||
}
|
||||
}
|
||||
if (ImGui::Button(playing_ ? "Pause" : "Play", ImVec2(60.f, 0.f))) setPlaying(!playing_);
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button("Rewind")) setMotionFrame(0.f);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Loop", &loopMotion_);
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button("Open...")) fileBrowser_.open();
|
||||
ImGui::SameLine();
|
||||
if (ImGui::Button("Unload")) unloadMotion();
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("%.1f / %.1f s", motionFrame_ / kMotionFps, last / kMotionFps);
|
||||
ImGui::SetNextItemWidth(-1.f);
|
||||
float frame = motionFrame_;
|
||||
if (ImGui::SliderFloat("##frame", &frame, 0.f, std::max(last, 1.f), "frame %.0f")) setMotionFrame(frame);
|
||||
}
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void App::setShowSkeleton(bool show) {
|
||||
showSkeleton_ = show;
|
||||
applyViewSettings();
|
||||
@@ -111,11 +323,12 @@ void App::drawUi() {
|
||||
if (ImGui::Button("Dismiss")) loadError_.clear();
|
||||
ImGui::End();
|
||||
}
|
||||
if (fileBrowser_.draw()) loadModel(fileBrowser_.selectedPath());
|
||||
if (fileBrowser_.draw()) openFile(fileBrowser_.selectedPath());
|
||||
if (modelNode_) {
|
||||
drawModelWindow();
|
||||
drawBonesWindow();
|
||||
drawMorphsWindow();
|
||||
drawMotionWindow();
|
||||
} else {
|
||||
ImGui::SetNextWindowPos(ImVec2(10, 40), ImGuiCond_FirstUseEver);
|
||||
ImGui::Begin("Welcome", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
|
||||
@@ -129,7 +342,7 @@ void App::drawUi() {
|
||||
void App::drawMenuBar() {
|
||||
if (!ImGui::BeginMainMenuBar()) return;
|
||||
if (ImGui::BeginMenu("File")) {
|
||||
if (ImGui::MenuItem("Open...")) fileBrowser_.open();
|
||||
if (ImGui::MenuItem("Open model or motion...")) fileBrowser_.open();
|
||||
if (ImGui::MenuItem("Quit")) viewer_.setDone(true);
|
||||
ImGui::EndMenu();
|
||||
}
|
||||
@@ -139,6 +352,7 @@ void App::drawMenuBar() {
|
||||
changed |= ImGui::MenuItem("Wireframe", nullptr, &wireframe_);
|
||||
changed |= ImGui::MenuItem("Backface culling", nullptr, &backfaceCulling_);
|
||||
changed |= ImGui::MenuItem("Light follows camera", nullptr, &lightFollowsCamera_);
|
||||
ImGui::MenuItem("Solve IK", nullptr, &ikEnabled_);
|
||||
ImGui::Separator();
|
||||
changed |= ImGui::RadioButton("MMD toon shading", &lightingModel_, 0);
|
||||
changed |= ImGui::RadioButton("Lambert shading", &lightingModel_, 1);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "app/FileBrowser.h"
|
||||
#include "audio/AudioPlayer.h"
|
||||
#include "model/Motion.h"
|
||||
#include "render/ModelNode.h"
|
||||
#include "ui/ImGuiOsg.h"
|
||||
|
||||
@@ -21,6 +23,14 @@ public:
|
||||
void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f);
|
||||
void setShowSkeleton(bool show);
|
||||
void setGpuSkinning(bool enabled);
|
||||
|
||||
bool loadMotion(const std::string& path);
|
||||
void unloadMotion();
|
||||
void setMotionFrame(float frame);
|
||||
bool loadAudio(const std::string& path);
|
||||
void setPlaying(bool playing);
|
||||
// Advances playback; called once per frame from the update traversal.
|
||||
void tick(double time);
|
||||
ImGuiOsg* imgui() { return imgui_.get(); }
|
||||
|
||||
void drawUi();
|
||||
@@ -32,6 +42,12 @@ private:
|
||||
void drawBoneEditor();
|
||||
void drawMorphsWindow();
|
||||
void applyViewSettings();
|
||||
void drawMotionWindow();
|
||||
void openFile(const std::string& path);
|
||||
float timelineEnd() const;
|
||||
void applyFrame();
|
||||
void applyCamera();
|
||||
void restoreCamera();
|
||||
|
||||
osgViewer::Viewer& viewer_;
|
||||
osg::ref_ptr<osg::Group> root_;
|
||||
@@ -47,6 +63,21 @@ private:
|
||||
bool lightFollowsCamera_ = false;
|
||||
int lightingModel_ = 0;
|
||||
int skinning_ = 1; // 1 hardware (GPU), 0 software (CPU)
|
||||
bool ikEnabled_ = true;
|
||||
std::shared_ptr<Motion> motion_;
|
||||
std::unique_ptr<MotionPlayer> player_;
|
||||
std::string motionName_;
|
||||
float motionFrame_ = 0.f;
|
||||
bool playing_ = false;
|
||||
bool loopMotion_ = true;
|
||||
double lastTick_ = -1.0;
|
||||
std::shared_ptr<Motion> camera_;
|
||||
std::string cameraName_;
|
||||
bool useMotionCamera_ = true;
|
||||
double defaultFov_ = 0.0;
|
||||
AudioPlayer audio_;
|
||||
std::string audioName_;
|
||||
float volume_ = 1.f;
|
||||
bool showDemo_ = false;
|
||||
bool onlyVisibleBones_ = true;
|
||||
int selectedBone_ = -1;
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace mr {
|
||||
namespace {
|
||||
bool isModelFile(const std::string& name) {
|
||||
std::string lower = toLowerAscii(name);
|
||||
for (const char* ext : {".pmx", ".pmd", ".fbx", ".obj", ".gltf", ".glb", ".dae"})
|
||||
for (const char* ext : {".pmx", ".pmd", ".fbx", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"})
|
||||
if (lower.size() >= std::strlen(ext) && lower.compare(lower.size() - std::strlen(ext), std::string::npos, ext) == 0)
|
||||
return true;
|
||||
return false;
|
||||
@@ -75,7 +75,7 @@ bool FileBrowser::draw() {
|
||||
chosen = true;
|
||||
}
|
||||
}
|
||||
ImGui::TextDisabled("Supported: .pmx .pmd .fbx (also .obj .gltf .glb .dae)");
|
||||
ImGui::TextDisabled("Models: .pmx .pmd .fbx (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac");
|
||||
if (!error_.empty()) ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", error_.c_str());
|
||||
ImGui::BeginChild("entries", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), ImGuiChildFlags_Borders);
|
||||
std::string enterDir;
|
||||
|
||||
+25
-1
@@ -40,6 +40,11 @@ void printUsage() {
|
||||
" --frames N frames to render before the screenshot (default 5)\n"
|
||||
" --list print bone and morph names after loading\n"
|
||||
" --skinning gpu|cpu hardware or software skinning (default gpu)\n"
|
||||
" --motion FILE.vmd load an MMD motion\n"
|
||||
" --frame N motion frame to show (30 per second)\n"
|
||||
" --camera FILE.vmd load an MMD camera motion\n"
|
||||
" --audio FILE load a song (.wav .mp3 .flac)\n"
|
||||
" --play start playback\n"
|
||||
" --bench N time N idle and N animated frames, then exit\n";
|
||||
}
|
||||
|
||||
@@ -102,7 +107,9 @@ void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) {
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
std::string modelPath, screenshot;
|
||||
std::string modelPath, screenshot, motionPath, cameraPath, audioPath;
|
||||
float motionFrame = 0.f;
|
||||
bool play = false;
|
||||
std::vector<std::pair<std::string, std::string>> morphArgs, boneArgs;
|
||||
int width = 1280, height = 800, frames = 5, benchFrames = 0;
|
||||
float azimuth = 0.f, elevation = 0.f, uiScale = 1.f;
|
||||
@@ -147,6 +154,16 @@ int main(int argc, char** argv) {
|
||||
listNames = true;
|
||||
} else if (a == "--skinning") {
|
||||
gpuSkinning = next() != "cpu";
|
||||
} else if (a == "--motion") {
|
||||
motionPath = next();
|
||||
} else if (a == "--camera") {
|
||||
cameraPath = next();
|
||||
} else if (a == "--audio") {
|
||||
audioPath = next();
|
||||
} else if (a == "--frame") {
|
||||
motionFrame = std::strtof(next().c_str(), nullptr);
|
||||
} else if (a == "--play") {
|
||||
play = true;
|
||||
} else if (a == "--bench") {
|
||||
benchFrames = std::max(1, std::atoi(next().c_str()));
|
||||
} else if (a == "--frames") {
|
||||
@@ -206,6 +223,13 @@ int main(int argc, char** argv) {
|
||||
for (size_t k = 0; k < 3 && k < v.size(); ++k) pose.eulerDegrees[k] = v[k];
|
||||
for (size_t k = 3; k < 6 && k < v.size(); ++k) pose.translation[k - 3] = v[k];
|
||||
}
|
||||
for (const std::string& path : {motionPath, cameraPath})
|
||||
if (!path.empty() && !app.loadMotion(path)) std::cerr << app.loadError() << "\n";
|
||||
if (!audioPath.empty() && !app.loadAudio(audioPath)) std::cerr << app.loadError() << "\n";
|
||||
if (!motionPath.empty() || !cameraPath.empty() || !audioPath.empty()) {
|
||||
app.setMotionFrame(motionFrame);
|
||||
app.setPlaying(play);
|
||||
}
|
||||
app.setShowSkeleton(skeleton);
|
||||
app.frameModel(azimuth, elevation);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#include "audio/AudioPlayer.h"
|
||||
|
||||
#include <miniaudio.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace mr {
|
||||
|
||||
struct AudioPlayer::Impl {
|
||||
ma_engine engine;
|
||||
ma_sound sound;
|
||||
bool engineReady = false, device = false, soundReady = false;
|
||||
|
||||
Impl() {
|
||||
device = engineReady = ma_engine_init(nullptr, &engine) == MA_SUCCESS;
|
||||
if (!engineReady) {
|
||||
ma_engine_config config = ma_engine_config_init();
|
||||
config.noDevice = MA_TRUE;
|
||||
config.channels = 2;
|
||||
config.sampleRate = 48000;
|
||||
engineReady = ma_engine_init(&config, &engine) == MA_SUCCESS;
|
||||
}
|
||||
}
|
||||
~Impl() {
|
||||
if (soundReady) ma_sound_uninit(&sound);
|
||||
if (engineReady) ma_engine_uninit(&engine);
|
||||
}
|
||||
};
|
||||
|
||||
AudioPlayer::AudioPlayer() : impl_(new Impl) {}
|
||||
AudioPlayer::~AudioPlayer() = default;
|
||||
|
||||
bool AudioPlayer::load(const std::string& path, std::string& error) {
|
||||
unload();
|
||||
if (!impl_->engineReady) {
|
||||
error = "audio engine unavailable";
|
||||
return false;
|
||||
}
|
||||
const ma_uint32 flags = MA_SOUND_FLAG_STREAM | MA_SOUND_FLAG_NO_SPATIALIZATION;
|
||||
const ma_result result = ma_sound_init_from_file(&impl_->engine, path.c_str(), flags, nullptr, nullptr, &impl_->sound);
|
||||
if (result != MA_SUCCESS) {
|
||||
error = ma_result_description(result);
|
||||
return false;
|
||||
}
|
||||
impl_->soundReady = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void AudioPlayer::unload() {
|
||||
if (!impl_->soundReady) return;
|
||||
ma_sound_uninit(&impl_->sound);
|
||||
impl_->soundReady = false;
|
||||
}
|
||||
|
||||
bool AudioPlayer::loaded() const { return impl_->soundReady; }
|
||||
bool AudioPlayer::hasDevice() const { return impl_->device; }
|
||||
|
||||
double AudioPlayer::length() const {
|
||||
float seconds = 0.f;
|
||||
if (impl_->soundReady) ma_sound_get_length_in_seconds(&impl_->sound, &seconds);
|
||||
return seconds;
|
||||
}
|
||||
|
||||
double AudioPlayer::position() const {
|
||||
float seconds = 0.f;
|
||||
if (impl_->soundReady) ma_sound_get_cursor_in_seconds(&impl_->sound, &seconds);
|
||||
return seconds;
|
||||
}
|
||||
|
||||
void AudioPlayer::play() {
|
||||
if (impl_->soundReady && impl_->device) ma_sound_start(&impl_->sound);
|
||||
}
|
||||
|
||||
void AudioPlayer::pause() {
|
||||
if (impl_->soundReady) ma_sound_stop(&impl_->sound);
|
||||
}
|
||||
|
||||
bool AudioPlayer::playing() const { return impl_->soundReady && ma_sound_is_playing(&impl_->sound); }
|
||||
|
||||
void AudioPlayer::seek(double seconds) {
|
||||
if (!impl_->soundReady) return;
|
||||
const ma_uint32 rate = ma_engine_get_sample_rate(&impl_->engine);
|
||||
ma_sound_seek_to_pcm_frame(&impl_->sound, static_cast<ma_uint64>(std::max(0.0, seconds) * rate));
|
||||
}
|
||||
|
||||
void AudioPlayer::setVolume(float volume) {
|
||||
if (impl_->soundReady) ma_sound_set_volume(&impl_->sound, volume);
|
||||
}
|
||||
|
||||
} // namespace mr
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace mr {
|
||||
|
||||
// Streams one sound file (.wav, .mp3, .flac) to the default output device via miniaudio.
|
||||
// Without an output device the file still loads, so its length is known, but it stays silent.
|
||||
class AudioPlayer {
|
||||
public:
|
||||
AudioPlayer();
|
||||
~AudioPlayer();
|
||||
AudioPlayer(const AudioPlayer&) = delete;
|
||||
AudioPlayer& operator=(const AudioPlayer&) = delete;
|
||||
|
||||
bool load(const std::string& path, std::string& error);
|
||||
void unload();
|
||||
bool loaded() const;
|
||||
bool hasDevice() const;
|
||||
|
||||
double length() const; // seconds
|
||||
double position() const; // seconds
|
||||
void play();
|
||||
void pause();
|
||||
bool playing() const;
|
||||
void seek(double seconds);
|
||||
void setVolume(float volume);
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
} // namespace mr
|
||||
@@ -0,0 +1,4 @@
|
||||
#define MINIAUDIO_IMPLEMENTATION
|
||||
#define MA_NO_GENERATION
|
||||
#define MA_NO_ENCODING
|
||||
#include <miniaudio.h>
|
||||
@@ -61,4 +61,16 @@ void Model::normalizeWeights() {
|
||||
}
|
||||
}
|
||||
|
||||
void validateIk(Bone& bone, int index, int boneCount) {
|
||||
auto valid = [&](int b) { return b >= 0 && b < boneCount && b != index; };
|
||||
bool ok = bone.isIK && valid(bone.ikTarget) && !bone.ikLinks.empty();
|
||||
for (const auto& link : bone.ikLinks) ok = ok && valid(link.bone);
|
||||
if (!ok) {
|
||||
bone.isIK = false;
|
||||
bone.ikTarget = -1;
|
||||
bone.ikLinks.clear();
|
||||
}
|
||||
bone.ikIterations = std::min(std::max(bone.ikIterations, 0), 256);
|
||||
}
|
||||
|
||||
} // namespace mr
|
||||
@@ -55,6 +55,23 @@ struct Material {
|
||||
uint32_t indexCount = 0;
|
||||
};
|
||||
|
||||
// One joint of an IK chain. Limits are Euler angles in radians (model axes, applied X, Y, Z).
|
||||
struct IkLink {
|
||||
int bone = -1;
|
||||
bool limited = false;
|
||||
osg::Vec3f lower, upper;
|
||||
};
|
||||
|
||||
// Mirroring Z negates rotations about X and Y, so the limits swap and change sign.
|
||||
inline void mmdLimitsToRightHanded(const osg::Vec3f& lowerLH, const osg::Vec3f& upperLH, osg::Vec3f& lower,
|
||||
osg::Vec3f& upper) {
|
||||
lower.set(-upperLH.x(), -upperLH.y(), lowerLH.z());
|
||||
upper.set(-lowerLH.x(), -lowerLH.y(), upperLH.z());
|
||||
}
|
||||
|
||||
struct Bone;
|
||||
void validateIk(Bone& bone, int index, int boneCount);
|
||||
|
||||
struct Bone {
|
||||
std::string name;
|
||||
std::string nameEn;
|
||||
@@ -71,6 +88,10 @@ struct Bone {
|
||||
bool inheritRotation = false;
|
||||
bool inheritTranslation = false;
|
||||
bool isIK = false;
|
||||
int ikTarget = -1; // bone the chain tries to bring to this bone's position
|
||||
int ikIterations = 0;
|
||||
float ikLimitAngle = 0.f; // max rotation per link per iteration, radians
|
||||
std::vector<IkLink> ikLinks; // ordered from the target outward
|
||||
int layer = 0;
|
||||
bool afterPhysics = false;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
#include "model/Motion.h"
|
||||
|
||||
#include "model/BinaryReader.h"
|
||||
#include "model/TextEncoding.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace mr {
|
||||
|
||||
float BezierCurve::eval(float x) const {
|
||||
if (x <= 0.f) return 0.f;
|
||||
if (x >= 1.f) return 1.f;
|
||||
auto bezier = [](float t, float p1, float p2) {
|
||||
const float s = 1.f - t;
|
||||
return 3.f * s * s * t * p1 + 3.f * s * t * t * p2 + t * t * t;
|
||||
};
|
||||
// x(t) is monotonic because both control x values lie in [0, 1].
|
||||
float lo = 0.f, hi = 1.f, t = x;
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
t = 0.5f * (lo + hi);
|
||||
if (bezier(t, x1, x2) < x) lo = t;
|
||||
else hi = t;
|
||||
}
|
||||
return bezier(t, y1, y2);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Fixed-size Shift-JIS field: stop at NUL and drop a lead byte cut off by truncation.
|
||||
std::string fixedSjis(BinaryReader& r, size_t size) {
|
||||
const std::string raw(reinterpret_cast<const char*>(r.bytes(size)), size);
|
||||
size_t end = raw.find('\0');
|
||||
if (end == std::string::npos) end = raw.size();
|
||||
size_t i = 0, valid = 0;
|
||||
while (i < end) {
|
||||
const auto c = static_cast<unsigned char>(raw[i]);
|
||||
const size_t len = (c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC) ? 2 : 1;
|
||||
if (i + len > end) break;
|
||||
i += len;
|
||||
valid = i;
|
||||
}
|
||||
return shiftJisToUtf8(raw.substr(0, valid));
|
||||
}
|
||||
|
||||
osg::Vec3f vmdPosition(BinaryReader& r) {
|
||||
const osg::Vec3f p = r.vec3();
|
||||
return osg::Vec3f(p.x(), p.y(), -p.z());
|
||||
}
|
||||
|
||||
// Mirroring Z turns a left-handed rotation (x, y, z, w) into (-x, -y, z, w).
|
||||
osg::Quat vmdRotation(BinaryReader& r) {
|
||||
const float x = r.f32(), y = r.f32(), z = r.f32(), w = r.f32();
|
||||
return osg::Quat(-x, -y, z, w);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::shared_ptr<Motion> loadVmd(const std::string& path, std::string& error) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) {
|
||||
error = "cannot open file";
|
||||
return nullptr;
|
||||
}
|
||||
const std::vector<uint8_t> data((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
try {
|
||||
BinaryReader r(data);
|
||||
const std::string magic(reinterpret_cast<const char*>(r.bytes(30)), 30);
|
||||
size_t nameSize;
|
||||
if (magic.compare(0, 25, "Vocaloid Motion Data 0002") == 0) nameSize = 20;
|
||||
else if (magic.compare(0, 25, "Vocaloid Motion Data file") == 0) nameSize = 10;
|
||||
else throw std::runtime_error("not a VMD motion file");
|
||||
|
||||
auto motion = std::make_shared<Motion>();
|
||||
motion->modelName = fixedSjis(r, nameSize);
|
||||
|
||||
const uint32_t boneKeys = r.u32();
|
||||
if (static_cast<size_t>(boneKeys) * 111 > r.remaining()) throw std::runtime_error("truncated bone keyframes");
|
||||
for (uint32_t i = 0; i < boneKeys; ++i) {
|
||||
const std::string name = fixedSjis(r, 15);
|
||||
BoneKeyframe key;
|
||||
key.frame = r.u32();
|
||||
key.translation = vmdPosition(r);
|
||||
key.rotation = vmdRotation(r);
|
||||
const uint8_t* interp = r.bytes(64);
|
||||
auto at = [&](int i) { return interp[i] / 127.f; };
|
||||
for (int c = 0; c < 4; ++c) key.curves[c] = BezierCurve{at(c), at(c + 4), at(c + 8), at(c + 12)};
|
||||
motion->boneTracks[name].push_back(key);
|
||||
motion->lastFrame = std::max(motion->lastFrame, key.frame);
|
||||
}
|
||||
|
||||
if (r.remaining() >= 4) {
|
||||
const uint32_t morphKeys = r.u32();
|
||||
if (static_cast<size_t>(morphKeys) * 23 > r.remaining()) throw std::runtime_error("truncated morph keyframes");
|
||||
for (uint32_t i = 0; i < morphKeys; ++i) {
|
||||
const std::string name = fixedSjis(r, 15);
|
||||
MorphKeyframe key;
|
||||
key.frame = r.u32();
|
||||
key.weight = r.f32();
|
||||
motion->morphTracks[name].push_back(key);
|
||||
motion->lastFrame = std::max(motion->lastFrame, key.frame);
|
||||
}
|
||||
}
|
||||
|
||||
bool more = r.remaining() >= 4;
|
||||
if (more) {
|
||||
const uint32_t count = r.u32();
|
||||
if (static_cast<size_t>(count) * 61 > r.remaining()) throw std::runtime_error("truncated camera keyframes");
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
CameraKeyframe key;
|
||||
key.frame = r.u32();
|
||||
key.distance = r.f32();
|
||||
key.target = vmdPosition(r);
|
||||
key.rotation = r.vec3();
|
||||
const uint8_t* interp = r.bytes(24);
|
||||
auto at = [&](int i) { return interp[i] / 127.f; };
|
||||
for (int c = 0; c < 6; ++c)
|
||||
key.curves[c] = BezierCurve{at(4 * c), at(4 * c + 2), at(4 * c + 1), at(4 * c + 3)};
|
||||
key.fov = static_cast<float>(r.u32());
|
||||
r.u8(); // perspective flag
|
||||
motion->cameraKeys.push_back(key);
|
||||
motion->lastFrame = std::max(motion->lastFrame, key.frame);
|
||||
}
|
||||
}
|
||||
// Light and self-shadow sections are skipped for now; IK on/off keys follow them.
|
||||
for (size_t recordSize : {size_t(28), size_t(9)}) {
|
||||
if (!more || r.remaining() < 4) {
|
||||
more = false;
|
||||
break;
|
||||
}
|
||||
const uint32_t count = r.u32();
|
||||
if (static_cast<size_t>(count) * recordSize > r.remaining()) throw std::runtime_error("truncated VMD section");
|
||||
r.skip(count * recordSize);
|
||||
}
|
||||
if (more && r.remaining() >= 4) {
|
||||
const uint32_t count = r.u32();
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
IkKeyframe key;
|
||||
key.frame = r.u32();
|
||||
r.u8(); // model visible
|
||||
const uint32_t iks = r.u32();
|
||||
if (static_cast<size_t>(iks) * 21 > r.remaining()) throw std::runtime_error("truncated IK keyframes");
|
||||
for (uint32_t k = 0; k < iks; ++k) {
|
||||
std::string name = fixedSjis(r, 20);
|
||||
key.enabled.emplace_back(std::move(name), r.u8() != 0);
|
||||
}
|
||||
motion->ikKeyframes.push_back(std::move(key));
|
||||
}
|
||||
}
|
||||
|
||||
auto byFrame = [](const auto& a, const auto& b) { return a.frame < b.frame; };
|
||||
for (auto& [name, keys] : motion->boneTracks) std::stable_sort(keys.begin(), keys.end(), byFrame);
|
||||
for (auto& [name, keys] : motion->morphTracks) std::stable_sort(keys.begin(), keys.end(), byFrame);
|
||||
std::stable_sort(motion->ikKeyframes.begin(), motion->ikKeyframes.end(), byFrame);
|
||||
std::stable_sort(motion->cameraKeys.begin(), motion->cameraKeys.end(), byFrame);
|
||||
return motion;
|
||||
} catch (const std::exception& e) {
|
||||
error = e.what();
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// VMD names are cut to 15 bytes of Shift-JIS, so a truncated track name matches as a prefix.
|
||||
template <typename Items>
|
||||
int findByName(const Items& items, const std::string& name) {
|
||||
int prefix = -1;
|
||||
for (size_t i = 0; i < items.size(); ++i) {
|
||||
if (items[i].name == name) return static_cast<int>(i);
|
||||
if (prefix < 0 && name.size() >= 6 && items[i].name.compare(0, name.size(), name) == 0)
|
||||
prefix = static_cast<int>(i);
|
||||
}
|
||||
return prefix;
|
||||
}
|
||||
|
||||
template <typename Key>
|
||||
std::pair<const Key*, const Key*> segment(const std::vector<Key>& keys, float frame, float& t) {
|
||||
auto next = std::upper_bound(keys.begin(), keys.end(), frame,
|
||||
[](float f, const Key& k) { return f < static_cast<float>(k.frame); });
|
||||
if (next == keys.begin()) {
|
||||
t = 0.f;
|
||||
return {&keys.front(), &keys.front()};
|
||||
}
|
||||
if (next == keys.end()) {
|
||||
t = 0.f;
|
||||
return {&keys.back(), &keys.back()};
|
||||
}
|
||||
const Key* prev = &*(next - 1);
|
||||
t = (frame - prev->frame) / static_cast<float>(next->frame - prev->frame);
|
||||
return {prev, &*next};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CameraPose evaluateCamera(const std::vector<CameraKeyframe>& keys, float frame) {
|
||||
CameraPose pose;
|
||||
if (keys.empty()) return pose;
|
||||
float t;
|
||||
const auto ends = segment(keys, frame, t);
|
||||
const CameraKeyframe* a = ends.first;
|
||||
const CameraKeyframe* b = ends.second->frame - a->frame <= 1 ? a : ends.second;
|
||||
auto lerp = [&](float x, float y, int curve) { return x + (y - x) * b->curves[curve].eval(t); };
|
||||
osg::Vec3f target, rotation;
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
target[k] = lerp(a->target[k], b->target[k], k);
|
||||
rotation[k] = lerp(a->rotation[k], b->rotation[k], 3);
|
||||
}
|
||||
const float distance = lerp(a->distance, b->distance, 4);
|
||||
pose.fov = lerp(a->fov, b->fov, 5);
|
||||
// Mirroring Z keeps the X and Y angles and negates Z; MMD pitches, then rolls, then yaws.
|
||||
const osg::Matrixf rotate = osg::Matrixf::rotate(rotation.x(), osg::X_AXIS) *
|
||||
osg::Matrixf::rotate(-rotation.z(), osg::Z_AXIS) *
|
||||
osg::Matrixf::rotate(rotation.y(), osg::Y_AXIS);
|
||||
pose.center = target;
|
||||
pose.eye = target + osg::Vec3f(0.f, 0.f, -distance) * rotate;
|
||||
pose.up = osg::Matrixf::transform3x3(osg::Vec3f(0.f, 1.f, 0.f), rotate);
|
||||
return pose;
|
||||
}
|
||||
|
||||
MotionPlayer::MotionPlayer(std::shared_ptr<const Motion> motion, const Model& model) : motion_(std::move(motion)) {
|
||||
for (const auto& [name, keys] : motion_->boneTracks) {
|
||||
const int bone = findByName(model.bones, name);
|
||||
if (bone >= 0 && !keys.empty()) bones_.emplace_back(bone, &keys);
|
||||
}
|
||||
for (const auto& [name, keys] : motion_->morphTracks) {
|
||||
const int morph = findByName(model.morphs, name);
|
||||
if (morph >= 0 && !keys.empty()) morphs_.emplace_back(morph, &keys);
|
||||
}
|
||||
for (const auto& key : motion_->ikKeyframes) {
|
||||
ik_.emplace_back();
|
||||
for (const auto& [name, on] : key.enabled) {
|
||||
const int bone = findByName(model.bones, name);
|
||||
if (bone >= 0) ik_.back().emplace_back(bone, on);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MotionPlayer::apply(float frame, Poser& poser) const {
|
||||
auto& motion = poser.motionPoses();
|
||||
for (const auto& [bone, keys] : bones_) {
|
||||
float t;
|
||||
auto [a, b] = segment(*keys, frame, t);
|
||||
osg::Vec3f translation;
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
const float s = b->curves[k].eval(t);
|
||||
translation[k] = a->translation[k] + (b->translation[k] - a->translation[k]) * s;
|
||||
}
|
||||
osg::Quat rotation;
|
||||
rotation.slerp(b->curves[3].eval(t), a->rotation, b->rotation);
|
||||
motion[bone].translation = translation;
|
||||
motion[bone].rotation = rotation;
|
||||
}
|
||||
auto& weights = poser.morphWeights();
|
||||
for (const auto& [morph, keys] : morphs_) {
|
||||
float t;
|
||||
auto [a, b] = segment(*keys, frame, t);
|
||||
weights[morph] = a->weight + (b->weight - a->weight) * t;
|
||||
}
|
||||
auto& ikEnabled = poser.ikBoneEnabled();
|
||||
std::fill(ikEnabled.begin(), ikEnabled.end(), 1);
|
||||
const auto& ikKeys = motion_->ikKeyframes;
|
||||
for (size_t i = 0; i < ikKeys.size() && static_cast<float>(ikKeys[i].frame) <= frame; ++i)
|
||||
for (const auto& [bone, on] : ik_[i]) ikEnabled[bone] = on ? 1 : 0;
|
||||
}
|
||||
|
||||
} // namespace mr
|
||||
@@ -0,0 +1,88 @@
|
||||
#pragma once
|
||||
|
||||
#include "model/Model.h"
|
||||
#include "model/Poser.h"
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace mr {
|
||||
|
||||
// MMD keyframe easing: cubic Bezier from (0,0) to (1,1) with two control points in [0,1].
|
||||
struct BezierCurve {
|
||||
float x1 = 20.f / 127.f, y1 = 20.f / 127.f, x2 = 107.f / 127.f, y2 = 107.f / 127.f;
|
||||
float eval(float t) const;
|
||||
};
|
||||
|
||||
struct BoneKeyframe {
|
||||
uint32_t frame = 0;
|
||||
osg::Vec3f translation; // internal right-handed space
|
||||
osg::Quat rotation;
|
||||
BezierCurve curves[4]; // X, Y, Z translation, rotation; ease the segment ending at this key
|
||||
};
|
||||
|
||||
struct MorphKeyframe {
|
||||
uint32_t frame = 0;
|
||||
float weight = 0.f;
|
||||
};
|
||||
|
||||
struct IkKeyframe {
|
||||
uint32_t frame = 0;
|
||||
std::vector<std::pair<std::string, bool>> enabled; // IK bone name -> on/off
|
||||
};
|
||||
|
||||
struct CameraKeyframe {
|
||||
uint32_t frame = 0;
|
||||
float distance = 0.f; // MMD convention: negative puts the camera in front of the target
|
||||
osg::Vec3f target; // internal right-handed space
|
||||
osg::Vec3f rotation; // radians, as stored in the VMD (left-handed)
|
||||
float fov = 30.f; // vertical, degrees
|
||||
BezierCurve curves[6]; // target X, Y, Z, rotation, distance, fov
|
||||
};
|
||||
|
||||
// Camera in model space (Y up).
|
||||
struct CameraPose {
|
||||
osg::Vec3f eye, center, up;
|
||||
float fov = 30.f;
|
||||
};
|
||||
|
||||
struct Motion {
|
||||
std::string modelName;
|
||||
std::map<std::string, std::vector<BoneKeyframe>> boneTracks; // sorted by frame
|
||||
std::map<std::string, std::vector<MorphKeyframe>> morphTracks;
|
||||
std::vector<IkKeyframe> ikKeyframes;
|
||||
std::vector<CameraKeyframe> cameraKeys;
|
||||
uint32_t lastFrame = 0;
|
||||
};
|
||||
|
||||
// MMD motion files run at 30 frames per second.
|
||||
constexpr float kMotionFps = 30.f;
|
||||
|
||||
std::shared_ptr<Motion> loadVmd(const std::string& path, std::string& error);
|
||||
|
||||
// Keys one frame apart are a cut, as in MMD: the camera jumps instead of interpolating.
|
||||
CameraPose evaluateCamera(const std::vector<CameraKeyframe>& keys, float frame);
|
||||
|
||||
// Binds a motion's tracks to a model by name and writes the pose at a frame into a Poser.
|
||||
class MotionPlayer {
|
||||
public:
|
||||
MotionPlayer(std::shared_ptr<const Motion> motion, const Model& model);
|
||||
|
||||
const Motion& motion() const { return *motion_; }
|
||||
size_t boundBones() const { return bones_.size(); }
|
||||
size_t boundMorphs() const { return morphs_.size(); }
|
||||
size_t boneTrackCount() const { return motion_->boneTracks.size(); }
|
||||
size_t morphTrackCount() const { return motion_->morphTracks.size(); }
|
||||
|
||||
void apply(float frame, Poser& poser) const;
|
||||
|
||||
private:
|
||||
std::shared_ptr<const Motion> motion_;
|
||||
std::vector<std::pair<int, const std::vector<BoneKeyframe>*>> bones_;
|
||||
std::vector<std::pair<int, const std::vector<MorphKeyframe>*>> morphs_;
|
||||
std::vector<std::vector<std::pair<int, bool>>> ik_; // per IkKeyframe, resolved bone indices
|
||||
};
|
||||
|
||||
} // namespace mr
|
||||
+26
-6
@@ -174,15 +174,35 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
static bool isKnee(const std::string& name) { return name.find("ひざ") != std::string::npos; }
|
||||
|
||||
void parseIK() {
|
||||
uint16_t count = r_.u16();
|
||||
const int n = static_cast<int>(model_.bones.size());
|
||||
for (uint16_t i = 0; i < count; ++i) {
|
||||
r_.u16(); // IK bone
|
||||
r_.u16(); // target
|
||||
uint8_t chain = r_.u8();
|
||||
r_.u16(); // iterations
|
||||
r_.f32(); // limit
|
||||
r_.skip(2u * chain);
|
||||
const int ikBone = r_.u16();
|
||||
const int target = r_.u16();
|
||||
const uint8_t chain = r_.u8();
|
||||
const int iterations = r_.u16();
|
||||
const float limit = r_.f32();
|
||||
std::vector<IkLink> links(chain);
|
||||
for (auto& link : links) link.bone = r_.u16();
|
||||
if (ikBone >= n) continue;
|
||||
Bone& b = model_.bones[ikBone];
|
||||
b.isIK = true;
|
||||
b.ikTarget = target;
|
||||
b.ikIterations = iterations;
|
||||
b.ikLimitAngle = limit * 4.f; // PMD stores a quarter of the per-iteration limit (radians)
|
||||
for (auto& link : links) {
|
||||
// PMD has no limits; MMD restricts knees to bend one way, like PMX's usual knee limits.
|
||||
if (link.bone < n && isKnee(model_.bones[link.bone].name)) {
|
||||
link.limited = true;
|
||||
mmdLimitsToRightHanded(osg::Vec3f(-osg::PIf, 0, 0), osg::Vec3f(-osg::DegreesToRadians(0.5f), 0, 0),
|
||||
link.lower, link.upper);
|
||||
}
|
||||
}
|
||||
b.ikLinks = std::move(links);
|
||||
validateIk(b, ikBone, n);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-8
@@ -226,16 +226,18 @@ private:
|
||||
}
|
||||
if (flags & 0x2000) r_.i32(); // external parent key
|
||||
if (flags & 0x0020) {
|
||||
boneIndex(); // IK target
|
||||
r_.i32(); // loop count
|
||||
r_.f32(); // limit angle
|
||||
b.ikTarget = boneIndex();
|
||||
b.ikIterations = r_.i32();
|
||||
b.ikLimitAngle = r_.f32();
|
||||
int32_t links = r_.i32();
|
||||
if (links < 0) throw std::runtime_error("invalid IK link count");
|
||||
for (int32_t i = 0; i < links; ++i) {
|
||||
boneIndex();
|
||||
if (r_.u8()) {
|
||||
r_.vec3();
|
||||
r_.vec3();
|
||||
b.ikLinks.resize(static_cast<size_t>(links));
|
||||
for (auto& link : b.ikLinks) {
|
||||
link.bone = boneIndex();
|
||||
link.limited = r_.u8() != 0;
|
||||
if (link.limited) {
|
||||
const osg::Vec3f lower = r_.vec3(), upper = r_.vec3();
|
||||
mmdLimitsToRightHanded(lower, upper, link.lower, link.upper);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,6 +250,7 @@ private:
|
||||
b.inheritParent = -1;
|
||||
b.inheritRotation = b.inheritTranslation = false;
|
||||
}
|
||||
validateIk(b, i, n);
|
||||
osg::Vec3f parentPos = b.parent >= 0 ? model_.bones[b.parent].restPosition : osg::Vec3f();
|
||||
b.localBind = osg::Matrixf::translate(b.restPosition - parentPos);
|
||||
b.inverseBind = osg::Matrixf::translate(-b.restPosition);
|
||||
|
||||
+115
-11
@@ -37,8 +37,24 @@ Poser::Poser(std::shared_ptr<const Model> model) : model_(std::move(model)) {
|
||||
animTranslation_.resize(boneCount);
|
||||
globals_.resize(boneCount);
|
||||
skin_.resize(boneCount);
|
||||
motion_.resize(boneCount);
|
||||
ikBoneEnabled_.assign(boneCount, 1);
|
||||
computeEvaluationOrder();
|
||||
|
||||
isIkLink_.assign(boneCount, 0);
|
||||
ikAffected_.resize(boneCount);
|
||||
for (size_t b = 0; b < boneCount; ++b) {
|
||||
const Bone& bone = model_->bones[b];
|
||||
if (!bone.isIK) continue;
|
||||
std::vector<uint8_t> moved(boneCount, 0);
|
||||
for (const auto& link : bone.ikLinks) moved[link.bone] = isIkLink_[link.bone] = 1;
|
||||
for (int o : order_) {
|
||||
const int parent = model_->bones[o].parent;
|
||||
if (parent >= 0 && moved[parent]) moved[o] = 1;
|
||||
if (moved[o]) ikAffected_[b].push_back(o);
|
||||
}
|
||||
}
|
||||
|
||||
bindRotation_.resize(boneCount);
|
||||
std::vector<osg::Matrixf> rest(boneCount);
|
||||
for (int b : order_) {
|
||||
@@ -55,6 +71,11 @@ void Poser::resetPose() { std::fill(poses_.begin(), poses_.end(), BonePose()); }
|
||||
|
||||
void Poser::resetMorphs() { std::fill(weights_.begin(), weights_.end(), 0.f); }
|
||||
|
||||
void Poser::resetMotion() {
|
||||
std::fill(motion_.begin(), motion_.end(), MotionPose());
|
||||
std::fill(ikBoneEnabled_.begin(), ikBoneEnabled_.end(), 1);
|
||||
}
|
||||
|
||||
void Poser::computeEvaluationOrder() {
|
||||
const auto& bones = model_->bones;
|
||||
const int n = static_cast<int>(bones.size());
|
||||
@@ -65,7 +86,14 @@ void Poser::computeEvaluationOrder() {
|
||||
return bones[a].layer < bones[b].layer;
|
||||
});
|
||||
|
||||
// Depth-first so parents and inheritance sources are always evaluated first.
|
||||
// Depth-first so parents, inheritance sources and IK chains are always evaluated first.
|
||||
auto dependency = [&](int bone, int step) {
|
||||
const Bone& b = bones[bone];
|
||||
if (step == 0) return b.parent;
|
||||
if (step == 1) return b.inheritParent;
|
||||
if (step == 2) return b.ikTarget;
|
||||
return b.ikLinks[step - 3].bone;
|
||||
};
|
||||
std::vector<int> state(n, 0); // 0 = new, 1 = visiting, 2 = done
|
||||
order_.clear();
|
||||
order_.reserve(n);
|
||||
@@ -76,10 +104,9 @@ void Poser::computeEvaluationOrder() {
|
||||
state[start] = 1;
|
||||
while (!stack.empty()) {
|
||||
auto& [bone, step] = stack.back();
|
||||
int dep = -1;
|
||||
if (step == 0) dep = bones[bone].parent;
|
||||
else if (step == 1) dep = bones[bone].inheritParent;
|
||||
if (step < 2) {
|
||||
const int steps = 3 + static_cast<int>(bones[bone].ikLinks.size());
|
||||
if (step < steps) {
|
||||
const int dep = dependency(bone, step);
|
||||
++step;
|
||||
if (dep >= 0 && state[dep] == 0) {
|
||||
state[dep] = 1;
|
||||
@@ -110,12 +137,89 @@ void Poser::setSkinningMode(SkinningMode mode) {
|
||||
firstUpdate_ = true;
|
||||
}
|
||||
|
||||
void Poser::updateGlobal(int b) {
|
||||
const Bone& bone = model_->bones[b];
|
||||
const osg::Matrixf local =
|
||||
osg::Matrixf::rotate(animRotation_[b]) * osg::Matrixf::translate(animTranslation_[b]) * bone.localBind;
|
||||
globals_[b] = bone.parent >= 0 ? local * globals_[bone.parent] : local;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Euler angles (X, then Y, then Z, as in eulerToQuat) of a rotation, in radians.
|
||||
osg::Vec3f quatToEuler(const osg::Quat& q) {
|
||||
const osg::Matrixf m = osg::Matrixf::rotate(q);
|
||||
const float sy = std::min(1.f, std::max(-1.f, -m(0, 2)));
|
||||
return osg::Vec3f(std::atan2(m(1, 2), m(2, 2)), std::asin(sy), std::atan2(m(0, 1), m(0, 0)));
|
||||
}
|
||||
|
||||
// Axis index when a limit allows rotation about exactly one axis, otherwise -1.
|
||||
int singleLimitAxis(const IkLink& link) {
|
||||
int axis = -1;
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
if (link.lower[k] == 0.f && link.upper[k] == 0.f) continue;
|
||||
if (axis >= 0) return -1;
|
||||
axis = k;
|
||||
}
|
||||
return axis;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Cyclic coordinate descent, as MMD does: each link in turn rotates to point the target at the IK bone.
|
||||
void Poser::solveIk(int ikBone) {
|
||||
const Bone& ik = model_->bones[ikBone];
|
||||
const osg::Vec3f goal = globals_[ikBone].getTrans();
|
||||
for (int iter = 0; iter < ik.ikIterations; ++iter) {
|
||||
if ((globals_[ik.ikTarget].getTrans() - goal).length2() < 1e-10f) break;
|
||||
for (const IkLink& link : ik.ikLinks) {
|
||||
const int b = link.bone;
|
||||
const osg::Matrixf inv = osg::Matrixf::inverse(globals_[b]);
|
||||
osg::Vec3f toTarget = globals_[ik.ikTarget].getTrans() * inv;
|
||||
osg::Vec3f toGoal = goal * inv;
|
||||
if (toTarget.normalize() < 1e-6f || toGoal.normalize() < 1e-6f) continue;
|
||||
|
||||
const int axisIndex = link.limited ? singleLimitAxis(link) : -1;
|
||||
if (axisIndex >= 0) {
|
||||
osg::Vec3f axis;
|
||||
axis[axisIndex] = 1.f;
|
||||
osg::Vec3f u = toTarget - axis * (toTarget * axis), v = toGoal - axis * (toGoal * axis);
|
||||
if (u.normalize() < 1e-6f || v.normalize() < 1e-6f) continue;
|
||||
float delta = std::atan2(axis * (u ^ v), u * v);
|
||||
delta = std::min(ik.ikLimitAngle, std::max(-ik.ikLimitAngle, delta));
|
||||
const osg::Quat& q = animRotation_[b];
|
||||
const float current = 2.f * std::atan2(osg::Vec3f(q.x(), q.y(), q.z()) * axis, float(q.w()));
|
||||
const float angle =
|
||||
std::min(link.upper[axisIndex], std::max(link.lower[axisIndex], current + delta));
|
||||
animRotation_[b] = osg::Quat(angle, axis);
|
||||
} else {
|
||||
const float angle = std::min(ik.ikLimitAngle, std::acos(std::min(1.f, std::max(-1.f, toTarget * toGoal))));
|
||||
osg::Vec3f axis = toTarget ^ toGoal;
|
||||
if (angle < 1e-6f || axis.normalize() < 1e-6f) continue;
|
||||
osg::Quat rotation = osg::Quat(angle, axis) * animRotation_[b];
|
||||
if (link.limited) {
|
||||
osg::Vec3f e = quatToEuler(rotation);
|
||||
for (int k = 0; k < 3; ++k) e[k] = std::min(link.upper[k], std::max(link.lower[k], e[k]));
|
||||
rotation = osg::Quat(e.x(), osg::X_AXIS, e.y(), osg::Y_AXIS, e.z(), osg::Z_AXIS);
|
||||
}
|
||||
animRotation_[b] = rotation;
|
||||
}
|
||||
for (int a : ikAffected_[ikBone]) updateGlobal(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool Poser::update() {
|
||||
if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_) return false;
|
||||
if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_ && motion_ == lastMotion_ &&
|
||||
ikEnabled_ == lastIkEnabled_ && ikBoneEnabled_ == lastIkBoneEnabled_)
|
||||
return false;
|
||||
morphsChanged_ = firstUpdate_ || weights_ != lastWeights_;
|
||||
firstUpdate_ = false;
|
||||
lastPoses_ = poses_;
|
||||
lastWeights_ = weights_;
|
||||
lastMotion_ = motion_;
|
||||
lastIkEnabled_ = ikEnabled_;
|
||||
lastIkBoneEnabled_ = ikBoneEnabled_;
|
||||
|
||||
const Model& model = *model_;
|
||||
const auto& bones = model.bones;
|
||||
@@ -140,8 +244,8 @@ bool Poser::update() {
|
||||
// Convert the model-space pose into the bone's own frame.
|
||||
const osg::Quat& g = bindRotation_[b];
|
||||
const osg::Quat poseRotation = g * eulerToQuat(poses_[b].eulerDegrees) * g.inverse();
|
||||
osg::Quat rotation = morphRotation_[b] * poseRotation;
|
||||
osg::Vec3f translation = g.inverse() * poses_[b].translation + morphTranslation_[b];
|
||||
osg::Quat rotation = morphRotation_[b] * motion_[b].rotation * poseRotation;
|
||||
osg::Vec3f translation = g.inverse() * poses_[b].translation + morphTranslation_[b] + motion_[b].translation;
|
||||
if (bone.inheritParent >= 0) {
|
||||
if (bone.inheritRotation)
|
||||
rotation = rotation * scaledRotation(animRotation_[bone.inheritParent], bone.inheritWeight);
|
||||
@@ -149,10 +253,10 @@ bool Poser::update() {
|
||||
}
|
||||
animRotation_[b] = rotation;
|
||||
animTranslation_[b] = translation;
|
||||
osg::Matrixf local = osg::Matrixf::rotate(rotation) * osg::Matrixf::translate(translation) * bone.localBind;
|
||||
globals_[b] = bone.parent >= 0 ? local * globals_[bone.parent] : local;
|
||||
skin_[b] = bone.inverseBind * globals_[b];
|
||||
updateGlobal(b);
|
||||
if (bone.isIK && ikEnabled_ && ikBoneEnabled_[b]) solveIk(b);
|
||||
}
|
||||
for (size_t b = 0; b < bones.size(); ++b) skin_[b] = bones[b].inverseBind * globals_[b];
|
||||
|
||||
const size_t vertexCount = model.vertices.size();
|
||||
if (morphsChanged_) {
|
||||
|
||||
+24
-1
@@ -21,6 +21,14 @@ struct BonePose {
|
||||
bool operator!=(const BonePose& o) const { return !(*this == o); }
|
||||
};
|
||||
|
||||
// Keyframed bone transform from a motion (e.g. VMD): parent-aligned offset from rest + rotation.
|
||||
struct MotionPose {
|
||||
osg::Vec3f translation;
|
||||
osg::Quat rotation;
|
||||
|
||||
bool operator==(const MotionPose& o) const { return translation == o.translation && rotation == o.rotation; }
|
||||
};
|
||||
|
||||
// Applies morph weights and bone poses to a model (CPU morphing + linear blend skinning).
|
||||
class Poser {
|
||||
public:
|
||||
@@ -30,10 +38,18 @@ public:
|
||||
std::vector<BonePose>& bonePoses() { return poses_; }
|
||||
std::vector<float>& morphWeights() { return weights_; }
|
||||
|
||||
// Motion transforms are applied before the user pose, which acts as an offset on top.
|
||||
std::vector<MotionPose>& motionPoses() { return motion_; }
|
||||
// IK chains are solved after posing; per-bone flags come from motion files.
|
||||
void setIkEnabled(bool enabled) { ikEnabled_ = enabled; }
|
||||
bool ikEnabled() const { return ikEnabled_; }
|
||||
std::vector<uint8_t>& ikBoneEnabled() { return ikBoneEnabled_; }
|
||||
bool isIkLink(int bone) const { return bone >= 0 && bone < int(isIkLink_.size()) && isIkLink_[bone]; }
|
||||
|
||||
void resetPose();
|
||||
void resetMorphs();
|
||||
void resetMotion();
|
||||
|
||||
// Recomputes the deformed mesh if anything changed. Returns true when it did.
|
||||
void setSkinningMode(SkinningMode mode);
|
||||
SkinningMode skinningMode() const { return mode_; }
|
||||
|
||||
@@ -53,10 +69,17 @@ public:
|
||||
private:
|
||||
void computeEvaluationOrder();
|
||||
void accumulateMorph(int morph, float weight, int depth);
|
||||
void updateGlobal(int bone);
|
||||
void solveIk(int ikBone);
|
||||
|
||||
std::shared_ptr<const Model> model_;
|
||||
std::vector<BonePose> poses_, lastPoses_;
|
||||
std::vector<float> weights_, lastWeights_;
|
||||
std::vector<MotionPose> motion_, lastMotion_;
|
||||
std::vector<uint8_t> ikBoneEnabled_, lastIkBoneEnabled_;
|
||||
bool ikEnabled_ = true, lastIkEnabled_ = true;
|
||||
std::vector<std::vector<int>> ikAffected_; // per IK bone: bones whose globals the chain moves, in order
|
||||
std::vector<uint8_t> isIkLink_;
|
||||
bool firstUpdate_ = true;
|
||||
bool morphsChanged_ = true;
|
||||
SkinningMode mode_ = SkinningMode::Software;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,5 +1,7 @@
|
||||
// Loader and posing tests. Test models are generated by tools/make_test_models.py.
|
||||
#include "model/ModelLoader.h"
|
||||
#include "audio/AudioPlayer.h"
|
||||
#include "model/Motion.h"
|
||||
#include "model/PathUtil.h"
|
||||
#include "model/Poser.h"
|
||||
|
||||
@@ -153,6 +155,104 @@ void testPmd() {
|
||||
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 6, 1), 1e-3f));
|
||||
}
|
||||
|
||||
// column.pmx: IK bone at (0, 10, 0) pulls the eye (0, 9, 0) via the upper body (pivot (0, 5, 0)),
|
||||
// limited to [-1, 1] rad about X.
|
||||
void testIk() {
|
||||
auto model = load("column.pmx");
|
||||
CHECK(model);
|
||||
if (!model) return;
|
||||
const int ik = model->findBone("IK"), upper = model->findBone("上半身"), eye = model->findBone("目");
|
||||
CHECK(ik >= 0 && model->bones[ik].isIK && model->bones[ik].ikTarget == eye);
|
||||
CHECK(model->bones[ik].ikLinks.size() == 1 && model->bones[ik].ikLinks[0].bone == upper);
|
||||
CHECK(near(model->bones[ik].ikLinks[0].lower.x(), -1.f) && near(model->bones[ik].ikLinks[0].upper.x(), 1.f));
|
||||
if (ik < 0 || upper < 0 || eye < 0) return;
|
||||
|
||||
mr::Poser poser(model);
|
||||
poser.update();
|
||||
float maxErr = 0.f;
|
||||
for (size_t i = 0; i < model->vertices.size(); ++i)
|
||||
maxErr = std::max(maxErr, (poser.positions()[i] - model->vertices[i].position).length());
|
||||
CHECK(maxErr < 1e-3f);
|
||||
|
||||
auto reach = [&](float deg) {
|
||||
const float a = osg::DegreesToRadians(deg);
|
||||
poser.bonePoses()[ik].translation.set(0, 5 * std::cos(a) - 5, 5 * std::sin(a));
|
||||
poser.update();
|
||||
return poser.boneGlobals()[eye].getTrans();
|
||||
};
|
||||
const float a30 = osg::DegreesToRadians(30.f);
|
||||
CHECK(near(reach(30), osg::Vec3f(0, 5 + 4 * std::cos(a30), 4 * std::sin(a30)), 1e-2f));
|
||||
CHECK(near(reach(80), osg::Vec3f(0, 5 + 4 * std::cos(1.f), 4 * std::sin(1.f)), 1e-2f)); // clamped at 1 rad
|
||||
poser.setIkEnabled(false);
|
||||
poser.update();
|
||||
CHECK(near(poser.boneGlobals()[eye].getTrans(), osg::Vec3f(0, 9, 0)));
|
||||
}
|
||||
|
||||
void testVmd() {
|
||||
mr::BezierCurve linear;
|
||||
CHECK(near(linear.eval(0.5f), 0.5f, 1e-3f));
|
||||
mr::BezierCurve easeIn{1.f, 0.f, 1.f, 1.f};
|
||||
CHECK(easeIn.eval(0.5f) < 0.4f && near(easeIn.eval(1.f), 1.f));
|
||||
|
||||
std::string error;
|
||||
auto motion = mr::loadVmd(std::string(MR_TEST_DATA_DIR) + "/column.vmd", error);
|
||||
CHECK(motion);
|
||||
if (!motion) {
|
||||
std::printf("loadVmd failed: %s\n", error.c_str());
|
||||
return;
|
||||
}
|
||||
CHECK(motion->modelName == "テスト");
|
||||
CHECK(motion->lastFrame == 20 && motion->boneTracks.size() == 2 && motion->morphTracks.size() == 1);
|
||||
CHECK(motion->ikKeyframes.size() == 1);
|
||||
|
||||
auto model = load("column.pmx");
|
||||
if (!model) return;
|
||||
mr::MotionPlayer player(motion, *model);
|
||||
CHECK(player.boundBones() == 2 && player.boundMorphs() == 1);
|
||||
mr::Poser poser(model);
|
||||
// Frame 5: upper body 45 deg about Z, center up 1, mouth morph 0.5, IK switched off by the motion.
|
||||
player.apply(5.f, poser);
|
||||
poser.update();
|
||||
CHECK(poser.ikBoneEnabled()[model->findBone("IK")] == 0);
|
||||
CHECK(near(poser.morphWeights()[0], 0.5f));
|
||||
const float h = std::sqrt(0.5f);
|
||||
CHECK(near(poser.positions()[16], osg::Vec3f(h * (1.5f - 5.f), 6.f + h * (1.5f + 5.f), 1.25f), 1e-3f));
|
||||
player.apply(100.f, poser); // past the end holds the last key
|
||||
poser.update();
|
||||
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 9, 1.5f), 1e-3f)); // morph held at 1
|
||||
}
|
||||
|
||||
void testCameraAndAudio() {
|
||||
std::vector<mr::CameraKeyframe> keys(3);
|
||||
keys[0].distance = -45.f;
|
||||
keys[0].target.set(0, 10, 0);
|
||||
keys[1] = keys[0];
|
||||
keys[1].frame = 30;
|
||||
keys[1].rotation.set(0, osg::PI_2f, 0);
|
||||
keys[1].fov = 50.f;
|
||||
keys[2] = keys[1];
|
||||
keys[2].frame = 31;
|
||||
keys[2].target.set(0, 20, 0);
|
||||
mr::CameraPose c = mr::evaluateCamera(keys, 0.f);
|
||||
CHECK(near(c.eye, osg::Vec3f(0, 10, 45)) && near(c.center, osg::Vec3f(0, 10, 0)) && near(c.up, osg::Vec3f(0, 1, 0)));
|
||||
CHECK(near(c.fov, 30.f));
|
||||
c = mr::evaluateCamera(keys, 30.5f); // cut: holds frame 30
|
||||
CHECK(near(c.eye, osg::Vec3f(45, 10, 0), 1e-3f) && near(c.fov, 50.f));
|
||||
c = mr::evaluateCamera(keys, 15.f);
|
||||
CHECK(near(c.fov, 40.f, 1e-2f) && near(c.eye.length2(), 0.f) == false);
|
||||
CHECK(near((c.eye - c.center).length(), 45.f, 1e-3f));
|
||||
c = mr::evaluateCamera(keys, 99.f);
|
||||
CHECK(near(c.center, osg::Vec3f(0, 20, 0)));
|
||||
|
||||
mr::AudioPlayer audio;
|
||||
std::string error;
|
||||
CHECK(audio.load(std::string(MR_TEST_DATA_DIR) + "/tone.wav", error));
|
||||
CHECK(near(static_cast<float>(audio.length()), 0.5f, 1e-2f));
|
||||
audio.seek(0.25);
|
||||
CHECK(near(static_cast<float>(audio.position()), 0.25f, 1e-2f));
|
||||
CHECK(!audio.load(std::string(MR_TEST_DATA_DIR) + "/missing.wav", error));
|
||||
}
|
||||
|
||||
void testFbx() {
|
||||
auto model = load("rigged_box.fbx");
|
||||
CHECK(model);
|
||||
@@ -193,6 +293,9 @@ int main() {
|
||||
testPmx();
|
||||
testPmd();
|
||||
testFbx();
|
||||
testIk();
|
||||
testVmd();
|
||||
testCameraAndAudio();
|
||||
if (g_failures == 0) std::printf("All tests passed\n");
|
||||
return g_failures == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Writes VMD motions: tests/data/column.vmd for the unit tests, or a demo dance for MMD-rigged
|
||||
models with --demo OUT (standard Japanese bone/morph names; unknown names are ignored)."""
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
LINEAR = bytes([20] * 8 + [107] * 8) + bytes(48)
|
||||
|
||||
|
||||
def name(s, n):
|
||||
b = s.encode("cp932")[:n]
|
||||
return b + b"\0" * (n - len(b))
|
||||
|
||||
|
||||
def quat(axis, deg):
|
||||
# Right-handed rotation converted to MMD's left-handed space: (x, y, z, w) -> (-x, -y, z, w).
|
||||
s, c = math.sin(math.radians(deg) / 2), math.cos(math.radians(deg) / 2)
|
||||
x, y, z = (a * s for a in axis)
|
||||
return (-x, -y, z, c)
|
||||
|
||||
|
||||
def bone(nm, frame, pos=(0, 0, 0), rot=(0, 0, 0, 1)):
|
||||
# pos is right-handed (+Z = forward), stored left-handed.
|
||||
return name(nm, 15) + struct.pack("<I3f4f", frame, pos[0], pos[1], -pos[2], *rot) + LINEAR
|
||||
|
||||
|
||||
def write(path, model, bones, morphs, iks=()):
|
||||
out = b"Vocaloid Motion Data 0002".ljust(30, b"\0") + name(model, 20)
|
||||
out += struct.pack("<I", len(bones)) + b"".join(bones)
|
||||
out += struct.pack("<I", len(morphs)) + b"".join(name(n, 15) + struct.pack("<If", f, w) for n, f, w in morphs)
|
||||
out += struct.pack("<III", 0, 0, 0) # camera, light, self shadow
|
||||
out += struct.pack("<I", len(iks))
|
||||
for frame, states in iks:
|
||||
out += struct.pack("<IBI", frame, 1, len(states))
|
||||
out += b"".join(name(n, 20) + bytes([on]) for n, on in states)
|
||||
with open(path, "wb") as f:
|
||||
f.write(out)
|
||||
|
||||
|
||||
def column(path):
|
||||
bones = [bone("上半身", 0), bone("上半身", 10, rot=quat((0, 0, 1), 90)), bone("上半身", 20, rot=quat((0, 0, 1), 90)),
|
||||
bone("センター", 0), bone("センター", 10, pos=(0, 2, 0))]
|
||||
write(path, "テスト", bones, [("あ", 0, 0.0), ("あ", 10, 1.0)], [(0, [("IK", 0)])])
|
||||
|
||||
|
||||
def demo(path):
|
||||
bones, morphs = [], []
|
||||
for f in range(0, 121, 15):
|
||||
down = (f // 15) % 2 == 1
|
||||
bones.append(bone("センター", f, pos=(0, -0.8 if down else 0, 0)))
|
||||
bones.append(bone("左腕", f, rot=quat((0, 0, 1), -35 if down else -20)))
|
||||
bones.append(bone("右腕", f, rot=quat((0, 0, 1), 35 if down else 20)))
|
||||
bones.append(bone("頭", f, rot=quat((1, 0, 0), 10 if down else -5)))
|
||||
morphs += [("あ", f, 0.8 if down else 0.0)]
|
||||
bones += [bone("左足IK", 0), bone("左足IK", 30, pos=(0, 1.5, 1.5)), bone("左足IK", 60),
|
||||
bone("右足IK", 60), bone("右足IK", 90, pos=(0, 1.5, 1.5)), bone("右足IK", 120)]
|
||||
for blink in ("まばたき", "blink"):
|
||||
morphs += [(blink, 40, 0.0), (blink, 44, 1.0), (blink, 48, 0.0)]
|
||||
write(path, "demo", bones, morphs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--demo":
|
||||
demo(sys.argv[2])
|
||||
else:
|
||||
column(os.path.join(os.path.dirname(__file__), "..", "tests", "data", "column.vmd"))
|
||||
Reference in new issue
Block a user