Compare commits

Author SHA1 Message Date
dev 21d0910e8e Merge pull request 'Camera fit: made-for height, distance and offset for camera motions' (#11) from devin/1796110078-camera-fit into main
Merge PR #11: camera fit
2026-12-01 08:35:43 -05:00
dev 73834b8c70 Merge pull request 'Post-processing: bloom, ambient occlusion, colour grading, FXAA' (#10) from devin/1796106677-postfx into main
Merge PR #10: bloom, colour grading, AO, FXAA; UV and material morphs
2026-12-01 08:35:31 -05:00
gs5579andDevin AI dc9d9fa46e Camera fit: made-for height, height scale, distance, offset; camera follows model placement
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 07:29:56 +00:00
gs5579andDevin AI 302e7c4f20 UV and material morphs; FXAA-only path skips composite, 8-bit post targets
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 07:03:56 +00:00
gs5579andDevin AI 799c4ac344 Grid: no depth writes so AO ignores it
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:48:44 +00:00
gs5579andDevin AI e786a88dec AO: distance-scaled bias against flat-ground self-occlusion
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:47:37 +00:00
gs5579andDevin AI 637a2c12f2 Post-FX: fit near/far for big stages, explicit grid shader, fade AO with distance
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:42:48 +00:00
gs5579andDevin AI 4b33a676eb Bloom: luminance threshold, gentler defaults; README
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:35:26 +00:00
gs5579andDevin AI 5be372d773 Post-processing: bloom, ambient occlusion, filmic tone mapping, colour grading, FXAA
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:34:45 +00:00
dev fd6f56826e Merge pull request 'Look panel: outlines, shadows, cel/studio shading, rim light' (#9) from devin/1796104981-shaders into main 2026-12-01 01:31:13 -05:00
26 changed files with 1118 additions and 40 deletions

No files matched your search

+1
View File
@@ -142,6 +142,7 @@ add_executable(model_renderer
src/render/Grid.cpp
src/render/ModelNode.cpp
src/render/Look.cpp
src/render/PostFx.cpp
src/render/TextureLoader.cpp
src/render/Shaders.cpp
src/render/GpuCaps.cpp
+12
View File
@@ -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
@@ -151,6 +158,11 @@ restores the default).
stage is visible), rim light, and one-click presets. Saved in `.mrscene` files and used in final
renders. Command line: `--shading toon|lambert|cel|soft`, `--shadows on|off`,
`--outlines on|off`, `--rim S`.
* **Post-processing** (Look panel): bloom, ambient occlusion, FXAA anti-aliasing, filmic tone
mapping and colour grading (exposure, contrast, saturation, temperature, vignette). All off by
default, so older GPUs pay nothing; the Anime and Studio presets turn some on. Also applied to
the pop-out window and final renders. Command line: `--bloom S`, `--ao on|off`,
`--fxaa on|off`, `--filmic on|off`.
* **View**: floor grid with labelled X (red), Y (green) and Z (blue) axes (hidden in renders),
skeleton overlay, wireframe, culling, shading style, outlines, shadows, GPU vs CPU skinning,
UI scale (use 2 on Retina).
+157 -16
View File
@@ -74,11 +74,18 @@ App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulato
root_->addUpdateCallback(new TickCallback(this));
viewer_.getCamera()->setProjectionResizePolicy(osg::Camera::FIXED);
imgui_->attach(viewer_);
sceneRoot_ = new osg::Group;
grid_ = createGrid(50.f, 5.f);
root_->addChild(grid_);
sceneRoot_->addChild(grid_);
sceneGroup_ = new osg::Group;
root_->addChild(sceneGroup_);
sceneLook_ = std::make_unique<SceneLook>(root_.get(), sceneGroup_.get());
sceneRoot_->addChild(sceneGroup_);
sceneLook_ = std::make_unique<SceneLook>(sceneRoot_.get(), sceneGroup_.get());
// One post-processing chain per output camera; each camera's cull mask picks its own.
mainChain_ = new PostChain(sceneRoot_.get(), kMainViewMask);
popChain_ = new PostChain(sceneRoot_.get(), kPopViewMask);
renderChain_ = new PostChain(sceneRoot_.get(), kRenderViewMask);
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) root_->addChild(chain);
viewer_.getCamera()->setCullMask(kMainViewMask | kGridNodeMask);
}
void App::setLook(const LookSettings& look) {
@@ -87,7 +94,20 @@ void App::setLook(const LookSettings& look) {
}
void App::updateLook() {
if (gpuCaps().probed) sceneLook_->setShadowsSupported(gpuCaps().shadows);
if (gpuCaps().probed) {
sceneLook_->setShadowsSupported(gpuCaps().shadows);
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()})
chain->setSupported(gpuCaps().framebufferObjects, gpuCaps().floatTextures);
}
osg::Camera* master = viewer_.getCamera();
if (const osg::Viewport* vp = master->getViewport())
mainChain_->setSize(static_cast<int>(vp->width()), static_cast<int>(vp->height()));
mainChain_->setClearColor(master->getClearColor());
if (popCamera_ && popCamera_->getViewport()) {
popChain_->setSize(static_cast<int>(popCamera_->getViewport()->width()),
static_cast<int>(popCamera_->getViewport()->height()));
popChain_->setClearColor(popCamera_->getClearColor());
}
// Shadows cover the characters; with only stages visible they cover a capped part of the stage.
osg::BoundingSphere characters, stages;
for (const auto& item : items_) {
@@ -168,9 +188,11 @@ 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() {
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) chain->apply(look_);
sceneLook_->apply(look_);
for (auto& item : items_) {
ModelNode* node = item->node.get();
@@ -297,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<int>(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;
}
@@ -359,6 +449,7 @@ void App::updatePopOut() {
popCamera_->setClearMask(master->getClearMask());
// Slaves inherit the master's cull settings; the master's cull mask hides the scene.
popCamera_->setInheritanceMask(popCamera_->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
popCamera_->setCullMask(kPopViewMask | kGridNodeMask);
popCamera_->setDrawBuffer(GL_BACK);
popCamera_->setReadBuffer(GL_BACK);
viewer_.addSlave(popCamera_.get(), true);
@@ -375,7 +466,7 @@ void App::updatePopOut() {
popCamera_->setGraphicsContext(nullptr);
}
popCamera_ = nullptr;
master->setCullMask(~0u);
master->setCullMask(kMainViewMask | kGridNodeMask);
}
if (!popCamera_) return;
const osg::GraphicsContext::Traits* traits = popCamera_->getGraphicsContext()->getTraits();
@@ -526,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_) {
@@ -778,10 +881,14 @@ void App::drawLookWindow() {
bool outlines;
float rim;
osg::Vec3f light;
bool bloom, ao, fxaa;
int toneMapping;
float saturation, vignette;
};
const Preset presets[] = {{"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}},
{"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}},
{"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}}};
const Preset presets[] = {
{"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}, false, false, false, 0, 1.f, 0.f},
{"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}, true, false, true, 0, 1.1f, 0.f},
{"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}, true, true, true, 1, 1.f, 0.3f}};
for (const Preset& p : presets) {
if (&p != presets) ImGui::SameLine();
if (ImGui::Button(p.name)) {
@@ -790,6 +897,12 @@ void App::drawLookWindow() {
look_.rimStrength = p.rim;
look_.lightColor = p.light;
look_.shadows = true;
look_.bloom = p.bloom;
look_.ambientOcclusion = p.ao;
look_.fxaa = p.fxaa;
look_.toneMapping = p.toneMapping;
look_.saturation = p.saturation;
look_.vignette = p.vignette;
changed = true;
}
}
@@ -836,6 +949,35 @@ void App::drawLookWindow() {
changed |= ImGui::SliderFloat("Rim strength", &look_.rimStrength, 0.f, 1.5f, "%.2f");
changed |= ImGui::ColorEdit3("Rim color", look_.rimColor.ptr(), ImGuiColorEditFlags_Float);
ImGui::SeparatorText("Post-processing");
const bool postOk = mainChain_->supported() || !gpuCaps().probed;
ImGui::BeginDisabled(!postOk);
changed |= ImGui::Checkbox("Bloom", &look_.bloom);
ImGui::BeginDisabled(!look_.bloom);
changed |= ImGui::SliderFloat("Bloom strength", &look_.bloomStrength, 0.f, 2.f, "%.2f");
changed |= ImGui::SliderFloat("Bloom threshold", &look_.bloomThreshold, 0.f, 1.5f, "%.2f");
changed |= ImGui::SliderFloat("Bloom size", &look_.bloomRadius, 0.25f, 4.f, "%.2f");
ImGui::EndDisabled();
changed |= ImGui::Checkbox("Ambient occlusion", &look_.ambientOcclusion);
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Soft darkening in creases and where objects meet.");
ImGui::BeginDisabled(!look_.ambientOcclusion);
changed |= ImGui::SliderFloat("AO strength", &look_.aoStrength, 0.f, 3.f, "%.2f");
changed |= ImGui::SliderFloat("AO radius", &look_.aoRadius, 0.2f, 6.f, "%.1f");
ImGui::EndDisabled();
changed |= ImGui::Checkbox("Anti-aliasing (FXAA)", &look_.fxaa);
ImGui::SeparatorText("Colour grading");
const char* toneMaps[] = {"Off", "Filmic"};
changed |= ImGui::Combo("Tone mapping", &look_.toneMapping, toneMaps, IM_ARRAYSIZE(toneMaps));
changed |= ImGui::SliderFloat("Exposure", &look_.exposure, 0.25f, 3.f, "%.2f");
changed |= ImGui::SliderFloat("Contrast", &look_.contrast, 0.5f, 1.5f, "%.2f");
changed |= ImGui::SliderFloat("Saturation", &look_.saturation, 0.f, 2.f, "%.2f");
changed |= ImGui::SliderFloat("Temperature", &look_.temperature, -1.f, 1.f, "%.2f");
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Negative is cooler (blue), positive warmer (orange).");
changed |= ImGui::SliderFloat("Vignette", &look_.vignette, 0.f, 1.f, "%.2f");
ImGui::EndDisabled();
if (!postOk) ImGui::TextDisabled("This GPU cannot run post-processing.");
ImGui::Separator();
if (ImGui::Button("Reset look")) {
const int shading = look_.shading;
@@ -872,8 +1014,7 @@ void App::drawMorphsWindow() {
if (morph.panel != panel) continue;
if (!containsCaseInsensitive(morph.name, morphFilter_) && !containsCaseInsensitive(morph.nameEn, morphFilter_))
continue;
const bool supported = morph.type == MorphType::Vertex || morph.type == MorphType::Group ||
morph.type == MorphType::Bone || morph.type == MorphType::Flip;
const bool supported = morph.type != MorphType::Impulse;
ImGui::BeginDisabled(!supported);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
std::string label = morph.name + "##m" + std::to_string(i);
@@ -881,7 +1022,7 @@ void App::drawMorphsWindow() {
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
ImGui::SetTooltip("%s%s", morph.nameEn.empty() ? morph.name.c_str() : morph.nameEn.c_str(),
supported ? "" : " (UV/material morphs are not supported yet)");
supported ? "" : " (impulse morphs are not supported yet)");
}
}
ImGui::End();
+20
View File
@@ -8,6 +8,7 @@
#include "model/Motion.h"
#include "render/Look.h"
#include "render/ModelNode.h"
#include "render/PostFx.h"
#include "ui/ImGuiOsg.h"
#include <osgGA/TrackballManipulator>
@@ -44,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);
@@ -89,7 +103,9 @@ private:
osgViewer::Viewer& viewer_;
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osg::Group> sceneRoot_; // everything 3D; drawn through a post-processing chain
osg::ref_ptr<osg::Group> sceneGroup_; // models and stages
osg::ref_ptr<PostChain> mainChain_, popChain_, renderChain_;
std::unique_ptr<SceneLook> sceneLook_;
osg::ref_ptr<osgGA::TrackballManipulator> manipulator_;
osg::ref_ptr<ImGuiOsg> imgui_;
@@ -105,6 +121,7 @@ private:
std::unique_ptr<MotionPlayer> player;
std::string motionName;
};
const SceneItem* followedItem() const;
SceneItem* activeItem() { return active_ >= 0 ? items_[active_].get() : nullptr; }
void updatePlacement(SceneItem& item);
void drawSceneList();
@@ -135,6 +152,9 @@ private:
std::shared_ptr<Motion> 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;
+3 -1
View File
@@ -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();
+2 -1
View File
@@ -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<std::pair<std::string, bool>> 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_;
+3 -1
View File
@@ -80,10 +80,12 @@ void App::startRender() {
cam->attach(osg::Camera::COLOR_BUFFER, render_.image.get(), 4, 0);
cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
cam->setCullMask(~kGridNodeMask);
cam->setCullMask(kRenderViewMask);
osg::Vec4 clear = master->getClearColor();
if (render_.transparent) clear.a() = 0.f;
cam->setClearColor(clear);
renderChain_->setSize(render_.width, render_.height);
renderChain_->setClearColor(clear);
cam->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
viewer_.addSlave(cam.get(), true);
if (!cam->getRenderer()) cam->setRenderer(new osgViewer::Renderer(cam.get()));
+10
View File
@@ -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;
+6
View File
@@ -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();
+46
View File
@@ -13,6 +13,7 @@
#include <functional>
#include <cstdlib>
#include <iostream>
#include <optional>
#if defined(_WIN32)
#define NOMINMAX
@@ -79,6 +80,10 @@ void printUsage() {
" --shadows on|off shadow mapping (default on)\n"
" --outlines on|off MMD edge outlines (default on)\n"
" --rim S rim light strength (0 = off)\n"
" --bloom S bloom strength (0 = off)\n"
" --ao on|off ambient occlusion\n"
" --fxaa on|off FXAA anti-aliasing\n"
" --filmic on|off filmic tone mapping\n"
" --pop-out show the 3D view in its own window\n"
" --render DIR render PNG frames into DIR and exit\n"
" --range A,B frames to render (default: whole timeline)\n"
@@ -174,9 +179,14 @@ int main(int argc, char** argv) {
bool physics = true, grid = true;
std::vector<std::string> stagePaths, extraModels;
float modelScale = 1.f, stageScale = 1.f;
std::optional<float> cameraMadeFor, cameraHeight, cameraDistance;
std::optional<osg::Vec3f> cameraOffset;
bool cameraFitToModel = false;
std::string saveScenePath;
bool orbitSet = false, physicsSet = false;
int shading = -1, shadows = -1, outlines = -1;
float bloom = -1.f;
int ao = -1, fxaa = -1, filmic = -1;
float rim = -1.f;
int reloadTest = 0;
std::string renderDir;
@@ -242,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") {
@@ -256,6 +278,14 @@ int main(int argc, char** argv) {
shadows = next() != "off" ? 1 : 0;
} else if (a == "--outlines") {
outlines = next() != "off" ? 1 : 0;
} else if (a == "--bloom") {
bloom = std::stof(next());
} else if (a == "--ao") {
ao = next() != "off";
} else if (a == "--fxaa") {
fxaa = next() != "off";
} else if (a == "--filmic") {
filmic = next() != "off";
} else if (a == "--rim") {
rim = std::strtof(next().c_str(), nullptr);
} else if (a == "--reload-test") {
@@ -319,6 +349,13 @@ int main(int argc, char** argv) {
{
mr::LookSettings look = app.look();
if (shading >= 0) look.shading = shading;
if (bloom >= 0.f) {
look.bloom = bloom > 0.f;
look.bloomStrength = bloom > 0.f ? bloom : look.bloomStrength;
}
if (ao >= 0) look.ambientOcclusion = ao == 1;
if (fxaa >= 0) look.fxaa = fxaa == 1;
if (filmic >= 0) look.toneMapping = filmic;
if (shadows >= 0) look.shadows = shadows == 1;
if (outlines >= 0) look.outlines = outlines == 1;
if (rim >= 0.f) look.rimStrength = rim;
@@ -364,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";
+34
View File
@@ -120,6 +120,38 @@ struct BoneMorphOffset {
osg::Quat rotation;
};
struct UvMorphOffset {
uint32_t vertex;
osg::Vec2f offset; // in the OpenGL UV convention (V up)
};
enum class MaterialMorphOp : uint8_t { Multiply = 0, Add = 1 };
struct MaterialMorphOffset {
int material = -1; // -1: every material
MaterialMorphOp op = MaterialMorphOp::Multiply;
osg::Vec4f diffuse;
osg::Vec3f specular;
float shininess = 0.f;
osg::Vec3f ambient;
osg::Vec4f edgeColor;
float edgeSize = 0.f;
osg::Vec4f textureTint, sphereTint, toonTint;
};
// Material values after material morphs. Texture tints apply as texel * mul + add.
struct MaterialState {
osg::Vec4f diffuse;
osg::Vec3f specular;
float shininess = 0.f;
osg::Vec3f ambient;
osg::Vec4f edgeColor;
float edgeSize = 0.f;
osg::Vec4f textureMul{1.f, 1.f, 1.f, 1.f}, textureAdd;
osg::Vec4f sphereMul{1.f, 1.f, 1.f, 1.f}, sphereAdd;
osg::Vec4f toonMul{1.f, 1.f, 1.f, 1.f}, toonAdd;
};
struct Morph {
std::string name;
std::string nameEn;
@@ -128,6 +160,8 @@ struct Morph {
std::vector<VertexMorphOffset> vertexOffsets;
std::vector<GroupMorphOffset> groupOffsets; // Group and Flip
std::vector<BoneMorphOffset> boneOffsets;
std::vector<UvMorphOffset> uvOffsets; // main UV channel only
std::vector<MaterialMorphOffset> materialOffsets;
};
enum class RigidShape : uint8_t { Sphere = 0, Box = 1, Capsule = 2 };
+19 -5
View File
@@ -303,18 +303,32 @@ private:
m.boneOffsets.push_back({idx, t, toRH(osg::Quat(q.x(), q.y(), q.z(), q.w()))});
}
break;
case 3: case 4: case 5: case 6: case 7: // UV / additional UV
case 3: case 4: case 5: case 6: case 7: // UV / additional UV (only the main UV is used)
m.type = MorphType::UV;
for (int32_t i = 0; i < offsets; ++i) {
r_.vertexIndex(h_.vertexIndexSize);
r_.skip(16);
int64_t idx = r_.vertexIndex(h_.vertexIndexSize);
osg::Vec4f d = r_.vec4();
if (type == 3 && idx >= 0 && idx < vertexCount)
m.uvOffsets.push_back({static_cast<uint32_t>(idx), osg::Vec2f(d.x(), -d.y())});
}
break;
case 8: // material
m.type = MorphType::Material;
for (int32_t i = 0; i < offsets; ++i) {
r_.signedIndex(h_.materialIndexSize);
r_.skip(1 + 16 + 12 + 4 + 12 + 16 + 4 + 16 + 16 + 16);
MaterialMorphOffset o;
o.material = r_.signedIndex(h_.materialIndexSize);
o.op = r_.u8() == 1 ? MaterialMorphOp::Add : MaterialMorphOp::Multiply;
o.diffuse = r_.vec4();
o.specular = r_.vec3();
o.shininess = r_.f32();
o.ambient = r_.vec3();
o.edgeColor = r_.vec4();
o.edgeSize = r_.f32();
o.textureTint = r_.vec4();
o.sphereTint = r_.vec4();
o.toonTint = r_.vec4();
if (o.material >= -1 && o.material < static_cast<int>(model_.materials.size()))
m.materialOffsets.push_back(o);
}
break;
case 10: // impulse
+88
View File
@@ -32,6 +32,10 @@ Poser::Poser(std::shared_ptr<const Model> model) : model_(std::move(model)) {
poses_.resize(boneCount);
weights_.assign(model_->morphs.size(), 0.f);
effective_.assign(model_->morphs.size(), 0.f);
for (const Morph& m : model_->morphs) {
hasUvMorphs_ |= !m.uvOffsets.empty();
hasMaterialMorphs_ |= !m.materialOffsets.empty();
}
morphTranslation_.resize(boneCount);
morphRotation_.resize(boneCount);
animRotation_.resize(boneCount);
@@ -141,6 +145,89 @@ void Poser::accumulateMorph(int morph, float weight, int depth) {
}
}
namespace {
template <typename T>
T towardOne(const T& offset, float w, const T& one) {
return one + (offset - one) * w;
}
} // namespace
// Like MMD, multiply offsets and add offsets accumulate separately: value = base * mul + add.
void Poser::applyUvAndMaterialMorphs() {
const Model& model = *model_;
if (hasUvMorphs_) {
uvs_.resize(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) uvs_[i] = model.vertices[i].uv;
for (size_t i = 0; i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f) continue;
for (const auto& o : model.morphs[i].uvOffsets) uvs_[o.vertex] += o.offset * w;
}
}
const size_t count = model.materials.size();
const osg::Vec4f one4(1.f, 1.f, 1.f, 1.f);
const osg::Vec3f one3(1.f, 1.f, 1.f);
std::vector<MaterialMorphOffset> mul(count), add(count);
for (auto& m : mul) {
m.diffuse = m.edgeColor = m.textureTint = m.sphereTint = m.toonTint = one4;
m.specular = m.ambient = one3;
m.shininess = m.edgeSize = 1.f;
}
for (size_t i = 0; hasMaterialMorphs_ && i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f) continue;
for (const auto& o : model.morphs[i].materialOffsets) {
const size_t first = o.material < 0 ? 0 : static_cast<size_t>(o.material);
const size_t last = o.material < 0 ? count : first + 1;
for (size_t k = first; k < last && k < count; ++k) {
if (o.op == MaterialMorphOp::Multiply) {
MaterialMorphOffset& a = mul[k];
a.diffuse = osg::componentMultiply(a.diffuse, towardOne(o.diffuse, w, one4));
a.specular = osg::componentMultiply(a.specular, towardOne(o.specular, w, one3));
a.shininess *= towardOne(o.shininess, w, 1.f);
a.ambient = osg::componentMultiply(a.ambient, towardOne(o.ambient, w, one3));
a.edgeColor = osg::componentMultiply(a.edgeColor, towardOne(o.edgeColor, w, one4));
a.edgeSize *= towardOne(o.edgeSize, w, 1.f);
a.textureTint = osg::componentMultiply(a.textureTint, towardOne(o.textureTint, w, one4));
a.sphereTint = osg::componentMultiply(a.sphereTint, towardOne(o.sphereTint, w, one4));
a.toonTint = osg::componentMultiply(a.toonTint, towardOne(o.toonTint, w, one4));
} else {
MaterialMorphOffset& a = add[k];
a.diffuse += o.diffuse * w;
a.specular += o.specular * w;
a.shininess += o.shininess * w;
a.ambient += o.ambient * w;
a.edgeColor += o.edgeColor * w;
a.edgeSize += o.edgeSize * w;
a.textureTint += o.textureTint * w;
a.sphereTint += o.sphereTint * w;
a.toonTint += o.toonTint * w;
}
}
}
}
materials_.resize(count);
for (size_t k = 0; k < count; ++k) {
const Material& base = model.materials[k];
const MaterialMorphOffset &m = mul[k], &a = add[k];
MaterialState& s = materials_[k];
s.diffuse = osg::componentMultiply(base.diffuse, m.diffuse) + a.diffuse;
s.specular = osg::componentMultiply(base.specular, m.specular) + a.specular;
s.shininess = base.shininess * m.shininess + a.shininess;
s.ambient = osg::componentMultiply(base.ambient, m.ambient) + a.ambient;
s.edgeColor = osg::componentMultiply(base.edgeColor, m.edgeColor) + a.edgeColor;
s.edgeSize = base.edgeSize * m.edgeSize + a.edgeSize;
s.textureMul = m.textureTint;
s.textureAdd = a.textureTint;
s.sphereMul = m.sphereTint;
s.sphereAdd = a.sphereTint;
s.toonMul = m.toonTint;
s.toonAdd = a.toonTint;
}
}
void Poser::setSkinningMode(SkinningMode mode) {
if (mode == mode_) return;
mode_ = mode;
@@ -302,6 +389,7 @@ bool Poser::update() {
if (w == 0.f || model.morphs[i].type != MorphType::Vertex) continue;
for (const auto& o : model.morphs[i].vertexOffsets) morphed_[o.vertex] += o.offset * w;
}
applyUvAndMaterialMorphs();
}
if (mode_ == SkinningMode::Hardware) return true;
+9
View File
@@ -77,10 +77,16 @@ public:
const std::vector<osg::Vec3f>& normals() const { return normals_; }
const std::vector<osg::Matrixf>& boneGlobals() const { return globals_; }
const std::vector<float>& effectiveMorphWeights() const { return effective_; }
// Main UVs after UV morphs; empty when the model has no UV morphs.
const std::vector<osg::Vec2f>& morphedUvs() const { return uvs_; }
// Per-material values after material morphs.
const std::vector<MaterialState>& materialStates() const { return materials_; }
bool hasMaterialMorphs() const { return hasMaterialMorphs_; }
private:
void computeEvaluationOrder();
void accumulateMorph(int morph, float weight, int depth);
void applyUvAndMaterialMorphs();
void updateGlobal(int bone);
void solveIk(int ikBone);
@@ -109,6 +115,9 @@ private:
std::vector<osg::Vec3f> animTranslation_;
std::vector<osg::Matrixf> globals_, skin_;
std::vector<osg::Vec3f> morphed_, positions_, normals_;
std::vector<osg::Vec2f> uvs_;
std::vector<MaterialState> materials_;
bool hasUvMorphs_ = false, hasMaterialMorphs_ = false;
};
} // namespace mr
+2
View File
@@ -27,6 +27,8 @@ void GpuCapsProbe::operator()(osg::GraphicsContext* gc) {
caps.skinning = vertexUnits > 0 && floatTextures;
caps.shadows = osg::isGLExtensionOrVersionSupported(contextID, "GL_ARB_depth_texture", 1.4f) &&
osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f);
caps.framebufferObjects = osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f);
caps.floatTextures = floatTextures;
caps.probed = true;
if (next_) (*next_)(gc);
}
+2
View File
@@ -10,6 +10,8 @@ struct GpuCaps {
bool probed = false;
bool skinning = false; // vertex texture fetch + float textures
bool shadows = false; // depth textures + framebuffer objects
bool framebufferObjects = false;
bool floatTextures = false;
std::string renderer;
};
+15 -2
View File
@@ -1,9 +1,11 @@
#include "render/Grid.h"
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/LineWidth>
#include <osg/Program>
#include <osgText/Text>
namespace mr {
@@ -63,8 +65,10 @@ osg::Node* createGrid(float halfExtent, float spacing) {
addLine(av, ac, {0, 0, z}, {0, 0, up}, green);
auto* geode = new osg::Geode;
geode->addDrawable(lineGeometry(gv, gc, 1.f));
geode->addDrawable(lineGeometry(av, ac, 2.f));
osg::Geometry* gridLines = lineGeometry(gv, gc, 1.f);
osg::Geometry* axisLines = lineGeometry(av, ac, 2.f);
geode->addDrawable(gridLines);
geode->addDrawable(axisLines);
geode->addDrawable(label("X", {h + spacing * 0.4f, 0, z}, red));
geode->addDrawable(label("Y", {0, 0, up + spacing * 0.3f}, green));
geode->addDrawable(label("Z", {0, h + spacing * 0.4f, z}, blue));
@@ -73,6 +77,15 @@ osg::Node* createGrid(float halfExtent, float spacing) {
ss->setMode(GL_BLEND, osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
// No depth writes: thin lines would otherwise show up as occluders in ambient occlusion.
ss->setAttributeAndModes(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false));
// Explicit vertex-colour program so no model shader state can leak onto the lines.
auto* program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::VERTEX,
"#version 120\nvoid main() { gl_FrontColor = gl_Color;"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }\n"));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, "#version 120\nvoid main() { gl_FragColor = gl_Color; }\n"));
for (osg::Geometry* lines : {gridLines, axisLines}) lines->getOrCreateStateSet()->setAttributeAndModes(program);
geode->setNodeMask(kGridNodeMask);
return geode;
}
+60 -8
View File
@@ -5,6 +5,7 @@
#include "render/Shaders.h"
#include "render/TextureLoader.h"
#include <algorithm>
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Depth>
@@ -51,6 +52,8 @@ ModelNode::ModelNode(std::shared_ptr<Model> model) : model_(std::move(model)), p
ss->addUniform(new osg::Uniform("u_texture", 0));
ss->addUniform(new osg::Uniform("u_sphere", 1));
ss->addUniform(new osg::Uniform("u_toon", 2));
for (const char* name : {"u_texMul", "u_sphereMul", "u_toonMul"}) ss->addUniform(new osg::Uniform(name, osg::Vec4f(1, 1, 1, 1)));
for (const char* name : {"u_texAdd", "u_sphereAdd", "u_toonAdd"}) ss->addUniform(new osg::Uniform(name, osg::Vec4f()));
const bool isMmd = model_->format != SourceFormat::Assimp;
lightingUniform_ = new osg::Uniform("u_lightingModel", isMmd ? 0 : 1);
ss->addUniform(lightingUniform_);
@@ -88,10 +91,20 @@ osg::Texture2D* ModelNode::texture(int index, bool clamp) {
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));
MaterialUniforms& u = materialUniforms_[order];
u.diffuse = new osg::Uniform("u_diffuse", m.diffuse);
u.ambient = new osg::Uniform("u_ambient", m.ambient);
u.specular = new osg::Uniform("u_specular", m.specular);
u.shininess = new osg::Uniform("u_shininess", m.shininess);
u.textureMul = new osg::Uniform("u_texMul", osg::Vec4f(1, 1, 1, 1));
u.textureAdd = new osg::Uniform("u_texAdd", osg::Vec4f());
u.sphereMul = new osg::Uniform("u_sphereMul", osg::Vec4f(1, 1, 1, 1));
u.sphereAdd = new osg::Uniform("u_sphereAdd", osg::Vec4f());
u.toonMul = new osg::Uniform("u_toonMul", osg::Vec4f(1, 1, 1, 1));
u.toonAdd = new osg::Uniform("u_toonAdd", osg::Vec4f());
for (osg::Uniform* uniform : {u.diffuse.get(), u.ambient.get(), u.specular.get(), u.shininess.get(), u.textureMul.get(),
u.textureAdd.get(), u.sphereMul.get(), u.sphereAdd.get(), u.toonMul.get(), u.toonAdd.get()})
ss->addUniform(uniform);
osg::Texture2D* main = texture(m.texture, false);
if (main) ss->setTextureAttributeAndModes(0, main, osg::StateAttribute::ON);
@@ -126,7 +139,9 @@ 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());
uvs_ = new osg::Vec2Array(model.vertices.size());
osg::Vec2Array* uvs = uvs_.get();
materialUniforms_.assign(model.materials.size(), MaterialUniforms());
for (size_t i = 0; i < model.vertices.size(); ++i) {
(*positions_)[i] = model.vertices[i].position;
(*normals_)[i] = model.vertices[i].normal;
@@ -134,6 +149,7 @@ void ModelNode::buildMesh() {
}
positions_->setDataVariance(osg::Object::DYNAMIC);
normals_->setDataVariance(osg::Object::DYNAMIC);
uvs_->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
for (size_t i = 0; i < model.materials.size(); ++i) {
@@ -157,7 +173,7 @@ void ModelNode::buildMesh() {
}
meshGroup_ = geode;
addChild(meshGroup_);
buildEdges(uvs.get());
buildEdges(uvs);
}
void ModelNode::buildEdges(osg::Vec2Array* uvs) {
@@ -191,8 +207,10 @@ void ModelNode::buildEdges(osg::Vec2Array* uvs) {
geom->addPrimitiveSet(new osg::DrawElementsUInt(GL_TRIANGLES, model.indices.begin() + m.indexOffset,
model.indices.begin() + m.indexOffset + m.indexCount));
osg::StateSet* es = geom->getOrCreateStateSet();
es->addUniform(new osg::Uniform("u_edgeColor", m.edgeColor));
es->addUniform(new osg::Uniform("u_edgeSize", m.edgeSize));
materialUniforms_[i].edgeColor = new osg::Uniform("u_edgeColor", m.edgeColor);
materialUniforms_[i].edgeSize = new osg::Uniform("u_edgeSize", m.edgeSize);
es->addUniform(materialUniforms_[i].edgeColor);
es->addUniform(materialUniforms_[i].edgeSize);
// Drawn after every material of the model, like MMD's edge pass.
es->setRenderBinDetails(10 + materialCount + static_cast<int>(i), "RenderBin");
geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this));
@@ -385,6 +403,7 @@ void ModelNode::updateDeformation() {
}
}
if (poser_.update()) {
if (poser_.morphsChangedInLastUpdate()) applyMorphedMaterials();
if (activeSkinning_ == SkinningMode::Software) {
const auto& p = poser_.positions();
const auto& n = poser_.normals();
@@ -409,6 +428,39 @@ void ModelNode::updateDeformation() {
}
}
void ModelNode::applyMorphedMaterials() {
const auto& uvs = poser_.morphedUvs();
if (!uvs.empty()) {
std::copy(uvs.begin(), uvs.end(), uvs_->begin());
uvs_->dirty();
}
if (!poser_.hasMaterialMorphs()) return;
const auto& states = poser_.materialStates();
for (size_t i = 0; i < states.size() && i < materialUniforms_.size(); ++i) {
const MaterialState& s = states[i];
MaterialUniforms& u = materialUniforms_[i];
if (!u.diffuse) continue;
u.diffuse->set(s.diffuse);
u.ambient->set(s.ambient);
u.specular->set(s.specular);
u.shininess->set(s.shininess);
u.textureMul->set(s.textureMul);
u.textureAdd->set(s.textureAdd);
u.sphereMul->set(s.sphereMul);
u.sphereAdd->set(s.sphereAdd);
u.toonMul->set(s.toonMul);
u.toonAdd->set(s.toonAdd);
if (u.edgeColor) {
// Fading a material out (a common morph) fades its outline with it.
osg::Vec4f edge = s.edgeColor;
const float baseAlpha = model_->materials[i].diffuse.a();
if (baseAlpha > 0.f) edge.a() *= std::clamp(s.diffuse.a() / baseAlpha, 0.f, 1.f);
u.edgeColor->set(edge);
u.edgeSize->set(s.edgeSize);
}
}
}
void ModelNode::setShowSkeleton(bool show) {
skeletonGeode_->setNodeMask(show ? ~0u : 0u);
skeletonDirty_ = true;
+8
View File
@@ -48,6 +48,7 @@ private:
void preloadTextureImages();
osg::Texture2D* texture(int index, bool clamp);
void buildEdges(osg::Vec2Array* uvs);
void applyMorphedMaterials();
void buildSkinning();
void uploadBoneMatrices();
void buildSkeleton();
@@ -58,6 +59,13 @@ private:
osg::ref_ptr<osg::Group> meshGroup_;
osg::ref_ptr<osg::Vec3Array> positions_;
osg::ref_ptr<osg::Vec3Array> normals_;
osg::ref_ptr<osg::Vec2Array> uvs_;
// Per-material uniforms that UV/material morphs update.
struct MaterialUniforms {
osg::ref_ptr<osg::Uniform> diffuse, ambient, specular, shininess, textureMul, textureAdd, sphereMul, sphereAdd,
toonMul, toonAdd, edgeColor, edgeSize;
};
std::vector<MaterialUniforms> materialUniforms_;
std::vector<osg::ref_ptr<osg::Geometry>> geometries_;
std::vector<osg::ref_ptr<osg::Texture2D>> textures_;
std::vector<bool> textureTried_;
+443
View File
@@ -0,0 +1,443 @@
#include "render/PostFx.h"
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Program>
#include <osgUtil/CullVisitor>
#include <algorithm>
#include <cmath>
#ifndef GL_RGBA16F_ARB
#define GL_RGBA16F_ARB 0x881A
#endif
#ifndef GL_DEPTH_COMPONENT24
#define GL_DEPTH_COMPONENT24 0x81A6
#endif
namespace mr {
namespace {
// GLSL 1.20 throughout, for macOS's legacy OpenGL profile.
const char* kQuadVertex = R"(#version 120
varying vec2 v_uv;
void main() {
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
)";
// Downsample with a soft-knee threshold: only bright areas glow.
const char* kBrightFragment = R"(#version 120
uniform sampler2D u_color;
uniform vec2 u_texel;
uniform float u_threshold;
varying vec2 v_uv;
void main() {
vec3 c = 0.25 * (texture2D(u_color, v_uv + u_texel * vec2(-1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(-1.0, 1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, 1.0)).rgb);
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
float knee = 0.5 * u_threshold + 1e-4;
float soft = clamp(l - u_threshold + knee, 0.0, 2.0 * knee);
soft = soft * soft / (4.0 * knee);
gl_FragColor = vec4(c * (max(soft, l - u_threshold) / max(l, 1e-4)), 1.0);
}
)";
// 9-tap Gaussian using bilinear taps.
const char* kBlurFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_dir;
varying vec2 v_uv;
void main() {
vec3 c = texture2D(u_src, v_uv).rgb * 0.227027;
c += (texture2D(u_src, v_uv + u_dir * 1.384615).rgb + texture2D(u_src, v_uv - u_dir * 1.384615).rgb) * 0.316216;
c += (texture2D(u_src, v_uv + u_dir * 3.230769).rgb + texture2D(u_src, v_uv - u_dir * 3.230769).rgb) * 0.070270;
gl_FragColor = vec4(c, 1.0);
}
)";
// Screen-space ambient occlusion from the depth buffer (normals from depth derivatives).
const char* kAoFragment = R"(#version 120
uniform sampler2D u_depth;
uniform vec4 u_proj; // projection m00, m11, m20, m21
uniform vec2 u_projZ; // projection m22, m32
uniform float u_radius;
uniform float u_strength;
varying vec2 v_uv;
vec3 viewPos(vec2 uv) {
float zn = texture2D(u_depth, uv).r * 2.0 - 1.0;
float z = u_projZ.y / (zn + u_projZ.x);
vec2 ndc = uv * 2.0 - 1.0;
return vec3(z * (ndc.x + u_proj.z) / u_proj.x, z * (ndc.y + u_proj.w) / u_proj.y, z);
}
void main() {
if (texture2D(u_depth, v_uv).r >= 1.0) { gl_FragColor = vec4(1.0); return; }
vec3 p = viewPos(v_uv);
vec3 n = normalize(cross(dFdx(p), dFdy(p)));
if (n.z > 0.0) n = -n;
vec2 r = vec2(u_proj.x, u_proj.y) * (0.5 * u_radius / p.z);
float angle = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
float occlusion = 0.0;
for (int i = 0; i < 12; ++i) {
float t = (float(i) + 0.5) / 12.0;
float a = angle + float(i) * 2.3999632;
vec3 v = viewPos(v_uv + vec2(cos(a), sin(a)) * t * r) - p;
float vv = dot(v, v);
float falloff = max(0.0, 1.0 - vv / (u_radius * u_radius));
// The distance-scaled bias stops flat ground self-occluding as depth precision drops.
occlusion += falloff * max(0.0, (dot(v, n) - 0.004 * p.z) * inversesqrt(vv + 1e-6) - 0.15);
}
float ao = clamp(1.0 - u_strength * occlusion / 4.0, 0.0, 1.0);
// Depth precision runs out far away (sky domes, distant terrain): fade out instead of banding.
ao = mix(ao, 1.0, smoothstep(60.0 * u_radius, 120.0 * u_radius, p.z));
gl_FragColor = vec4(ao, ao, ao, 1.0);
}
)";
const char* kCompositeFragment = R"(#version 120
uniform sampler2D u_color;
uniform sampler2D u_bloom;
uniform sampler2D u_ao;
uniform vec2 u_aoTexel;
uniform int u_bloomOn;
uniform int u_aoOn;
uniform int u_toneMap;
uniform float u_bloomStrength;
uniform float u_exposure;
uniform float u_contrast;
uniform float u_saturation;
uniform vec3 u_tint;
uniform float u_vignette;
varying vec2 v_uv;
vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
void main() {
vec4 src = texture2D(u_color, v_uv);
vec3 c = src.rgb;
if (u_aoOn == 1) {
float ao = 0.25 * (texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, 0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, 0.75)).r);
c *= ao;
}
if (u_bloomOn == 1) c += texture2D(u_bloom, v_uv).rgb * u_bloomStrength;
c *= u_exposure * u_tint;
// Filmic: ACES fit, scaled so white lands near 0.85 and highlights roll off instead of clipping.
if (u_toneMap == 1) c = pow(aces(max(c, 0.0) * 0.8) / 0.886, vec3(1.15));
c = (c - 0.5) * u_contrast + 0.5;
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
c = mix(vec3(l), c, u_saturation);
vec2 d = v_uv - 0.5;
c *= 1.0 - u_vignette * smoothstep(0.25, 0.75, dot(d, d) * 2.0);
gl_FragColor = vec4(clamp(c, 0.0, 1.0), src.a);
}
)";
// FXAA (the compact "console" variant) or a plain copy.
const char* kFinalFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_texel;
uniform int u_fxaa;
varying vec2 v_uv;
float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }
void main() {
vec4 m = texture2D(u_src, v_uv);
if (u_fxaa == 0) { gl_FragColor = m; return; }
float lNW = luma(texture2D(u_src, v_uv + vec2(-1.0, -1.0) * u_texel).rgb);
float lNE = luma(texture2D(u_src, v_uv + vec2(1.0, -1.0) * u_texel).rgb);
float lSW = luma(texture2D(u_src, v_uv + vec2(-1.0, 1.0) * u_texel).rgb);
float lSE = luma(texture2D(u_src, v_uv + vec2(1.0, 1.0) * u_texel).rgb);
float lM = luma(m.rgb);
float lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE)));
float lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE)));
vec2 dir = vec2(-((lNW + lNE) - (lSW + lSE)), (lNW + lSW) - (lNE + lSE));
float reduce = max((lNW + lNE + lSW + lSE) * 0.03125, 1.0 / 128.0);
float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);
dir = clamp(dir * rcp, vec2(-8.0), vec2(8.0)) * u_texel;
vec3 a = 0.5 * (texture2D(u_src, v_uv - dir / 6.0).rgb + texture2D(u_src, v_uv + dir / 6.0).rgb);
vec3 b = a * 0.5 + 0.25 * (texture2D(u_src, v_uv - dir * 0.5).rgb + texture2D(u_src, v_uv + dir * 0.5).rgb);
float lB = luma(b);
gl_FragColor = vec4((lB < lMin || lB > lMax) ? a : b, m.a);
}
)";
osg::ref_ptr<osg::Texture2D> makeTexture(GLint internalFormat, GLenum format, GLenum type, bool linear) {
osg::ref_ptr<osg::Texture2D> t = new osg::Texture2D;
t->setInternalFormat(internalFormat);
t->setSourceFormat(format);
t->setSourceType(type);
const osg::Texture::FilterMode f = linear ? osg::Texture::LINEAR : osg::Texture::NEAREST;
t->setFilter(osg::Texture::MIN_FILTER, f);
t->setFilter(osg::Texture::MAG_FILTER, f);
t->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
t->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
t->setResizeNonPowerOfTwoHint(false);
t->setTextureSize(4, 4);
return t;
}
// A pass that draws one fullscreen quad with `fragment` into `target` (or into the parent camera).
osg::ref_ptr<osg::Camera> makePass(const char* name, const char* fragment, osg::Texture2D* target, int order) {
osg::ref_ptr<osg::Camera> cam = new osg::Camera;
cam->setName(name);
cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
cam->setProjectionMatrix(osg::Matrixd::ortho2D(0.0, 1.0, 0.0, 1.0));
cam->setViewMatrix(osg::Matrixd::identity());
cam->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
cam->setCullMask(~0u);
if (target) {
cam->setRenderOrder(osg::Camera::PRE_RENDER, order);
cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
cam->setClearMask(0);
cam->attach(osg::Camera::COLOR_BUFFER, target);
} else {
cam->setRenderOrder(osg::Camera::NESTED_RENDER);
cam->setClearMask(0);
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0, 0, 0), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0)));
geode->setCullingActive(false);
osg::StateSet* ss = geode->getOrCreateStateSet();
osg::ref_ptr<osg::Program> program = new osg::Program;
program->setName(name);
program->addShader(new osg::Shader(osg::Shader::VERTEX, kQuadVertex));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragment));
ss->setAttributeAndModes(program, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0.0, 1.0, false),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cam->addChild(geode);
return cam;
}
void bind(osg::Camera* pass, unsigned unit, osg::Texture2D* tex, const char* sampler) {
osg::StateSet* ss = pass->getChild(0)->getOrCreateStateSet();
ss->setTextureAttribute(unit, tex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->addUniform(new osg::Uniform(sampler, static_cast<int>(unit)));
}
osg::Uniform* uniform(osg::Camera* pass, osg::Uniform* u) {
pass->getChild(0)->getOrCreateStateSet()->addUniform(u);
return u;
}
void resizeTarget(osg::Camera* cam, osg::Camera::BufferComponent buffer, osg::Texture2D* tex, int w, int h) {
tex->setTextureSize(w, h);
tex->dirtyTextureObject();
cam->setViewport(0, 0, w, h);
cam->detach(buffer);
cam->attach(buffer, tex);
cam->setRenderingCache(nullptr);
}
class ProjectionCallback : public osg::NodeCallback {
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
if (auto* cv = nv->asCullVisitor())
if (cv->getProjectionMatrix() && cv->getModelViewMatrix())
static_cast<PostChain*>(node)->cullUpdate(*cv->getProjectionMatrix(), *cv->getModelViewMatrix());
traverse(node, nv);
}
};
} // namespace
bool postFxActive(const LookSettings& s) {
return s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.fxaa || s.exposure != 1.f || s.contrast != 1.f ||
s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
}
PostChain::PostChain(osg::Node* scene, unsigned viewMask) : scene_(scene) {
setNodeMask(viewMask);
setCullCallback(new ProjectionCallback);
addChild(scene_);
}
void PostChain::setSupported(bool framebufferObjects, bool floatTextures) {
if (framebufferObjects == supported_ && floatTextures == floatColor_) return;
supported_ = framebufferObjects;
if (!built_) floatColor_ = floatTextures;
refresh();
}
void PostChain::apply(const LookSettings& settings) {
settings_ = settings;
refresh();
}
void PostChain::setClearColor(const osg::Vec4& color) {
clearColor_ = color;
if (sceneCam_) sceneCam_->setClearColor(color);
}
void PostChain::cullUpdate(const osg::Matrixd& p, const osg::Matrixd& view) {
if (!active_) return;
osg::Matrixd fitted = p;
const osg::BoundingSphere bs = scene_->getBound();
if (p(2, 3) != 0.0 && p(3, 2) != 0.0 && bs.valid()) {
// Perspective: re-fit near/far around the scene, as OSG does for the output camera itself,
// so large stages and sky domes are not clipped.
const double dist = -(bs.center() * view).z(), r = bs.radius();
const double f = std::max(dist + r, 1.0);
// Same near/far ratio OSG uses for the window, which keeps depth precision for sky domes.
const double n = std::max(std::max(dist - r, f * 0.0005), 0.1);
const double m22 = -(f + n) / (f - n), m32 = -2.0 * f * n / (f - n);
osg::Matrixd correction; // remaps clip-space z only
correction(2, 2) = m32 / p(3, 2);
correction(3, 2) = p(2, 2) * m32 / p(3, 2) - m22;
fitted = p * correction;
}
sceneCam_->setViewMatrix(view);
sceneCam_->setProjectionMatrix(fitted);
proj_->set(osg::Vec4f(fitted(0, 0), fitted(1, 1), fitted(2, 0), fitted(2, 1)));
projZ_->set(osg::Vec2f(fitted(2, 2), fitted(3, 2)));
}
void PostChain::build() {
// Model shaders clamp to [0, 1], so 8-bit targets lose nothing and halve the bandwidth of float ones.
const GLint colorFormat = GL_RGBA8;
const GLenum colorType = GL_UNSIGNED_BYTE;
color_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
depth_ = makeTexture(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false);
bloomA_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
bloomB_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
ao_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
ldr_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
// Uses the output camera's view and projection (set each cull) and inherits its cull mask.
sceneCam_ = new osg::Camera;
sceneCam_->setName("PostSceneCamera");
sceneCam_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
sceneCam_->setRenderOrder(osg::Camera::PRE_RENDER, 0);
sceneCam_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
sceneCam_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
sceneCam_->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
sceneCam_->setClearColor(clearColor_);
sceneCam_->attach(osg::Camera::COLOR_BUFFER, color_.get());
sceneCam_->attach(osg::Camera::DEPTH_BUFFER, depth_.get());
sceneCam_->addChild(scene_);
brightCam_ = makePass("PostBright", kBrightFragment, bloomA_.get(), 1);
bind(brightCam_, 0, color_.get(), "u_color");
brightTexel_ = uniform(brightCam_, new osg::Uniform("u_texel", osg::Vec2f()));
threshold_ = uniform(brightCam_, new osg::Uniform("u_threshold", 0.75f));
blurHCam_ = makePass("PostBlurH", kBlurFragment, bloomB_.get(), 2);
bind(blurHCam_, 0, bloomA_.get(), "u_src");
blurHDir_ = uniform(blurHCam_, new osg::Uniform("u_dir", osg::Vec2f()));
blurVCam_ = makePass("PostBlurV", kBlurFragment, bloomA_.get(), 3);
bind(blurVCam_, 0, bloomB_.get(), "u_src");
blurVDir_ = uniform(blurVCam_, new osg::Uniform("u_dir", osg::Vec2f()));
aoCam_ = makePass("PostAo", kAoFragment, ao_.get(), 4);
bind(aoCam_, 0, depth_.get(), "u_depth");
proj_ = uniform(aoCam_, new osg::Uniform("u_proj", osg::Vec4f(1, 1, 0, 0)));
projZ_ = uniform(aoCam_, new osg::Uniform("u_projZ", osg::Vec2f(-1, -0.2f)));
aoRadius_ = uniform(aoCam_, new osg::Uniform("u_radius", 1.5f));
aoStrength_ = uniform(aoCam_, new osg::Uniform("u_strength", 1.f));
compositeCam_ = makePass("PostComposite", kCompositeFragment, ldr_.get(), 5);
bind(compositeCam_, 0, color_.get(), "u_color");
bind(compositeCam_, 1, bloomA_.get(), "u_bloom");
bind(compositeCam_, 2, ao_.get(), "u_ao");
compositeAoTexel_ = uniform(compositeCam_, new osg::Uniform("u_aoTexel", osg::Vec2f()));
bloomOn_ = uniform(compositeCam_, new osg::Uniform("u_bloomOn", 0));
aoOn_ = uniform(compositeCam_, new osg::Uniform("u_aoOn", 0));
toneMap_ = uniform(compositeCam_, new osg::Uniform("u_toneMap", 0));
bloomStrength_ = uniform(compositeCam_, new osg::Uniform("u_bloomStrength", 0.5f));
exposure_ = uniform(compositeCam_, new osg::Uniform("u_exposure", 1.f));
contrast_ = uniform(compositeCam_, new osg::Uniform("u_contrast", 1.f));
saturation_ = uniform(compositeCam_, new osg::Uniform("u_saturation", 1.f));
tint_ = uniform(compositeCam_, new osg::Uniform("u_tint", osg::Vec3f(1, 1, 1)));
vignette_ = uniform(compositeCam_, new osg::Uniform("u_vignette", 0.f));
finalCam_ = makePass("PostFinal", kFinalFragment, nullptr, 0);
bind(finalCam_, 0, ldr_.get(), "u_src");
fxaaOn_ = uniform(finalCam_, new osg::Uniform("u_fxaa", 0));
fxaaTexel_ = uniform(finalCam_, new osg::Uniform("u_texel", osg::Vec2f()));
built_ = true;
const int w = width_, h = height_;
width_ = height_ = 0;
setSize(std::max(w, 1), std::max(h, 1));
}
void PostChain::setSize(int width, int height) {
width = std::max(width, 1);
height = std::max(height, 1);
if (width == width_ && height == height_) return;
width_ = width;
height_ = height;
if (!built_) return;
const int bw = std::max(width / 4, 1), bh = std::max(height / 4, 1);
const int aw = std::max(width / 2, 1), ah = std::max(height / 2, 1);
resizeTarget(sceneCam_, osg::Camera::COLOR_BUFFER, color_, width, height);
resizeTarget(sceneCam_, osg::Camera::DEPTH_BUFFER, depth_, width, height);
resizeTarget(brightCam_, osg::Camera::COLOR_BUFFER, bloomA_, bw, bh);
resizeTarget(blurHCam_, osg::Camera::COLOR_BUFFER, bloomB_, bw, bh);
blurVCam_->setViewport(0, 0, bw, bh);
blurVCam_->setRenderingCache(nullptr);
resizeTarget(aoCam_, osg::Camera::COLOR_BUFFER, ao_, aw, ah);
resizeTarget(compositeCam_, osg::Camera::COLOR_BUFFER, ldr_, width, height);
brightTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
compositeAoTexel_->set(osg::Vec2f(1.f / aw, 1.f / ah));
fxaaTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
refresh();
}
void PostChain::refresh() {
const bool active = supported_ && postFxActive(settings_);
if (active && !built_) build();
if (active != active_) {
active_ = active;
removeChildren(0, getNumChildren());
if (active) {
for (osg::Camera* cam : {sceneCam_.get(), brightCam_.get(), blurHCam_.get(), blurVCam_.get(), aoCam_.get(),
compositeCam_.get(), finalCam_.get()})
addChild(cam);
} else {
addChild(scene_);
}
}
if (!built_) return;
const LookSettings& s = settings_;
const unsigned bloomMask = s.bloom ? ~0u : 0u;
brightCam_->setNodeMask(bloomMask);
blurHCam_->setNodeMask(bloomMask);
blurVCam_->setNodeMask(bloomMask);
aoCam_->setNodeMask(s.ambientOcclusion ? ~0u : 0u);
// FXAA alone reads the scene directly and skips the full-screen composite pass.
const bool composite = s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.exposure != 1.f ||
s.contrast != 1.f || s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
compositeCam_->setNodeMask(composite ? ~0u : 0u);
finalCam_->getChild(0)->getOrCreateStateSet()->setTextureAttribute(
0, composite ? ldr_.get() : color_.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
const float bw = static_cast<float>(std::max(width_ / 4, 1)), bh = static_cast<float>(std::max(height_ / 4, 1));
// Blur radius scales with the image height so the glow looks the same at any resolution.
const float spread = s.bloomRadius * std::max(height_, 1) / 540.f;
blurHDir_->set(osg::Vec2f(spread / bw, 0.f));
blurVDir_->set(osg::Vec2f(0.f, spread / bh));
threshold_->set(s.bloomThreshold);
bloomOn_->set(s.bloom ? 1 : 0);
bloomStrength_->set(s.bloomStrength);
aoOn_->set(s.ambientOcclusion ? 1 : 0);
aoRadius_->set(s.aoRadius);
aoStrength_->set(s.aoStrength);
toneMap_->set(s.toneMapping);
exposure_->set(s.exposure);
contrast_->set(s.contrast);
saturation_->set(s.saturation);
const float t = std::clamp(s.temperature, -1.f, 1.f);
tint_->set(osg::Vec3f(1.f + 0.12f * t, 1.f + 0.02f * t, 1.f - 0.15f * t));
vignette_->set(s.vignette);
fxaaOn_->set(s.fxaa ? 1 : 0);
}
} // namespace mr
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <osg/Camera>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/Uniform>
#include "scene/LookSettings.h"
namespace mr {
// Node-mask bits that pick which output camera draws which post-processing chain.
constexpr unsigned kMainViewMask = 0x10;
constexpr unsigned kPopViewMask = 0x20;
constexpr unsigned kRenderViewMask = 0x40;
// True when any post-processing effect is switched on.
bool postFxActive(const LookSettings& settings);
// Post-processing for one output camera. Nested cameras render the scene into textures with the
// output camera's view and projection, then bloom, ambient occlusion, tone mapping, colour grading
// and FXAA are composited onto a fullscreen quad. With every effect off the scene is drawn directly.
class PostChain : public osg::Group {
public:
PostChain(osg::Node* scene, unsigned viewMask);
void setSupported(bool framebufferObjects, bool floatTextures);
bool supported() const { return supported_; }
void apply(const LookSettings& settings);
void setSize(int width, int height);
void setClearColor(const osg::Vec4& color);
// Called while culling: fits near/far to the scene (the output camera's are fixed) and
// passes the resulting projection to the ambient-occlusion pass.
void cullUpdate(const osg::Matrixd& projection, const osg::Matrixd& view);
private:
void build();
void refresh();
osg::ref_ptr<osg::Node> scene_;
LookSettings settings_;
bool supported_ = false, floatColor_ = false, built_ = false, active_ = false;
int width_ = 0, height_ = 0;
osg::Vec4 clearColor_{0.f, 0.f, 0.f, 1.f};
osg::ref_ptr<osg::Texture2D> color_, depth_, bloomA_, bloomB_, ao_, ldr_;
osg::ref_ptr<osg::Camera> sceneCam_, brightCam_, blurHCam_, blurVCam_, aoCam_, compositeCam_, finalCam_;
osg::ref_ptr<osg::Uniform> brightTexel_, threshold_, blurHDir_, blurVDir_, aoTexel_, aoRadius_, aoStrength_,
proj_, projZ_, bloomOn_, aoOn_, bloomStrength_, toneMap_, exposure_, contrast_, saturation_, tint_,
vignette_, compositeAoTexel_, fxaaOn_, fxaaTexel_;
};
} // namespace mr
+15 -5
View File
@@ -118,6 +118,12 @@ uniform vec3 u_lightColor;
uniform float u_shadowStrength;
uniform float u_rimStrength;
uniform vec3 u_rimColor;
uniform vec4 u_texMul; // material-morph tints: texel * mul + add
uniform vec4 u_texAdd;
uniform vec4 u_sphereMul;
uniform vec4 u_sphereAdd;
uniform vec4 u_toonMul;
uniform vec4 u_toonAdd;
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
@@ -132,11 +138,12 @@ void main() {
float shadow = u_receiveShadow == 1 ? shadowFactor(v_viewPos, ndl) : 1.0;
float lit = mix(1.0, shadow, u_shadowStrength);
vec4 base = u_diffuse;
if (u_useTexture == 1) base *= texture2D(u_texture, v_uv);
vec4 texel = vec4(1.0);
if (u_useTexture == 1) texel = clamp(texture2D(u_texture, v_uv) * u_texMul + u_texAdd, 0.0, 1.0);
vec4 base = u_diffuse * texel;
float alpha = base.a;
if (alpha < 0.004) discard;
vec3 tex = u_useTexture == 1 ? texture2D(u_texture, v_uv).rgb : vec3(1.0);
vec3 tex = texel.rgb;
vec3 color;
if (u_lightingModel == 0) {
@@ -157,13 +164,16 @@ void main() {
color = base.rgb * (ambient + wrap * u_lightColor * 1.25);
}
if (u_sphereMode != 0) {
vec3 s = texture2D(u_sphere, n.xy * 0.5 + 0.5).rgb;
vec3 s = clamp(texture2D(u_sphere, n.xy * 0.5 + 0.5).rgb * u_sphereMul.rgb + u_sphereAdd.rgb, 0.0, 1.0);
if (u_sphereMode == 1) color *= s;
else color += s * (u_lightingModel == 2 ? 0.5 + 0.5 * lit : 1.0);
}
if (u_lightingModel == 0) {
float t = clamp(ndl + 0.5, 0.0, 1.0);
if (u_useToon == 1) color *= texture2D(u_toon, vec2(0.5, min(t, mix(1.0, t * shadow, u_shadowStrength)))).rgb;
if (u_useToon == 1) {
vec3 toon = texture2D(u_toon, vec2(0.5, min(t, mix(1.0, t * shadow, u_shadowStrength)))).rgb;
color *= clamp(toon * u_toonMul.rgb + u_toonAdd.rgb, 0.0, 1.0);
}
else color *= mix(1.0, 0.55 + 0.45 * shadow, u_shadowStrength);
}
vec3 h = normalize(toLight + toEye);
+16
View File
@@ -25,6 +25,22 @@ struct LookSettings {
float rimStrength = 0.f;
osg::Vec3f rimColor{1.f, 1.f, 1.f};
// Post-processing; with all of it off the scene is drawn directly, at no extra cost.
bool bloom = false;
float bloomStrength = 0.4f;
float bloomThreshold = 0.8f;
float bloomRadius = 1.f;
bool ambientOcclusion = false;
float aoStrength = 1.f;
float aoRadius = 1.5f; // world units; a character is about 20 tall
int toneMapping = 0; // 0 off, 1 filmic
float exposure = 1.f;
float contrast = 1.f;
float saturation = 1.f;
float temperature = 0.f; // -1 cool .. 1 warm
float vignette = 0.f;
bool fxaa = false;
};
} // namespace mr
+41 -1
View File
@@ -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)
@@ -118,7 +123,21 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error)
{"groundShadow", look.groundShadow},
{"groundShadowOpacity", look.groundShadowOpacity},
{"rimStrength", look.rimStrength},
{"rimColor", vec(look.rimColor)}};
{"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},
@@ -197,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);
}
@@ -233,6 +259,20 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) {
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);
+5
View File
@@ -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;
+48
View File
@@ -377,7 +377,14 @@ void testSceneFile() {
scene.look.shadows = false;
scene.look.rimStrength = 0.5f;
scene.look.rimColor = osg::Vec3f(1.f, 0.5f, 0.25f);
scene.look.bloom = true;
scene.look.ambientOcclusion = true;
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));
@@ -390,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"));
@@ -405,6 +414,8 @@ void testSceneFile() {
CHECK(loaded.look.shading == 2 && loaded.renderWidth == 1280);
CHECK(!loaded.look.shadows && loaded.look.outlines && std::abs(loaded.look.rimStrength - 0.5f) < 1e-6f);
CHECK(std::abs(loaded.look.rimColor.y() - 0.5f) < 1e-6f);
CHECK(loaded.look.bloom && loaded.look.ambientOcclusion && loaded.look.toneMapping == 1 && !loaded.look.fxaa);
CHECK(std::abs(loaded.look.vignette - 0.3f) < 1e-6f);
CHECK(!loaded.audioPath.empty() && loaded.cameraMotionPath.empty());
const std::string bad = mr::pathToUtf8(dir / "bad.mrscene");
@@ -413,8 +424,45 @@ void testSceneFile() {
fs::remove_all(dir);
}
// UV morphs offset the main UVs; material morphs combine as base * mul + add, like MMD.
void testUvAndMaterialMorphs() {
auto model = load("column.pmx");
mr::Morph uv;
uv.type = mr::MorphType::UV;
uv.uvOffsets.push_back({16, osg::Vec2f(0.25f, -0.5f)});
model->morphs.push_back(uv);
mr::Morph mat;
mat.type = mr::MorphType::Material;
mr::MaterialMorphOffset fade; // multiply every material's alpha toward 0
fade.diffuse = osg::Vec4f(1, 1, 1, 0);
fade.specular = fade.ambient = osg::Vec3f(1, 1, 1);
fade.shininess = fade.edgeSize = 1.f;
fade.edgeColor = fade.textureTint = fade.sphereTint = fade.toonTint = osg::Vec4f(1, 1, 1, 1);
mr::MaterialMorphOffset tint; // add red to material 0's texture
tint.material = 0;
tint.op = mr::MaterialMorphOp::Add;
tint.textureTint = osg::Vec4f(0.2f, 0, 0, 0);
mat.materialOffsets = {fade, tint};
model->morphs.push_back(mat);
const int uvMorph = static_cast<int>(model->morphs.size()) - 2, matMorph = uvMorph + 1;
mr::Poser poser(model);
poser.update();
CHECK((poser.morphedUvs()[16] - model->vertices[16].uv).length() < 1e-6f);
CHECK(poser.materialStates()[0].diffuse == model->materials[0].diffuse);
poser.morphWeights()[uvMorph] = 1.f;
poser.morphWeights()[matMorph] = 0.5f;
poser.update();
CHECK((poser.morphedUvs()[16] - (model->vertices[16].uv + osg::Vec2f(0.25f, -0.5f))).length() < 1e-6f);
for (size_t i = 0; i < model->materials.size(); ++i)
CHECK(std::abs(poser.materialStates()[i].diffuse.a() - model->materials[i].diffuse.a() * 0.5f) < 1e-6f);
CHECK(std::abs(poser.materialStates()[0].textureAdd.x() - 0.1f) < 1e-6f);
CHECK(poser.materialStates()[0].textureMul == osg::Vec4f(1, 1, 1, 1));
}
int main() {
testPmx();
testUvAndMaterialMorphs();
testPmd();
testFbx();
testIk();