载入中...
搜索中...
未找到
VrmRuntime.cpp
浏览该文件的文档.
1#include "avatar/VrmRuntime.h"
2#include <assimp/scene.h>
3#include <glm/gtc/quaternion.hpp>
4#include <glm/gtx/matrix_decompose.hpp>
5#include <stdexcept>
11#include "avatar/VrmSurface.h"
12#include "common/Module.h"
14#include "filesystem/FileData.h"
16#include "graphics/Graphics.h"
17#include "graphics/Material.h"
18#include "graphics/Mesh.h"
20#include "graphics/Texture.h"
21#include "model3d/Model3D.h"
22#include "model3d/ModelData.h"
23
24namespace eve::avatar {
25VrmRuntime::VrmRuntime() = default;
27 for (auto& part : parts) {
28 if (auto* entity = ecs::try_get(part.entity)) ecs::DestroyEntity(entity);
29 if (auto* entity = ecs::try_get(part.outline)) ecs::DestroyEntity(entity);
30 }
31 if (auto* gfx = ModuleManager::getInstance<graphics::Graphics>("Graphics"); gfx && !providerLifetime.expired()) {
32 for (auto& part : parts)
33 if (gfx->releaseMesh(part.mesh)) delete part.mesh;
34 surfaces.clear();
35 for (auto* texture : textures)
36 if (gfx->releaseTexture(texture)) delete texture;
37 }
38}
41 try {
42 auto* fs = filesystem::Filesystem::create();
43 std::unique_ptr<filesystem::FileData> file(fs->read(std::string(path)));
44 if (!file) throw std::runtime_error("VRM file could not be read");
45 auto parsed = parseVrm({static_cast<const std::byte*>(file->getData()), file->getSize()});
46 if (!parsed.ok()) return R::failure(parsed.status());
47 auto* gfx = ModuleManager::getInstance<graphics::Graphics>("Graphics");
48 if (!gfx || gfx->getBackendName() != "vulkan")
50 "VRM import requires an initialized graphics provider",
51 std::string(path)));
52 auto candidate = std::make_unique<VrmRuntime>();
53 candidate->document = std::move(parsed).takeValue();
54 candidate->providerLifetime = gfx->resourceLifetime();
55 auto& d = candidate->document;
56 // Uncached owning model: replacing/reloading a cache entry cannot invalidate this import.
57 candidate->model.reset(model3d::Model3D::create()->newModelData(file.get(), ".glb"));
58 candidate->skeleton.reset(animation::AnimImporter::loadSkeletonFromModel(candidate->model.get()));
59 candidate->player = std::make_unique<animation::AnimPlayer>(candidate->skeleton.get());
60 candidate->nodeBones.resize(d.nodes.size(), -1);
61 for (size_t n = 0; n < d.nodes.size(); ++n) {
62 if (!d.nodes[n].empty()) candidate->nodeBones[n] = candidate->skeleton->findBone(d.nodes[n]);
63 }
64 auto requireNode = [&](int node) {
65 if (node >= 0 && candidate->nodeBones[node] < 0)
66 throw std::runtime_error("Cannot resolve VRM node: " + d.nodes[node]);
67 };
68 for (auto& [semantic, node] : d.humanoid) requireNode(node);
69 for (auto& c : d.colliders) requireNode(c.node);
70 for (auto& s : d.springs) {
71 requireNode(s.center);
72 for (auto& j : s.joints) requireNode(j.node);
73 }
74 std::vector<VrmAtlasRect> rectangles;
75 auto* atlas = &buildVrmAtlas(*gfx, d, rectangles);
76 candidate->textures.push_back(atlas);
77 for (auto& m : d.materials) candidate->surfaces.push_back(buildVrmSurface(*gfx, m, *atlas, rectangles));
78 const auto* scene = candidate->model->getScene();
79 for (size_t n = 0; n < d.nodes.size(); ++n) {
80 if (d.nodeMeshes[n] < 0) continue;
81 const auto* node = scene->mRootNode->FindNode(d.nodes[n].c_str());
82 if (!node) throw std::runtime_error("Cannot resolve VRM mesh node: " + d.nodes[n]);
83 const auto& slots = d.meshMaterials[d.nodeMeshes[n]];
84 if (node->mNumMeshes != slots.size())
85 throw std::runtime_error("VRM primitive mapping changed during decode");
86 for (unsigned p = 0; p < node->mNumMeshes; ++p) {
87 Part part;
88 part.sourceMesh = int(node->mMeshes[p]);
89 part.node = int(n);
90 part.material = slots[p];
91 if (part.material < 0) throw std::runtime_error("VRM primitive is missing its material");
92 candidate->parts.push_back(std::move(part));
93 auto& owned = candidate->parts.back();
94 owned.mesh = gfx->newMeshFromAssimp(*scene->mMeshes[owned.sourceMesh]);
95 if (!owned.mesh) throw std::runtime_error("Mesh upload failed");
96 if (candidate->model->hasBones(owned.sourceMesh)) {
97 owned.skin.reset(animation::AnimSkin::fromModel(candidate->model.get(), owned.sourceMesh,
98 candidate->skeleton.get()));
99 if (!owned.skin->bindGpuMesh(gfx, owned.mesh))
100 throw std::runtime_error("VRM GPU skin upload failed");
101 }
102 auto* entity = graphics::Renderable3D::create();
103 owned.entity = ecs::handle_of(entity);
104 entity->setVisible(false);
105 entity->setMesh(owned.mesh);
106 entity->setMaterial(candidate->surfaces[owned.material]->material.get());
107 if (auto* material = candidate->surfaces[owned.material]->outlineMaterial.get()) {
108 auto* outline = graphics::Renderable3D::create();
109 owned.outline = ecs::handle_of(outline);
110 outline->setVisible(false);
111 outline->setMesh(owned.mesh);
112 outline->setMaterial(material);
113 }
114 }
115 }
116 if (candidate->parts.empty()) throw std::runtime_error("VRM contains no renderable primitives");
117 candidate->particles_.resize(d.springs.size());
118 for (size_t i = 0; i < d.springs.size(); ++i) candidate->particles_[i].resize(d.springs[i].joints.size());
119 return R::success(std::move(candidate));
120 } catch (const std::exception& e) {
121 return R::failure(
122 eve::Diagnostic::error(eve::DiagnosticCode::Failed, e.what(), std::string(path), {}, "avatar.vrm.import"));
123 }
124}
125void VrmRuntime::sync(AvatarInstance&, const glm::mat4& matrix, bool visible) {
126 visible = visible && !providerLifetime.expired();
127 world = matrix;
128 for (auto& part : parts) {
129 glm::mat4 partWorld = matrix;
130 if (!part.skin && nodeBones[part.node] >= 0) {
131 glm::mat4 nodeMatrix(1);
132 player->getPose()->getWorldMatrix(nodeBones[part.node], &nodeMatrix[0][0]);
133 partWorld *= nodeMatrix;
134 }
135 glm::vec3 scale, translation, skew;
136 glm::quat rotation;
137 glm::vec4 perspective;
138 glm::decompose(partWorld, scale, rotation, translation, skew, perspective);
139 float yaw = 0.f, pitch = 0.f, roll = 0.f;
141 for (auto handle : {part.entity, part.outline})
142 if (auto* entity = dynamic_cast<graphics::Renderable3D*>(ecs::try_get(handle))) {
143 entity->setPosition(translation.x, translation.y, translation.z);
144 entity->setRotation(yaw, pitch, roll);
145 entity->setScale(scale.x, scale.y, scale.z);
146 entity->setVisible(visible);
147 }
148 }
149}
151 if (providerLifetime.expired()) return;
152 time += dt;
153 springs(pose, dt);
154 for (auto& part : parts)
155 if (part.skin && !part.skin->updateGpuMesh(part.mesh, &pose))
156 throw std::runtime_error("VRM skin palette no longer matches imported skeleton");
157}
159 if (providerLifetime.expired()) return;
160 std::vector<float> weights;
161 float blink = 0, mouth = 0, look = 0;
162 auto overrideValue = [](const std::string& mode, float weight) {
163 return mode == "block" && weight > 0 ? 1.f : mode == "blend" ? weight : 0.f;
164 };
165 for (const auto& e : document.expressions) {
166 float w = std::clamp(avatar.getParameter(e.name) + (gazeWeights_.contains(e.name) ? gazeWeights_[e.name] : 0.f),
167 0.f, 1.f);
168 if (e.binary) w = w > .5f ? 1.f : 0.f;
169 weights.push_back(w);
170 blink += overrideValue(e.overrideBlink, w);
171 mouth += overrideValue(e.overrideMouth, w);
172 look += overrideValue(e.overrideLookAt, w);
173 }
174 for (auto& s : surfaces) {
175 s->current = s->base;
176 s->uvScale = {1, 1};
177 s->uvOffset = {0, 0};
178 }
179 for (auto& part : parts) {
180 part.mesh->clearMorphWeights();
181 for (int i = 0; i < part.mesh->getMorphCount(); ++i) {
182 auto name = part.mesh->getMorphName(i);
183 if (avatar.hasParameter(name)) part.mesh->setMorphWeight(name, avatar.getParameter(name));
184 }
185 }
186 for (size_t i = 0; i < document.expressions.size(); ++i) {
187 const auto& e = document.expressions[i];
188 float suppression = 0;
189 if (e.name == "blink" || e.name == "blinkLeft" || e.name == "blinkRight") suppression = blink;
190 if (e.name == "aa" || e.name == "ih" || e.name == "ou" || e.name == "ee" || e.name == "oh") suppression = mouth;
191 if (e.name == "lookUp" || e.name == "lookDown" || e.name == "lookLeft" || e.name == "lookRight")
192 suppression = look;
193 float w = weights[i] * (1 - std::clamp(suppression, 0.f, 1.f));
194 if (e.binary && suppression > 0) w = 0;
195 for (const auto& bind : e.morphs)
196 for (auto& part : parts)
197 if (part.node == bind.node) {
198 auto name = part.mesh->getMorphName(bind.index);
199 part.mesh->setMorphWeight(name, part.mesh->getMorphWeight(name) + bind.weight * w);
200 }
201 for (const auto& b : e.colors) {
202 auto& s = *surfaces[b.material];
203 auto add = [&](auto& out, const auto& base) {
204 for (size_t c = 0; c < out.size(); ++c) out[c] += (b.target[c] - base[c]) * w;
205 };
206 if (b.type == "color")
207 add(s.current.color, s.base.color);
208 else if (b.type == "emissionColor")
209 add(s.current.emission, s.base.emission);
210 else if (b.type == "shadeColor")
211 add(s.current.shade, s.base.shade);
212 else if (b.type == "matcapColor")
213 add(s.current.matcap, s.base.matcap);
214 else if (b.type == "rimColor")
215 add(s.current.rim, s.base.rim);
216 else if (b.type == "outlineColor")
217 add(s.current.outline, s.base.outline);
218 }
219 for (const auto& b : e.uvs)
220 for (int c = 0; c < 2; ++c) {
221 surfaces[b.material]->uvScale[c] += (b.scale[c] - 1) * w;
222 surfaces[b.material]->uvOffset[c] += b.offset[c] * w;
223 }
224 }
225 auto* gfx = ModuleManager::getInstance<graphics::Graphics>("Graphics");
226 if (gfx)
227 for (auto& part : parts)
228 if (part.mesh->isMorphDirty()) gfx->bakeMeshMorph(part.mesh);
229 for (auto& surface : surfaces) surface->update(time);
230}
231} // namespace eve::avatar
double m[16]
float w
Definition AnimClip.cpp:738
ActiveSource owned
eve::EntitySpatialPose pose
const std::string & s
float yaw
Definition BushMesh.cpp:37
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
std::array< float, 4 > rotation
std::array< float, 3 > scale
MeleePoint3 b
Definition MeleeHit.cpp:41
double dt
std::array< uint32_t, 16 > material
Texture * texture
std::string path
Definition PlayHost.cpp:111
std::weak_ptr< PrimitiveScene > scene
PrimitiveHandle handle
std::string file
float d
const EntityFact * entity
const RoadNode * node
uint32_t semantic
glm::dmat4 matrix
ScriptStructure out
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
float weights[3]
bool visible
double weight
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static AnimSkeleton * loadSkeletonFromModel(const model3d::ModelData *model)
ModelData wrappers (AnimImporterModel.cpp; requires model3d).
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
static AnimSkin * fromModel(const model3d::ModelData *model, int meshIndex, const AnimSkeleton *skeleton)
Build skin binding for meshIndex on model, mapping bone names onto skeleton. Throws if the mesh has n...
Unified avatar instance. Kind is a string: "image" | "live2d" | "vroid". Script-facing API avoids ove...
float getParameter(const std::string &name) const
Returns the parameter.
bool hasParameter(const std::string &name) const
True when parameter.
static eve::Result< std::unique_ptr< VrmRuntime > > prepare(std::string_view path)
Prepare.
std::vector< int > nodeBones
Definition VrmRuntime.h:52
void animate(AvatarInstance &avatar, animation::AnimPose &pose, float dt)
Animate.
std::vector< std::unique_ptr< VrmSurface > > surfaces
Definition VrmRuntime.h:63
void morphs(AvatarInstance &avatar)
Morphs.
std::vector< graphics::Texture * > textures
Definition VrmRuntime.h:64
std::vector< Part > parts
Definition VrmRuntime.h:62
void sync(AvatarInstance &avatar, const glm::mat4 &world, bool visible)
Synchronizes .
std::weak_ptr< const void > providerLifetime
Definition VrmRuntime.h:47
std::unique_ptr< animation::AnimPlayer > player
Definition VrmRuntime.h:51
VrmRuntime()
Constructs a VrmRuntime.
~VrmRuntime()
Releases VrmRuntime resources.
EVENGINE_API_BACKENDS public API.
eve::Result< VrmDocument > parseVrm(std::span< const std::byte > bytes)
Validate a self-contained GLB's VRM extension before publishing runtime state.
graphics::Texture & buildVrmAtlas(graphics::Graphics &gfx, const VrmDocument &d, std::vector< VrmAtlasRect > &rects)
Prepare an atlas using the provider's owning resource factory. @ownership Graphics owns the result; c...
std::unique_ptr< VrmSurface > buildVrmSurface(graphics::Graphics &gfx, const VrmMaterial &data, graphics::Texture &atlas, const std::vector< VrmAtlasRect > &rects)
Builds vrm surface.
void eulerYxzFromQuat(const glm::qua< T, glm::defaultp > &q, T &yaw, T &pitch, T &roll)
Quaternion overload of eulerYxzFromMatrix(); float and double both work.
std::vector< VrmExpression > expressions
Definition VrmDocument.h:94