载入中...
搜索中...
未找到
InventorySystem.cpp
浏览该文件的文档.
3#include "inventory/Bag.h"
5#include "inventory/Item.h"
6
7#include <algorithm>
8#include <cmath>
9#include <limits>
10#include <type_traits>
11#include <utility>
12
13namespace eve::inventory {
14
16 Bag *target = nullptr;
17 std::unique_ptr<Bag> baseline;
18 std::unique_ptr<Bag> candidate;
19 std::vector<InventoryChangeEvent> events;
20 int totalAdded = 0;
21};
22
24 Bag *target = nullptr;
25 std::unique_ptr<Bag> baseline;
26 std::unique_ptr<Bag> candidate;
28 int totalRemoved = 0;
29};
30
34PreparedInventoryAdd &PreparedInventoryAdd::operator=(PreparedInventoryAdd &&) noexcept = default;
39
40namespace {
41
42bool tagsIntersect(const std::vector<std::string> &a, const std::vector<std::string> &b) {
43 for (const auto &t : a) {
44 if (std::find(b.begin(), b.end(), t) != b.end()) return true;
45 }
46 return false;
47}
48
49bool propsEqual(const std::unordered_map<std::string, std::string> &a,
50 const std::unordered_map<std::string, std::string> &b) {
51 return a == b;
52}
53
54} // namespace
55
56std::unordered_map<std::string, InventorySystem::AcceptFn> &InventorySystem::acceptRules() {
57 static std::unordered_map<std::string, AcceptFn> t;
58 return t;
59}
60
61std::unordered_map<std::string, InventorySystem::CapacityFn> &InventorySystem::capacityPolicies() {
62 static std::unordered_map<std::string, CapacityFn> t;
63 return t;
64}
65
66std::unordered_map<std::string, InventorySystem::StackFn> &InventorySystem::stackRules() {
67 static std::unordered_map<std::string, StackFn> t;
68 return t;
69}
70
71std::unordered_map<std::string, InventorySystem::ChangeHook> &InventorySystem::changeHooks() {
72 static std::unordered_map<std::string, ChangeHook> t;
73 return t;
74}
75
76std::vector<InventoryChangeEvent> &InventorySystem::eventQueue() {
77 static std::vector<InventoryChangeEvent> q;
78 return q;
79}
80
81int &InventorySystem::instanceCounter() {
82 static int c = 1;
83 return c;
84}
85
86bool &InventorySystem::builtinsReady() {
87 static bool ready = false;
88 return ready;
89}
90
91bool &InventorySystem::changeHooksSuppressed() {
92 static bool suppressed = false;
93 return suppressed;
94}
95
97 if (name.empty() || !fn) return;
98 acceptRules()[name] = std::move(fn);
99}
100
101void InventorySystem::unregisterAcceptRule(const std::string &name) { acceptRules().erase(name); }
102
103bool InventorySystem::hasAcceptRule(const std::string &name) {
105 return acceptRules().count(name) > 0;
106}
107
109 if (name.empty() || !fn) return;
110 capacityPolicies()[name] = std::move(fn);
111}
112
114 capacityPolicies().erase(name);
115}
116
117bool InventorySystem::hasCapacityPolicy(const std::string &name) {
119 return capacityPolicies().count(name) > 0;
120}
121
123 if (name.empty() || !fn) return;
124 stackRules()[name] = std::move(fn);
125}
126
127void InventorySystem::unregisterStackRule(const std::string &name) { stackRules().erase(name); }
128
129bool InventorySystem::hasStackRule(const std::string &name) {
131 return stackRules().count(name) > 0;
132}
133
135 if (name.empty() || !fn) return;
136 changeHooks()[name] = std::move(fn);
137}
138
139void InventorySystem::unregisterChangeHook(const std::string &name) { changeHooks().erase(name); }
140
141bool InventorySystem::hasChangeHook(const std::string &name) {
142 return changeHooks().count(name) > 0;
143}
144
146 if (builtinsReady()) return;
147 builtinsReady() = true;
148
149 registerAcceptRule("any", [](const Bag &, const ItemDefinition &, int, std::string *) {
150 return true;
151 });
152
153 registerAcceptRule("default", [](const Bag &bag, const ItemDefinition &def, int,
154 std::string *reason) {
155 if (!bag.rejectTags().empty() && tagsIntersect(def.tags, bag.rejectTags())) {
156 if (reason) *reason = "rejected_tag";
157 return false;
158 }
159 if (!bag.acceptTags().empty() && !tagsIntersect(def.tags, bag.acceptTags())) {
160 if (reason) *reason = "accept_tag_mismatch";
161 return false;
162 }
163 return true;
164 });
165
166 auto slotsOk = [](const Bag &bag, const ItemDefinition &def, int quantity, std::string *reason) {
167 int need = quantity;
168 for (int i = 0; i < bag.getSlotCount() && need > 0; ++i) {
169 int space = freeSpaceInSlot(bag, i, def);
170 if (space > 0) need -= space;
171 }
172 if (need > 0) {
173 if (reason) *reason = "no_slot";
174 return false;
175 }
176 return true;
177 };
178
179 auto weightOk = [](const Bag &bag, const ItemDefinition &def, int quantity, std::string *reason) {
180 if (bag.getMaxWeight() <= 0.f) return true;
181 float add = def.weight * float(quantity);
182 if (usedWeight(&bag) + add > bag.getMaxWeight() + 1e-6f) {
183 if (reason) *reason = "over_weight";
184 return false;
185 }
186 return true;
187 };
188
189 auto volumeOk = [](const Bag &bag, const ItemDefinition &def, int quantity, std::string *reason) {
190 if (bag.getMaxVolume() <= 0.f) return true;
191 float add = def.volume * float(quantity);
192 if (usedVolume(&bag) + add > bag.getMaxVolume() + 1e-6f) {
193 if (reason) *reason = "over_volume";
194 return false;
195 }
196 return true;
197 };
198
199 registerCapacityPolicy("unlimited",
200 [](const Bag &, const ItemDefinition &, int, std::string *) { return true; });
201 registerCapacityPolicy("slots", slotsOk);
202 registerCapacityPolicy("weight", weightOk);
203 registerCapacityPolicy("volume", volumeOk);
204 registerCapacityPolicy("slotsAndWeight", [slotsOk, weightOk](const Bag &bag,
205 const ItemDefinition &def,
206 int quantity, std::string *reason) {
207 return slotsOk(bag, def, quantity, reason) && weightOk(bag, def, quantity, reason);
208 });
209 registerCapacityPolicy("slotsWeightVolume",
210 [slotsOk, weightOk, volumeOk](const Bag &bag, const ItemDefinition &def,
211 int quantity, std::string *reason) {
212 return slotsOk(bag, def, quantity, reason) &&
213 weightOk(bag, def, quantity, reason) &&
214 volumeOk(bag, def, quantity, reason);
215 });
216
217 registerStackRule("sameItem",
218 [](const ItemStack &a, const ItemStack &b, const ItemDefinition &) {
219 return !a.empty() && !b.empty() && a.itemId == b.itemId;
220 });
221 registerStackRule("sameItemAndProps",
222 [](const ItemStack &a, const ItemStack &b, const ItemDefinition &) {
223 return !a.empty() && !b.empty() && a.itemId == b.itemId &&
224 propsEqual(a.props, b.props) &&
225 std::fabs(a.durability - b.durability) < 1e-6f;
226 });
227 registerStackRule("never", [](const ItemStack &, const ItemStack &, const ItemDefinition &) {
228 return false;
229 });
230}
231
232int InventorySystem::nextInstanceId() { return instanceCounter()++; }
233
234void InventorySystem::ensureNextInstanceIdAbove(int usedInstanceId) noexcept {
235 if (instanceCounter() <= usedInstanceId) instanceCounter() = usedInstanceId + 1;
236}
237
238std::unique_ptr<Bag> InventorySystem::cloneBag(const Bag &source) {
239 auto clone = std::make_unique<Bag>(source.getSlotCount());
240 clone->id_ = source.id_;
241 clone->kind_ = source.kind_;
242 clone->maxWeight_ = source.maxWeight_;
243 clone->maxVolume_ = source.maxVolume_;
244 clone->acceptRule_ = source.acceptRule_;
245 clone->capacityPolicy_ = source.capacityPolicy_;
246 clone->stackRule_ = source.stackRule_;
247 clone->acceptTags_ = source.acceptTags_;
248 clone->rejectTags_ = source.rejectTags_;
249 clone->slots_ = source.slots_;
250 clone->extra_ = source.extra_;
251 return clone;
252}
253
254bool InventorySystem::bagsEqual(const Bag &target, const Bag &baseline) {
255 if (target.id_ != baseline.id_ || target.kind_ != baseline.kind_ ||
256 target.maxWeight_ != baseline.maxWeight_ || target.maxVolume_ != baseline.maxVolume_ ||
257 target.acceptRule_ != baseline.acceptRule_ ||
258 target.capacityPolicy_ != baseline.capacityPolicy_ || target.stackRule_ != baseline.stackRule_ ||
259 target.acceptTags_ != baseline.acceptTags_ || target.rejectTags_ != baseline.rejectTags_ ||
260 target.extra_ != baseline.extra_ || target.slots_.size() != baseline.slots_.size())
261 return false;
262 for (std::size_t i = 0; i < target.slots_.size(); ++i) {
263 const auto &a = target.slots_[i];
264 const auto &b = baseline.slots_[i];
265 if (a.instanceId != b.instanceId || a.itemId != b.itemId || a.quantity != b.quantity ||
266 a.durability != b.durability || a.props != b.props || a.tags != b.tags)
267 return false;
268 }
269 return true;
270}
271
272void InventorySystem::emit(InventoryChangeEvent ev) {
273 if (!changeHooksSuppressed()) {
274 for (auto &kv : changeHooks()) {
275 if (!kv.second) continue;
276 try {
277 kv.second(ev);
278 } catch (...) {
279 // Hooks are post-commit observers. One faulty observer must not
280 // unwind an already committed authoritative inventory change or
281 // prevent the remaining observers and poll queue from seeing it.
282 }
283 }
284 }
285 eventQueue().push_back(std::move(ev));
286}
287
288void InventorySystem::pushEvent(InventoryChangeEvent ev) { emit(std::move(ev)); }
289
290void InventorySystem::pollEvents(std::vector<InventoryChangeEvent> &out) {
291 out = eventQueue();
292 eventQueue().clear();
293}
294
295void InventorySystem::clearEvents() { eventQueue().clear(); }
296
297const std::vector<InventoryChangeEvent> &InventorySystem::events() { return eventQueue(); }
298
299bool InventorySystem::canStackTogether(const Bag &bag, const ItemStack &a, const ItemStack &b,
300 const ItemDefinition &def) {
302 auto it = stackRules().find(bag.getStackRule());
303 if (it == stackRules().end() || !it->second) {
304 return !a.empty() && !b.empty() && a.itemId == b.itemId;
305 }
306 return it->second(a, b, def);
307}
308
309bool InventorySystem::checkAccept(const Bag &bag, const ItemDefinition &def, int quantity,
310 std::string *reason) {
312 auto it = acceptRules().find(bag.getAcceptRule());
313 if (it == acceptRules().end() || !it->second) {
314 if (reason) *reason = "unknown_accept_rule";
315 return false;
316 }
317 return it->second(bag, def, quantity, reason);
318}
319
320bool InventorySystem::checkCapacity(const Bag &bag, const ItemDefinition &def, int quantity,
321 std::string *reason) {
323 auto it = capacityPolicies().find(bag.getCapacityPolicy());
324 if (it == capacityPolicies().end() || !it->second) {
325 if (reason) *reason = "unknown_capacity_policy";
326 return false;
327 }
328 return it->second(bag, def, quantity, reason);
329}
330
331int InventorySystem::freeSpaceInSlot(const Bag &bag, int slot, const ItemDefinition &def) {
332 if (slot < 0 || slot >= bag.getSlotCount()) return 0;
333 const auto &s = bag.slots()[size_t(slot)];
334 int maxStack = def.maxStack > 0 ? def.maxStack : 1;
335 // If the bag's stack rule rejects merging two identical probes, treat every
336 // slot as capacity 1 (e.g. built-in "never").
337 {
338 ItemStack probeA;
339 probeA.itemId = def.id;
340 probeA.quantity = 1;
341 ItemStack probeB = probeA;
342 probeB.instanceId = 1;
343 if (!canStackTogether(bag, probeA, probeB, def)) maxStack = 1;
344 }
345 if (s.empty()) return maxStack;
346 ItemStack probe;
347 probe.itemId = def.id;
348 probe.quantity = 1;
349 if (!canStackTogether(bag, s, probe, def)) return 0;
350 return std::max(0, maxStack - s.quantity);
351}
352
353bool InventorySystem::canAdd(Bag *bag, const std::string &itemId, int quantity,
354 std::string *reason) {
355 if (!bag || quantity <= 0) {
356 if (reason) *reason = "invalid_args";
357 return false;
358 }
360 if (!def) {
361 if (reason) *reason = "unknown_item";
362 return false;
363 }
364 if (!checkAccept(*bag, *def, quantity, reason)) return false;
365 if (!checkCapacity(*bag, *def, quantity, reason)) return false;
366 return true;
367}
368
369int InventorySystem::addItem(Bag *bag, const std::string &itemId, int quantity) {
370 return addItemImpl(bag, itemId, quantity, true);
371}
372
373int InventorySystem::addItemImpl(Bag *bag, const std::string &itemId, int quantity,
374 bool publish) {
375 if (!bag || quantity <= 0) return 0;
377 if (!def) return 0;
378 // Accept is all-or-nothing for the requested item type (not quantity-scaled).
379 if (!checkAccept(*bag, *def, 1, nullptr)) return 0;
380
381 int remaining = quantity;
382 int added = 0;
383
384 auto maxFittable = [&](int space) -> int {
385 int lo = 0, hi = std::min(space, remaining);
386 while (lo < hi) {
387 int mid = lo + (hi - lo + 1) / 2;
388 if (checkCapacity(*bag, *def, mid, nullptr))
389 lo = mid;
390 else
391 hi = mid - 1;
392 }
393 return lo;
394 };
395
396 // Pass 1: fill existing stacks.
397 for (int i = 0; i < bag->getSlotCount() && remaining > 0; ++i) {
398 int space = freeSpaceInSlot(*bag, i, *def);
399 auto &s = bag->slots()[size_t(i)];
400 if (s.empty() || space <= 0) continue;
401 int put = maxFittable(space);
402 if (put <= 0) continue;
403 s.quantity += put;
404 remaining -= put;
405 added += put;
406 }
407
408 // Pass 2: empty slots.
409 for (int i = 0; i < bag->getSlotCount() && remaining > 0; ++i) {
410 auto &s = bag->slots()[size_t(i)];
411 if (!s.empty()) continue;
412 int space = freeSpaceInSlot(*bag, i, *def);
413 int put = maxFittable(space);
414 if (put <= 0) continue;
415 s.instanceId = nextInstanceId();
416 s.itemId = def->id;
417 s.quantity = put;
418 s.durability = -1.f;
419 s.props.clear();
420 s.tags.clear();
421 remaining -= put;
422 added += put;
423 }
424
425 if (publish && added > 0) {
426 InventoryChangeEvent ev;
427 ev.action = "add";
428 ev.bagId = bag->getId();
429 ev.itemId = itemId;
430 ev.quantity = added;
431 emit(std::move(ev));
432 }
433 return added;
434}
435
437InventorySystem::prepareAddBatch(Bag *bag, const std::vector<InventoryItemGrant> &grants) {
438 if (!bag)
440 eve::DiagnosticCode::InvalidArgument, "inventory batch requires a Bag", "bag"));
441 if (grants.empty())
443 eve::DiagnosticCode::InvalidArgument, "inventory batch requires at least one grant", "grants"));
444
445 PreparedInventoryAdd prepared;
446 prepared.state_ = std::make_unique<PreparedInventoryAdd::State>();
447 prepared.state_->target = bag;
448 prepared.state_->baseline = cloneBag(*bag);
449 prepared.state_->candidate = cloneBag(*bag);
450 prepared.state_->events.reserve(grants.size());
451 for (std::size_t index = 0; index < grants.size(); ++index) {
452 const auto &grant = grants[index];
453 if (grant.itemId.empty() || grant.quantity <= 0)
455 eve::DiagnosticCode::InvalidArgument, "inventory grant requires an item id and positive quantity",
456 "grants[" + std::to_string(index) + "]"));
457 const int added = addItemImpl(prepared.state_->candidate.get(), grant.itemId, grant.quantity, false);
458 if (added != grant.quantity)
462 ItemRegistry::find(grant.itemId) ? "inventory cannot fit the complete reward batch"
463 : "inventory reward references an unknown item",
464 "grants[" + std::to_string(index) + "].itemId", {{"itemId", grant.itemId}},
465 "inventory.prepare-add-batch"));
466 if (prepared.state_->totalAdded > std::numeric_limits<int>::max() - added)
468 eve::DiagnosticCode::InvalidArgument, "inventory batch total quantity overflows", "grants"));
469 prepared.state_->totalAdded += added;
471 event.action = "add";
472 event.bagId = bag->getId();
473 event.itemId = grant.itemId;
474 event.quantity = added;
475 prepared.state_->events.push_back(std::move(event));
476 }
477 return eve::Result<PreparedInventoryAdd>::success(std::move(prepared),
479}
480
482 if (!prepared.state_ || !prepared.state_->target || !prepared.state_->baseline ||
483 !prepared.state_->candidate)
485 eve::DiagnosticCode::InvalidArgument, "inventory batch is empty or already consumed", "prepared"));
486 Bag &target = *prepared.state_->target;
487 const Bag &baseline = *prepared.state_->baseline;
488 if (!bagsEqual(target, baseline))
490 eve::DiagnosticCode::Conflict, "Bag changed after inventory batch preparation", "bag"));
491
492 target.slots_.swap(prepared.state_->candidate->slots_);
493 const int totalAdded = prepared.state_->totalAdded;
494 for (auto &event : prepared.state_->events) emit(std::move(event));
495 prepared.state_.reset();
497}
498
500InventorySystem::prepareRemove(Bag *bag, const std::string &itemId, int quantity) {
501 if (!bag || itemId.empty() || quantity <= 0)
504 "inventory removal requires a Bag, item id, and positive quantity", "removal"));
507 eve::DiagnosticCode::NotFound, "inventory removal references an unknown item", "itemId",
508 {{"itemId", itemId}}, "inventory.prepare-remove"));
509 if (countItem(bag, itemId) < quantity)
512 "inventory does not contain the complete removal quantity", "quantity",
513 {{"itemId", itemId}}, "inventory.prepare-remove"));
514
516 prepared.state_ = std::make_unique<PreparedInventoryRemove::State>();
517 prepared.state_->target = bag;
518 prepared.state_->baseline = cloneBag(*bag);
519 prepared.state_->candidate = cloneBag(*bag);
520 int remaining = quantity;
521 for (auto &stack : prepared.state_->candidate->slots_) {
522 if (remaining <= 0) break;
523 if (stack.empty() || stack.itemId != itemId) continue;
524 const int take = std::min(stack.quantity, remaining);
525 stack.quantity -= take;
526 remaining -= take;
527 if (stack.quantity <= 0) stack.clear();
528 }
529 prepared.state_->totalRemoved = quantity;
530 prepared.state_->event.action = "remove";
531 prepared.state_->event.bagId = bag->getId();
532 prepared.state_->event.itemId = itemId;
533 prepared.state_->event.quantity = quantity;
535 std::move(prepared), eve::Status::success(eve::StatusCode::Pending));
536}
537
539 if (!prepared.state_ || !prepared.state_->target || !prepared.state_->baseline ||
540 !prepared.state_->candidate)
542 eve::DiagnosticCode::InvalidArgument, "inventory removal is empty or already consumed", "prepared"));
543 Bag &target = *prepared.state_->target;
544 if (!bagsEqual(target, *prepared.state_->baseline))
546 eve::DiagnosticCode::Conflict, "Bag changed after inventory removal preparation", "bag"));
547 target.slots_.swap(prepared.state_->candidate->slots_);
548 const int removed = prepared.state_->totalRemoved;
549 emit(std::move(prepared.state_->event));
550 prepared.state_.reset();
552}
553
554int InventorySystem::removeItem(Bag *bag, const std::string &itemId, int quantity) {
555 if (!bag || quantity <= 0 || itemId.empty()) return 0;
556 int remaining = quantity;
557 int removed = 0;
558 for (int i = 0; i < bag->getSlotCount() && remaining > 0; ++i) {
559 auto &s = bag->slots()[size_t(i)];
560 if (s.empty() || s.itemId != itemId) continue;
561 int take = std::min(s.quantity, remaining);
562 s.quantity -= take;
563 remaining -= take;
564 removed += take;
565 if (s.quantity <= 0) s.clear();
566 }
567 if (removed > 0) {
569 ev.action = "remove";
570 ev.bagId = bag->getId();
571 ev.itemId = itemId;
572 ev.quantity = removed;
573 emit(std::move(ev));
574 }
575 return removed;
576}
577
578int InventorySystem::removeAt(Bag *bag, int slot, int quantity) {
579 if (!bag || slot < 0 || slot >= bag->getSlotCount() || quantity <= 0) return 0;
580 auto &s = bag->slots()[size_t(slot)];
581 if (s.empty()) return 0;
582 int take = std::min(s.quantity, quantity);
583 std::string itemId = s.itemId;
584 s.quantity -= take;
585 if (s.quantity <= 0) s.clear();
587 ev.action = "remove";
588 ev.bagId = bag->getId();
589 ev.itemId = itemId;
590 ev.quantity = take;
591 ev.slot = slot;
592 emit(std::move(ev));
593 return take;
594}
595
596bool InventorySystem::swapSlots(Bag *bag, int slotA, int slotB) {
597 if (!bag || slotA < 0 || slotB < 0 || slotA >= bag->getSlotCount() ||
598 slotB >= bag->getSlotCount() || slotA == slotB)
599 return false;
600 std::swap(bag->slots()[size_t(slotA)], bag->slots()[size_t(slotB)]);
602 ev.action = "swap";
603 ev.bagId = bag->getId();
604 ev.slot = slotA;
605 ev.otherSlot = slotB;
606 emit(std::move(ev));
607 return true;
608}
609
610bool InventorySystem::moveSlot(Bag *bag, int fromSlot, int toSlot) {
611 if (!bag || fromSlot < 0 || toSlot < 0 || fromSlot >= bag->getSlotCount() ||
612 toSlot >= bag->getSlotCount() || fromSlot == toSlot)
613 return false;
614 auto &from = bag->slots()[size_t(fromSlot)];
615 auto &to = bag->slots()[size_t(toSlot)];
616 if (from.empty()) return false;
617
618 if (to.empty()) {
619 to = from;
620 from.clear();
622 ev.action = "move";
623 ev.bagId = bag->getId();
624 ev.itemId = to.itemId;
625 ev.quantity = to.quantity;
626 ev.slot = fromSlot;
627 ev.otherSlot = toSlot;
628 emit(std::move(ev));
629 return true;
630 }
631
632 const ItemDefinition *def = ItemRegistry::find(from.itemId);
633 if (!def) return false;
634 if (canStackTogether(*bag, from, to, *def)) {
635 int maxStack = def->maxStack > 0 ? def->maxStack : 1;
636 int space = maxStack - to.quantity;
637 if (space <= 0) return false;
638 int put = std::min(space, from.quantity);
639 to.quantity += put;
640 from.quantity -= put;
641 if (from.quantity <= 0) from.clear();
643 ev.action = "merge";
644 ev.bagId = bag->getId();
645 ev.itemId = to.itemId;
646 ev.quantity = put;
647 ev.slot = fromSlot;
648 ev.otherSlot = toSlot;
649 emit(std::move(ev));
650 return true;
651 }
652 return swapSlots(bag, fromSlot, toSlot);
653}
654
655bool InventorySystem::splitStack(Bag *bag, int slot, int quantity, int toSlot) {
656 if (!bag || slot < 0 || toSlot < 0 || slot >= bag->getSlotCount() ||
657 toSlot >= bag->getSlotCount() || slot == toSlot || quantity <= 0)
658 return false;
659 auto &from = bag->slots()[size_t(slot)];
660 auto &to = bag->slots()[size_t(toSlot)];
661 if (from.empty() || !to.empty()) return false;
662 if (quantity >= from.quantity) return false;
663
664 to = from;
665 to.instanceId = nextInstanceId();
666 to.quantity = quantity;
667 from.quantity -= quantity;
668
670 ev.action = "split";
671 ev.bagId = bag->getId();
672 ev.itemId = from.itemId;
673 ev.quantity = quantity;
674 ev.slot = slot;
675 ev.otherSlot = toSlot;
676 emit(std::move(ev));
677 return true;
678}
679
680int InventorySystem::transfer(Bag *from, Bag *to, const std::string &itemId, int quantity) {
681 if (!from || !to || quantity <= 0 || itemId.empty()) return 0;
682 int available = countItem(from, itemId);
683 int want = std::min(available, quantity);
684 if (want <= 0) return 0;
685
686 for (int n = want; n >= 1; --n) {
687 if (!canAdd(to, itemId, n, nullptr)) continue;
688
689 // Detach from source without emitting per-slot remove events.
690 int remaining = n;
691 for (int i = 0; i < from->getSlotCount() && remaining > 0; ++i) {
692 auto &s = from->slots()[size_t(i)];
693 if (s.empty() || s.itemId != itemId) continue;
694 int take = std::min(s.quantity, remaining);
695 s.quantity -= take;
696 remaining -= take;
697 if (s.quantity <= 0) s.clear();
698 }
699
700 int added = addItem(to, itemId, n);
701 if (added < n) {
702 // Roll back shortfall into source (best-effort).
703 int needRestore = n - added;
704 addItem(from, itemId, needRestore);
705 }
706 if (added > 0) {
708 ev.action = "transfer";
709 ev.bagId = from->getId();
710 ev.otherBagId = to->getId();
711 ev.itemId = itemId;
712 ev.quantity = added;
713 emit(std::move(ev));
714 }
715 return added;
716 }
717 return 0;
718}
719
720int InventorySystem::transferSlot(Bag *from, int fromSlot, Bag *to, int quantity) {
721 if (!from || !to || fromSlot < 0 || fromSlot >= from->getSlotCount() || quantity <= 0)
722 return 0;
723 auto &s = from->slots()[size_t(fromSlot)];
724 if (s.empty()) return 0;
725 int want = std::min(s.quantity, quantity);
726 std::string itemId = s.itemId;
727
728 for (int n = want; n >= 1; --n) {
729 if (!canAdd(to, itemId, n, nullptr)) continue;
730
731 // Prefer preserving instance/props when moving a whole stack into an empty target slot.
732 if (n == s.quantity) {
733 int empty = -1;
734 for (int i = 0; i < to->getSlotCount(); ++i) {
735 if (to->slots()[size_t(i)].empty()) {
736 empty = i;
737 break;
738 }
739 }
741 bool canPlaceWhole = empty >= 0 && def != nullptr;
742 if (canPlaceWhole) {
743 // Also allow merging into an existing compatible stack instead.
744 bool merged = false;
745 for (int i = 0; i < to->getSlotCount(); ++i) {
746 auto &ts = to->slots()[size_t(i)];
747 if (ts.empty()) continue;
748 if (!canStackTogether(*to, s, ts, *def)) continue;
749 int maxStack = def->maxStack > 0 ? def->maxStack : 1;
750 int space = maxStack - ts.quantity;
751 if (space < n) continue;
752 if (!checkCapacity(*to, *def, n, nullptr)) continue;
753 ts.quantity += n;
754 s.clear();
756 ev.action = "transfer";
757 ev.bagId = from->getId();
758 ev.otherBagId = to->getId();
759 ev.itemId = itemId;
760 ev.quantity = n;
761 ev.slot = fromSlot;
762 ev.otherSlot = i;
763 emit(std::move(ev));
764 merged = true;
765 break;
766 }
767 if (merged) return n;
768
769 if (checkCapacity(*to, *def, n, nullptr) && checkAccept(*to, *def, n, nullptr)) {
770 to->slots()[size_t(empty)] = s;
771 s.clear();
773 ev.action = "transfer";
774 ev.bagId = from->getId();
775 ev.otherBagId = to->getId();
776 ev.itemId = itemId;
777 ev.quantity = n;
778 ev.slot = fromSlot;
779 ev.otherSlot = empty;
780 emit(std::move(ev));
781 return n;
782 }
783 }
784 }
785
786 s.quantity -= n;
787 if (s.quantity <= 0) s.clear();
788 int added = addItem(to, itemId, n);
789 if (added < n) {
790 // Restore remainder into original slot if possible.
791 auto &fs = from->slots()[size_t(fromSlot)];
792 if (fs.empty()) {
793 fs.itemId = itemId;
794 fs.quantity = n - added;
795 fs.instanceId = nextInstanceId();
796 } else if (fs.itemId == itemId) {
797 fs.quantity += (n - added);
798 } else {
799 addItem(from, itemId, n - added);
800 }
801 }
802 if (added > 0) {
804 ev.action = "transfer";
805 ev.bagId = from->getId();
806 ev.otherBagId = to->getId();
807 ev.itemId = itemId;
808 ev.quantity = added;
809 ev.slot = fromSlot;
810 emit(std::move(ev));
811 }
812 return added;
813 }
814 return 0;
815}
816
817int InventorySystem::countItem(const Bag *bag, const std::string &itemId) {
818 if (!bag) return 0;
819 int n = 0;
820 for (const auto &s : bag->slots()) {
821 if (!s.empty() && s.itemId == itemId) n += s.quantity;
822 }
823 return n;
824}
825
826int InventorySystem::findItem(const Bag *bag, const std::string &itemId) {
827 if (!bag) return -1;
828 for (int i = 0; i < bag->getSlotCount(); ++i) {
829 const auto &s = bag->slots()[size_t(i)];
830 if (!s.empty() && s.itemId == itemId) return i;
831 }
832 return -1;
833}
834
835int InventorySystem::findItemByTag(const Bag *bag, const std::string &tag) {
836 if (!bag || tag.empty()) return -1;
837 for (int i = 0; i < bag->getSlotCount(); ++i) {
838 const auto &s = bag->slots()[size_t(i)];
839 if (s.empty()) continue;
840 if (s.hasTag(tag)) return i;
841 const ItemDefinition *def = ItemRegistry::find(s.itemId);
842 if (def && def->hasTag(tag)) return i;
843 }
844 return -1;
845}
846
848 if (!bag) return 0.f;
849 float w = 0.f;
850 for (const auto &s : bag->slots()) {
851 if (s.empty()) continue;
852 const ItemDefinition *def = ItemRegistry::find(s.itemId);
853 if (def) w += def->weight * float(s.quantity);
854 }
855 return w;
856}
857
859 if (!bag) return 0.f;
860 float v = 0.f;
861 for (const auto &s : bag->slots()) {
862 if (s.empty()) continue;
863 const ItemDefinition *def = ItemRegistry::find(s.itemId);
864 if (def) v += def->volume * float(s.quantity);
865 }
866 return v;
867}
868
870 if (!bag) return 0;
871 int n = 0;
872 for (const auto &s : bag->slots()) {
873 if (!s.empty()) ++n;
874 }
875 return n;
876}
877
879 if (!bag) return;
880 for (auto &s : bag->slots()) s.clear();
882 ev.action = "remove";
883 ev.bagId = bag->getId();
884 ev.quantity = 0;
885 emit(std::move(ev));
886}
887
888bool InventorySystem::equipFromBag(EquipmentSet *eq, const std::string &equipSlot, Bag *bag,
889 int bagSlot) {
890 if (!eq || !bag) return false;
891 std::string reason;
892 if (!eq->canEquipFromBag(bag, bagSlot, equipSlot, &reason)) return false;
893
894 auto &bs = bag->slots()[size_t(bagSlot)];
895 ItemStack moving = bs;
896 static_assert(std::is_nothrow_move_assignable_v<ItemStack>);
897 // Equipment slots hold one logical item (quantity preserved but typically 1).
898 bs.clear();
899
900 auto *dest = eq->stackAt(equipSlot);
901 if (!dest) {
902 // restore
903 bag->slots()[size_t(bagSlot)] = std::move(moving);
904 return false;
905 }
906
907 // If slot occupied, try swap into bagSlot (now empty).
908 if (!dest->empty()) {
909 bag->slots()[size_t(bagSlot)] = *dest;
910 }
911 *dest = std::move(moving);
912
914 ev.action = "equip";
915 ev.bagId = bag->getId();
916 ev.itemId = dest->itemId;
917 ev.quantity = dest->quantity;
918 ev.slot = bagSlot;
919 ev.equipSlot = equipSlot;
920 emit(std::move(ev));
921 return true;
922}
923
924bool InventorySystem::unequipToBag(EquipmentSet *eq, const std::string &equipSlot, Bag *bag) {
925 if (!eq || !bag) return false;
926 auto *src = eq->stackAt(equipSlot);
927 if (!src || src->empty()) return false;
928
929 // Find empty slot first to preserve instance/props.
930 int empty = -1;
931 for (int i = 0; i < bag->getSlotCount(); ++i) {
932 if (bag->slots()[size_t(i)].empty()) {
933 empty = i;
934 break;
935 }
936 }
937 if (empty < 0) {
938 // Fall back to addItem (may stack, losing instance identity).
939 if (!canAdd(bag, src->itemId, src->quantity, nullptr)) return false;
940 std::string itemId = src->itemId;
941 int qty = src->quantity;
942 src->clear();
943 int added = addItem(bag, itemId, qty);
944 if (added < qty) {
945 // restore
946 src->itemId = itemId;
947 src->quantity = qty - added;
948 src->instanceId = nextInstanceId();
949 }
951 ev.action = "unequip";
952 ev.bagId = bag->getId();
953 ev.itemId = itemId;
954 ev.quantity = added;
955 ev.equipSlot = equipSlot;
956 emit(std::move(ev));
957 return added > 0;
958 }
959
960 bag->slots()[size_t(empty)] = *src;
961 std::string itemId = src->itemId;
962 int qty = src->quantity;
963 src->clear();
964
966 ev.action = "unequip";
967 ev.bagId = bag->getId();
968 ev.itemId = itemId;
969 ev.quantity = qty;
970 ev.slot = empty;
971 ev.equipSlot = equipSlot;
972 emit(std::move(ev));
973 return true;
974}
975
976} // namespace eve::inventory
LogicalId target
LogicalId itemId
float w
Definition AnimClip.cpp:738
int mid
Definition AnimSmr.cpp:120
const std::string & s
std::string name
Definition ECS.cpp:154
int bagSlot
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
float v
std::int32_t c
std::string to
std::string from
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
const std::string * tag
float t
std::string slot
int removed
ScriptStructure out
std::string_view source
size_t end
Share string attribute map operations through the Windows Foundation DLL.
uint32_t index
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
格子型物品容器(脚本可直接操作)。
Definition Bag.h:22
std::string getId() const
容器 id(变更事件定位用)。
Definition Bag.h:36
float getMaxVolume() const
Returns the max volume.
Definition Bag.h:55
const std::vector< ItemStack > & slots() const
Slots.
Definition Bag.h:150
const std::vector< std::string > & rejectTags() const
Reject tags.
Definition Bag.h:156
float getMaxWeight() const
重量 / 体积上限(容量策略用)。
Definition Bag.h:51
const std::vector< std::string > & acceptTags() const
Accept tags.
Definition Bag.h:154
std::string getStackRule() const
Returns the stack rule.
Definition Bag.h:68
int getSlotCount() const
格数。
Definition Bag.h:46
EVENGINE_API_FOUNDATION public API.
Definition Equipment.h:19
const ItemStack * stackAt(const std::string &slotName) const
Stack at.
Definition Equipment.cpp:68
bool canEquipFromBag(Bag *bag, int bagSlot, const std::string &equipSlot, std::string *reason=nullptr) const
Can equip from bag.
Definition Equipment.cpp:83
static void unregisterStackRule(const std::string &name)
Unregisters stack rule.
static int addItem(Bag *bag, const std::string &itemId, int quantity)
返回实际放入数量(可能部分成功)。
static void registerStackRule(const std::string &name, StackFn fn)
Registers stack rule.
static bool equipFromBag(EquipmentSet *eq, const std::string &equipSlot, Bag *bag, int bagSlot)
Equip from bag.
static void ensureBuiltins()
确保内置规则已注册(模块首次使用时自动调用)。
static const std::vector< InventoryChangeEvent > & events()
Events.
static bool unequipToBag(EquipmentSet *eq, const std::string &equipSlot, Bag *bag)
Unequip to bag.
static bool canAdd(Bag *bag, const std::string &itemId, int quantity, std::string *reason=nullptr)
Can add.
static bool swapSlots(Bag *bag, int slotA, int slotB)
Swap slots.
static float usedWeight(const Bag *bag)
Used weight.
static bool hasChangeHook(const std::string &name)
True when change hook.
static eve::Result< int > commitRemove(PreparedInventoryRemove prepared)
Commit a prepared removal and publish its event after the no-fail slot swap.
std::function< void(const InventoryChangeEvent &ev)> ChangeHook
static void registerCapacityPolicy(const std::string &name, CapacityFn fn)
Registers capacity policy.
static float usedVolume(const Bag *bag)
Used volume.
std::function< bool(const Bag &bag, const ItemDefinition &def, int quantity, std::string *reason)> CapacityFn
static eve::Result< int > commitAddBatch(PreparedInventoryAdd prepared)
Commit one prepared addition and then publish its change events.
static void unregisterCapacityPolicy(const std::string &name)
Unregisters capacity policy.
static int nextInstanceId()
Next instance id.
static void pushEvent(InventoryChangeEvent ev)
Pushes event.
static eve::Result< PreparedInventoryAdd > prepareAddBatch(Bag *bag, const std::vector< InventoryItemGrant > &grants)
Validate a multi-item addition against a private candidate Bag.
static bool splitStack(Bag *bag, int slot, int quantity, int toSlot)
Split stack.
std::function< bool(const Bag &bag, const ItemDefinition &def, int quantity, std::string *reason)> AcceptFn
static void registerAcceptRule(const std::string &name, AcceptFn fn)
Registers accept rule.
static int countItem(const Bag *bag, const std::string &itemId)
Returns the number of item.
static void registerChangeHook(const std::string &name, ChangeHook fn)
Registers change hook.
static int usedSlotCount(const Bag *bag)
Used slot count.
static bool hasStackRule(const std::string &name)
True when stack rule.
static void clearBag(Bag *bag)
Clears bag.
static int transfer(Bag *from, Bag *to, const std::string &itemId, int quantity)
Transfer.
static bool hasAcceptRule(const std::string &name)
True when accept rule.
static void unregisterAcceptRule(const std::string &name)
Unregisters accept rule.
std::function< bool(const ItemStack &a, const ItemStack &b, const ItemDefinition &def)> StackFn
static void unregisterChangeHook(const std::string &name)
Unregisters change hook.
static int removeAt(Bag *bag, int slot, int quantity)
Removes at.
static int removeItem(Bag *bag, const std::string &itemId, int quantity)
static bool moveSlot(Bag *bag, int fromSlot, int toSlot)
Moves slot.
static bool hasCapacityPolicy(const std::string &name)
True when capacity policy.
static int transferSlot(Bag *from, int fromSlot, Bag *to, int quantity)
Transfer slot.
static int findItemByTag(const Bag *bag, const std::string &tag)
Finds item by tag.
static void clearEvents()
Clears events.
static void pollEvents(std::vector< InventoryChangeEvent > &out)
Polls events.
static eve::Result< PreparedInventoryRemove > prepareRemove(Bag *bag, const std::string &itemId, int quantity)
Prepare removal of one exact item quantity without mutation or events.
static int findItem(const Bag *bag, const std::string &itemId)
Finds item.
static const ItemDefinition * find(const std::string &id)
Finds find.
Definition Item.cpp:53
Move-only, validated inventory state prepared for one Bag.
PreparedInventoryAdd()
Prepared inventory add.
~PreparedInventoryAdd()
Prepared inventory add.
Move-only, validated inventory removal prepared for one Bag.
运行时容器:固定格数的背包 / 箱子 / 商店栏等。 行为由 InventorySystem 提供;本类暴露便于脚本绑定的薄封装方法。
SettlementPipeline::Stage fn
一次成功库存变更的事件(供脚本 poll / C++ hook)。
Definition ItemTypes.h:56
std::string action
add/remove/move/swap/split/merge/transfer/equip/unequip
Definition ItemTypes.h:57
物品模板(进程级注册表中的定义,不含运行时数量)。
Definition ItemTypes.h:16
std::vector< std::string > tags
Definition ItemTypes.h:22
bool hasTag(const std::string &tag) const
True when tag.
Definition Item.cpp:11
容器中的一格堆叠(空槽:itemId 为空或 quantity <= 0)。
Definition ItemTypes.h:35
void clear()
Clears clear.
Definition Item.cpp:20
std::vector< InventoryChangeEvent > events