载入中...
搜索中...
未找到
AvatarInstance.cpp
浏览该文件的文档.
12#include "animation/Tween.h"
13#include "avatar/Avatar.h"
14#include "avatar/VrmRuntime.h"
15#include "common/ECS.h"
16#include "common/Module.h"
18#include "graphics/DrawItem2D.h"
19#include "graphics/Graphics.h"
20#include "graphics/Mesh.h"
23#include "graphics/Texture.h"
24#include "image/ImageData.h"
25#include "inventory/Equipment.h"
26#include "model3d/ModelData.h"
27#include "scene/Scene.h"
28
29#include <algorithm>
30#include <cctype>
31#include <cstdlib>
32#include <functional>
33#include <sstream>
34
35namespace eve::avatar {
36namespace {
37
38std::string trimCopy(const std::string &s) {
39 size_t b = 0;
40 while (b < s.size() && std::isspace(static_cast<unsigned char>(s[b]))) ++b;
41 size_t e = s.size();
42 while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) --e;
43 return s.substr(b, e - b);
44}
45
46bool parseBoolish(const std::string &v, bool &out) {
47 std::string t;
48 t.reserve(v.size());
49 for (char c : v) t.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));
50 if (t == "1" || t == "true" || t == "on" || t == "yes") {
51 out = true;
52 return true;
53 }
54 if (t == "0" || t == "false" || t == "off" || t == "no") {
55 out = false;
56 return true;
57 }
58 return false;
59}
60
61} // namespace
62
63AvatarInstance::AvatarInstance(std::string kind) : kind_(std::move(kind)) {
64 equipmentLayers_.emplace("body", EquipmentLayer{"", 0, {}});
65 equipmentLayers_.emplace("underwear", EquipmentLayer{"body", 100, {}});
66 equipmentLayers_.emplace("shirt", EquipmentLayer{"underwear", 200, {}});
67 equipmentLayers_.emplace("outerwear", EquipmentLayer{"shirt", 300, {}});
68 equipmentLayers_.emplace("cape", EquipmentLayer{"outerwear", 400, {}});
69 equipmentLayers_.emplace("weapon", EquipmentLayer{"body", 500, {}});
70 if (auto *mod = ModuleManager::getInstance<Avatar>("Avatar"))
71 mod->registerInstance(this);
72}
73
75
77 if (released_) return;
78 released_ = true;
79 // Notify owners (e.g. Dialogue) before the object is destroyed so they can
80 // drop dangling raw pointers. Runs exactly once: the destructor re-enters
81 // release() but the guard above short-circuits.
82 for (auto &[hookId, hook] : destroyHooks_) {
83 try {
84 hook(this);
85 } catch (...) {
86 }
87 }
88 destroyHooks_.clear();
89 tween_ = nullptr;
90 animPlayer_ = nullptr;
91 animLayerMixer_ = nullptr;
92 animStateMachine_ = nullptr;
93 animConstraintStack_.reset();
94 footIKSolver_.reset();
95 dynamicBoneSolver_ = nullptr;
96 animSkin_ = nullptr;
97 animSkeleton_ = nullptr;
98 attachmentPoseMatrices_.clear();
99 motions_.clear();
100 attachments_.clear();
101 hideEquipmentVisuals();
102 equipment_ = nullptr;
103 equipmentVisuals_.clear();
104 skinnedParts_.clear();
105 projectedEquipment_.clear();
106 skinnedPositions_.clear();
107 if (sceneAnchor2d_) {
108 ecs::DestroyEntity(sceneAnchor2d_);
109 sceneAnchor2d_ = nullptr;
110 }
111 sceneLinked_ = false;
112 if (auto *mod = ModuleManager::getInstance<Avatar>("Avatar"))
113 mod->unregisterInstance(this);
114 destroyLayers();
115 destroyVroid();
116 delete live2d_;
117 live2d_ = nullptr;
118}
119
121 if (!hook)
122 return static_cast<size_t>(-1);
123 const size_t id = nextDestroyHookId_++;
124 destroyHooks_.emplace_back(id, std::move(hook));
125 return id;
126}
127
129 for (auto it = destroyHooks_.begin(); it != destroyHooks_.end(); ++it) {
130 if (it->first == id) {
131 destroyHooks_.erase(it);
132 return;
133 }
134 }
135}
136
137void AvatarInstance::setPosition(float x, float y) {
138 x_ = x;
139 y_ = y;
140}
141
142void AvatarInstance::setScale(float sx, float sy) {
143 sx_ = sx;
144 sy_ = sy;
145}
146
148
149void AvatarInstance::setLayer(int layer) { layer_ = layer; }
150
152 if (!equipment) return unbindEquipment();
153 equipment_ = equipment;
154 equipmentSignature_.clear();
156}
157
159 const bool hadBinding = equipment_ != nullptr || !projectedEquipment_.empty();
160 equipment_ = nullptr;
161 equipmentSignature_.clear();
162 projectedEquipment_.clear();
163 hideEquipmentVisuals();
165}
166
168 const std::string& itemId, const std::string& equipmentSlot, const std::string& layerName,
169 graphics::Texture* texture, int zIndex) {
170 if (kind_ != "image" || itemId.empty() || equipmentSlot.empty() || layerName.empty())
172 for (auto& visual : equipmentVisuals_) {
173 if (visual.itemId != itemId || visual.equipmentSlot != equipmentSlot) continue;
174 if (visual.layerName == layerName && visual.texture == texture && visual.zIndex == zIndex)
176 visual.layerName = layerName;
177 visual.texture = texture;
178 visual.zIndex = zIndex;
179 equipmentSignature_.clear();
181 }
182 EquipmentVisual visual;
183 visual.itemId = itemId;
184 visual.equipmentSlot = equipmentSlot;
185 visual.layerName = layerName;
186 visual.texture = texture;
187 visual.wearLayer = equipmentSlot;
188 visual.zIndex = zIndex;
189 equipmentVisuals_.push_back(std::move(visual));
190 equipmentSignature_.clear();
192}
193
195 const std::string& itemId, const std::string& equipmentSlot,
196 graphics::Renderable3D* renderable, const std::string& boneSemanticOrName, float ox, float oy,
197 float oz) {
198 if (kind_ != "vroid" || itemId.empty() || equipmentSlot.empty() || !renderable)
200 for (auto& visual : equipmentVisuals_) {
201 if (visual.itemId != itemId || visual.equipmentSlot != equipmentSlot) continue;
202 if (visual.renderable == renderable && visual.boneName == boneSemanticOrName &&
203 visual.ox == ox && visual.oy == oy && visual.oz == oz)
205 visual.renderable = renderable;
206 visual.boneName = boneSemanticOrName;
207 visual.ox = ox;
208 visual.oy = oy;
209 visual.oz = oz;
210 equipmentSignature_.clear();
212 }
213 EquipmentVisual visual;
214 visual.itemId = itemId;
215 visual.equipmentSlot = equipmentSlot;
216 visual.renderable = renderable;
217 visual.boneName = boneSemanticOrName;
218 visual.wearLayer = equipmentSlot;
219 visual.ox = ox;
220 visual.oy = oy;
221 visual.oz = oz;
222 equipmentVisuals_.push_back(std::move(visual));
223 renderable->setVisible(false);
224 equipmentSignature_.clear();
226}
227
229 const std::string& itemId, const std::string& equipmentSlot, int partIndex,
230 const std::string& partName, graphics::Mesh* mesh, graphics::Material* material,
231 animation::AnimSkin* skin) {
232 if (kind_ != "vroid" || itemId.empty() || equipmentSlot.empty() || partName.empty() ||
233 !mesh || !skin || partIndex < 0 ||
236 if (!renderable3d_) renderable3d_ = graphics::Renderable3D::create();
237 for (const auto& part : skinnedParts_) {
238 if (part.partIndex == partIndex) return EquipmentVisualChange::Rejected;
239 }
240 for (const auto& visual : equipmentVisuals_) {
241 if (visual.partIndex == partIndex && visual.equipmentSlot != equipmentSlot)
243 }
244 for (auto& visual : equipmentVisuals_) {
245 if (visual.itemId != itemId || visual.equipmentSlot != equipmentSlot) continue;
246 if (visual.partIndex == partIndex && visual.layerName == partName &&
247 visual.skinnedMesh == mesh && visual.skinnedMaterial == material &&
248 visual.skinnedSkin == skin)
250 if (renderable3d_ && visual.partIndex >= 0) {
251 renderable3d_->setPart(visual.partIndex, visual.layerName, nullptr, nullptr);
252 renderable3d_->clearPartSortPriority(visual.partIndex);
253 }
254 if (visual.renderable) visual.renderable->setVisible(false);
255 if (!visual.boneName.empty()) detachAttachment("equipment:" + visual.equipmentSlot);
256 visual.partIndex = partIndex;
257 visual.layerName = partName;
258 visual.skinnedMesh = mesh;
259 visual.skinnedMaterial = material;
260 visual.skinnedSkin = skin;
261 visual.renderable = nullptr;
262 visual.boneName.clear();
263 visual.cpuPositions.clear();
264 equipmentSignature_.clear();
266 }
267 EquipmentVisual visual;
268 visual.itemId = itemId;
269 visual.equipmentSlot = equipmentSlot;
270 visual.layerName = partName;
271 visual.wearLayer = equipmentSlot;
272 visual.partIndex = partIndex;
273 visual.skinnedMesh = mesh;
274 visual.skinnedMaterial = material;
275 visual.skinnedSkin = skin;
276 equipmentVisuals_.push_back(std::move(visual));
277 equipmentSignature_.clear();
279}
280
282 const std::string& parent) {
283 if (name.empty() || name == parent || (!parent.empty() && !equipmentLayers_.count(parent)))
285 auto found = equipmentLayers_.find(name);
286 if (found != equipmentLayers_.end() && found->second.order == order &&
287 found->second.parent == parent)
289 auto& layer = equipmentLayers_[name];
290 layer.order = order;
291 layer.parent = parent;
292 equipmentSignature_.clear();
294}
295
297 const std::string& innerLayer) {
298 const auto outer = equipmentLayers_.find(outerLayer);
299 const auto inner = equipmentLayers_.find(innerLayer);
300 if (outer == equipmentLayers_.end() || inner == equipmentLayers_.end() ||
301 outerLayer == innerLayer || outer->second.order <= inner->second.order)
303 auto& occludes = outer->second.occludes;
304 if (std::find(occludes.begin(), occludes.end(), innerLayer) != occludes.end())
306 occludes.push_back(innerLayer);
307 equipmentSignature_.clear();
309}
310
312 const std::string& itemId, const std::string& equipmentSlot, const std::string& wearLayer,
313 int withinLayerOrder) {
314 if (!equipmentLayers_.count(wearLayer)) return EquipmentVisualChange::Rejected;
315 for (auto& visual : equipmentVisuals_) {
316 if (visual.itemId != itemId || visual.equipmentSlot != equipmentSlot) continue;
317 if (visual.wearLayer == wearLayer && visual.withinLayerOrder == withinLayerOrder)
319 visual.wearLayer = wearLayer;
320 visual.withinLayerOrder = withinLayerOrder;
321 equipmentSignature_.clear();
323 }
325}
326
327int AvatarInstance::equipmentLayerOrder(const std::string& name) const {
328 const auto found = equipmentLayers_.find(name);
329 return found == equipmentLayers_.end() ? 0 : found->second.order;
330}
331
332void AvatarInstance::hideEquipmentVisuals() {
333 for (auto& visual : equipmentVisuals_) {
334 visual.updateMode = SkinnedPartUpdateMode::Unavailable;
335 if (kind_ == "image" && !visual.layerName.empty()) {
336 if (Layer* layer = findLayer(visual.layerName)) setLayerVisible(layer->name, false);
337 }
338 if (visual.renderable) visual.renderable->setVisible(false);
339 if (visual.partIndex >= 0 && renderable3d_)
340 renderable3d_->setPart(visual.partIndex, visual.layerName, nullptr, nullptr);
341 if (visual.partIndex >= 0 && renderable3d_)
342 renderable3d_->clearPartSortPriority(visual.partIndex);
343 if (!visual.boneName.empty()) detachAttachment("equipment:" + visual.equipmentSlot);
344 }
345}
346
348 if (!equipment_) return EquipmentVisualChange::Rejected;
349 std::string signature;
350 std::unordered_map<std::string, std::string> equipped;
351 for (int index = 0; index < equipment_->getSlotCount(); ++index) {
352 const std::string slot = equipment_->getSlotName(index);
353 const std::string item = equipment_->getSlotItemId(slot);
354 signature.append(slot);
355 signature.push_back('=');
356 signature.append(item);
357 signature.push_back('#');
358 signature.append(std::to_string(equipment_->getSlotInstanceId(slot)));
359 signature.push_back(';');
360 if (!item.empty()) equipped.emplace(slot, item);
361 }
362 if (signature == equipmentSignature_) return EquipmentVisualChange::Unchanged;
363
364 hideEquipmentVisuals();
365 projectedEquipment_.clear();
366 equipmentRenderStack_.clear();
367 std::vector<std::string> occludedLayers;
368 for (const auto& visual : equipmentVisuals_) {
369 const auto active = equipped.find(visual.equipmentSlot);
370 if (active == equipped.end() || active->second != visual.itemId) continue;
371 const auto layer = equipmentLayers_.find(visual.wearLayer);
372 if (layer == equipmentLayers_.end()) continue;
373 occludedLayers.insert(occludedLayers.end(), layer->second.occludes.begin(),
374 layer->second.occludes.end());
375 }
376 for (auto& visual : equipmentVisuals_) {
377 const auto active = equipped.find(visual.equipmentSlot);
378 if (active == equipped.end() || active->second != visual.itemId) continue;
379 if (std::find(occludedLayers.begin(), occludedLayers.end(), visual.wearLayer) !=
380 occludedLayers.end())
381 continue;
382 const int renderOrder = equipmentLayerOrder(visual.wearLayer) * 1000 +
383 visual.withinLayerOrder;
384 if (kind_ == "image" && !visual.layerName.empty()) {
385 if (!hasLayer(visual.layerName)) addLayer(visual.layerName, visual.texture, visual.zIndex);
386 setLayerTexture(visual.layerName, visual.texture);
387 setLayerZ(visual.layerName, renderOrder + visual.zIndex);
388 setLayerVisible(visual.layerName, true);
389 }
390 if (visual.renderable) {
391 visual.renderable->setVisible(visible_);
392 if (visual.boneName.empty()) {
393 visual.renderable->setPosition(x3_ + visual.ox, y3_ + visual.oy, z3_ + visual.oz);
394 visual.renderable->setRotation(yaw_, pitch_, roll_);
395 visual.renderable->setScale(sx3_, sy3_, sz3_);
396 } else {
397 attachToBone("equipment:" + visual.equipmentSlot, visual.boneName, visual.renderable,
398 visual.ox, visual.oy, visual.oz);
399 }
400 }
401 if (visual.partIndex >= 0 && visual.skinnedMesh && renderable3d_) {
402 renderable3d_->setPart(visual.partIndex, visual.layerName, visual.skinnedMesh,
403 visual.skinnedMaterial);
404 renderable3d_->setPartSortPriority(visual.partIndex, renderOrder);
405 }
406 projectedEquipment_[visual.equipmentSlot] = visual.itemId;
407 equipmentRenderStack_.push_back({visual.itemId, visual.wearLayer, renderOrder});
408 }
409 std::stable_sort(equipmentRenderStack_.begin(), equipmentRenderStack_.end(),
410 [](const EquipmentRenderEntry& a, const EquipmentRenderEntry& b) {
411 if (a.order != b.order) return a.order < b.order;
412 return a.itemId < b.itemId;
413 });
414 equipmentSignature_ = std::move(signature);
416}
417
418std::string AvatarInstance::getEquipmentVisualItem(const std::string& equipmentSlot) const {
419 const auto found = projectedEquipment_.find(equipmentSlot);
420 return found == projectedEquipment_.end() ? std::string{} : found->second;
421}
422
424 return static_cast<int>(equipmentRenderStack_.size());
425}
426
428 return index < 0 || index >= static_cast<int>(equipmentRenderStack_.size())
429 ? std::string{}
430 : equipmentRenderStack_[static_cast<size_t>(index)].itemId;
431}
432
434 return index < 0 || index >= static_cast<int>(equipmentRenderStack_.size())
435 ? std::string{}
436 : equipmentRenderStack_[static_cast<size_t>(index)].wearLayer;
437}
438
439void AvatarInstance::setExpression(const std::string &name) {
440 if (vrm_) {
441 for (const auto& e : vrm_->document.expressions) setParameter(e.name, e.name == name ? 1.f : 0.f);
442 expression_ = name;
443 return;
444 }
445 expression_ = name;
446 if (kind_ == "image") {
448 } else if (kind_ == "live2d") {
449 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
450 if (live2d_) live2d_->setExpression(name);
451 } else if (kind_ == "vroid") {
452 if (expressionDefs_.count(name)) {
454 } else if (!name.empty()) {
455 // Solo morph: zero known morph params then set named weight to 1.
456 if (boundMesh_ && boundMesh_->hasMorphData()) {
457 for (int i = 0; i < boundMesh_->getMorphCount(); ++i) {
458 const std::string mn = boundMesh_->getMorphName(i);
459 ensureParameter(mn, 0.f);
460 }
461 }
462 ensureParameter(name, 1.f);
463 syncMorphWeightsToMesh();
464 }
465 }
466}
467
468void AvatarInstance::setMotion(const std::string &name) {
469 motion_ = name;
470 if (kind_ == "live2d") {
471 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
472 if (live2d_) live2d_->setMotion(name);
473 }
474 if (kind_ == "vroid") {
475 auto it = motions_.find(name);
476 if (animPlayer_ && it != motions_.end()) {
477 if (animPlayer_->isPlaying() && motionBlendTime_ > 0.f)
478 animPlayer_->crossFade(it->second, motionBlendTime_);
479 else
480 animPlayer_->play(it->second);
481 hasPreviousRoot_ = false;
482 }
483 if (animStateMachine_) animStateMachine_->setTrigger(name);
484 setParameter("motion:" + name, 1.f);
485 }
486}
487
488void AvatarInstance::setParameter(const std::string &name, float value) {
489 if (name.empty()) return;
490 ensureParameter(name, value);
491 if (kind_ == "live2d") {
492 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
493 if (live2d_) live2d_->setParameter(name, value);
494 } else if (kind_ == "vroid") {
495 if (boundMesh_ && boundMesh_->hasMorph(name)) boundMesh_->setMorphWeight(name, value);
496 } else if (kind_ == "image") {
497 // Parameter name matching a layer drives that layer's alpha (lip-sync etc.).
498 if (Layer *L = findLayer(name)) {
499 float a = value;
500 if (a < 0.f) a = 0.f;
501 if (a > 1.f) a = 1.f;
502 L->entity->sprite()->a = a;
503 L->visible = a > 0.001f;
504 L->entity->sprite()->visible = visible_ && L->visible;
505 }
506 }
507}
508
509float AvatarInstance::getParameter(const std::string &name) const {
510 if (kind_ == "live2d" && live2d_) return live2d_->getParameter(name);
511 auto it = parameters_.find(name);
512 return it == parameters_.end() ? 0.f : it->second;
513}
514
515bool AvatarInstance::hasParameter(const std::string &name) const {
516 if (kind_ == "live2d" && live2d_) {
517 // Backend may not expose has; fall through to local cache.
518 }
519 return parameters_.find(name) != parameters_.end();
520}
521
522int AvatarInstance::getParameterCount() const { return int(parameterOrder_.size()); }
523
525 if (index < 0 || size_t(index) >= parameterOrder_.size()) return {};
526 return parameterOrder_[size_t(index)];
527}
528
530 if (equipment_) (void)syncEquipmentAppearance();
531 applyTweenTracks();
532 updateExpressionTransition(dt);
533 if (kind_ == "live2d") {
534 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
535 if (live2d_) live2d_->update(dt);
536 }
537 if (kind_ == "vroid") updateSkeletalAnimation(dt);
538}
539
541 if (kind_ != "vroid" || vrm_) return false;
542 animPlayer_ = player;
543 animStateMachine_ = nullptr;
544 animLayerMixer_ = nullptr;
545 animSkeleton_ = player ? player->getSkeleton() : nullptr;
546 attachmentPoseMatrices_.clear();
547 hasPreviousRoot_ = false;
548 if (footIKSolver_) footIKSolver_->setSkeleton(animSkeleton_);
549 if (animConstraintStack_) animConstraintStack_->setSkeleton(animSkeleton_);
550 if (dynamicBoneSolver_) dynamicBoneSolver_->setSkeleton(animSkeleton_);
551 return player != nullptr;
552}
553
555 if (kind_ != "vroid" || vrm_) return false;
556 animStateMachine_ = machine;
557 animPlayer_ = nullptr;
558 animLayerMixer_ = nullptr;
559 animSkeleton_ = machine ? machine->getSkeleton() : nullptr;
560 attachmentPoseMatrices_.clear();
561 hasPreviousRoot_ = false;
562 if (footIKSolver_) footIKSolver_->setSkeleton(animSkeleton_);
563 if (animConstraintStack_) animConstraintStack_->setSkeleton(animSkeleton_);
564 if (dynamicBoneSolver_) dynamicBoneSolver_->setSkeleton(animSkeleton_);
565 return machine != nullptr;
566}
567
569 if (kind_ != "vroid" || vrm_) return false;
570 animLayerMixer_ = mixer;
571 animStateMachine_ = nullptr;
572 animPlayer_ = mixer ? mixer->getBasePlayer() : nullptr;
573 animSkeleton_ = mixer ? mixer->getSkeleton() : nullptr;
574 attachmentPoseMatrices_.clear();
575 hasPreviousRoot_ = false;
576 if (footIKSolver_) footIKSolver_->setSkeleton(animSkeleton_);
577 if (animConstraintStack_) animConstraintStack_->setSkeleton(animSkeleton_);
578 if (dynamicBoneSolver_) dynamicBoneSolver_->setSkeleton(animSkeleton_);
579 return mixer != nullptr;
580}
581
583 if (kind_ != "vroid" || !stack) {
584 animConstraintStack_.reset();
585 return;
586 }
587 animConstraintStack_ = std::make_unique<animation::AnimConstraintStack>(*stack);
588 animConstraintStack_->setSkeleton(animSkeleton_);
589}
590
592 if (kind_ != "vroid" || !solver) {
593 footIKSolver_.reset();
594 return;
595 }
596 footIKSolver_ = std::make_unique<animation::FootIKSolver>(*solver);
597 footIKSolver_->setSkeleton(animSkeleton_);
598}
599
601 if (kind_ != "vroid") {
602 dynamicBoneSolver_.reset();
603 return;
604 }
605 if (!solver) {
606 dynamicBoneSolver_.reset();
607 return;
608 }
609 dynamicBoneSolver_ = std::make_unique<animation::DynamicBoneSolver>(*solver);
610 if (dynamicBoneSolver_) dynamicBoneSolver_->setSkeleton(animSkeleton_);
611}
612
614 if (kind_ != "vroid" || vrm_) return false;
615 animSkin_ = skin;
616 skinnedPositions_.clear();
617 return skin != nullptr;
618}
619
621 int partIndex, const std::string& partName, graphics::Mesh* mesh,
623 if (kind_ != "vroid" || partIndex < 0 ||
624 partIndex >= graphics::Renderable3D::MeshRenderer::kMaxParts || partName.empty() ||
625 !mesh || !skin)
627 for (const auto& visual : equipmentVisuals_) {
628 if (visual.partIndex == partIndex) return EquipmentVisualChange::Rejected;
629 }
630 for (auto& part : skinnedParts_) {
631 if (part.partIndex != partIndex) continue;
632 if (part.partName == partName && part.mesh == mesh && part.material == material &&
633 part.skin == skin)
635 part.partName = partName;
636 part.mesh = mesh;
637 part.material = material;
638 part.skin = skin;
639 part.cpuPositions.clear();
640 if (!renderable3d_) renderable3d_ = graphics::Renderable3D::create();
641 renderable3d_->setPart(partIndex, partName, mesh, material);
643 }
644 SkinnedPart part;
645 part.partIndex = partIndex;
646 part.partName = partName;
647 part.mesh = mesh;
648 part.material = material;
649 part.skin = skin;
650 skinnedParts_.push_back(std::move(part));
651 if (!renderable3d_) renderable3d_ = graphics::Renderable3D::create();
652 renderable3d_->setPart(partIndex, partName, mesh, material);
654}
655
657 const auto found = std::find_if(skinnedParts_.begin(), skinnedParts_.end(),
658 [&](const SkinnedPart& part) {
659 return part.partIndex == partIndex;
660 });
661 if (found == skinnedParts_.end()) return EquipmentVisualChange::Unchanged;
662 skinnedParts_.erase(found);
663 if (renderable3d_) renderable3d_->setPart(partIndex, {}, nullptr, nullptr);
665}
666
668 for (const auto& part : skinnedParts_) {
669 if (part.partIndex == partIndex) return part.updateMode;
670 }
671 for (const auto& visual : equipmentVisuals_) {
672 if (visual.partIndex == partIndex) return visual.updateMode;
673 }
675}
676
678 if (kind_ != "vroid" || name.empty() || !clip) return false;
679 motions_[name] = clip;
680 return true;
681}
682
683void AvatarInstance::setMotionBlendTime(float seconds) { motionBlendTime_ = std::max(0.f, seconds); }
684
686 applyRootMotion_ = enabled;
687 hasPreviousRoot_ = false;
688}
689
690// ---- image ----
691
692AvatarInstance::Layer *AvatarInstance::findLayer(const std::string &name) {
693 for (auto &L : layers_)
694 if (L.name == name) return &L;
695 return nullptr;
696}
697
698const AvatarInstance::Layer *AvatarInstance::findLayer(const std::string &name) const {
699 for (const auto &L : layers_)
700 if (L.name == name) return &L;
701 return nullptr;
702}
703
704bool AvatarInstance::addLayer(const std::string &name, graphics::Texture *texture, int zIndex) {
705 if (kind_ != "image" || name.empty() || findLayer(name)) return false;
706 Layer L;
707 L.name = name;
708 L.zIndex = zIndex;
709 L.entity = graphics::Renderable2D::create();
710 auto sp = L.entity->sprite();
711 sp->texture = texture;
712 // Layered portraits are UI-style artwork and retain their authored colors
713 // when the scene has no Camera2D ambient light configured.
714 sp->receiveLight = false;
715 if (texture && !texture->hasDeferredFilePixels()) {
716 sp->width = float(texture->getWidth());
717 sp->height = float(texture->getHeight());
718 }
719 layers_.push_back(L);
720 return true;
721}
722
724 Layer *L = findLayer(name);
725 if (!L) return false;
726 auto sp = L->entity->sprite();
727 sp->texture = texture;
728 if (texture && L->autoSize && !texture->hasDeferredFilePixels()) {
729 sp->width = float(texture->getWidth());
730 sp->height = float(texture->getHeight());
731 }
732 return true;
733}
734
735bool AvatarInstance::setLayerVisible(const std::string &name, bool visible) {
736 Layer *L = findLayer(name);
737 if (!L) return false;
738 L->visible = visible;
739 L->entity->sprite()->visible = visible_ && visible;
740 return true;
741}
742
743bool AvatarInstance::setLayerOffset(const std::string &name, float ox, float oy) {
744 Layer *L = findLayer(name);
745 if (!L) return false;
746 L->ox = ox;
747 L->oy = oy;
748 return true;
749}
750
751bool AvatarInstance::setLayerColor(const std::string &name, float r, float g, float b, float a) {
752 Layer *L = findLayer(name);
753 if (!L) return false;
754 L->entity->setColor(r, g, b, a);
755 return true;
756}
757
758bool AvatarInstance::setLayerZ(const std::string &name, int zIndex) {
759 Layer *L = findLayer(name);
760 if (!L) return false;
761 L->zIndex = zIndex;
762 return true;
763}
764
765bool AvatarInstance::setLayerSize(const std::string &name, float w, float h) {
766 Layer *L = findLayer(name);
767 if (!L) return false;
768 L->autoSize = false;
769 L->entity->setSize(w, h);
770 return true;
771}
772
773int AvatarInstance::getLayerCount() const { return int(layers_.size()); }
774
775std::string AvatarInstance::getLayerName(int index) const {
776 if (index < 0 || size_t(index) >= layers_.size()) return {};
777 return layers_[size_t(index)].name;
778}
779
780bool AvatarInstance::hasLayer(const std::string &name) const { return findLayer(name) != nullptr; }
781
783 Layer* L = findLayer(name);
784 return L ? L->entity : nullptr;
785}
786
787bool AvatarInstance::defineExpression(const std::string &name, const std::string &spec) {
788 if ((kind_ != "image" && kind_ != "vroid") || name.empty()) return false;
789 expressionDefs_[name] = spec;
790 return true;
791}
792
793bool AvatarInstance::applyExpressionSpec(const std::string &spec) {
794 if (spec.empty()) return true;
795 std::stringstream ss(spec);
796 std::string part;
797 while (std::getline(ss, part, ';')) {
798 part = trimCopy(part);
799 if (part.empty()) continue;
800 const auto eq = part.find('=');
801 if (eq == std::string::npos) continue;
802 const std::string key = trimCopy(part.substr(0, eq));
803 const std::string val = trimCopy(part.substr(eq + 1));
804 if (key.empty()) continue;
805
806 if (kind_ == "vroid") {
807 bool flag = false;
808 if (parseBoolish(val, flag)) {
809 setParameter(key, flag ? 1.f : 0.f);
810 } else {
811 char *end = nullptr;
812 const float f = std::strtof(val.c_str(), &end);
813 if (end && end != val.c_str())
815 else
816 setParameter(key, 1.f);
817 }
818 continue;
819 }
820
821 Layer *L = findLayer(key);
822 if (!L) {
823 // Unknown layer name still recorded as parameter for tooling.
824 setParameter(key, 1.f);
825 continue;
826 }
827 bool flag = false;
828 if (parseBoolish(val, flag)) {
829 L->visible = flag;
830 L->entity->sprite()->visible = visible_ && flag;
831 } else {
832 // Non-bool value: show layer and stash as parameter (texture swap by name).
833 L->visible = true;
834 L->entity->sprite()->visible = visible_;
835 setParameter(key, 1.f);
836 setParameter(key + ".variant", float(std::hash<std::string>{}(val) & 0xffff));
837 }
838 }
839 return true;
840}
841
842bool AvatarInstance::applyExpression(const std::string &name) {
843 if (vrm_) {
844 for (const auto& e : vrm_->document.expressions)
845 if (e.name == name) {
847 return true;
848 }
849 }
850 auto it = expressionDefs_.find(name);
851 if (it == expressionDefs_.end()) return false;
852 expressionBlendFrom_.clear();
853 expressionBlendTo_.clear();
854 expressionBlendDuration_ = 0.f;
855 expression_ = name;
856 const bool ok = applyExpressionSpec(it->second);
857 if (kind_ == "vroid") syncMorphWeightsToMesh();
858 return ok;
859}
860
861bool AvatarInstance::transitionExpression(const std::string& name, float duration) {
862 const auto definition = expressionDefs_.find(name);
863 if (definition == expressionDefs_.end()) return false;
864 if (duration <= 0.f) return applyExpression(name);
865
866 std::unordered_map<std::string, float> targets;
867 if (kind_ == "vroid" && boundMesh_ && boundMesh_->hasMorphData()) {
868 for (int i = 0; i < boundMesh_->getMorphCount(); ++i) targets[boundMesh_->getMorphName(i)] = 0.f;
869 }
870 std::stringstream stream(definition->second);
871 std::string part;
872 while (std::getline(stream, part, ';')) {
873 part = trimCopy(part);
874 const auto eq = part.find('=');
875 if (eq == std::string::npos) continue;
876 const std::string key = trimCopy(part.substr(0, eq));
877 const std::string value = trimCopy(part.substr(eq + 1));
878 if (key.empty()) continue;
879 bool flag = false;
880 if (parseBoolish(value, flag)) {
881 targets[key] = flag ? 1.f : 0.f;
882 continue;
883 }
884 char* end = nullptr;
885 const float numeric = std::strtof(value.c_str(), &end);
886 if (!end || end == value.c_str() || *end != '\0') return applyExpression(name);
887 targets[key] = numeric;
888 }
889 if (targets.empty()) return applyExpression(name);
890
891 expressionBlendFrom_.clear();
892 expressionBlendTo_ = std::move(targets);
893 for (const auto& [key, target] : expressionBlendTo_) {
894 (void)target;
895 if (kind_ == "image") {
896 const Layer* layer = findLayer(key);
897 expressionBlendFrom_[key] = layer ? layer->entity->sprite()->a : getParameter(key);
898 } else {
899 expressionBlendFrom_[key] = getParameter(key);
900 }
901 }
902 expression_ = name;
903 expressionBlendElapsed_ = 0.f;
904 expressionBlendDuration_ = duration;
905 return true;
906}
907
908void AvatarInstance::updateExpressionTransition(float dt) {
909 if (expressionBlendDuration_ <= 0.f || expressionBlendTo_.empty()) return;
910 expressionBlendElapsed_ += std::max(0.f, dt);
911 const float t = std::clamp(expressionBlendElapsed_ / expressionBlendDuration_, 0.f, 1.f);
912 for (const auto& [key, target] : expressionBlendTo_) {
913 const auto start = expressionBlendFrom_.find(key);
914 const float from = start == expressionBlendFrom_.end() ? getParameter(key) : start->second;
915 setParameter(key, from + (target - from) * t);
916 }
917 if (t >= 1.f) {
918 expressionBlendFrom_.clear();
919 expressionBlendTo_.clear();
920 expressionBlendDuration_ = 0.f;
921 }
922}
923
924void AvatarInstance::syncImageLayers() {
925 float parentX = 0.f, parentY = 0.f, parentRot = 0.f, parentSx = 1.f, parentSy = 1.f;
926 bool parentVisible = true;
927 if (sceneLinked_ && sceneAnchor2d_) {
928 auto anchorTf = sceneAnchor2d_->transform();
929 parentX = anchorTf->x;
930 parentY = anchorTf->y;
931 parentRot = anchorTf->rot;
932 parentSx = anchorTf->sx;
933 parentSy = anchorTf->sy;
934 parentVisible = sceneAnchor2d_->sprite()->visible;
935 }
936 const float parentRadians = parentRot * 3.14159265358979323846f / 180.f;
937 const float c = std::cos(parentRadians);
938 const float s = std::sin(parentRadians);
939 for (Layer &L : layers_) {
940 if (!L.entity) L.entity = graphics::Renderable2D::create();
941 auto tf = L.entity->transform();
942 auto sp = L.entity->sprite();
943 const float localX = (x_ + L.ox * sx_) * parentSx;
944 const float localY = (y_ + L.oy * sy_) * parentSy;
945 tf->x = parentX + c * localX - s * localY;
946 tf->y = parentY + s * localX + c * localY;
947 tf->rot = tf->rot - L.appliedParentRotation + parentRot;
948 L.appliedParentRotation = parentRot;
949 tf->sx = sx_ * parentSx;
950 tf->sy = sy_ * parentSy;
951 sp->layer = layer_ + L.zIndex;
952 sp->visible = parentVisible && visible_ && L.visible;
953 }
954}
955
956void AvatarInstance::destroyLayers() {
957 for (Layer &L : layers_) {
958 if (L.entity) {
959 ecs::DestroyEntity(L.entity);
960 L.entity = nullptr;
961 }
962 }
963 layers_.clear();
964}
965
966// ---- live2d ----
967
968bool AvatarInstance::loadLive2DModel(const std::string &path) {
969 if (kind_ != "live2d") return false;
970 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
971 if (!live2d_) return false;
972 return live2d_->loadModel(path);
973}
974
976 if (live2d_) return live2d_->getName();
978}
979
981 if (live2d_) return live2d_->isRuntimeAvailable();
983}
984
985void AvatarInstance::collectLive2DDrawItems(std::vector<graphics::DrawItem2D>& out) {
986 if (kind_ != "live2d" || !visible_) return;
987 if (!live2d_) live2d_ = Avatar::createLive2DBackend();
988 if (live2d_) live2d_->collectDrawItems(out);
989}
990
991} // namespace eve::avatar
double y
double x
LogicalId target
Duration start
LogicalId itemId
bool & active
float w
Definition AnimClip.cpp:738
float duration
const std::string & s
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< FieldTarget > targets
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec4 clip
double r
float v
std::int32_t second
std::int32_t c
int h
const ColourScope * parent
std::string from
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
OceanMeshSettings mesh
double dt
std::array< uint32_t, 16 > material
Texture * texture
TileLayer * layer
float f
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
float t
std::string slot
bool found
ScriptStructure out
size_t end
std::string kind
Share string attribute map operations through the Windows Foundation DLL.
bool visible
uint32_t index
double oy
double ox
Keyframed skeletal animation clip (local TRS tracks per bone). Script type: AnimClip.
Definition AnimClip.h:145
Ordered main-thread post-process stack with aim, limb IK and foot planting.
Combines a borrowed base pose source with ordered override/additive layers.
AnimSkeleton * getSkeleton() const override
Return the mixer skeleton. @ownership Borrowed @lifetime Valid while the owning animation object rema...
AnimPlayer * getBasePlayer() const
Return the base when it is an AnimPlayer; otherwise null. @ownership Borrowed @lifetime Valid while t...
Single-clip (or cross-fading) 3D animation player. Script type: AnimPlayer.
Definition AnimPlayer.h:33
AnimSkeleton * getSkeleton() const override
Borrowed pointer accessor. @ownership Borrowed @lifetime Valid while the owning animation object rema...
Definition AnimPlayer.h:47
void crossFade(AnimClip *clip, float blendSeconds)
Cross-fade to clip over blendSeconds (keeps sampling previous until done).
bool isPlaying() const noexcept
True when playing.
Definition AnimPlayer.h:80
void play(AnimClip *clip)
Play.
CPU linear-blend skinning binding for one mesh against an AnimSkeleton.
Definition AnimSkin.h:47
Clip-driven animation state machine with float/bool/trigger parameters and cross-fade transitions....
void setTrigger(const std::string &name)
Sets the trigger.
AnimSkeleton * getSkeleton() const override
Borrowed pointer accessor. @ownership Borrowed @lifetime Valid while the owning animation object rema...
World-space spring-chain solver that writes results as local bone rotations.
Paired-foot IK with contact smoothing and pelvis compensation.
void setScale(float sx, float sy)
Sets the scale.
void setExpression(const std::string &name)
Sets the expression.
bool bindAnimStateMachine(animation::AnimStateMachine *machine)
Bind an animation state machine that the avatar advances each update.
bool setLayerColor(const std::string &name, float r, float g, float b, float a)
Sets the layer color.
void setApplyRootMotion(bool enabled)
Apply root-bone X/Z deltas to the Avatar transform while animating.
bool setLayerOffset(const std::string &name, float ox, float oy)
Sets the layer offset.
EquipmentVisualChange addEquipmentLayerOcclusion(const std::string &outerLayer, const std::string &innerLayer)
Record that an equipped outer layer fully hides an inner layer.
void setLayer(int layer)
Sets the layer.
EquipmentVisualChange bindSkinnedPart(int partIndex, const std::string &partName, graphics::Mesh *mesh, graphics::Material *material, animation::AnimSkin *skin)
Bind an always-visible skinned mesh/material part to the shared Avatar pose.
EquipmentVisualChange unbindSkinnedPart(int partIndex)
Remove a shared-pose skinned part and clear its material slot.
float getParameter(const std::string &name) const
Returns the parameter.
bool registerMotion(const std::string &name, animation::AnimClip *clip)
Register a motion name for setMotion(); the clip is not owned.
bool bindAnimPlayer(animation::AnimPlayer *player)
Bind a clip player that the avatar advances and skins each update.
bool detachAttachment(const std::string &name)
Remove an attachment without destroying its Renderable3D.
~AvatarInstance()
Avatar instance.
bool hasLayer(const std::string &name) const
True when layer.
std::function< void(AvatarInstance *)> DestroyHook
Callback fired exactly once, when the instance is destroyed.
bool attachToBone(const std::string &name, const std::string &boneSemanticOrName, graphics::Renderable3D *renderable, float ox=0.f, float oy=0.f, float oz=0.f)
Attach a non-owned Renderable3D to a mapped humanoid semantic or bone name.
bool applyExpression(const std::string &name)
Applies expression.
EquipmentVisualChange bindEquipment(inventory::EquipmentSet *equipment)
Bind the authoritative equipment set whose visual projection this Avatar rebuilds.
std::string getParameterName(int index) const
Returns the parameter name.
graphics::Renderable2D * getLayerRenderable(const std::string &name)
Return the native Renderable2D owned by a named image layer.
std::string getEquipmentRenderStackItem(int index) const
Active item id at a render-stack index, or empty text.
void removeDestroyHook(size_t id)
Remove a previously registered destruction hook.
bool bindAnimLayerMixer(animation::AnimLayerMixer *mixer)
Bind an override/additive layer mixer that the avatar advances each update.
EquipmentVisualChange unbindEquipment()
Remove the equipment binding and hide all registered equipment visuals.
EquipmentVisualChange setEquipmentVisualLayer(const std::string &itemId, const std::string &equipmentSlot, const std::string &wearLayer, int withinLayerOrder=0)
Assign an item visual to a wear layer and a stable order inside that layer.
void setVisible(bool visible)
Sets the visible.
void update(float dt)
Updates .
int getEquipmentRenderStackCount() const
Number of active visuals in canonical back-to-front render order.
EquipmentVisualChange syncEquipmentAppearance()
Rebuild visuals from the current authoritative slots when their signature changed.
void setAnimConstraintStack(animation::AnimConstraintStack *stack)
Copy an IK/aim stack into Avatar-owned storage; null disables it.
int getLayerCount() const
Returns the layer count.
bool bindAnimSkin(animation::AnimSkin *skin)
Bind CPU skin data used to deform the avatar mesh from the active pose.
void setDynamicBoneSolver(animation::DynamicBoneSolver *solver)
Copy dynamic-bone configuration into Avatar-owned storage.
EquipmentVisualChange defineEquipmentVisual3D(const std::string &itemId, const std::string &equipmentSlot, graphics::Renderable3D *renderable, const std::string &boneSemanticOrName, float ox=0.f, float oy=0.f, float oz=0.f)
Map an item to a borrowed 3D renderable, optionally following a humanoid semantic/bone.
EquipmentVisualChange defineEquipmentVisual2D(const std::string &itemId, const std::string &equipmentSlot, const std::string &layerName, graphics::Texture *texture, int zIndex)
Map an item to a 2D Avatar layer. Texture is borrowed and must remain valid while registered.
size_t addDestroyHook(DestroyHook hook)
Register a destruction hook; returns an id usable with removeDestroyHook().
void setParameter(const std::string &name, float value)
Sets the parameter.
void collectLive2DDrawItems(std::vector< graphics::DrawItem2D > &out)
Append this instance's Live2D drawables to a shared draw queue.
bool transitionExpression(const std::string &name, float duration)
Blend numeric/bool expression channels over duration seconds.
std::string getLayerName(int index) const
Returns the layer name.
std::string getEquipmentVisualItem(const std::string &equipmentSlot) const
Return the currently projected item for a slot, or empty text when none is shown.
bool hasLive2DBackend() const
True when live 2 d backend.
std::string getEquipmentRenderStackLayer(int index) const
Wear-layer name at a render-stack index, or empty text.
void setPosition(float x, float y)
Sets the position.
void setMotion(const std::string &name)
Sets the motion.
AvatarInstance(std::string kind)
Avatar instance.
EquipmentVisualChange defineEquipmentLayer(const std::string &name, int order, const std::string &parent={})
Define a named back-to-front wear layer and its optional semantic parent.
bool loadLive2DModel(const std::string &path)
Loads live 2 d model.
bool setLayerZ(const std::string &name, int zIndex)
Sets the layer z.
int getParameterCount() const
Returns the parameter count.
void setMotionBlendTime(float seconds)
Set the cross-fade duration used when switching registered motions.
bool setLayerTexture(const std::string &name, graphics::Texture *texture)
Sets the layer texture.
bool addLayer(const std::string &name, graphics::Texture *texture, int zIndex)
Adds layer.
EquipmentVisualChange defineEquipmentSkinnedVisual3D(const std::string &itemId, const std::string &equipmentSlot, int partIndex, const std::string &partName, graphics::Mesh *mesh, graphics::Material *material, animation::AnimSkin *skin)
Map wearable equipment to a skinned mesh/material part sharing the Avatar pose.
std::string getLive2DBackendName() const
Returns the live 2 d backend name.
bool setLayerSize(const std::string &name, float w, float h)
Sets the layer size.
bool setLayerVisible(const std::string &name, bool visible)
Sets the layer visible.
bool hasParameter(const std::string &name) const
True when parameter.
void setFootIKSolver(animation::FootIKSolver *solver)
Copy paired-foot IK configuration into Avatar-owned storage; null disables it.
SkinnedPartUpdateMode getSkinnedPartUpdateMode(int partIndex) const
Return the latest GPU/CPU/unavailable update mode for a material slot.
bool defineExpression(const std::string &name, const std::string &spec)
Spec: "eyes=1;mouth=smile;blush=0" (semicolon-separated name=value).
static bool hasLive2DBackend()
True when the active backend is a real rendering runtime, not the null stub.
Definition Avatar.cpp:179
static std::string getLive2DBackendName()
Backend name currently in effect ("null" when using the built-in stub).
Definition Avatar.cpp:171
static ILive2DBackend * createLive2DBackend()
Always returns a backend: custom factory, else NullLive2DBackend.
Definition Avatar.cpp:166
virtual void setParameter(const std::string &name, float value)=0
Sets the parameter.
virtual void update(float dt)=0
Updates .
virtual void collectDrawItems(std::vector< graphics::DrawItem2D > &)
Optional: push drawables into the 2D queue. Default no-op.
virtual std::string getName() const =0
Returns the name.
virtual bool setMotion(const std::string &name)=0
Sets the motion.
virtual bool isRuntimeAvailable() const
True only for a backend that can render a real Live2D model.
virtual float getParameter(const std::string &name) const =0
Returns the parameter.
virtual bool loadModel(const std::string &path)=0
Loads model.
virtual bool setExpression(const std::string &name)=0
Sets the expression.
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
bool hasMorphData() const
True when morph data.
Definition Mesh.h:133
bool setMorphWeight(const std::string &name, float weight)
Sets the morph weight.
Definition Mesh.cpp:257
bool hasMorph(const std::string &name) const
True when morph.
Definition Mesh.cpp:253
int getMorphCount() const
Returns the morph count.
Definition Mesh.cpp:246
std::string getMorphName(int index) const
Returns the morph name.
Definition Mesh.cpp:248
Default renderable entity for declarative 2D sprites / solid quads.
EVENGINE_API_BACKENDS public API.
void setPartSortPriority(int index, int priority)
Override transparent sorting for one part without mutating its shared Material.
void setPart(int index, const std::string &name, Mesh *mesh, Material *material)
Bind a named mesh+material part (e.g. Assimp submesh / body region). index 0..kMaxParts-1....
void clearPartSortPriority(int index)
Clear a part's per-instance sort override and use its Material priority.
void setVisible(bool visible)
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
EVENGINE_API_FOUNDATION public API.
Definition Equipment.h:19
int getSlotInstanceId(const std::string &slotName) const
Returns the slot instance id.
Definition Equipment.cpp:62
std::string getSlotName(int index) const
Returns the slot name.
Definition Equipment.cpp:39
std::string getSlotItemId(const std::string &slotName) const
Returns the slot item id.
Definition Equipment.cpp:50
int getSlotCount() const
Returns the slot count.
Definition Equipment.cpp:37
EquipmentVisualChange
Outcome of changing or rebuilding the equipment appearance projection.
SkinnedPartUpdateMode
Observable backend selected for a shared-pose skinned part.
bool enabled