载入中...
搜索中...
未找到
Card.cpp
浏览该文件的文档.
1#include "card/Card.h"
2#include <glm/geometric.hpp>
3#include <glm/vec3.hpp>
5#include "card/CardControl.h"
7
8#include <cmath>
9
10#include "common/Json.h"
11#include "common/SubjectRef.h"
13#include "graphics/Graphics.h"
14
15#include <simplesquirrel/simplesquirrel.hpp>
16#include <squirrel.h>
17
18#include <algorithm>
19#include <cstdint>
20#include <utility>
21
22namespace eve::card {
23
25
26void CardPlaneMapper::setLogicalRect(float x, float y, float width, float height) {
27 logicalX_ = x;
28 logicalY_ = y;
29 logicalWidth_ = width;
30 logicalHeight_ = height;
31}
32
33void CardPlaneMapper::setPlane(float ox, float oy, float oz, float ux, float uy, float uz,
34 float vx, float vy, float vz) {
35 origin_ = glm::vec3(ox, oy, oz);
36 axisU_ = glm::vec3(ux, uy, uz);
37 axisV_ = glm::vec3(vx, vy, vz);
38}
39
40bool CardPlaneMapper::mapRay(float ox, float oy, float oz, float dx, float dy, float dz) {
41 const glm::vec3 normal = glm::cross(axisU_, axisV_);
42 const glm::vec3 direction(dx, dy, dz);
43 const float denominator = glm::dot(normal, direction);
44 if (std::abs(denominator) < 1e-6f) return false;
45 const float t = glm::dot(normal, origin_ - glm::vec3(ox, oy, oz)) / denominator;
46 if (t < 0.f) return false;
47 resultWorld_ = glm::vec3(ox, oy, oz) + direction * t;
48 const glm::vec3 relative = resultWorld_ - origin_;
49 const float uu = glm::dot(axisU_, axisU_);
50 const float uv = glm::dot(axisU_, axisV_);
51 const float vv = glm::dot(axisV_, axisV_);
52 const float determinant = uu * vv - uv * uv;
53 if (std::abs(determinant) < 1e-8f || logicalWidth_ == 0.f || logicalHeight_ == 0.f)
54 return false;
55 const float wu = glm::dot(relative, axisU_);
56 const float wv = glm::dot(relative, axisV_);
57 const float u = (wu * vv - wv * uv) / determinant;
58 const float v = (wv * uu - wu * uv) / determinant;
59 resultLogicalX_ = logicalX_ + u * logicalWidth_;
60 resultLogicalY_ = logicalY_ + v * logicalHeight_;
61 return true;
62}
63
64bool CardPlaneMapper::mapLayout(float x, float y) {
65 if (logicalWidth_ == 0.f || logicalHeight_ == 0.f) return false;
66 const float u = (x - logicalX_) / logicalWidth_;
67 const float v = (y - logicalY_) / logicalHeight_;
68 resultLogicalX_ = x;
69 resultLogicalY_ = y;
70 resultWorld_ = origin_ + axisU_ * u + axisV_ * v;
71 return true;
72}
73
74eve::Result<void> CardPlaneMapper::mapCardPose(float x, float y, float layoutAngleDeg, float flipProgress,
75 float liftPeak, int flipAxis) {
76 if (!mapLayout(x, y)) {
78 eve::DiagnosticCode::InvalidArgument, "card plane mapper logical rect is degenerate", "card.planeMapper"));
79 }
80 const CardFlipPose pose = evaluateCardFlip(flipProgress, liftPeak);
81 resultShowingFront_ = pose.showingFront;
82
83 glm::vec3 u = axisU_;
84 glm::vec3 v = axisV_;
85 const float uLen = glm::length(u);
86 const float vLen = glm::length(v);
87 if (uLen < 1e-8f || vLen < 1e-8f) {
89 eve::DiagnosticCode::InvalidArgument, "card plane mapper axes are degenerate", "card.planeMapper"));
90 }
91 u *= (1.f / uLen);
92 v *= (1.f / vLen);
93 glm::vec3 n = glm::normalize(glm::cross(u, v));
94 v = glm::normalize(v - u * glm::dot(v, u));
95 n = glm::normalize(glm::cross(u, v));
96
97 const float layoutRad = layoutAngleDeg * 3.14159265358979323846f / 180.f;
98 const float lc = std::cos(layoutRad);
99 const float ls = std::sin(layoutRad);
100 const glm::vec3 laidU = u * lc + v * ls;
101 const glm::vec3 laidV = v * lc - u * ls;
102
103 const float fc = std::cos(pose.angleRadians);
104 const float fs = std::sin(pose.angleRadians);
105 if (flipAxis == 1) {
106 resultBasisU_ = laidU;
107 resultBasisV_ = laidV * fc + n * fs;
108 resultBasisN_ = n * fc - laidV * fs;
109 } else {
110 resultBasisV_ = laidV;
111 resultBasisU_ = laidU * fc + n * fs;
112 resultBasisN_ = n * fc - laidU * fs;
113 }
114 resultWorld_ = resultWorld_ + n * pose.lift;
116}
117
118namespace {
120
121using eve::json::Value;
122
123bool parseDefinition(Value o, std::unordered_map<std::string, CardDefinition> &defs) {
124 std::string id = o.getString("id");
125 if (id.empty()) return false;
126 CardDefinition def;
127 def.id = id;
128 def.name = o.getString("name", id);
129 def.kind = o.getString("kind", "creature");
130 def.cost = o.getInt("cost");
131 def.attack = o.getInt("attack");
132 def.health = o.getInt("health");
133 def.tags = o.getStringArray("tags");
134 auto tint = o.getFloatArray("tint");
135 if (tint.size() >= 3) def.tint = glm::vec3(tint[0], tint[1], tint[2]);
136 defs[id] = def;
137 return true;
138}
139
140template <typename T>
141T *resolve(const ecs::EntityHandle &h) {
142 return static_cast<T *>(ecs::try_get(h));
143}
144
145void destroyHandles(std::vector<ecs::EntityHandle> &hs) {
146 for (auto &h : hs) {
147 if (ecs::Entity *e = ecs::try_get(h)) ecs::DestroyEntity(e);
148 }
149 hs.clear();
150}
151
152template <typename T>
153void registerCppEntityClassForScript(const ssq::Class &cls) {
154 eve::registerCppEntityView(cls, [](ssq::Array &out) {
155 HSQUIRRELVM vm = out.getHandle();
156 sq_pushobject(vm, out.getRaw());
157 ecs::Table *table = ecs::current();
158 if (table == nullptr) {
159 sq_pop(vm, 1);
160 return;
161 }
162 ecs::IComponentManager &cm = table->getOrCreateManager<T>();
163 auto *reg = cm.getOrCreateRegistryComponentBuffer<T>();
164 std::vector<ecs::IComponentBuffer *> stack;
165 stack.push_back(reg);
166 while (!stack.empty()) {
167 ecs::IComponentBuffer *buf = stack.back();
168 stack.pop_back();
169 auto *r = dynamic_cast<ecs::IRegistryComponentBuffer *>(buf);
170 if (r != nullptr) {
171 for (uint32_t i = 0; i < r->entity_count(); ++i) {
172 ecs::Entity *ent = r->entity_at(i);
173 if (ent != nullptr && ecs::is_entity_visible(ent)) {
174 ssq::detail::pushByPtr<T>(vm, static_cast<T *>(ent));
175 sq_arrayappend(vm, -2);
176 }
177 }
178 }
179 if (buf->children != nullptr) stack.push_back(buf->children);
180 if (buf->next != nullptr) stack.push_back(buf->next);
181 }
182 sq_pop(vm, 1);
183 });
184}
185
186} // namespace
187
188Card::Card() = default;
189
190Card::Card(Card &&) noexcept = default;
191Card &Card::operator=(Card &&) noexcept = default;
192
194 clearGameplayControls();
195 destroyHandles(hands_);
196 destroyHandles(decks_);
197 destroyHandles(zones_);
198 destroyHandles(cards_);
199 activeDeck_ = nullptr;
200 activeConfig_ = nullptr;
201}
202
203eve::Result<void> Card::publishGameplay(const std::string &instanceId, const std::string &ownerId, Hand *hand,
205 if (instanceId.empty() || ownerId.empty() || hand == nullptr)
208 "publishGameplay needs an instance id, an owner id and a hand", "instanceId"));
209 const auto instance = eve::PersistentId::parse(instanceId);
210 const auto owner = eve::PersistentId::parse(ownerId);
211 if (!instance.has_value() || !owner.has_value())
214 "instance and owner ids must be canonical persistent ids", "instanceId"));
215 if (!gameplay_) gameplay_ = std::make_unique<CardControl>(*this);
216 return gameplay_->publish(eve::SubjectRef::fromPersistentId(*instance), eve::SubjectRef::fromPersistentId(*owner),
217 *hand, account);
218}
219
221 if (!gameplay_)
223 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "no card instance is published", "instanceId"));
224 const auto instance = eve::PersistentId::parse(instanceId);
225 if (!instance.has_value())
227 eve::DiagnosticCode::InvalidArgument, "the instance id must be a canonical persistent id", "instanceId"));
228 return gameplay_->unpublish(eve::SubjectRef::fromPersistentId(*instance));
229}
230
232 if (gameplay_) gameplay_->clear();
233}
234
235int Card::gameplayControlCount() const { return gameplay_ ? gameplay_->count() : 0; }
236
237std::vector<std::string> Card::gameplayInstances() const {
238 std::vector<std::string> result;
239 if (!gameplay_) return result;
240 for (const auto &instance : gameplay_->instances()) result.push_back(instance.format());
241 return result;
242}
243
244// ---------------------------------------------------------------------------
245// 卡牌类型定义
246// ---------------------------------------------------------------------------
247
248int Card::registerCardsFromJson(const std::string &json) {
250 if (!doc.valid()) return 0;
251 const Value root = doc.root();
252 int n = 0;
253 if (root.isArray()) {
254 for (size_t i = 0; i < root.size(); ++i)
255 if (parseDefinition(root.at(i), defs_)) ++n;
256 } else if (root.isObject()) {
257 if (parseDefinition(root, defs_)) ++n;
258 }
259 if (n > 0) definitionViewDirty_ = true;
260 return n;
261}
262
264 defs_.clear();
265 definitionView_.clear();
266 definitionViewDirty_ = false;
267}
268
269int Card::getCardDefinitionCount() { return static_cast<int>(defs_.size()); }
270
271std::string Card::getCardDefinitionId(int index) const {
272 if (definitionViewDirty_) {
273 definitionView_.clear();
274 definitionView_.reserve(defs_.size());
275 for (const auto &[id, definition] : defs_) definitionView_.push_back(id);
276 std::sort(definitionView_.begin(), definitionView_.end());
277 definitionViewDirty_ = false;
278 }
279 return index >= 0 && index < static_cast<int>(definitionView_.size())
280 ? definitionView_[static_cast<size_t>(index)]
281 : std::string{};
282}
283
284bool Card::hasCardDefinition(const std::string &id) { return defs_.count(id) != 0; }
285
286bool Card::setCardDefinition(const std::string &id, const std::string &name, const std::string &kind,
287 int cost, int attack, int health, float tintR, float tintG, float tintB) {
288 if (id.empty() || cost < 0 || attack < 0 || health < 0) return false;
289 CardDefinition definition;
290 definition.id = id;
291 definition.name = name.empty() ? id : name;
292 definition.kind = kind.empty() ? "creature" : kind;
293 definition.cost = cost;
294 definition.attack = attack;
295 definition.health = health;
296 definition.tint = glm::vec3(std::clamp(tintR, 0.f, 1.f), std::clamp(tintG, 0.f, 1.f),
297 std::clamp(tintB, 0.f, 1.f));
298 defs_[id] = std::move(definition);
299 definitionViewDirty_ = true;
300 return true;
301}
302
303bool Card::removeCardDefinition(const std::string &id) {
304 if (defs_.erase(id) == 0) return false;
305 definitionViewDirty_ = true;
306 return true;
307}
308
310 auto it = defs_.find(id);
311 if (it == defs_.end())
313 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "card definition was not found", id));
314 if (!condition.isValid())
316 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "card play condition is invalid", id));
317 it->second.playCondition = std::move(condition);
319}
320
321const CardDefinition *Card::findDef(const std::string &id) const {
322 auto it = defs_.find(id);
323 return it == defs_.end() ? nullptr : &it->second;
324}
325
328 const auto *definition = findDef(const_cast<CardData *>(card)->identity()->definitionId);
330 return CardPlayConditionAdapter::evaluate(card, *definition, definition->playCondition, std::move(queries));
331}
332
334 if (!ownsCard(cards_, card))
336 "card does not belong to this Card facade", "card"));
338}
339
340eve::Result<void> Card::setCardAttribute(CardData &card, std::string_view attribute, double value) const {
341 if (!ownsCard(cards_, card))
343 "card does not belong to this Card facade", "card"));
345}
346
348 eve::SubjectRef subject) const {
349 if (!ownsCard(cards_, card))
351 eve::DiagnosticCode::StaleHandle, "card does not belong to this Card facade", "card"));
354 return card.effects()->values.apply(definition, subject);
355}
356
358 std::size_t settled = 0;
359 for (const auto &handle : cards_) {
360 auto *card = resolve<CardData>(handle);
361 if (card == nullptr || card->effects()->values.count() == 0) continue;
362 auto updated = card->effects()->values.advance(simulationStep);
364 auto result = std::move(updated).takeValue();
366 static_cast<double>(card->effects()->values.target().health));
367 if (!projected) return eve::Result<std::size_t>::failure(projected.status());
368 settled += result.settled;
369 }
372}
373
374std::string Card::getCardDefinitionName(const std::string &id) {
375 const auto *d = findDef(id);
376 return d ? d->name : std::string{};
377}
378
379std::string Card::getCardDefinitionKind(const std::string &id) {
380 const auto *d = findDef(id);
381 return d ? d->kind : std::string{};
382}
383
384int Card::getCardDefinitionCost(const std::string &id) {
385 const auto *d = findDef(id);
386 return d ? d->cost : 0;
387}
388
389int Card::getCardDefinitionAttack(const std::string &id) {
390 const auto *d = findDef(id);
391 return d ? d->attack : 0;
392}
393
394int Card::getCardDefinitionHealth(const std::string &id) {
395 const auto *d = findDef(id);
396 return d ? d->health : 0;
397}
398
399float Card::getCardDefinitionTintR(const std::string &id) {
400 const auto *d = findDef(id);
401 return d ? d->tint.r : 0.f;
402}
403
404float Card::getCardDefinitionTintG(const std::string &id) {
405 const auto *d = findDef(id);
406 return d ? d->tint.g : 0.f;
407}
408
409float Card::getCardDefinitionTintB(const std::string &id) {
410 const auto *d = findDef(id);
411 return d ? d->tint.b : 0.f;
412}
413
414// ---------------------------------------------------------------------------
415// 工厂
416// ---------------------------------------------------------------------------
417
419 auto cfg = std::make_unique<LayoutConfig>();
420 LayoutConfig *raw = cfg.get();
421 configs_.push_back(std::move(cfg));
422 if (!activeConfig_) activeConfig_ = raw;
423 return raw;
424}
425
426CardData *Card::newCard(const std::string &defId) {
427 const CardDefinition *d = findDef(defId);
428 if (!d) return nullptr;
430 c->identity()->id = defId + "#" + std::to_string(nextInstance_++);
431 c->identity()->definitionId = defId;
432 c->identity()->name = d->name;
433 c->identity()->kind = d->kind;
434 c->stats()->cost = d->cost;
435 c->stats()->attack = d->attack;
436 c->stats()->health = d->health;
437 c->visual()->tint = d->tint;
439 if (!attributes) {
440 attributes.ignore("Card::newCard could not seed canonical attributes");
441 c->release();
442 return nullptr;
443 }
444 if (d->health > 0) {
445 auto target = c->effects()->values.initializeTarget(CardEffectTarget{d->health, d->health, 0, 0});
446 if (!target) {
447 target.ignore("Card::newCard could not seed the effect target");
448 c->release();
449 return nullptr;
450 }
451 }
452 cards_.push_back(ecs::handle_of(c));
453 return c;
454}
455
458 decks_.push_back(ecs::handle_of(d));
459 activeDeck_ = d;
460 return d;
461}
462
463Zone *Card::newZone(const std::string &id, const std::string &label, float x, float y, float w, float h) {
465 auto *R = z->rect().operator->();
466 R->id = id;
467 R->label = label;
468 R->x = x;
469 R->y = y;
470 R->w = w;
471 R->h = h;
472 zones_.push_back(ecs::handle_of(z));
473 return z;
474}
475
478 h->meta()->config = cfg;
479 hands_.push_back(ecs::handle_of(h));
480 return h;
481}
482
484 auto mapper = std::make_unique<CardPlaneMapper>();
485 CardPlaneMapper *raw = mapper.get();
486 planeMappers_.push_back(std::move(mapper));
487 return raw;
488}
489
490// ---------------------------------------------------------------------------
491// 游戏状态
492// ---------------------------------------------------------------------------
493
495 if (cfg) activeConfig_ = cfg;
496}
497
498LayoutConfig *Card::getConfig() const { return activeConfig_; }
499
500int Card::handCount() const { return static_cast<int>(hands_.size()); }
501
503 if (index < 0 || static_cast<size_t>(index) >= hands_.size()) return nullptr;
504 return resolve<Hand>(hands_[static_cast<size_t>(index)]);
505}
506
507Hand *Card::findHand(const std::string &owner) const {
508 for (const auto &h : hands_) {
509 Hand *hand = resolve<Hand>(h);
510 if (hand && hand->meta()->owner == owner) return hand;
511 }
512 return nullptr;
513}
514
515int Card::zoneCount() const { return static_cast<int>(zones_.size()); }
516
518 if (index < 0 || static_cast<size_t>(index) >= zones_.size()) return nullptr;
519 return resolve<Zone>(zones_[static_cast<size_t>(index)]);
520}
521
522Deck *Card::getDeck() const { return activeDeck_; }
523
524CardData *Card::drawCard(const std::string &handOwner) {
525 Hand *h = findHand(handOwner);
526 if (!h || !activeDeck_) return nullptr;
527 CardData *c = activeDeck_->draw();
528 if (!c) return nullptr;
529 if (activeConfig_) {
530 c->layout()->x = activeConfig_->deckX;
531 c->layout()->y = activeConfig_->deckY;
532 }
533 c->state()->phase = CardState::Deck;
534 h->addCard(c);
535 return c;
536}
537
539 presentation_.clear();
540 presentation_.reserve(cards_.size());
541 for (const auto &handle : cards_) {
542 CardData *card = resolve<CardData>(handle);
543 if (!card) continue;
544 Hand *ownerHand = nullptr;
545 LayoutConfig cfg = activeConfig_ ? *activeConfig_ : LayoutConfig{};
546 for (const auto &handHandle : hands_) {
547 if (Hand *hand = resolve<Hand>(handHandle)) {
548 if (hand->find(card->identity()->id) != nullptr) {
549 ownerHand = hand;
550 if (hand->meta()->config) cfg = *hand->meta()->config;
551 break;
552 }
553 }
554 }
555 const auto *identity = card->identity().operator->();
556 const auto *layout = card->layout().operator->();
557 const auto *state = card->state().operator->();
558 const auto *visual = card->visual().operator->();
559 const bool handFaceDown = ownerHand != nullptr && ownerHand->meta()->faceDown;
560 const bool handPeek = ownerHand != nullptr && ownerHand->meta()->peek;
561 const bool wantFaceUp = resolveCardWantFaceUp(visual->faceUp, handFaceDown, handPeek);
562 const CardFlipPose pose = evaluateCardFlip(visual->flip, cfg.flipLift);
563 presentation_.push_back({identity->id,
564 identity->definitionId,
565 cardStateName(state->phase),
566 layout->x,
567 layout->y,
568 layout->w,
569 layout->h,
570 layout->angle,
571 layout->scale,
572 layout->alpha,
573 state->hovered,
574 state->dragging,
575 visual->disabled,
576 wantFaceUp,
577 pose.progress,
578 pose.angleDegrees,
579 pose.lift,
580 pose.axisScale,
581 pose.showingFront,
582 cfg.flipAxis});
583 }
584 return static_cast<int>(presentation_.size());
585}
586
587int Card::getPresentationCount() const { return static_cast<int>(presentation_.size()); }
588
590 if (index < 0 || static_cast<size_t>(index) >= presentation_.size()) return nullptr;
591 return &presentation_[static_cast<size_t>(index)];
592}
593
594// ---------------------------------------------------------------------------
595// 每帧
596// ---------------------------------------------------------------------------
597
598void Card::update(float dt, float mx, float my, bool down) {
599 std::vector<Zone *> zonePtrs;
600 zonePtrs.reserve(zones_.size());
601 for (auto &h : zones_) {
602 if (Zone *z = resolve<Zone>(h)) zonePtrs.push_back(z);
603 }
604 for (auto &h : hands_) {
605 if (Hand *hand = resolve<Hand>(h)) hand->update(dt, mx, my, down, zonePtrs, events_);
606 }
607 const LayoutConfig fallback = activeConfig_ ? *activeConfig_ : LayoutConfig{};
608 for (auto &handle : cards_) {
609 CardData *card = resolve<CardData>(handle);
610 if (!card) continue;
611 bool inHand = false;
612 for (auto &handHandle : hands_) {
613 if (Hand *hand = resolve<Hand>(handHandle)) {
614 if (hand->find(card->identity()->id) != nullptr) {
615 inHand = true;
616 break;
617 }
618 }
619 }
620 if (inHand) continue;
621 const float targetFlip = resolveCardWantFaceUp(card->visual()->faceUp, false, false) ? 0.f : 1.f;
622 advanceCardFlip(card->visual()->flip, targetFlip, fallback.flipSpeed, dt);
623 }
624}
625
627 if (!builtInVisuals_)
628 return;
629 if (activeConfig_ && activeConfig_->showZones) {
630 for (auto &h : zones_) {
631 if (Zone *z = resolve<Zone>(h)) z->render(gfx, true);
632 }
633 }
634 for (auto &h : hands_) {
635 if (Hand *hand = resolve<Hand>(h)) hand->render(gfx);
636 }
637}
638
639void Card::beginTargeting(const std::string &sourceId, float x, float y) {
640 targetingActive_ = true;
641 targetingValid_ = false;
642 targetingSource_ = sourceId;
643 targetingId_.clear();
644 targetingStartX_ = targetingX_ = x;
645 targetingStartY_ = targetingY_ = y;
646}
647
648void Card::updateTargeting(float x, float y, const std::string &targetId, bool valid) {
649 if (!targetingActive_)
650 return;
651 targetingX_ = x;
652 targetingY_ = y;
653 targetingId_ = targetId;
654 targetingValid_ = valid;
655}
656
657void Card::cancelTargeting() {
658 targetingActive_ = false;
659 targetingValid_ = false;
660 targetingSource_.clear();
661 targetingId_.clear();
662}
663
664void Card::renderTargeting(graphics::Graphics *gfx) {
665 if (!gfx || !targetingActive_)
666 return;
667 const float dx = targetingX_ - targetingStartX_;
668 const float dy = targetingY_ - targetingStartY_;
669 const float length = std::sqrt(dx * dx + dy * dy);
670 if (length < 2.f)
671 return;
672 constexpr float radiansToDegrees = 57.2957795131f;
673 const float angle = std::atan2(dy, dx) * radiansToDegrees;
674 const graphics::Color color = targetingValid_ ? graphics::Color(0.15f, 1.f, 0.25f, 0.9f)
675 : graphics::Color(1.f, 0.12f, 0.06f, 0.9f);
676 gfx->drawSolidRectRotated(targetingStartX_ + dx * 0.5f, targetingStartY_ + dy * 0.5f,
677 length, 12.f, angle, color);
678 gfx->drawSolidRectRotated(targetingX_ - std::cos((angle - 28.f) / radiansToDegrees) * 12.f,
679 targetingY_ - std::sin((angle - 28.f) / radiansToDegrees) * 12.f,
680 32.f, 10.f, angle - 28.f, color);
681 gfx->drawSolidRectRotated(targetingX_ - std::cos((angle + 28.f) / radiansToDegrees) * 12.f,
682 targetingY_ - std::sin((angle + 28.f) / radiansToDegrees) * 12.f,
683 32.f, 10.f, angle + 28.f, color);
684}
685
687 if (!activeDeck_ || !activeConfig_) return;
688 const LayoutConfig &cfg = *activeConfig_;
689 const int c = activeDeck_->count();
690 if (c <= 0) return;
691 const float w = cfg.cardW * 0.9f;
692 const float h = cfg.cardH * 0.9f;
693 for (int i = 0; i < 3 && i < c; ++i) {
694 const float off = static_cast<float>(i) * 3.f;
695 renderCardBack(gfx, cfg.deckX - w * 0.5f + off, cfg.deckY - h * 0.5f - off, w, h, 0.f, 1.f);
696 }
697 if (gfx->getFont())
698 printCentered(gfx, std::to_string(c), cfg.deckX, cfg.deckY - h * 0.5f - 12.f, 1.2f,
699 glm::vec4(0.95f, 0.9f, 0.8f, 1.f));
700}
701
702// ---------------------------------------------------------------------------
703// 事件
704// ---------------------------------------------------------------------------
705
706void Card::clearEvents() { events_.clear(); }
707
708int Card::getEventCount() const { return static_cast<int>(events_.size()); }
709
710std::string Card::getEventType(int index) const {
711 if (index < 0 || static_cast<size_t>(index) >= events_.size()) return {};
712 return events_[static_cast<size_t>(index)].type;
713}
714
715std::string Card::getEventHand(int index) const {
716 if (index < 0 || static_cast<size_t>(index) >= events_.size()) return {};
717 return events_[static_cast<size_t>(index)].hand;
718}
719
720std::string Card::getEventZone(int index) const {
721 if (index < 0 || static_cast<size_t>(index) >= events_.size()) return {};
722 return events_[static_cast<size_t>(index)].zoneId;
723}
724
725std::string Card::getEventCardId(int index) const {
726 if (index < 0 || static_cast<size_t>(index) >= events_.size()) return {};
727 return events_[static_cast<size_t>(index)].cardId;
728}
729
730std::string Card::getEventReason(int index) const {
731 if (index < 0 || static_cast<size_t>(index) >= events_.size()) return {};
732 return events_[static_cast<size_t>(index)].reason;
733}
734
735// ---------------------------------------------------------------------------
736// 脚本绑定
737// ---------------------------------------------------------------------------
738
739void Card::expose(ssq::Table &table) {
740 const auto vm = table.getHandle();
741 auto cls = table.addClass(name, ssq::Class::Ctor<Card()>(), true);
742 expose(cls);
743
744 // LayoutConfig —— 全部布局参数(UiCard Configs)
745 auto cfgCls = table.addClass<LayoutConfig>(
746 "LayoutConfig", std::function<LayoutConfig *()>([]() -> LayoutConfig * { return nullptr; }), false);
747 cfgCls.addFunc("getCardW", [](LayoutConfig *c) -> float { return c ? c->cardW : 0.f; });
748 cfgCls.addFunc("setCardW", [](LayoutConfig *c, float v) { if (c) c->cardW = v; });
749 cfgCls.addFunc("getCardH", [](LayoutConfig *c) -> float { return c ? c->cardH : 0.f; });
750 cfgCls.addFunc("setCardH", [](LayoutConfig *c, float v) { if (c) c->cardH = v; });
751 cfgCls.addFunc("getSpacing", [](LayoutConfig *c) -> float { return c ? c->spacing : 0.f; });
752 cfgCls.addFunc("setSpacing", [](LayoutConfig *c, float v) { if (c) c->spacing = v; });
753 cfgCls.addFunc("getHandX", [](LayoutConfig *c) -> float { return c ? c->handX : 0.f; });
754 cfgCls.addFunc("setHandX", [](LayoutConfig *c, float v) { if (c) c->handX = v; });
755 cfgCls.addFunc("getHandY", [](LayoutConfig *c) -> float { return c ? c->handY : 0.f; });
756 cfgCls.addFunc("setHandY", [](LayoutConfig *c, float v) { if (c) c->handY = v; });
757 cfgCls.addFunc("getArcHeight", [](LayoutConfig *c) -> float { return c ? c->arcHeight : 0.f; });
758 cfgCls.addFunc("setArcHeight", [](LayoutConfig *c, float v) { if (c) c->arcHeight = v; });
759 cfgCls.addFunc("getRotationAngle", [](LayoutConfig *c) -> float { return c ? c->rotationAngle : 0.f; });
760 cfgCls.addFunc("setRotationAngle", [](LayoutConfig *c, float v) { if (c) c->rotationAngle = v; });
761 cfgCls.addFunc("getHoverRotation", [](LayoutConfig *c) -> bool { return c ? c->hoverRotation : false; });
762 cfgCls.addFunc("setHoverRotation", [](LayoutConfig *c, bool v) { if (c) c->hoverRotation = v; });
763 cfgCls.addFunc("getHoverScale", [](LayoutConfig *c) -> float { return c ? c->hoverScale : 0.f; });
764 cfgCls.addFunc("setHoverScale", [](LayoutConfig *c, float v) { if (c) c->hoverScale = v; });
765 cfgCls.addFunc("getHoverLift", [](LayoutConfig *c) -> float { return c ? c->hoverLift : 0.f; });
766 cfgCls.addFunc("setHoverLift", [](LayoutConfig *c, float v) { if (c) c->hoverLift = v; });
767 cfgCls.addFunc("getHoverSpeed", [](LayoutConfig *c) -> float { return c ? c->hoverSpeed : 0.f; });
768 cfgCls.addFunc("setHoverSpeed", [](LayoutConfig *c, float v) { if (c) c->hoverSpeed = v; });
769 cfgCls.addFunc("getMotionSpeed", [](LayoutConfig *c) -> float { return c ? c->motionSpeed : 0.f; });
770 cfgCls.addFunc("setMotionSpeed", [](LayoutConfig *c, float v) { if (c) c->motionSpeed = v; });
771 cfgCls.addFunc("getFlipSpeed", [](LayoutConfig *c) -> float { return c ? c->flipSpeed : 0.f; });
772 cfgCls.addFunc("setFlipSpeed", [](LayoutConfig *c, float v) {
773 if (c) c->flipSpeed = v;
774 });
775 cfgCls.addFunc("getFlipLift", [](LayoutConfig *c) -> float { return c ? c->flipLift : 0.f; });
776 cfgCls.addFunc("setFlipLift", [](LayoutConfig *c, float v) {
777 if (c) c->flipLift = v;
778 });
779 cfgCls.addFunc("getFlipAxis", [](LayoutConfig *c) -> int { return c ? c->flipAxis : 0; });
780 cfgCls.addFunc("setFlipAxis", [](LayoutConfig *c, int v) {
781 if (c) c->flipAxis = (v == 1) ? 1 : 0;
782 });
783 cfgCls.addFunc("getDisabledAlpha", [](LayoutConfig *c) -> float { return c ? c->disabledAlpha : 0.f; });
784 cfgCls.addFunc("setDisabledAlpha", [](LayoutConfig *c, float v) { if (c) c->disabledAlpha = v; });
785 cfgCls.addFunc("getShowZones", [](LayoutConfig *c) -> bool { return c ? c->showZones : false; });
786 cfgCls.addFunc("setShowZones", [](LayoutConfig *c, bool v) { if (c) c->showZones = v; });
787 cfgCls.addFunc("getDeckX", [](LayoutConfig *c) -> float { return c ? c->deckX : 0.f; });
788 cfgCls.addFunc("setDeckX", [](LayoutConfig *c, float v) { if (c) c->deckX = v; });
789 cfgCls.addFunc("getDeckY", [](LayoutConfig *c) -> float { return c ? c->deckY : 0.f; });
790 cfgCls.addFunc("setDeckY", [](LayoutConfig *c, float v) { if (c) c->deckY = v; });
791 cfgCls.addFunc("getDragThreshold", [](LayoutConfig *c) -> float { return c ? c->dragThreshold : 0.f; });
792 cfgCls.addFunc("setDragThreshold", [](LayoutConfig *c, float v) { if (c) c->dragThreshold = v; });
793
794 auto mapperCls = table.addClass<CardPlaneMapper>(
795 "CardPlaneMapper", std::function<CardPlaneMapper *()>([]() -> CardPlaneMapper * {
796 return nullptr;
797 }), false);
798 mapperCls.addFunc("setLogicalRect", &CardPlaneMapper::setLogicalRect);
799 mapperCls.addFunc("setPlane", &CardPlaneMapper::setPlane);
800 mapperCls.addFunc("mapRay", &CardPlaneMapper::mapRay);
801 mapperCls.addFunc("mapLayout", &CardPlaneMapper::mapLayout);
802 mapperCls.addFunc("mapCardPose",
803 [](CardPlaneMapper *mapper, float x, float y, float layoutAngleDeg, float flipProgress,
804 float liftPeak, int flipAxis) -> bool {
805 if (!mapper) return false;
806 return mapper->mapCardPose(x, y, layoutAngleDeg, flipProgress, liftPeak, flipAxis).ok();
807 });
808 mapperCls.addFunc("getLogicalX", &CardPlaneMapper::getLogicalX);
809 mapperCls.addFunc("getLogicalY", &CardPlaneMapper::getLogicalY);
810 mapperCls.addFunc("getWorldX", &CardPlaneMapper::getWorldX);
811 mapperCls.addFunc("getWorldY", &CardPlaneMapper::getWorldY);
812 mapperCls.addFunc("getWorldZ", &CardPlaneMapper::getWorldZ);
813 mapperCls.addFunc("getBasisUX", &CardPlaneMapper::getBasisUX);
814 mapperCls.addFunc("getBasisUY", &CardPlaneMapper::getBasisUY);
815 mapperCls.addFunc("getBasisUZ", &CardPlaneMapper::getBasisUZ);
816 mapperCls.addFunc("getBasisVX", &CardPlaneMapper::getBasisVX);
817 mapperCls.addFunc("getBasisVY", &CardPlaneMapper::getBasisVY);
818 mapperCls.addFunc("getBasisVZ", &CardPlaneMapper::getBasisVZ);
819 mapperCls.addFunc("getBasisNX", &CardPlaneMapper::getBasisNX);
820 mapperCls.addFunc("getBasisNY", &CardPlaneMapper::getBasisNY);
821 mapperCls.addFunc("getBasisNZ", &CardPlaneMapper::getBasisNZ);
822 mapperCls.addFunc("isShowingFront", &CardPlaneMapper::isShowingFront);
823
824 // CardData
825 auto cardCls = table.addClass<CardData>(
826 "CardData", std::function<CardData *()>([]() -> CardData * { return nullptr; }), false);
827 registerCppEntityClassForScript<CardData>(cardCls);
828 cardCls.addFunc("getId", [](CardData *c) -> std::string { return c ? c->identity()->id : std::string{}; });
829 cardCls.addFunc("getInstanceId", [](CardData *c) -> std::string {
830 return c ? c->identity()->id : std::string{};
831 });
832 cardCls.addFunc("getDefinitionId", [](CardData *c) -> std::string {
833 return c ? c->identity()->definitionId : std::string{};
834 });
835 cardCls.addFunc("setId", [](CardData *c, const std::string &v) { if (c) c->identity()->id = v; });
836 cardCls.addFunc("getName", [](CardData *c) -> std::string { return c ? c->identity()->name : std::string{}; });
837 cardCls.addFunc("setName", [](CardData *c, const std::string &v) { if (c) c->identity()->name = v; });
838 cardCls.addFunc("getKind", [](CardData *c) -> std::string { return c ? c->identity()->kind : std::string{}; });
839 cardCls.addFunc("setKind", [](CardData *c, const std::string &v) { if (c) c->identity()->kind = v; });
840 cardCls.addFunc("getCost", [](CardData *c) -> int { return c ? c->stats()->cost : 0; });
841 cardCls.addFunc("setCost", [](CardData *c, int v) { if (c) c->stats()->cost = v; });
842 cardCls.addFunc("getAttack", [](CardData *c) -> int { return c ? c->stats()->attack : 0; });
843 cardCls.addFunc("setAttack", [](CardData *c, int v) { if (c) c->stats()->attack = v; });
844 cardCls.addFunc("getHealth", [](CardData *c) -> int { return c ? c->stats()->health : 0; });
845 cardCls.addFunc("setHealth", [](CardData *c, int v) { if (c) c->stats()->health = v; });
846 cardCls.addFunc("configureSettlementRulesJson", [vm](CardData* value, const std::string& json) {
847 if (!value)
850 eve::DiagnosticCode::InvalidArgument, "CardData receiver must not be null", "card", {},
851 "card.squirrel")));
853 if (!rules)
856 value->effects()->values.configureSettlementRules(rules.value()));
857 });
858 cardCls.addFunc("isFaceUp", [](CardData *c) -> bool { return c ? c->visual()->faceUp : true; });
859 cardCls.addFunc("setFaceUp", [](CardData *c, bool v) {
860 if (!c) return;
861 c->visual()->faceUp = v;
862 });
863 cardCls.addFunc("snapFaceUp", [](CardData *c, bool v) {
864 if (!c) return;
865 c->visual()->faceUp = v;
866 c->visual()->flip = v ? 0.f : 1.f;
867 });
868 cardCls.addFunc("getFlip", [](CardData *c) -> float { return c ? c->visual()->flip : 0.f; });
869 cardCls.addFunc("setFlip", [](CardData *c, float v) {
870 if (!c) return;
871 c->visual()->flip = v < 0.f ? 0.f : (v > 1.f ? 1.f : v);
872 });
873 cardCls.addFunc("isShowingFront", [](CardData *c) -> bool {
874 return c ? evaluateCardFlip(c->visual()->flip, 0.f).showingFront : true;
875 });
876 cardCls.addFunc("isFlipping", [](CardData *c) -> bool {
877 if (!c) return false;
878 const float target = c->visual()->faceUp ? 0.f : 1.f;
879 return std::fabs(c->visual()->flip - target) > 0.001f;
880 });
881 cardCls.addFunc("isDisabled", [](CardData *c) -> bool { return c ? c->visual()->disabled : false; });
882 cardCls.addFunc("setDisabled", [](CardData *c, bool v) { if (c) c->visual()->disabled = v; });
883 cardCls.addFunc("getState", [](CardData *c) -> std::string {
884 return c ? cardStateName(c->state()->phase) : std::string{};
885 });
886 cardCls.addFunc("setState", [](CardData *c, const std::string &v) {
887 if (!c) return;
888 auto *st = c->state().operator->();
889 if (v == "deck") st->phase = CardState::Deck;
890 else if (v == "hand") st->phase = CardState::Hand;
891 else if (v == "hovered") st->phase = CardState::Hovered;
892 else if (v == "dragging") st->phase = CardState::Dragging;
893 else if (v == "returning") st->phase = CardState::Returning;
894 else if (v == "played") st->phase = CardState::Played;
895 else if (v == "discarded") st->phase = CardState::Discarded;
896 else if (v == "disabled") st->phase = CardState::Disabled;
897 });
898 cardCls.addFunc("getTintR", [](CardData *c) -> float { return c ? c->visual()->tint.r : 0.f; });
899 cardCls.addFunc("getTintG", [](CardData *c) -> float { return c ? c->visual()->tint.g : 0.f; });
900 cardCls.addFunc("getTintB", [](CardData *c) -> float { return c ? c->visual()->tint.b : 0.f; });
901 cardCls.addFunc("setTint", [](CardData *c, float r, float g, float b) {
902 if (c) c->visual()->tint = glm::vec3(r, g, b);
903 });
904 cardCls.addFunc("setArt", [](CardData *c, graphics::Texture *t) { if (c) c->visual()->texture = t; });
905 cardCls.addFunc("getArt", [](CardData *c) -> graphics::Texture * { return c ? c->visual()->texture : nullptr; });
906 cardCls.addFunc("getX", [](CardData *c) -> float { return c ? c->layout()->x : 0.f; });
907 cardCls.addFunc("getY", [](CardData *c) -> float { return c ? c->layout()->y : 0.f; });
908 cardCls.addFunc("getW", [](CardData *c) -> float { return c ? c->layout()->w : 0.f; });
909 cardCls.addFunc("getH", [](CardData *c) -> float { return c ? c->layout()->h : 0.f; });
910 cardCls.addFunc("getAngle", [](CardData *c) -> float { return c ? c->layout()->angle : 0.f; });
911 cardCls.addFunc("getScale", [](CardData *c) -> float { return c ? c->layout()->scale : 0.f; });
912 cardCls.addFunc("getAlpha", [](CardData *c) -> float { return c ? c->layout()->alpha : 0.f; });
913 cardCls.addFunc("isHovered", [](CardData *c) -> bool { return c ? c->state()->hovered : false; });
914 cardCls.addFunc("isDragging", [](CardData *c) -> bool { return c ? c->state()->dragging : false; });
915 cardCls.addFunc("hit", [](CardData *c, float px, float py) -> bool { return c && c->hit(px, py); });
916 cardCls.addFunc("describe", [](CardData *c) -> std::string { return c ? c->describe() : std::string{}; });
917
918 // Deck
919 auto deckCls = table.addClass<Deck>(
920 "Deck", std::function<Deck *()>([]() -> Deck * { return nullptr; }), false);
921 registerCppEntityClassForScript<Deck>(deckCls);
922 deckCls.addFunc("push", &Deck::push);
923 deckCls.addFunc("draw", &Deck::draw);
924 deckCls.addFunc("peek", &Deck::peek);
925 deckCls.addFunc("count", &Deck::count);
926 deckCls.addFunc("isEmpty", &Deck::isEmpty);
927 deckCls.addFunc("clear", &Deck::clear);
928 deckCls.addFunc("shuffle", &Deck::shuffle);
929 deckCls.addFunc("getCard", &Deck::get);
930
931 // Zone
932 auto zoneCls = table.addClass<Zone>(
933 "Zone", std::function<Zone *()>([]() -> Zone * { return nullptr; }), false);
934 registerCppEntityClassForScript<Zone>(zoneCls);
935 zoneCls.addFunc("getId", [](Zone *z) -> std::string { return z ? z->rect()->id : std::string{}; });
936 zoneCls.addFunc("setId", [](Zone *z, const std::string &v) { if (z) z->rect()->id = v; });
937 zoneCls.addFunc("getLabel", [](Zone *z) -> std::string { return z ? z->rect()->label : std::string{}; });
938 zoneCls.addFunc("setLabel", [](Zone *z, const std::string &v) { if (z) z->rect()->label = v; });
939 zoneCls.addFunc("getX", [](Zone *z) -> float { return z ? z->rect()->x : 0.f; });
940 zoneCls.addFunc("getY", [](Zone *z) -> float { return z ? z->rect()->y : 0.f; });
941 zoneCls.addFunc("getW", [](Zone *z) -> float { return z ? z->rect()->w : 0.f; });
942 zoneCls.addFunc("getH", [](Zone *z) -> float { return z ? z->rect()->h : 0.f; });
943 zoneCls.addFunc("setRect", [](Zone *z, float x, float y, float w, float h) {
944 if (!z) return;
945 auto *R = z->rect().operator->();
946 R->x = x; R->y = y; R->w = w; R->h = h;
947 });
948 zoneCls.addFunc("getColorR", [](Zone *z) -> float { return z ? z->rect()->color.r : 0.f; });
949 zoneCls.addFunc("getColorG", [](Zone *z) -> float { return z ? z->rect()->color.g : 0.f; });
950 zoneCls.addFunc("getColorB", [](Zone *z) -> float { return z ? z->rect()->color.b : 0.f; });
951 zoneCls.addFunc("setColor", [](Zone *z, float r, float g, float b) {
952 if (z) z->rect()->color = glm::vec3(r, g, b);
953 });
954 zoneCls.addFunc("getAlpha", [](Zone *z) -> float { return z ? z->rect()->alpha : 0.f; });
955 zoneCls.addFunc("setAlpha", [](Zone *z, float v) { if (z) z->rect()->alpha = v; });
956 zoneCls.addFunc("isEnabled", [](Zone *z) -> bool { return z ? z->rect()->enabled : false; });
957 zoneCls.addFunc("setEnabled", [](Zone *z, bool v) { if (z) z->rect()->enabled = v; });
958 zoneCls.addFunc("addAcceptKind", [](Zone *z, const std::string &k) { if (z) z->filter()->acceptKinds.push_back(k); });
959 zoneCls.addFunc("clearAcceptKinds", [](Zone *z) { if (z) z->filter()->acceptKinds.clear(); });
960 zoneCls.addFunc("accepts", [](Zone *z, CardData *c) -> bool { return z && z->accepts(c); });
961 zoneCls.addFunc("contains", [](Zone *z, float px, float py) -> bool { return z && z->contains(px, py); });
962 zoneCls.addFunc("render", [](Zone *z, graphics::Graphics *gfx, bool showLabel) {
963 if (z) z->render(gfx, showLabel);
964 });
965
966 // Hand
967 auto handCls = table.addClass<Hand>(
968 "Hand", std::function<Hand *()>([]() -> Hand * { return nullptr; }), false);
969 registerCppEntityClassForScript<Hand>(handCls);
970 handCls.addFunc("getOwner", [](Hand *h) -> std::string { return h ? h->meta()->owner : std::string{}; });
971 handCls.addFunc("setOwner", [](Hand *h, const std::string &v) { if (h) h->meta()->owner = v; });
972 handCls.addFunc("getConfig", [](Hand *h) -> LayoutConfig * { return h ? h->meta()->config : nullptr; });
973 handCls.addFunc("setConfig", [](Hand *h, LayoutConfig *c) { if (h) h->meta()->config = c; });
974 handCls.addFunc("isFaceDown", [](Hand *h) -> bool { return h ? h->meta()->faceDown : false; });
975 handCls.addFunc("setFaceDown", [](Hand *h, bool v) { if (h) h->meta()->faceDown = v; });
976 handCls.addFunc("isPeek", [](Hand *h) -> bool { return h ? h->meta()->peek : false; });
977 handCls.addFunc("setPeek", [](Hand *h, bool v) { if (h) h->meta()->peek = v; });
978 handCls.addFunc("isInteractive", [](Hand *h) -> bool { return h ? h->meta()->interactive : true; });
979 handCls.addFunc("setInteractive", [](Hand *h, bool v) { if (h) h->meta()->interactive = v; });
980 handCls.addFunc("addCard", &Hand::addCard);
981 handCls.addFunc("removeCard", &Hand::removeCard);
982 handCls.addFunc("clear", &Hand::clear);
983 handCls.addFunc("count", &Hand::count);
984 handCls.addFunc("getCard", &Hand::get);
985 handCls.addFunc("findCard", &Hand::find);
986 handCls.addFunc("pickCard", &Hand::pick);
987 handCls.addFunc("render", [](Hand *h, graphics::Graphics *gfx) { if (h) h->render(gfx); });
988
989 auto snapshotCls = table.addClass<CardPresentationSnapshot>(
990 "CardPresentationSnapshot",
991 std::function<CardPresentationSnapshot *()>([]() -> CardPresentationSnapshot * {
992 return nullptr;
993 }), false);
994 snapshotCls.addFunc("getInstanceId", [](CardPresentationSnapshot *s) { return s ? s->instanceId : std::string{}; });
995 snapshotCls.addFunc("getDefinitionId", [](CardPresentationSnapshot *s) { return s ? s->definitionId : std::string{}; });
996 snapshotCls.addFunc("getState", [](CardPresentationSnapshot *s) { return s ? s->state : std::string{}; });
997 snapshotCls.addFunc("getX", [](CardPresentationSnapshot *s) { return s ? s->x : 0.f; });
998 snapshotCls.addFunc("getY", [](CardPresentationSnapshot *s) { return s ? s->y : 0.f; });
999 snapshotCls.addFunc("getW", [](CardPresentationSnapshot *s) { return s ? s->width : 0.f; });
1000 snapshotCls.addFunc("getH", [](CardPresentationSnapshot *s) { return s ? s->height : 0.f; });
1001 snapshotCls.addFunc("getAngle", [](CardPresentationSnapshot *s) { return s ? s->angle : 0.f; });
1002 snapshotCls.addFunc("getScale", [](CardPresentationSnapshot *s) { return s ? s->scale : 0.f; });
1003 snapshotCls.addFunc("getAlpha", [](CardPresentationSnapshot *s) { return s ? s->alpha : 0.f; });
1004 snapshotCls.addFunc("isHovered", [](CardPresentationSnapshot *s) { return s && s->hovered; });
1005 snapshotCls.addFunc("isDragging", [](CardPresentationSnapshot *s) { return s && s->dragging; });
1006 snapshotCls.addFunc("isDisabled", [](CardPresentationSnapshot *s) { return s && s->disabled; });
1007 snapshotCls.addFunc("isFaceUp", [](CardPresentationSnapshot *s) { return s && s->faceUp; });
1008 snapshotCls.addFunc("getFlip", [](CardPresentationSnapshot *s) { return s ? s->flip : 0.f; });
1009 snapshotCls.addFunc("getFlipAngle", [](CardPresentationSnapshot *s) { return s ? s->flipAngle : 0.f; });
1010 snapshotCls.addFunc("getFlipLift", [](CardPresentationSnapshot *s) { return s ? s->flipLift : 0.f; });
1011 snapshotCls.addFunc("getFlipAxisScale", [](CardPresentationSnapshot *s) { return s ? s->flipAxisScale : 1.f; });
1012 snapshotCls.addFunc("isShowingFront", [](CardPresentationSnapshot *s) { return s && s->showingFront; });
1013 snapshotCls.addFunc("getFlipAxis", [](CardPresentationSnapshot *s) { return s ? s->flipAxis : 0; });
1014}
1015
1016void Card::expose(ssq::Class &cls) {
1018 cls.addFunc("registerCardsFromJson", &Card::registerCardsFromJson);
1019 cls.addFunc("clearCardDefinitions", &Card::clearCardDefinitions);
1020 cls.addFunc("getCardDefinitionCount", &Card::getCardDefinitionCount);
1021 cls.addFunc("getCardDefinitionId", &Card::getCardDefinitionId);
1022 cls.addFunc("hasCardDefinition", &Card::hasCardDefinition);
1023 cls.addFunc("setCardDefinition", &Card::setCardDefinition);
1024 cls.addFunc("removeCardDefinition", &Card::removeCardDefinition);
1025 cls.addFunc("getCardDefinitionName", &Card::getCardDefinitionName);
1026 cls.addFunc("getCardDefinitionKind", &Card::getCardDefinitionKind);
1027 cls.addFunc("getCardDefinitionCost", &Card::getCardDefinitionCost);
1028 cls.addFunc("getCardDefinitionAttack", &Card::getCardDefinitionAttack);
1029 cls.addFunc("getCardDefinitionHealth", &Card::getCardDefinitionHealth);
1030 cls.addFunc("getCardDefinitionTintR", &Card::getCardDefinitionTintR);
1031 cls.addFunc("getCardDefinitionTintG", &Card::getCardDefinitionTintG);
1032 cls.addFunc("getCardDefinitionTintB", &Card::getCardDefinitionTintB);
1033 cls.addFunc("newConfig", &Card::newConfig);
1034 cls.addFunc("newCard", &Card::newCard);
1035 cls.addFunc("newDeck", &Card::newDeck);
1036 cls.addFunc("newZone", &Card::newZone);
1037 cls.addFunc("newHand", &Card::newHand);
1038 cls.addFunc("newPlaneMapper", &Card::newPlaneMapper);
1039 cls.addFunc("setConfig", &Card::setConfig);
1040 cls.addFunc("getConfig", &Card::getConfig);
1041 cls.addFunc("handCount", &Card::handCount);
1042 cls.addFunc("getHand", &Card::getHand);
1043 cls.addFunc("findHand", &Card::findHand);
1044 cls.addFunc("zoneCount", &Card::zoneCount);
1045 cls.addFunc("getZone", &Card::getZone);
1046 cls.addFunc("getDeck", &Card::getDeck);
1047 cls.addFunc("drawCard", &Card::drawCard);
1048 cls.addFunc("capturePresentation", &Card::capturePresentation);
1049 cls.addFunc("getPresentationCount", &Card::getPresentationCount);
1050 cls.addFunc("getPresentation", &Card::getPresentation);
1051 cls.addFunc("update", &Card::update);
1052 cls.addFunc("render", &Card::render);
1053 cls.addFunc("setBuiltInVisuals", &Card::setBuiltInVisuals);
1054 cls.addFunc("getBuiltInVisuals", &Card::getBuiltInVisuals);
1055 cls.addFunc("beginTargeting", &Card::beginTargeting);
1056 cls.addFunc("updateTargeting", &Card::updateTargeting);
1057 cls.addFunc("cancelTargeting", &Card::cancelTargeting);
1058 cls.addFunc("renderTargeting", &Card::renderTargeting);
1059 cls.addFunc("isTargeting", &Card::isTargeting);
1060 cls.addFunc("isTargetValid", &Card::isTargetValid);
1061 cls.addFunc("getTargetSource", &Card::getTargetSource);
1062 cls.addFunc("getTargetId", &Card::getTargetId);
1063 cls.addFunc("renderDeck", &Card::renderDeck);
1064 cls.addFunc("clearEvents", &Card::clearEvents);
1065 cls.addFunc("getEventCount", &Card::getEventCount);
1066 cls.addFunc("getEventType", &Card::getEventType);
1067 cls.addFunc("getEventHand", &Card::getEventHand);
1068 cls.addFunc("getEventZone", &Card::getEventZone);
1069 cls.addFunc("getEventCardId", &Card::getEventCardId);
1070 cls.addFunc("getEventReason", &Card::getEventReason);
1071
1072 // 把手牌发布到共享玩法协议(`eve_gameplay` / MCP)。返回 {ok, message}:
1073 // 失败原因(非规范持久 id、重复实例、空 hand)不被丢弃。account 可为 null,
1074 // 此时 `card:play` 走"未绑定支付"边界:零费卡照常出牌,收费卡得到明确诊断。
1075 cls.addFunc("publishGameplay", [vm = cls.getHandle()](Card *self, const std::string &instanceId,
1076 const std::string &ownerId, Hand *hand) {
1077 ssq::Table result(vm);
1078 if (self == nullptr || hand == nullptr) {
1079 result.set("ok", false);
1080 result.set("message", std::string("publishGameplay needs the card module and a hand"));
1081 return result;
1082 }
1083 const auto published = self->publishGameplay(instanceId, ownerId, hand, nullptr);
1084 result.set("ok", published.ok());
1085 result.set("message", published.ok() ? std::string("published") : published.status().describe());
1086 return result;
1087 });
1088 cls.addFunc("unpublishGameplay", [vm = cls.getHandle()](Card *self, const std::string &instanceId) {
1089 ssq::Table result(vm);
1090 const auto unpublished = self == nullptr ? eve::Result<void>::failure(eve::Diagnostic::error(
1091 eve::DiagnosticCode::Failed, "card module unavailable", "self"))
1092 : self->unpublishGameplay(instanceId);
1093 result.set("ok", unpublished.ok());
1094 result.set("message", unpublished.ok() ? std::string("unpublished") : unpublished.status().describe());
1095 return result;
1096 });
1097 cls.addFunc("clearGameplayControls", &Card::clearGameplayControls);
1098 cls.addFunc("getGameplayControlCount", &Card::gameplayControlCount);
1099}
1100
1101} // namespace eve::card
double z
double y
double x
LogicalId target
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
Vec3 relative
Definition AnimSmr.cpp:164
int subject
Definition AnimSmr.cpp:163
eve::EntitySpatialPose pose
const std::string & s
Selective canonical attributes for card combat values.
float uv
struct SQVM * HSQUIRRELVM
eve::resource::CostSpec cost
eve::resource::IResourceAccount * account
eve::Value condition
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
double raw
int instanceId
std::uint64_t sourceId
std::string layout
tensor::Graph g
Definition GpuGraph.cpp:7
wgpu::PopErrorScopeStatus status
glm::vec4 tint
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
int h
std::vector< Colorf > px
std::uint32_t height
std::uint32_t width
float length
std::string label
std::string id
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
Texture * normal
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec3 dx
glm::dvec3 dz
double dt
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
std::uint32_t targetId
PrimitiveHandle handle
Object::Ptr value
float d
float t
std::map< std::string, double > attributes
std::string attribute
RoadLaneDirection direction
Graphics * graphics
ScriptStructure out
std::string kind
std::string string
float dy
Definition Shadow.cpp:151
The single Squirrel projection for common Result, Status and Value.
Stable reference to a runtime gameplay subject.
uint32_t index
double oy
double ox
uint64_t identity
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 Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Strong, domain-neutral reference to a runtime subject.
Definition SubjectRef.h:26
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static eve::Result< void > ensure(CardData &card)
Bind and seed the card's selected attributes exactly once.
static constexpr std::string_view healthAttribute
static eve::Result< double > read(CardData &card, std::string_view attribute)
Read a selected final card attribute and refresh compatibility fields.
static eve::Result< void > setBase(CardData &card, std::string_view attribute, double value)
Set a selected canonical base and refresh the legacy projection.
单张卡牌:ECS 实体,数据拆成 Identity / Stats / Visual / Layout / State。
Definition CardTypes.h:106
static CardData * createCard()
创建并触摸全部组件。
Maps a logical card canvas to a 3D parallelogram without depending on graphics.
Definition Card.h:72
float getBasisUX() const
Local card right axis after layout rotation and flip (world space).
Definition Card.h:108
float getBasisUY() const
Basis U Y.
Definition Card.h:110
float getBasisNZ() const
Basis N Z.
Definition Card.h:124
float getWorldZ() const
Return the most recently mapped world Z coordinate.
Definition Card.h:106
float getBasisNX() const
Card facing normal after flip (world space).
Definition Card.h:120
void setLogicalRect(float x, float y, float width, float height)
Configure the logical rectangle represented by the world plane.
Definition Card.cpp:26
float getBasisVZ() const
Basis V Z.
Definition Card.h:118
bool mapLayout(float x, float y)
Map a logical point to the configured world plane.
Definition Card.cpp:64
float getLogicalY() const
Return the most recently mapped logical Y coordinate.
Definition Card.h:100
bool mapRay(float ox, float oy, float oz, float dx, float dy, float dz)
Intersect a world ray and store its logical and world hit coordinates.
Definition Card.cpp:40
float getWorldY() const
Return the most recently mapped world Y coordinate.
Definition Card.h:104
float getBasisVX() const
Local card up axis after layout rotation and flip (world space).
Definition Card.h:114
bool isShowingFront() const
Whether the most recent mapCardPose should bind the front face.
Definition Card.h:126
float getBasisNY() const
Basis N Y.
Definition Card.h:122
float getBasisUZ() const
Basis U Z.
Definition Card.h:112
float getBasisVY() const
Basis V Y.
Definition Card.h:116
void setPlane(float ox, float oy, float oz, float ux, float uy, float uz, float vx, float vy, float vz)
Configure world origin plus full-width U and full-height V vectors.
Definition Card.cpp:33
float getLogicalX() const
Return the most recently mapped logical X coordinate.
Definition Card.h:98
eve::Result< void > mapCardPose(float x, float y, float layoutAngleDeg, float flipProgress, float liftPeak, int flipAxis)
Map a card's logical center into a lifted/flipped world pose on the plane.
Definition Card.cpp:74
float getWorldX() const
Return the most recently mapped world X coordinate.
Definition Card.h:102
static condition::ConditionResult evaluate(const CardData *card, const CardDefinition &definition, const condition::Condition &condition, CardPlayConditionQueries queries={})
Evaluate a card definition's play condition against one instance.
Definition CardPlay.cpp:71
卡牌模块入口(eve.Card):定义注册、对象工厂与每帧 update/render。
Definition Card.h:146
condition::ConditionResult evaluatePlay(const CardData *card, CardPlayConditionQueries queries={}) const
Evaluate a card's pure play condition through the shared protocol.
Definition Card.cpp:326
Card()
Declared out of line so the incomplete CardControl member needs no deleter here.
int getCardDefinitionCost(const std::string &id)
Returns the card definition cost.
Definition Card.cpp:384
float getCardDefinitionTintB(const std::string &id)
Returns the card definition tint b.
Definition Card.cpp:409
int zoneCount() const
Zone count.
Definition Card.cpp:515
void renderDeck(graphics::Graphics *gfx)
Renders deck.
Definition Card.cpp:686
LayoutConfig * getConfig() const
Returns the config.
Definition Card.cpp:498
CardData * drawCard(const std::string &handOwner)
从牌库抽一张牌加入指定手牌;无牌时返回 nullptr。
Definition Card.cpp:524
void setBuiltInVisuals(bool enabled)
Enable or disable the built-in card visuals while retaining layout and interaction.
Definition Card.h:347
int getPresentationCount() const
Return the number of entries in the most recently captured buffer.
Definition Card.cpp:587
int registerCardsFromJson(const std::string &json)
从 JSON 注册卡牌类型;返回成功注册数量。
Definition Card.cpp:248
void render(graphics::Graphics *gfx)
绘制手牌/落牌区(与牌库)。
Definition Card.cpp:626
int handCount() const
Hand count.
Definition Card.cpp:500
bool getBuiltInVisuals() const
Return whether Card::render draws the built-in card faces.
Definition Card.h:349
bool hasCardDefinition(const std::string &id)
卡牌类型查询。
Definition Card.cpp:284
LayoutConfig * newConfig()
工厂:对象由 ECS 表持有,脚本持有的是非拥有句柄。
Definition Card.cpp:418
void update(float dt, float mx, float my, bool down)
每帧更新布局与交互。
Definition Card.cpp:598
eve::Result< void > setCardAttribute(CardData &card, std::string_view attribute, double value) const
Set one canonical combat attribute through the Card facade.
Definition Card.cpp:340
std::vector< std::string > gameplayInstances() const
已发布的玩法实例标识(发布顺序)。
Definition Card.cpp:237
Hand * newHand(LayoutConfig *cfg)
创建一个手牌布局。
Definition Card.cpp:476
eve::Result< effects::EffectHandle > applyEffect(CardData &card, const CardEffectDefinition &definition, eve::SubjectRef subject) const
Apply a domain card effect to the card-owned lifecycle component.
Definition Card.cpp:347
float getCardDefinitionTintG(const std::string &id)
Returns the card definition tint g.
Definition Card.cpp:404
void setConfig(LayoutConfig *cfg)
游戏状态:当前布局、手牌、落牌区、牌库。
Definition Card.cpp:494
int getCardDefinitionHealth(const std::string &id)
Returns the card definition health.
Definition Card.cpp:394
eve::Result< void > unpublishGameplay(const std::string &instanceId)
取消发布一个实例;该实例未发布(或 id 非法)时返回诊断。
Definition Card.cpp:220
eve::Result< void > publishGameplay(const std::string &instanceId, const std::string &ownerId, Hand *hand, eve::resource::IResourceAccount *account=nullptr)
把一副手牌发布到共享玩法协议(eve_gameplay / MCP)。
Definition Card.cpp:203
Hand * findHand(const std::string &owner) const
Finds hand.
Definition Card.cpp:507
void clearGameplayControls()
取消发布本模块持有的全部玩法实例。
Definition Card.cpp:231
CardPlaneMapper * newPlaneMapper()
Create a reusable logical-card-canvas to 3D plane mapper.
Definition Card.cpp:483
int gameplayControlCount() const
已发布的玩法实例数量。
Definition Card.cpp:235
Hand * getHand(int index) const
Returns the hand.
Definition Card.cpp:502
int getCardDefinitionCount()
已注册卡牌类型数量。
Definition Card.cpp:269
Deck * getDeck() const
Returns the deck.
Definition Card.cpp:522
bool removeCardDefinition(const std::string &id)
Remove one definition by stable identifier.
Definition Card.cpp:303
int getCardDefinitionAttack(const std::string &id)
Returns the card definition attack.
Definition Card.cpp:389
std::string getCardDefinitionId(int index) const
Return a definition ID in deterministic sorted order.
Definition Card.cpp:271
int capturePresentation()
Capture all live cards into a contiguous presentation snapshot buffer.
Definition Card.cpp:538
eve::Result< void > setCardPlayCondition(const std::string &id, condition::Condition condition)
Replace the side-effect-free condition required to play a definition.
Definition Card.cpp:309
eve::Result< std::size_t > step(const eve::SimulationStep &step)
Advance all card-owned effects and project current health.
Definition Card.cpp:357
bool setCardDefinition(const std::string &id, const std::string &name, const std::string &kind, int cost, int attack, int health, float tintR, float tintG, float tintB)
Insert or replace one definition for project-owned authoring tools.
Definition Card.cpp:286
float getCardDefinitionTintR(const std::string &id)
Returns the card definition tint r.
Definition Card.cpp:399
Deck * newDeck()
Creates a deck. @ownership Caller deletes unless documented otherwise.
Definition Card.cpp:456
std::string getCardDefinitionName(const std::string &id)
Definition Card.cpp:374
void clearCardDefinitions()
清空全部卡牌类型定义。
Definition Card.cpp:263
Zone * getZone(int index) const
Returns the zone.
Definition Card.cpp:517
Zone * newZone(const std::string &id, const std::string &label, float x, float y, float w, float h)
创建一个落牌区。
Definition Card.cpp:463
CardData * newCard(const std::string &defId)
Creates a card. @ownership Caller deletes unless documented otherwise.
Definition Card.cpp:426
CardPresentationSnapshot * getPresentation(int index)
Return an entry from the most recently captured buffer, or nullptr.
Definition Card.cpp:589
std::string getCardDefinitionKind(const std::string &id)
Returns the card definition kind.
Definition Card.cpp:379
eve::Result< double > getCardAttribute(CardData &card, std::string_view attribute) const
Read one canonical combat attribute through the Card facade.
Definition Card.cpp:333
牌库(栈顶在末尾)。
Definition CardTypes.h:207
CardData * get(int index)
CardData * peek()
查看栈顶卡牌(不弹出)。
void push(CardData *c)
将卡牌压入栈顶(末尾)。
Definition CardTypes.h:226
void shuffle()
洗牌。
CardData * draw()
弹出栈顶卡牌(末尾);空牌库返回 nullptr。
void clear()
清空牌库。
Definition CardTypes.h:232
static Deck * createDeck()
创建并触摸 Membership。
int count()
牌库数量/是否为空/按下标取牌。
Definition CardTypes.h:236
手牌:扇形布局 + 悬浮 + 拖拽 + 落区判定 + 渲染。
Definition CardTypes.h:292
CardData * get(int index)
static Hand * createHand()
创建并触摸全部组件。
bool removeCard(CardData *c)
CardData * pick(float px, float py)
命中检测:返回 (px,py) 处最上层卡牌。
void addCard(CardData *c)
手牌增删与查询。
CardData * find(const std::string &id)
落牌区(手牌区 / 出牌区 / 弃牌区),用于拖放命中判定。
Definition CardTypes.h:242
static Zone * createZone()
创建并触摸组件。
Explain one condition evaluation in a UI- and log-friendly form.
Definition Condition.h:137
static ConditionResult failed(ConditionReasonCode reason, Value evidence={}, Value details=Value::Object{})
Construct a rejected result with a stable reason and explanation.
Immutable condition AST node.
Definition Condition.h:199
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
Font * getFont() const
Returns the font.
Definition Graphics.h:1697
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
Provider-neutral resource account contract.
static eve::Result< SettlementRuleSet > fromJson(std::string_view json)
Decode and compile a strict versioned JSON rule document without mutating an existing rule set.
void exposeStageBindings(ssq::Class &cls)
bool ownsCard(const std::vector< ecs::EntityHandle > &handles, const CardData &card)
void renderCardBack(graphics::Graphics *gfx, float x, float y, float w, float h, float angle, float a)
绘制牌背。
void advanceCardFlip(float &flip, float targetFaceDown, float speed, float dt)
Advance animated flip toward a face-down target with frame-rate-normalized speed.
Definition CardTypes.cpp:85
bool resolveCardWantFaceUp(bool cardFaceUp, bool handFaceDown, bool handPeek)
Resolve whether a card should read as face-up under hand faceDown/peek rules.
Definition CardTypes.cpp:92
const char * cardStateName(CardState state)
状态枚举的字符串名(用于脚本/调试)。
Definition CardTypes.cpp:15
CardFlipPose evaluateCardFlip(float flipProgress, float liftPeak)
Evaluate face-down progress into an adapter-facing flip pose.
Definition CardTypes.cpp:74
void printCentered(graphics::Graphics *gfx, const std::string &text, float cx, float cy, float scale, const glm::vec4 &color)
渲染辅助(也供 Zone / Deck 复用)。
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
void registerCppEntityView(const ssq::Class &cls, CppEntityViewFn fn)
Registers cpp entity view.
Definition ECS.cpp:1642
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
One deterministic fixed-step emitted by SimulationClock.
Definition Time.h:158
卡牌类型定义(registerCardsFromJson 注册)。
Definition CardTypes.h:91
std::vector< std::string > tags
Definition tags available to HasTag nodes.
Definition CardTypes.h:102
Strong card definition projected into the common effect definition.
Definition CardEffects.h:40
Mutable card combat state changed by the card effect executor.
Definition CardEffects.h:32
Evaluated flip pose for external 2D/3D adapters (graphics-independent).
Definition CardTypes.h:355
Read-only extension points used while evaluating a card play.
Definition CardPlay.h:30
Immutable presentation data captured from one card for external 2D/3D adapters.
Definition Card.h:41
UiCard 风格的布局配置(脚本可实时修改,对应 UiCard 的 Configs 面板)。
Definition CardTypes.h:46
float cardW
卡牌宽/高(像素)。
Definition CardTypes.h:48
float flipLift
Peak lift (logical pixels) at the edge-on midpoint of a flip.
Definition CardTypes.h:73
float flipSpeed
Face flip lerp speed (same 60fps-normalized units as motionSpeed). Drives the animated 0....
Definition CardTypes.h:71
int flipAxis
Flip hinge: 0 = vertical (width foreshortens / rotate about local up), 1 = horizontal (height foresho...
Definition CardTypes.h:78
float deckX
牌库堆绘制位置。
Definition CardTypes.h:84
bool showZones
是否绘制落牌区。
Definition CardTypes.h:82
std::string id
Definition Widget.h:17
glm::vec4 color