19 std::vector<InventoryChangeEvent>
events;
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;
49bool propsEqual(
const std::unordered_map<std::string, std::string> &
a,
50 const std::unordered_map<std::string, std::string> &
b) {
56std::unordered_map<std::string, InventorySystem::AcceptFn> &InventorySystem::acceptRules() {
57 static std::unordered_map<std::string, AcceptFn>
t;
61std::unordered_map<std::string, InventorySystem::CapacityFn> &InventorySystem::capacityPolicies() {
62 static std::unordered_map<std::string, CapacityFn>
t;
66std::unordered_map<std::string, InventorySystem::StackFn> &InventorySystem::stackRules() {
67 static std::unordered_map<std::string, StackFn>
t;
71std::unordered_map<std::string, InventorySystem::ChangeHook> &InventorySystem::changeHooks() {
72 static std::unordered_map<std::string, ChangeHook>
t;
76std::vector<InventoryChangeEvent> &InventorySystem::eventQueue() {
77 static std::vector<InventoryChangeEvent>
q;
81int &InventorySystem::instanceCounter() {
86bool &InventorySystem::builtinsReady() {
87 static bool ready =
false;
91bool &InventorySystem::changeHooksSuppressed() {
92 static bool suppressed =
false;
97 if (
name.empty() || !
fn)
return;
98 acceptRules()[
name] = std::move(
fn);
105 return acceptRules().count(
name) > 0;
109 if (
name.empty() || !
fn)
return;
110 capacityPolicies()[
name] = std::move(
fn);
114 capacityPolicies().erase(
name);
119 return capacityPolicies().count(
name) > 0;
123 if (
name.empty() || !
fn)
return;
124 stackRules()[
name] = std::move(
fn);
131 return stackRules().count(
name) > 0;
135 if (
name.empty() || !
fn)
return;
136 changeHooks()[
name] = std::move(
fn);
142 return changeHooks().count(
name) > 0;
146 if (builtinsReady())
return;
147 builtinsReady() =
true;
154 std::string *reason) {
156 if (reason) *reason =
"rejected_tag";
160 if (reason) *reason =
"accept_tag_mismatch";
166 auto slotsOk = [](
const Bag &bag,
const ItemDefinition &def,
int quantity, std::string *reason) {
168 for (
int i = 0; i < bag.
getSlotCount() && need > 0; ++i) {
169 int space = freeSpaceInSlot(bag, i, def);
170 if (space > 0) need -= space;
173 if (reason) *reason =
"no_slot";
179 auto weightOk = [](
const Bag &bag,
const ItemDefinition &def,
int quantity, std::string *reason) {
181 float add = def.
weight * float(quantity);
183 if (reason) *reason =
"over_weight";
189 auto volumeOk = [](
const Bag &bag,
const ItemDefinition &def,
int quantity, std::string *reason) {
191 float add = def.
volume * float(quantity);
193 if (reason) *reason =
"over_volume";
206 int quantity, std::string *reason) {
207 return slotsOk(bag, def, quantity, reason) && weightOk(bag, def, quantity, reason);
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);
219 return !
a.empty() && !
b.empty() &&
a.itemId ==
b.itemId;
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;
234void InventorySystem::ensureNextInstanceIdAbove(
int usedInstanceId)
noexcept {
235 if (instanceCounter() <= usedInstanceId) instanceCounter() = usedInstanceId + 1;
238std::unique_ptr<Bag> InventorySystem::cloneBag(
const Bag &
source) {
239 auto clone = std::make_unique<Bag>(
source.getSlotCount());
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_;
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())
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)
272void InventorySystem::emit(InventoryChangeEvent ev) {
273 if (!changeHooksSuppressed()) {
274 for (
auto &kv : changeHooks()) {
275 if (!kv.second)
continue;
285 eventQueue().push_back(std::move(ev));
292 eventQueue().clear();
303 if (it == stackRules().
end() || !it->second) {
304 return !
a.empty() && !
b.empty() &&
a.itemId ==
b.itemId;
306 return it->second(
a,
b, def);
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";
317 return it->second(bag, def, quantity, reason);
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";
328 return it->second(bag, def, quantity, reason);
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;
339 probeA.itemId = def.id;
341 ItemStack probeB = probeA;
342 probeB.instanceId = 1;
343 if (!canStackTogether(bag, probeA, probeB, def)) maxStack = 1;
345 if (
s.empty())
return maxStack;
347 probe.itemId = def.id;
349 if (!canStackTogether(bag,
s, probe, def))
return 0;
350 return std::max(0, maxStack -
s.quantity);
354 std::string *reason) {
355 if (!bag || quantity <= 0) {
356 if (reason) *reason =
"invalid_args";
361 if (reason) *reason =
"unknown_item";
364 if (!checkAccept(*bag, *def, quantity, reason))
return false;
365 if (!checkCapacity(*bag, *def, quantity, reason))
return false;
370 return addItemImpl(bag,
itemId, quantity,
true);
373int InventorySystem::addItemImpl(
Bag *bag,
const std::string &
itemId,
int quantity,
375 if (!bag || quantity <= 0)
return 0;
379 if (!checkAccept(*bag, *def, 1,
nullptr))
return 0;
381 int remaining = quantity;
384 auto maxFittable = [&](
int space) ->
int {
385 int lo = 0, hi = std::min(space, remaining);
387 int mid = lo + (hi - lo + 1) / 2;
388 if (checkCapacity(*bag, *def,
mid,
nullptr))
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;
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;
425 if (publish && added > 0) {
426 InventoryChangeEvent ev;
428 ev.bagId = bag->
getId();
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());
452 const auto &grant = grants[
index];
453 if (grant.itemId.empty() || grant.quantity <= 0)
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)
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)
469 prepared.state_->totalAdded += added;
472 event.bagId = bag->
getId();
473 event.itemId = grant.itemId;
474 event.quantity = added;
475 prepared.state_->events.push_back(std::move(event));
482 if (!prepared.state_ || !prepared.state_->target || !prepared.state_->baseline ||
483 !prepared.state_->candidate)
487 const Bag &baseline = *prepared.state_->baseline;
488 if (!bagsEqual(
target, baseline))
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();
501 if (!bag ||
itemId.empty() || quantity <= 0)
504 "inventory removal requires a Bag, item id, and positive quantity",
"removal"));
508 {{
"itemId",
itemId}},
"inventory.prepare-remove"));
512 "inventory does not contain the complete removal quantity",
"quantity",
513 {{
"itemId",
itemId}},
"inventory.prepare-remove"));
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;
527 if (stack.quantity <= 0) stack.clear();
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;
539 if (!prepared.state_ || !prepared.state_->target || !prepared.state_->baseline ||
540 !prepared.state_->candidate)
544 if (!bagsEqual(
target, *prepared.state_->baseline))
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();
555 if (!bag || quantity <= 0 ||
itemId.empty())
return 0;
556 int remaining = quantity;
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);
565 if (
s.quantity <= 0)
s.clear();
579 if (!bag || slot < 0 || slot >= bag->
getSlotCount() || quantity <= 0)
return 0;
581 if (
s.empty())
return 0;
582 int take = std::min(
s.quantity, quantity);
585 if (
s.quantity <= 0)
s.clear();
597 if (!bag || slotA < 0 || slotB < 0 || slotA >= bag->
getSlotCount() ||
600 std::swap(bag->
slots()[
size_t(slotA)], bag->
slots()[
size_t(slotB)]);
611 if (!bag || fromSlot < 0 || toSlot < 0 || fromSlot >= bag->
getSlotCount() ||
614 auto &
from = bag->
slots()[size_t(fromSlot)];
615 auto &
to = bag->
slots()[size_t(toSlot)];
616 if (
from.empty())
return false;
633 if (!def)
return false;
634 if (canStackTogether(*bag,
from,
to, *def)) {
636 int space = maxStack -
to.quantity;
637 if (space <= 0)
return false;
638 int put = std::min(space,
from.quantity);
640 from.quantity -= put;
641 if (
from.quantity <= 0)
from.clear();
660 auto &
to = bag->
slots()[size_t(toSlot)];
661 if (
from.empty() || !
to.empty())
return false;
662 if (quantity >=
from.quantity)
return false;
666 to.quantity = quantity;
667 from.quantity -= quantity;
681 if (!
from || !
to || quantity <= 0 ||
itemId.empty())
return 0;
683 int want = std::min(available, quantity);
684 if (want <= 0)
return 0;
686 for (
int n = want;
n >= 1; --
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);
697 if (
s.quantity <= 0)
s.clear();
703 int needRestore =
n - added;
721 if (!
from || !
to || fromSlot < 0 || fromSlot >=
from->getSlotCount() || quantity <= 0)
723 auto &
s =
from->slots()[size_t(fromSlot)];
724 if (
s.empty())
return 0;
725 int want = std::min(
s.quantity, quantity);
728 for (
int n = want;
n >= 1; --
n) {
732 if (
n ==
s.quantity) {
734 for (
int i = 0; i <
to->getSlotCount(); ++i) {
735 if (
to->slots()[
size_t(i)].empty()) {
741 bool canPlaceWhole = empty >= 0 && def !=
nullptr;
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;
750 int space = maxStack - ts.quantity;
751 if (space <
n)
continue;
752 if (!checkCapacity(*
to, *def,
n,
nullptr))
continue;
767 if (merged)
return n;
769 if (checkCapacity(*
to, *def,
n,
nullptr) && checkAccept(*
to, *def,
n,
nullptr)) {
770 to->slots()[size_t(empty)] =
s;
787 if (
s.quantity <= 0)
s.clear();
791 auto &fs =
from->slots()[size_t(fromSlot)];
794 fs.quantity =
n - added;
796 }
else if (fs.itemId ==
itemId) {
797 fs.quantity += (
n - added);
820 for (
const auto &
s : bag->
slots()) {
821 if (!
s.empty() &&
s.itemId ==
itemId)
n +=
s.quantity;
829 const auto &
s = bag->
slots()[size_t(i)];
830 if (!
s.empty() &&
s.itemId ==
itemId)
return i;
836 if (!bag ||
tag.empty())
return -1;
838 const auto &
s = bag->
slots()[size_t(i)];
839 if (
s.empty())
continue;
840 if (
s.hasTag(
tag))
return i;
848 if (!bag)
return 0.f;
850 for (
const auto &
s : bag->
slots()) {
851 if (
s.empty())
continue;
853 if (def)
w += def->
weight * float(
s.quantity);
859 if (!bag)
return 0.f;
861 for (
const auto &
s : bag->
slots()) {
862 if (
s.empty())
continue;
864 if (def)
v += def->
volume * float(
s.quantity);
872 for (
const auto &
s : bag->
slots()) {
880 for (
auto &
s : bag->
slots())
s.clear();
890 if (!eq || !bag)
return false;
896 static_assert(std::is_nothrow_move_assignable_v<ItemStack>);
900 auto *dest = eq->
stackAt(equipSlot);
908 if (!dest->empty()) {
911 *dest = std::move(moving);
925 if (!eq || !bag)
return false;
926 auto *src = eq->
stackAt(equipSlot);
927 if (!src || src->empty())
return false;
932 if (bag->
slots()[
size_t(i)].empty()) {
939 if (!
canAdd(bag, src->itemId, src->quantity,
nullptr))
return false;
941 int qty = src->quantity;
947 src->quantity = qty - added;
960 bag->
slots()[size_t(empty)] = *src;
961 std::string
itemId = src->itemId;
962 int qty = src->quantity;
std::array< double, 10 > q
Share string attribute map operations through the Windows Foundation DLL.
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
std::string getId() const
容器 id(变更事件定位用)。
float getMaxVolume() const
Returns the max volume.
const std::vector< ItemStack > & slots() const
Slots.
const std::vector< std::string > & rejectTags() const
Reject tags.
float getMaxWeight() const
重量 / 体积上限(容量策略用)。
const std::vector< std::string > & acceptTags() const
Accept tags.
std::string getStackRule() const
Returns the stack rule.
int getSlotCount() const
格数。
EVENGINE_API_FOUNDATION public API.
const ItemStack * stackAt(const std::string &slotName) const
Stack at.
bool canEquipFromBag(Bag *bag, int bagSlot, const std::string &equipSlot, std::string *reason=nullptr) const
Can equip from bag.
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.
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)。
std::string action
add/remove/move/swap/split/merge/transfer/equip/unequip
物品模板(进程级注册表中的定义,不含运行时数量)。
std::vector< std::string > tags
bool hasTag(const std::string &tag) const
True when tag.
容器中的一格堆叠(空槽:itemId 为空或 quantity <= 0)。
void clear()
Clears clear.
std::unique_ptr< Bag > baseline
std::vector< InventoryChangeEvent > events
std::unique_ptr< Bag > candidate
std::unique_ptr< Bag > baseline
InventoryChangeEvent event
std::unique_ptr< Bag > candidate