21#include <simplesquirrel/simplesquirrel.hpp>
30std::string floatToString(
double v) {
32 std::snprintf(buf,
sizeof(buf),
"%g",
v);
38 if (!converted.ok()) {
39 converted.ignore(
"Dialogue scalar compatibility adapter rejected the value");
43 if (
value.isNull() ||
value.isArray() ||
value.isObject())
return false;
50 if (!
vm ||
object.isEmpty())
return false;
52 if (!converted.ok()) {
53 converted.ignore(
"Dialogue data compatibility adapter rejected the value");
56 out = std::move(converted).takeValue();
60bool objectToVarParams(
HSQUIRRELVM vm,
const ssq::Object &
object,
61 std::unordered_map<std::string, Dialogue::VarValue> &
out) {
63 if (!
vm ||
object.isEmpty() ||
object.getType() != ssq::Type::TABLE)
return true;
65 if (!converted.ok()) {
66 converted.ignore(
"Dialogue parameter compatibility adapter rejected the table");
72 for (
const auto &[
key, field] : *
fields) {
81 pushed.ignore(
"Dialogue scalar compatibility adapter could not push the value");
86void pushVarTable(
HSQUIRRELVM vm,
const std::unordered_map<std::string, Dialogue::VarValue> &vars) {
91 pushed.ignore(
"Dialogue parameter compatibility adapter could not push the table");
96std::vector<Dialogue*>& liveDialogues() {
97 static std::vector<Dialogue*> instances;
118 default:
return false;
125 const char* stateKind()
const override {
return "dialogue"; }
127 Result<Value> capture()
override {
129 for (Dialogue*
d : liveDialogues()) {
131 if (!
d->captureState(sv))
133 arr.pushBack(std::move(sv));
138 Result<void> restore(
const Value &
value)
override {
144 const size_t n = std::min(in.arraySize(), liveDialogues().
size());
145 for (
size_t i = 0; i <
n; ++i) {
147 if (!liveDialogues()[i]->restoreState(in.at(i), &
error))
153 Result<void> resetToDefaults()
override {
154 for (Dialogue*
d : liveDialogues())
d->reset();
161 static DialogueStateProvider
provider;
162 eve::cap::addListener<eve::caps::IStateProvider>(&
provider);
169 liveDialogues().push_back(
this);
177 liveDialogues().erase(std::remove(liveDialogues().
begin(), liveDialogues().
end(),
this), liveDialogues().
end());
179 for (
auto &kv : predicates_) sq_release(vm_, &kv.second);
188std::unordered_map<std::string, Dialogue::VarValue> *Dialogue::varsForScope(
189 const std::string &
scope) {
190 if (
scope ==
"global")
return &globalVars_;
191 if (
scope ==
"scene")
return &sceneVars_;
195const std::unordered_map<std::string, Dialogue::VarValue> *Dialogue::varsForScope(
196 const std::string &
scope)
const {
197 if (
scope ==
"global")
return &globalVars_;
198 if (
scope ==
"scene")
return &sceneVars_;
203 const std::string &
scope) {
204 auto *
m = varsForScope(
scope);
205 if (!
m ||
name.empty())
return false;
211 if (!vm_)
return false;
212 const SQInteger
top = sq_gettop(vm_);
213 sq_pushobject(vm_,
value.getRaw());
215 const bool ok = squirrelToVarValueAt(vm_, -1,
v);
217 if (!
ok)
return false;
222 const auto *
m = varsForScope(
scope);
224 const auto it =
m->find(
name);
241 const std::string &
scope)
const {
250 const std::string &
scope)
const {
259 const std::string &
scope)
const {
265 const auto *
m = varsForScope(
scope);
266 return m &&
m->find(
name) !=
m->end();
270 auto *
m = varsForScope(
scope);
271 return m &&
m->erase(
name) > 0;
275 if (
scope ==
"global") {
277 }
else if (
scope ==
"scene") {
279 }
else if (
scope ==
"all") {
290 if (!vm_ ||
name.empty())
return false;
291 HSQOBJECT
raw =
fn.getRaw();
293 if (
raw._type != OT_CLOSURE &&
raw._type != OT_NATIVECLOSURE)
return false;
294 const auto it = predicates_.find(
name);
295 if (it != predicates_.end()) {
296 sq_release(vm_, &it->second);
297 predicates_.erase(it);
299 sq_addref(vm_, &
raw);
305 const auto it = predicates_.find(
name);
306 if (it == predicates_.end())
return false;
307 if (vm_) sq_release(vm_, &it->second);
308 predicates_.erase(it);
314 if (!objectToDataValue(vm_, table,
v))
return false;
318bool Dialogue::parseCondition(
const DataValue &
v, Condition &
out, std::string &
error) {
320 out.kind = Condition::Kind::All;
321 for (
size_t i = 0; i <
v.arraySize(); ++i) {
322 const auto &item =
v.at(i);
324 if (!parseCondition(item, child,
error))
return false;
325 out.children.push_back(std::move(child));
330 error =
"condition must be a table";
335 error =
"script condition name must be a string";
338 out.kind = Condition::Kind::Script;
344 error =
"all must be an array";
347 out.kind = Condition::Kind::All;
348 for (
size_t i = 0; i <
all->arraySize(); ++i) {
349 const auto &item =
all->at(i);
351 if (!parseCondition(item, child,
error))
return false;
352 out.children.push_back(std::move(child));
358 error =
"any must be an array";
361 out.kind = Condition::Kind::Any;
362 for (
size_t i = 0; i < any->arraySize(); ++i) {
363 const auto &item = any->at(i);
365 if (!parseCondition(item, child,
error))
return false;
366 out.children.push_back(std::move(child));
371 out.kind = Condition::Kind::Not;
372 out.children.emplace_back();
373 return parseCondition(*notc,
out.children.back(),
error);
378 error =
"var/op condition requires string var and op";
381 static const char *kOps[] = {
"eq",
"ne",
"gt",
"ge",
"lt",
"le",
"has",
"missing"};
382 const std::string opStr = op->
asString();
383 if (std::find(std::begin(kOps), std::end(kOps), opStr) == std::end(kOps)) {
384 error =
"unknown condition op: " + opStr;
387 out.kind = Condition::Kind::Cmp;
388 out.var = var->asString();
392 switch (val->kind()) {
403 error =
"unrecognized condition table";
408 if (
a.isNumeric() &&
b.isNumeric()) {
418bool Dialogue::compareOrder(
const std::string &op,
const VarValue &
a,
const VarValue &
b)
const {
419 if (!
a.isNumeric() || !
b.isNumeric())
return false;
422 if (op ==
"gt")
return x >
y;
423 if (op ==
"ge")
return x >=
y;
424 if (op ==
"lt")
return x <
y;
425 if (op ==
"le")
return x <=
y;
429bool Dialogue::evalConditionInternal(
const Condition &
c,
430 const std::unordered_map<std::string, VarValue> &merged,
431 const std::unordered_map<std::string, VarValue> &
params,
432 const std::string &lineId)
const {
434 case Condition::Kind::Always:
436 case Condition::Kind::Cmp: {
437 const auto it = merged.find(
c.var);
438 const bool present = it != merged.end();
440 if (
c.op ==
"missing")
return !
present;
442 if (
c.op ==
"eq")
return compareEq(it->second,
c.value);
443 if (
c.op ==
"ne")
return !compareEq(it->second,
c.value);
444 return compareOrder(
c.op, it->second,
c.value);
446 case Condition::Kind::All:
448 if (!evalConditionInternal(
child, merged,
params, lineId)) return false;
450 case Condition::Kind::Any:
452 if (evalConditionInternal(
child, merged,
params, lineId)) return true;
454 case Condition::Kind::Not:
455 return c.children.empty() ||
456 !evalConditionInternal(
c.children.front(), merged,
params, lineId);
457 case Condition::Kind::Script:
458 return evalScriptPredicate(
c.script, merged,
params, lineId);
466 if (!parseCondition(cond,
c,
error))
return false;
467 return evalConditionInternal(
c, mergedVars({}), {},
"");
470bool Dialogue::evalScriptPredicate(
const std::string &
name,
471 const std::unordered_map<std::string, VarValue> &merged,
472 const std::unordered_map<std::string, VarValue> &
params,
473 const std::string &lineId)
const {
474 if (!vm_)
return false;
475 const auto it = predicates_.find(
name);
476 if (it == predicates_.end())
return false;
478 const SQInteger
top = sq_gettop(vm_);
484 sq_pushobject(vm_, it->second);
485 sq_pushroottable(vm_);
488 sq_pushstring(vm_,
"vars", -1);
489 pushVarTable(vm_, merged);
490 sq_newslot(vm_, -3, SQFalse);
492 sq_pushstring(vm_,
"params", -1);
493 pushVarTable(vm_,
params);
494 sq_newslot(vm_, -3, SQFalse);
496 sq_pushstring(vm_,
"lineId", -1);
497 sq_pushstring(vm_, lineId.c_str(), lineId.size());
498 sq_newslot(vm_, -3, SQFalse);
500 const SQInteger paramCount = sq_gettop(vm_) -
top - 1;
501 if (SQ_FAILED(sq_call(vm_, paramCount, SQTrue, SQTrue))) {
506 if (SQ_FAILED(sq_getbool(vm_, -1, &
result))) {
520 if (!objectToDataValue(vm_, table,
root)) {
521 lastPoolsError_ =
"pools root must be a table";
527bool Dialogue::parseLineData(
const std::string &poolId,
const DataValue &
v,
int index, Line &
line,
528 std::string &
error) {
530 error =
"line must be a table";
535 if (
line.id.empty())
line.id = poolId +
"." + std::to_string(
index);
543 if (
line.text.empty() &&
line.i18nKey.empty()) {
544 error =
"line '" +
line.id +
"': text or i18n required";
550 line.weight = double(
w->asInt());
552 line.weight =
w->asDouble();
554 error =
"line '" +
line.id +
"': weight must be a number";
560 if (!parseCondition(*when,
line.when,
error)) {
568 error =
"line '" +
line.id +
"': meta must be a table";
572 for (
const auto &mkv : *
fields) {
574 switch (mkv.second.kind()) {
582 line.meta[mkv.first] = val;
588 error =
"line '" +
line.id +
"': tags must be an array";
591 for (
size_t i = 0; i <
tags->arraySize(); ++i) {
592 const auto &
t =
tags->at(i);
603int Dialogue::applyPoolsFromData(
const DataValue &
root,
bool replace) {
604 lastPoolsError_.clear();
606 lastPoolsError_ =
"pools root must be an object";
611 lastPoolsError_ =
"missing pools object";
616 std::vector<Pool> candidate = replace ? std::vector<Pool>{} : pools_;
618 for (
const auto &kv : *poolFields) {
622 lastPoolsError_ =
"pool '" + kv.first +
"': expected object";
627 pool.noRepeat = int(nr->asInt());
629 pool.noRepeat = int(nr->asDouble());
630 if (pool.noRepeat < 0) pool.noRepeat = 0;
634 lastPoolsError_ =
"pool '" + kv.first +
"': missing lines array";
638 for (
size_t i = 0; i <
lines->arraySize(); ++i) {
639 const auto &lv =
lines->at(i);
642 if (!parseLineData(pool.id, lv, lineIndex,
line,
error)) {
643 lastPoolsError_ =
error;
646 pool.lines.push_back(std::move(
line));
649 auto existing = std::find_if(candidate.begin(), candidate.end(),
650 [&](
const Pool& item) { return item.id == pool.id; });
651 if (existing != candidate.end()) *existing = std::move(pool);
652 else candidate.push_back(std::move(pool));
655 pools_ = std::move(candidate);
664 if (
index < 0 ||
size_t(
index) >= pools_.size())
return {};
665 return pools_[size_t(
index)].id;
670Dialogue::Pool *Dialogue::findPool(
const std::string &
id) {
671 for (
auto &
p : pools_)
672 if (
p.
id ==
id) return &
p;
676const Dialogue::Pool *Dialogue::findPool(
const std::string &
id)
const {
677 for (
const auto &
p : pools_)
678 if (
p.
id ==
id) return &
p;
682Dialogue::Line *Dialogue::findLine(
const std::string &
id) {
683 for (
auto &
p : pools_)
685 if (l.
id ==
id) return &l;
689const Dialogue::Line *Dialogue::findLine(
const std::string &
id)
const {
690 for (
const auto &
p : pools_)
691 for (const auto &l :
p.
lines)
692 if (l.
id ==
id) return &l;
700std::unordered_map<std::string, Dialogue::VarValue> Dialogue::mergedVars(
701 const std::unordered_map<std::string, VarValue> &
params)
const {
702 std::unordered_map<std::string, VarValue>
m = globalVars_;
703 for (
const auto &kv : sceneVars_)
m[kv.
first] = kv.
second;
708std::unordered_map<std::string, std::string> Dialogue::stringParams(
709 const std::unordered_map<std::string, VarValue> &vars)
const {
710 std::unordered_map<std::string, std::string>
out;
715std::string Dialogue::interpolate(
const std::string &tpl,
716 const std::unordered_map<std::string, VarValue> &vars)
const {
718 out.reserve(tpl.size());
719 for (
size_t i = 0; i < tpl.size();) {
721 const size_t close = tpl.find(
'}', i + 1);
722 if (close != std::string::npos) {
723 const std::string
name = tpl.substr(i + 1, close - i - 1);
724 const auto it = vars.find(
name);
725 if (it != vars.end()) {
726 out += it->second.toString();
741uint32_t Dialogue::nextRandom() {
742 uint32_t
x = rngState_;
750double Dialogue::nextUnit() {
return (nextRandom() & 0xFFFFFFu) / 16777216.0; }
753 rngState_ =
seed ? uint32_t(
seed) : 1u;
754 for (
auto &
p : pools_)
p.recent.clear();
758 std::unordered_map<std::string, VarValue>
p;
759 objectToVarParams(vm_,
params,
p);
764 const std::string &poolId,
const std::unordered_map<std::string, VarValue> &
params) {
765 Pool *pool = findPool(poolId);
766 if (!pool)
return "";
767 const auto merged = mergedVars(
params);
769 auto collect = [&](std::vector<size_t> &
out,
bool allowRecent) {
770 for (
size_t i = 0; i < pool->lines.size(); ++i) {
771 const Line &
line = pool->lines[i];
772 if (
line.weight <= 0.0)
continue;
773 if (!evalConditionInternal(
line.when, merged,
params,
line.id))
continue;
774 if (!allowRecent && pool->noRepeat > 0 &&
775 std::find(pool->recent.begin(), pool->recent.end(), i) != pool->recent.end())
787 for (
const size_t i :
candidates) total += pool->lines[i].weight;
788 double roll = nextUnit() * total;
792 acc += pool->lines[i].weight;
798 if (pool->noRepeat > 0) {
799 pool->recent.push_back(picked);
800 if (pool->recent.size() > size_t(pool->noRepeat)) pool->recent.erase(pool->recent.begin());
802 return pool->lines[picked].id;
806 std::unordered_map<std::string, VarValue>
p;
807 objectToVarParams(vm_,
params,
p);
812 const std::unordered_map<std::string, VarValue> &
params) {
813 Line *
line = findLine(lineId);
814 if (!
line)
return false;
815 const auto merged = mergedVars(
params);
818 if (!
line->text.empty()) {
819 text = interpolate(
line->text, merged);
821 auto *i18n = eve::ModuleManager::getInstance<eve::i18n::I18n>(
"I18n");
822 text = i18n ? i18n->getWithParams(
line->i18nKey, stringParams(merged)) :
line->i18nKey;
828 currentLineId_ =
line->id;
829 currentLineMeta_ =
line->meta;
830 currentLineTags_ =
line->tags;
831 applyLineMeta(*
line);
836 std::unordered_map<std::string, VarValue>
p;
837 objectToVarParams(vm_,
params,
p);
842 const std::unordered_map<std::string, VarValue> &
params) {
848 const auto it = currentLineMeta_.find(field);
849 return it == currentLineMeta_.end() ? std::string{} : it->second;
854void Dialogue::applyLineMeta(
const Line &
line) {
855 if (
line.speaker.empty())
return;
856 const auto expr =
line.meta.find(
"expression");
857 const auto motion =
line.meta.find(
"motion");
858 if (expr ==
line.meta.end() && motion ==
line.meta.end())
return;
859 Character *
c = findCharacter(
line.speaker);
860 if (!
c || !
c->avatar)
return;
861 if (expr !=
line.meta.end())
c->avatar->setExpression(expr->second);
862 if (motion !=
line.meta.end())
c->avatar->setMotion(motion->second);
869void Dialogue::pollSceneChange() {
870 auto *scn = eve::ModuleManager::getInstance<eve::scene::Scene>(
"Scene");
874 if (!
name.empty() &&
name != lastSceneName_) sceneVars_.clear();
875 if (!
name.empty()) lastSceneName_ =
name;
878Dialogue::Character *Dialogue::findCharacter(
const std::string &
id) {
879 for (
auto &
c : characters_)
880 if (
c.
id ==
id) return &
c;
884const Dialogue::Character *Dialogue::findCharacter(
const std::string &
id)
const {
885 for (
const auto &
c : characters_)
886 if (
c.
id ==
id) return &
c;
891 if (
id.empty())
return false;
892 if (
auto *
c = findCharacter(
id)) {
893 c->displayName = displayName.empty() ?
id : displayName;
898 c.displayName = displayName.empty() ?
id : displayName;
899 characters_.push_back(
c);
906 const Character *
c = findCharacter(
id);
907 return c ?
c->displayName : std::string{};
911 Character *
c = findCharacter(
id);
912 if (!
c)
return false;
915 if (
c->avatar &&
c->avatarHook) {
916 c->avatar->removeDestroyHook(*
c->avatarHook);
917 c->avatarHook.reset();
922 if (Character *ch = findCharacter(
key))
923 ch->avatar =
nullptr;
930 const Character *
c = findCharacter(
id);
931 return c ?
c->avatar :
nullptr;
937 if (
index < 0 ||
size_t(
index) >= characters_.size())
return {};
938 return characters_[size_t(
index)].id;
942 Character *
c = findCharacter(
id);
943 if (!
c)
return false;
945 c->slot =
slot.empty() ?
"center" :
slot;
946 if (
c->avatar)
c->avatar->setVisible(
true);
951 Character *
c = findCharacter(
id);
952 if (!
c)
return false;
954 if (
c->avatar)
c->avatar->setVisible(
false);
959 const Character *
c = findCharacter(
id);
960 return c &&
c->shown;
964 const Character *
c = findCharacter(
id);
965 return c ?
c->slot : std::string{};
969 if (
slot.empty())
return;
970 slotX_[
slot] = xNorm;
974 auto it = slotX_.find(
slot);
975 if (it != slotX_.end())
return it->second;
976 if (
slot ==
"left")
return 0.25f;
977 if (
slot ==
"right")
return 0.75f;
978 if (
slot ==
"center")
return 0.5f;
983 Character *
c = findCharacter(
id);
984 if (!
c || !
c->avatar)
return false;
985 c->avatar->setExpression(expression);
990 Character *
c = findCharacter(
id);
991 if (!
c || !
c->avatar)
return false;
992 c->avatar->setMotion(motion);
998 for (Character &
c : characters_) {
999 if (!
c.avatar)
continue;
1000 c.avatar->setVisible(
c.shown);
1006 const float x = xn * stageWidth;
1008 c.avatar->setPosition(
x,
c.avatar->getY());
1013void Dialogue::beginLine(
const std::string &speakerId,
const std::string &
text) {
1014 speakerId_ = speakerId;
1017 selectedChoiceId_.clear();
1019 if (typeSpeed_ <= 0.f) {
1021 phase_ = Phase::WaitingAdvance;
1022 lipSyncValue_ = 0.f;
1024 phase_ = Phase::Typing;
1029 beginLine(speakerId,
text);
1037 if (phase_ == Phase::Typing) {
1039 phase_ = Phase::WaitingAdvance;
1050 if (phase_ == Phase::Typing) {
1054 if (phase_ == Phase::WaitingAdvance) phase_ = Phase::Idle;
1058 if (speakerId_.empty())
return {};
1063 if (fullText_.empty())
return {};
1065 size_t n = size_t(std::floor(typed_ + 1e-4f));
1066 if (
n == 0)
return {};
1067 if (
n >= total)
return fullText_;
1077 case Phase::WaitingAdvance:
1078 return "waiting_advance";
1079 case Phase::WaitingChoice:
1080 return "waiting_choice";
1087 selectedChoiceId_.clear();
1091 if (
id.empty())
return false;
1092 for (
auto &ch : choices_) {
1098 choices_.push_back(Choice{
id,
label});
1103 if (choices_.empty()) {
1104 phase_ = Phase::Idle;
1108 phase_ = Phase::WaitingChoice;
1116 if (
index < 0 ||
size_t(
index) >= choices_.size())
return {};
1117 return choices_[size_t(
index)].id;
1121 if (
index < 0 ||
size_t(
index) >= choices_.size())
return {};
1122 return choices_[size_t(
index)].label;
1126 if (phase_ != Phase::WaitingChoice)
return false;
1127 if (
index < 0 ||
size_t(
index) >= choices_.size())
return false;
1128 selectedChoiceId_ = choices_[size_t(
index)].id;
1129 phase_ = Phase::Idle;
1136 if (!
name.empty()) lipSyncParameter_ =
name;
1140 if (amplitude < 0.f) amplitude = 0.f;
1141 if (amplitude > 2.f) amplitude = 2.f;
1142 lipSyncAmplitude_ = amplitude;
1145void Dialogue::updateLipSync(
float dt) {
1146 if (
dt < 0.f)
dt = 0.f;
1147 if (lipSyncEnabled_ && phase_ == Phase::Typing && !speakerId_.empty()) {
1150 const float wave = std::fabs(std::sin(lipSyncTime_ * 14.f));
1151 lipSyncValue_ = lipSyncAmplitude_ * (0.25f + 0.75f * wave);
1154 lipSyncValue_ *= std::max(0.f, 1.f -
dt * 8.f);
1155 if (lipSyncValue_ < 0.01f) lipSyncValue_ = 0.f;
1157 applyLipSyncToSpeaker();
1160void Dialogue::applyLipSyncToSpeaker() {
1161 if (!lipSyncEnabled_ || speakerId_.empty() || lipSyncParameter_.empty())
return;
1163 if (!
c || !
c->avatar)
return;
1164 c->avatar->setParameter(lipSyncParameter_, lipSyncValue_);
1168 if (
dt < 0.f)
dt = 0.f;
1169 if (phase_ == Phase::Typing) {
1171 typed_ += typeSpeed_ *
dt;
1172 if (typed_ >= total) {
1174 phase_ = Phase::WaitingAdvance;
1182 phase_ = Phase::Idle;
1187 selectedChoiceId_.clear();
1188 lipSyncValue_ = 0.f;
1190 currentLineId_.clear();
1191 currentLineMeta_.clear();
1192 currentLineTags_.clear();
1193 for (Character &
c : characters_) {
1195 if (
c.avatar)
c.avatar->setVisible(
false);
1214 for (
const auto& kv : globalVars_)
global.set(kv.first, varValueToState(kv.second));
1215 out.set(
"globalVars", std::move(
global));
1218 for (
const auto& kv : sceneVars_)
scene.set(kv.first, varValueToState(kv.second));
1219 out.set(
"sceneVars", std::move(
scene));
1222 for (
const auto&
c : choices_) {
1226 choices.pushBack(std::move(item));
1231 for (
const auto&
c : characters_) {
1239 out.set(
"characters", std::move(chars));
1243 out.set(
"slotX", std::move(slotX));
1249 if (err) *err =
"dialogue: state is not an object";
1254 if (err) *err =
"dialogue: missing phase";
1257 const std::string phaseName =
phase->asString();
1258 if (phaseName ==
"idle")
1259 phase_ = Phase::Idle;
1260 else if (phaseName ==
"typing")
1261 phase_ = Phase::Typing;
1262 else if (phaseName ==
"waiting_advance")
1263 phase_ = Phase::WaitingAdvance;
1264 else if (phaseName ==
"waiting_choice")
1265 phase_ = Phase::WaitingChoice;
1267 if (err) *err =
"dialogue: unknown phase '" + phaseName +
"'";
1271 if (
const StateValue*
v = in.
find(
"speakerId");
v &&
v->isString()) speakerId_ =
v->asString();
1274 typed_ =
static_cast<float>(
v->isInt() ? double(
v->asInt()) :
v->asDouble());
1276 typeSpeed_ =
static_cast<float>(
v->isInt() ? double(
v->asInt()) :
v->asDouble());
1279 if (
const StateValue*
v = in.
find(
"lipSyncAmplitude");
v && (
v->isInt() ||
v->isFloat()))
1280 lipSyncAmplitude_ =
static_cast<float>(
v->isInt() ? double(
v->asInt()) :
v->asDouble());
1281 if (
const StateValue*
v = in.
find(
"rngState");
v &&
v->
isInt()) rngState_ =
static_cast<uint32_t
>(
v->asInt());
1285 globalVars_.clear();
1287 for (
const auto&
key : vars->keys()) {
1289 if (stateToVarValue(*vars->find(
key), val)) globalVars_[
key] = val;
1294 for (
const auto&
key : vars->keys()) {
1296 if (stateToVarValue(*vars->find(
key), val)) sceneVars_[
key] = val;
1302 for (
size_t i = 0; i <
choices->arraySize(); ++i) {
1306 if (
id &&
id->isString() &&
label &&
label->isString()) {
1307 choices_.push_back(Choice{
id->asString(),
label->asString()});
1313 for (
size_t i = 0; i < chars->arraySize(); ++i) {
1316 if (!
id || !
id->isString())
continue;
1317 Character *
c = findCharacter(
id->asString());
1319 characters_.push_back(Character{});
1320 c = &characters_.back();
1321 c->id =
id->asString();
1323 c->displayName =
name->asString();
1326 c->slot =
slot->asString();
1328 c->shown = shown->asBool();
1329 if (
c->avatar)
c->avatar->setVisible(
c->shown);
1336 for (
const auto &
key :
slots->keys()) {
1338 if (
v && (
v->isInt() ||
v->isFloat()))
1339 slotX_[
key] =
static_cast<float>(
v->isInt() ? double(
v->asInt()) :
v->asDouble());
1350void Dialogue::expose(ssq::Table &table) {
1351 if (
Dialogue *self = Dialogue::create()) self->vm_ = table.getHandle();
1352 auto cls = table.addClass(
name, Dialogue::create,
false);
1356void Dialogue::expose(ssq::Class &
cls) {
struct SQVM * HSQUIRRELVM
std::vector< std::string > fields
std::set< std::string > choices
#define Module_IMPL(ModuleName, newExpr)
std::weak_ptr< PrimitiveScene > scene
ScriptProviderHandle provider
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
The single Squirrel projection for common Result, Status and Value.
让脚本扮演 IStateQuery / IStateMutation(阶段 5 的第五、六个插座)。
Share string attribute map operations through the Windows Foundation DLL.
std::vector< std::string_view > lines
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
virtual std::string getName() const =0
Returns the name.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
JSON-compatible state value tree used by state hot reload.
static StateValue object()
Empty object.
static StateValue boolean(bool v)
Boolean value.
static StateValue array()
Empty array.
static StateValue integer(int64_t v)
Integer value.
void pushBack(StateValue v)
Append an element; only valid on arrays.
static StateValue number(double v)
Floating-point value.
const StateValue * find(const std::string &key) const
Look up key; nullptr when absent.
static StateValue null()
Null value.
StateValue & at(size_t index)
Indexed element (bounds-checked); only valid on arrays.
static StateValue string(std::string v)
String value.
void set(const std::string &key, StateValue v)
Insert or replace key; only valid on objects.
The canonical owning dynamic value used by data-facing protocols.
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
std::string typeName() const
Return the compatibility type name used by dialogue scripts.
std::map< std::string, Value > Object
static Value number(double value)
Compatibility factory for a Double value.
static Value string(std::string value)
Compatibility factory for a string value.
@ Int
Compatibility spelling used by the former dialogue value.
@ Float
Compatibility spelling used by the former dialogue value.
std::vector< Value > Array
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
static Value boolean(bool value)
Compatibility factory for a boolean value.
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Unified avatar instance. Kind is a string: "image" | "live2d" | "vroid". Script-facing API avoids ove...
size_t addDestroyHook(DestroyHook hook)
Register a destruction hook; returns an id usable with removeDestroyHook().
Runtime-state serialization for state hot reload.
Visual-novel style dialogue stage. Script: dlg <- eve.Dialogue();
std::string pickLineWithParams(const std::string &poolId, const std::unordered_map< std::string, VarValue > ¶ms)
Pick line with params.
bool setExpression(const std::string &id, const std::string &expression)
Sets the expression.
bool setMotion(const std::string &id, const std::string &motion)
Sets the motion.
std::string getSpeakerName() const
Returns the speaker name.
void presentChoices()
Present choices.
std::string getLastPoolsError() const
Returns the last pools error.
float getLipSyncAmplitude() const
Returns the lip sync amplitude.
bool clearVar(const std::string &name, const std::string &scope)
Clears var.
bool playLineWithParams(const std::string &lineId, const std::unordered_map< std::string, VarValue > ¶ms)
Play line with params.
std::string getSpeakerId() const
Returns the speaker id.
int getCharacterCount() const
Returns the character count.
bool captureState(StateValue &out) const
Serialize conversation state (vars, rng, phase, choices, stage).
bool restoreState(const StateValue &in, std::string *err=nullptr)
Restore conversation state captured by captureState().
std::string getCurrentLineMeta(const std::string &field) const
Returns the current line meta.
float getSlotX(const std::string &slot) const
Returns the slot x.
bool isIdle() const
True when idle.
bool evalCondition(ssq::Object table)
Eval condition.
std::string getCurrentLineId() const
Returns the current line id.
std::string getFullText() const
Returns the full text.
bool getVarBool(const std::string &name, bool defaultValue, const std::string &scope) const
Returns the var bool.
bool registerCharacter(const std::string &id, const std::string &displayName)
角色:注册 / 查询 / 绑定 Avatar。
bool playPool(const std::string &poolId, ssq::Object params)
Play pool.
std::vector< std::string > getCurrentLineTags() const
Returns the current line tags.
bool playLine(const std::string &lineId, ssq::Object params)
Play line.
void narrate(const std::string &text)
Narrate.
int loadPoolsFromData(const DataValue &root)
Loads pools from data.
void clearChoices()
选项:清空/添加/展示与选择。
int replacePoolsFromData(const DataValue &root)
Atomically replace all pools from a validated unified dnut workspace.
bool isTyping() const
True when typing.
int getPoolCount() const
Returns the pool count.
bool setVar(const std::string &name, ssq::Object value, const std::string &scope)
Sets the var.
bool selectChoice(int index)
Select choice.
bool hasCharacter(const std::string &id) const
True when character.
std::string getCharacterId(int index) const
Returns the character id.
void setLipSyncParameter(const std::string &name)
Sets the lip sync parameter.
bool addChoice(const std::string &id, const std::string &label)
Adds choice.
VarValue getVarValue(const std::string &name, const std::string &scope) const
Returns the var value.
bool show(const std::string &id, const std::string &slot)
舞台:显示/隐藏角色、槽位与表情/动作。
void setTypeSpeed(float charsPerSecond)
Sets the type speed.
float getVarFloat(const std::string &name, float defaultValue, const std::string &scope) const
Returns the var float.
int loadPoolsFromTable(ssq::Object table)
Loads pools from table.
bool hasPool(const std::string &id) const
True when pool.
std::string getChoiceId(int index) const
Returns the choice id.
avatar::AvatarInstance * getAvatar(const std::string &id) const
Returns the avatar.
bool playPoolWithParams(const std::string &poolId, const std::unordered_map< std::string, VarValue > ¶ms)
Play pool with params.
bool unregisterCondition(const std::string &name)
Unregisters condition.
void skipTyping()
Skip typing.
void update(float dt)
推进打字机 / 口型同步 / 阶段机;每帧调用。
void say(const std::string &speakerId, const std::string &text)
台词:说话/旁白、打字机效果与推进。
bool evalConditionData(const DataValue &cond)
Eval condition data.
bool isWaitingChoice() const
True when waiting choice.
float getLipSyncValue() const
Returns the lip sync value.
std::string pickLine(const std::string &poolId, ssq::Object params)
Pick line.
std::string getChoiceLabel(int index) const
Returns the choice label.
bool bindAvatar(const std::string &id, avatar::AvatarInstance *av)
Binds avatar.
void setRandomSeed(int seed)
Sets the random seed.
bool resetToDefaults()
Reset stage and line state (restore fallback).
std::string getVarType(const std::string &name, const std::string &scope) const
Returns the var type.
void setSlotX(const std::string &slot, float xNorm)
Sets the slot x.
bool registerCondition(const std::string &name, ssq::Object fn)
Registers condition.
std::string getVarString(const std::string &name, const std::string &defaultValue, const std::string &scope) const
Returns the var string.
int getRandomSeed() const
Returns the random seed.
bool isShown(const std::string &id) const
True when shown.
std::string getLipSyncParameter() const
Returns the lip sync parameter.
void syncStage(float stageWidth, float stageHeight)
Synchronizes stage.
bool setVarValue(const std::string &name, const VarValue &value, const std::string &scope)
Sets the var value.
~Dialogue() override
Dialogue.
std::string getSlot(const std::string &id) const
Returns the slot.
int getChoiceCount() const
Returns the choice count.
void setLipSyncEnabled(bool enabled)
口型同步:打字时驱动说话者 Avatar 参数。
std::string getSelectedChoiceId() const
Returns the selected choice id.
int getVarInt(const std::string &name, int defaultValue, const std::string &scope) const
Returns the var int.
void setLipSyncAmplitude(float amplitude)
Sets the lip sync amplitude.
std::string getPoolId(int index) const
Returns the pool id.
bool hide(const std::string &id)
Hide.
void clearVars(const std::string &scope)
Clears vars.
bool isWaitingAdvance() const
True when waiting advance.
bool isLipSyncEnabled() const
True when lip sync enabled.
std::string getDisplayName(const std::string &id) const
Returns the display name.
std::string getVisibleText() const
Returns the visible text.
float getTypeSpeed() const
Returns the type speed.
void clearPools()
Clears pools.
bool hasVar(const std::string &name, const std::string &scope) const
True when var.
std::string getPhase() const
Returns the phase.
bool isObject() const
True when object.
bool isArray() const
True when array.
bool isNull() const
True when null.
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
const std::string & getName()
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
EVENGINE_API_ORCHESTRATION void withdrawScriptStateQuerySeam()
撤回 IStateQuery 接缝与仍然在位的脚本适配器。
EVENGINE_API_ORCHESTRATION void declareScriptStateQuerySeam()
声明"`IStateQuery` 可以由脚本提供"这条接缝。
EVENGINE_API_ORCHESTRATION void withdrawScriptStateMutationSeam()
撤回 IStateMutation 接缝与仍然在位的脚本适配器。
eve::Value DataValue
Canonical data value used by dialogue pools, conditions and scripts.
EVENGINE_API_ORCHESTRATION void declareScriptStateMutationSeam()
声明"`IStateMutation` 可以由脚本提供"这条接缝。
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
Result< void > pushValue(HSQUIRRELVM vm, const Value &value, const SquirrelValueOptions &options)
Push a canonical Value into the active Squirrel VM.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
StateValue toLegacyStateValue(const Value &value)
Project a canonical value into the legacy reload snapshot format.
Value toCanonicalStateValue(const StateValue &value)
Copy a legacy reload tree into the canonical owning value protocol.
size_t utf8_codepoint_count(const std::string &s)
Count UTF-8 code points in a string. Invalid / truncated sequences stop the scan.
size_t utf8_byte_offset_for_codepoints(const std::string &s, size_t codepoints)
Byte offset of the N-th UTF-8 code point (0-based count of code points). Returns s....
SettlementPipeline::Stage fn