Files
3d-model-renderer/src/render/ModelNode.cpp
T
gs5579andDevin AI d842285390 Add OSG/Assimp/ImGui model renderer with PMX/PMD/FBX loading, posing and morphs
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-27 09:51:44 +00:00

272 lines
11 KiB
C++

#include "render/ModelNode.h"
#include "render/Shaders.h"
#include "render/TextureLoader.h"
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/LineWidth>
#include <osg/Point>
#include <osg/PolygonMode>
namespace mr {
namespace {
// MMD's default light: direction (-0.5, -1, 0.5) in its left-handed space.
const osg::Vec3f kMmdLightDirection(-0.5f, -1.0f, -0.5f);
class DeformCallback : public osg::NodeCallback {
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
static_cast<ModelNode*>(node)->updateDeformation();
traverse(node, nv);
}
};
} // namespace
ModelNode::ModelNode(std::shared_ptr<Model> model) : model_(std::move(model)), poser_(model_) {
setMatrix(osg::Matrix::rotate(osg::PI_2, osg::X_AXIS)); // Y-up model -> Z-up world
setDataVariance(osg::Object::DYNAMIC);
osg::StateSet* ss = getOrCreateStateSet();
ss->setAttributeAndModes(createModelProgram(), osg::StateAttribute::ON);
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
ss->addUniform(new osg::Uniform("u_texture", 0));
ss->addUniform(new osg::Uniform("u_sphere", 1));
ss->addUniform(new osg::Uniform("u_toon", 2));
ss->addUniform(new osg::Uniform("u_lightColor", osg::Vec3f(0.6f, 0.6f, 0.6f)));
const bool isMmd = model_->format != SourceFormat::Assimp;
lightingUniform_ = new osg::Uniform("u_lightingModel", isMmd ? 0 : 1);
lightFollowUniform_ = new osg::Uniform("u_lightFollowsCamera", 0);
osg::Vec3f worldLight = osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix()));
lightDirUniform_ = new osg::Uniform("u_lightDirection", worldLight);
ss->addUniform(lightingUniform_);
ss->addUniform(lightFollowUniform_);
ss->addUniform(lightDirUniform_);
textures_.resize(model_->textures.size());
textureTried_.assign(model_->textures.size(), false);
buildMesh();
buildSkeleton();
setShowSkeleton(false);
updateDeformation();
setUpdateCallback(new DeformCallback);
}
osg::Texture2D* ModelNode::texture(int index, bool clamp) {
if (index < 0 || index >= static_cast<int>(textures_.size())) return nullptr;
if (!textureTried_[index]) {
textureTried_[index] = true;
if (osg::ref_ptr<osg::Image> image = loadTextureImage(model_->textures[index]))
textures_[index] = makeTexture(image.get(), clamp);
}
return textures_[index].get();
}
osg::StateSet* ModelNode::buildMaterialState(const Material& m, int order) {
auto* ss = new osg::StateSet;
ss->addUniform(new osg::Uniform("u_diffuse", m.diffuse));
ss->addUniform(new osg::Uniform("u_ambient", m.ambient));
ss->addUniform(new osg::Uniform("u_specular", m.specular));
ss->addUniform(new osg::Uniform("u_shininess", m.shininess));
osg::Texture2D* main = texture(m.texture, false);
if (main) ss->setTextureAttributeAndModes(0, main, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_useTexture", main ? 1 : 0));
osg::Texture2D* sphere = nullptr;
if (m.sphereMode == SphereMode::Multiply || m.sphereMode == SphereMode::Add)
sphere = texture(m.sphereTexture, true);
if (sphere) ss->setTextureAttributeAndModes(1, sphere, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_sphereMode", !sphere ? 0 : m.sphereMode == SphereMode::Add ? 2 : 1));
osg::Texture2D* toon = texture(m.toonTexture, true);
if (!toon && m.sharedToon >= 0 && m.sharedToon <= 9) {
if (!sharedToons_[m.sharedToon]) sharedToons_[m.sharedToon] = makeTexture(makeSharedToonImage(m.sharedToon), true);
toon = sharedToons_[m.sharedToon].get();
}
if (toon) ss->setTextureAttributeAndModes(2, toon, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_useToon", toon ? 1 : 0));
osg::ref_ptr<osg::CullFace> cull = new osg::CullFace(osg::CullFace::BACK);
ss->setAttributeAndModes(cull, m.doubleSided ? osg::StateAttribute::OFF : osg::StateAttribute::ON);
// MMD draws materials in file order with alpha blending always enabled.
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
ss->setRenderBinDetails(10 + order, "RenderBin");
return ss;
}
void ModelNode::buildMesh() {
const Model& model = *model_;
positions_ = new osg::Vec3Array(model.vertices.size());
normals_ = new osg::Vec3Array(model.vertices.size());
osg::ref_ptr<osg::Vec2Array> uvs = new osg::Vec2Array(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) {
(*positions_)[i] = model.vertices[i].position;
(*normals_)[i] = model.vertices[i].normal;
(*uvs)[i] = model.vertices[i].uv;
}
positions_->setDataVariance(osg::Object::DYNAMIC);
normals_->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
for (size_t i = 0; i < model.materials.size(); ++i) {
const Material& m = model.materials[i];
if (m.indexCount == 0) continue;
osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
geom->setName(m.name);
geom->setDataVariance(osg::Object::DYNAMIC);
geom->setUseDisplayList(false);
geom->setUseVertexBufferObjects(true);
geom->setVertexArray(positions_);
geom->setNormalArray(normals_, osg::Array::BIND_PER_VERTEX);
geom->setTexCoordArray(0, uvs, osg::Array::BIND_PER_VERTEX);
osg::ref_ptr<osg::DrawElementsUInt> elements = new osg::DrawElementsUInt(
GL_TRIANGLES, model.indices.begin() + m.indexOffset, model.indices.begin() + m.indexOffset + m.indexCount);
geom->addPrimitiveSet(elements);
geom->setStateSet(buildMaterialState(m, static_cast<int>(i)));
geode->addDrawable(geom);
geometries_.push_back(geom);
}
meshGroup_ = geode;
addChild(meshGroup_);
}
void ModelNode::buildSkeleton() {
const Model& model = *model_;
for (size_t i = 0; i < model.bones.size(); ++i)
if (model.bones[i].visible || model.bones[i].isSkinBone) skeletonBones_.push_back(static_cast<int>(i));
skeletonGeode_ = new osg::Geode;
osg::StateSet* ss = skeletonGeode_->getOrCreateStateSet();
ss->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON); // fixed function
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
ss->setMode(GL_BLEND, osg::StateAttribute::OFF);
ss->setAttributeAndModes(new osg::PolygonMode(), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
ss->setAttribute(new osg::LineWidth(2.f));
ss->setAttribute(new osg::Point(6.f));
ss->setRenderBinDetails(100000, "RenderBin");
auto makeGeom = [](GLenum mode) {
osg::ref_ptr<osg::Geometry> g = new osg::Geometry;
g->setDataVariance(osg::Object::DYNAMIC);
g->setUseDisplayList(false);
g->setUseVertexBufferObjects(true);
g->setVertexArray(new osg::Vec3Array);
g->setColorArray(new osg::Vec4Array, osg::Array::BIND_PER_VERTEX);
g->addPrimitiveSet(new osg::DrawArrays(mode, 0, 0));
return g;
};
skeletonLines_ = makeGeom(GL_LINES);
skeletonPoints_ = makeGeom(GL_POINTS);
skeletonGeode_->addDrawable(skeletonLines_);
skeletonGeode_->addDrawable(skeletonPoints_);
addChild(skeletonGeode_);
}
void ModelNode::updateSkeleton() {
const auto& globals = poser_.boneGlobals();
const auto& bones = model_->bones;
auto* lineVerts = static_cast<osg::Vec3Array*>(skeletonLines_->getVertexArray());
auto* lineColors = static_cast<osg::Vec4Array*>(skeletonLines_->getColorArray());
auto* pointVerts = static_cast<osg::Vec3Array*>(skeletonPoints_->getVertexArray());
auto* pointColors = static_cast<osg::Vec4Array*>(skeletonPoints_->getColorArray());
lineVerts->clear();
lineColors->clear();
pointVerts->clear();
pointColors->clear();
const osg::Vec4 normal(0.3f, 0.8f, 1.f, 1.f), selected(1.f, 0.85f, 0.1f, 1.f);
for (int b : skeletonBones_) {
const osg::Vec4& color = b == selectedBone_ ? selected : normal;
osg::Vec3 head = globals[b].getTrans();
pointVerts->push_back(head);
pointColors->push_back(color);
int parent = bones[b].parent;
if (parent >= 0) {
lineVerts->push_back(globals[parent].getTrans());
lineVerts->push_back(head);
lineColors->push_back(color);
lineColors->push_back(color);
}
}
static_cast<osg::DrawArrays*>(skeletonLines_->getPrimitiveSet(0))->setCount(lineVerts->size());
static_cast<osg::DrawArrays*>(skeletonPoints_->getPrimitiveSet(0))->setCount(pointVerts->size());
for (osg::Array* a : {static_cast<osg::Array*>(lineVerts), static_cast<osg::Array*>(lineColors),
static_cast<osg::Array*>(pointVerts), static_cast<osg::Array*>(pointColors)})
a->dirty();
skeletonLines_->dirtyBound();
skeletonPoints_->dirtyBound();
}
void ModelNode::updateDeformation() {
if (poser_.update()) {
const auto& p = poser_.positions();
const auto& n = poser_.normals();
std::copy(p.begin(), p.end(), positions_->begin());
std::copy(n.begin(), n.end(), normals_->begin());
positions_->dirty();
normals_->dirty();
for (auto& g : geometries_) g->dirtyBound();
skeletonDirty_ = true;
}
if (skeletonDirty_ && skeletonGeode_->getNodeMask() != 0) {
updateSkeleton();
skeletonDirty_ = false;
}
}
void ModelNode::setShowSkeleton(bool show) {
skeletonGeode_->setNodeMask(show ? ~0u : 0u);
skeletonDirty_ = true;
}
void ModelNode::setSelectedBone(int bone) {
if (bone == selectedBone_) return;
selectedBone_ = bone;
skeletonDirty_ = true;
}
void ModelNode::setBackfaceCulling(bool enabled) {
osg::StateSet* ss = meshGroup_->getOrCreateStateSet();
if (enabled) ss->removeMode(GL_CULL_FACE);
else ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
void ModelNode::setWireframe(bool enabled) {
osg::StateSet* ss = meshGroup_->getOrCreateStateSet();
if (enabled)
ss->setAttributeAndModes(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
else ss->removeAttribute(osg::StateAttribute::POLYGONMODE);
}
void ModelNode::setLightingModel(LightingModel lighting) { lightingUniform_->set(static_cast<int>(lighting)); }
void ModelNode::setLightFollowsCamera(bool follow) {
lightFollowUniform_->set(follow ? 1 : 0);
// In view space a light from the upper left, slightly in front of the camera.
osg::Vec3f dir = follow ? osg::Vec3f(0.3f, -0.5f, -1.f)
: osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix()));
lightDirUniform_->set(dir);
}
osg::BoundingSphere ModelNode::restBound() const {
osg::Vec3f lo, hi;
model_->computeBounds(lo, hi);
osg::BoundingBox box(lo, hi);
osg::BoundingSphere sphere(box);
sphere.center() = sphere.center() * getMatrix();
return sphere;
}
} // namespace mr