87 private array $inventories = [];
93 private array $networkIdToInventoryMap = [];
98 private array $complexSlotToInventoryMap = [];
100 private int $lastInventoryNetworkId = ContainerIds::FIRST;
101 private int $currentWindowType = WindowTypes::CONTAINER;
103 private int $clientSelectedHotbarSlot = -1;
106 private ObjectSet $containerOpenCallbacks;
108 private ?
int $pendingCloseWindowId =
null;
110 private ?\Closure $pendingOpenWindowCallback =
null;
112 private int $nextItemStackId = 1;
113 private ?
int $currentItemStackRequestId =
null;
115 private bool $fullSyncRequested =
false;
118 private array $enchantingTableOptions = [];
121 private int $nextEnchantingTableOptionId = 100000;
123 public function __construct(
127 $this->containerOpenCallbacks =
new ObjectSet();
128 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
130 $this->add(ContainerIds::INVENTORY, $this->player->getInventory());
131 $this->add(ContainerIds::OFFHAND, $this->player->getOffHandInventory());
132 $this->add(ContainerIds::ARMOR, $this->player->getArmorInventory());
133 $this->addComplex(UIInventorySlotOffset::CURSOR, $this->player->getCursorInventory());
134 $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $this->player->getCraftingGrid());
136 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
139 private function associateIdWithInventory(
int $id,
Inventory $inventory) :
void{
140 $this->networkIdToInventoryMap[$id] = $inventory;
143 private function getNewWindowId() :
int{
144 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
145 return $this->lastInventoryNetworkId;
148 private function add(
int $id,
Inventory $inventory) :
void{
149 if(isset($this->inventories[spl_object_id($inventory)])){
150 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
153 $this->associateIdWithInventory($id, $inventory);
156 private function addDynamic(
Inventory $inventory) :
int{
157 $id = $this->getNewWindowId();
158 $this->add($id, $inventory);
166 private function addComplex(array|
int $slotMap,
Inventory $inventory) :
void{
167 if(isset($this->inventories[spl_object_id($inventory)])){
168 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
175 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
176 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
184 private function addComplexDynamic(array|
int $slotMap,
Inventory $inventory) :
int{
185 $this->addComplex($slotMap, $inventory);
186 $id = $this->getNewWindowId();
187 $this->associateIdWithInventory($id, $inventory);
191 private function remove(
int $id) :
void{
192 $inventory = $this->networkIdToInventoryMap[$id];
193 unset($this->networkIdToInventoryMap[$id]);
194 if($this->getWindowId($inventory) ===
null){
195 unset($this->inventories[spl_object_id($inventory)]);
196 foreach($this->complexSlotToInventoryMap as $netSlot => $entry){
197 if($entry->getInventory() === $inventory){
198 unset($this->complexSlotToInventoryMap[$netSlot]);
204 public function getWindowId(
Inventory $inventory) : ?
int{
205 return ($id = array_search($inventory, $this->networkIdToInventoryMap,
true)) !==
false ? $id :
null;
208 public function getCurrentWindowId() :
int{
209 return $this->lastInventoryNetworkId;
217 $entry = $this->complexSlotToInventoryMap[$netSlotId] ??
null;
221 $inventory = $entry->getInventory();
222 $coreSlotId = $entry->mapNetToCore($netSlotId);
223 return $coreSlotId !==
null && $inventory->
slotExists($coreSlotId) ? [$inventory, $coreSlotId] :
null;
225 $inventory = $this->networkIdToInventoryMap[$windowId] ??
null;
226 if($inventory !==
null && $inventory->
slotExists($netSlotId)){
227 return [$inventory, $netSlotId];
232 private function addPredictedSlotChangeInternal(Inventory $inventory,
int $slot, ItemStack $item) : void{
233 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
236 public function addPredictedSlotChange(Inventory $inventory,
int $slot, Item $item) : void{
237 $typeConverter = $this->session->getTypeConverter();
238 $itemStack = $typeConverter->coreItemStackToNet($item);
239 $this->addPredictedSlotChangeInternal($inventory, $slot, $itemStack);
242 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
243 foreach($tx->getActions() as $action){
244 if($action instanceof SlotChangeAction){
246 $this->addPredictedSlotChange(
247 $action->getInventory(),
249 $action->getTargetItem()
260 foreach($networkInventoryActions as $action){
261 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
267 if(match($action->windowId){
268 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
271 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
273 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
278 [$inventory, $slot] = $info;
279 $this->addPredictedSlotChangeInternal($inventory, $slot, $action->newItem->getItemStack());
283 public function setCurrentItemStackRequestId(?
int $id) : void{
284 $this->currentItemStackRequestId = $id;
301 private function openWindowDeferred(\Closure $func) : void{
302 if($this->pendingCloseWindowId !== null){
303 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
304 $this->pendingOpenWindowCallback = $func;
314 private function createComplexSlotMapping(Inventory $inventory) : ?array{
317 $inventory instanceof AnvilInventory => UIInventorySlotOffset::ANVIL,
318 $inventory instanceof EnchantInventory => UIInventorySlotOffset::ENCHANTING_TABLE,
319 $inventory instanceof LoomInventory => UIInventorySlotOffset::LOOM,
320 $inventory instanceof StonecutterInventory => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventory::SLOT_INPUT],
321 $inventory instanceof CraftingTableInventory => UIInventorySlotOffset::CRAFTING3X3_INPUT,
322 $inventory instanceof CartographyTableInventory => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
323 $inventory instanceof SmithingTableInventory => UIInventorySlotOffset::SMITHING_TABLE,
328 public function onCurrentWindowChange(Inventory $inventory) : void{
329 $this->onCurrentWindowRemove();
331 $this->openWindowDeferred(
function() use ($inventory) :
void{
332 if(($slotMap = $this->createComplexSlotMapping($inventory)) !==
null){
333 $windowId = $this->addComplexDynamic($slotMap, $inventory);
335 $windowId = $this->addDynamic($inventory);
338 foreach($this->containerOpenCallbacks as $callback){
339 $pks = $callback($windowId, $inventory);
342 foreach($pks as $pk){
343 if($pk instanceof ContainerOpenPacket){
345 $windowType = $pk->windowType;
347 $this->session->sendDataPacket($pk);
349 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
350 $this->syncContents($inventory);
354 throw new \LogicException(
"Unsupported inventory type");
369 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
370 $windowType = match(
true){
373 FurnaceType::FURNACE => WindowTypes::FURNACE,
374 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
375 FurnaceType::SMOKER => WindowTypes::SMOKER,
376 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE =>
throw new \LogicException(
"Campfire inventory cannot be displayed to a player")
386 default => WindowTypes::CONTAINER
388 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
393 public function onClientOpenMainInventory() : void{
394 $this->onCurrentWindowRemove();
396 $this->openWindowDeferred(
function() :
void{
397 $windowId = $this->getNewWindowId();
398 $this->associateIdWithInventory($windowId, $this->player->getInventory());
399 $this->currentWindowType = WindowTypes::INVENTORY;
401 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
403 $this->currentWindowType,
404 $this->player->getId()
409 public function onCurrentWindowRemove() : void{
410 if(isset($this->networkIdToInventoryMap[$this->lastInventoryNetworkId])){
411 $this->
remove($this->lastInventoryNetworkId);
412 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastInventoryNetworkId, $this->currentWindowType,
true));
413 if($this->pendingCloseWindowId !==
null){
414 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
416 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
417 $this->enchantingTableOptions = [];
421 public function onClientRemoveWindow(
int $id) : void{
422 if($id === $this->lastInventoryNetworkId){
423 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
425 $this->player->removeCurrentWindow();
428 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
433 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
435 if($this->pendingCloseWindowId === $id){
436 $this->pendingCloseWindowId =
null;
437 if($this->pendingOpenWindowCallback !==
null){
438 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
439 ($this->pendingOpenWindowCallback)();
440 $this->pendingOpenWindowCallback =
null;
452 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
453 if($left->getRawExtraData() === $right->getRawExtraData()){
457 $typeConverter = $this->session->getTypeConverter();
458 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
459 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
461 $leftNbt = $leftExtraData->getNbt();
462 $rightNbt = $rightExtraData->getNbt();
464 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
465 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
466 $leftNbt === $rightNbt ||
467 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
471 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
473 $left->getId() === $right->getId() &&
474 $left->getMeta() === $right->getMeta() &&
475 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
476 $left->getCount() === $right->getCount() &&
477 $this->itemStackExtraDataEqual($left, $right);
480 public function onSlotChange(Inventory $inventory,
int $slot) : void{
481 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
482 if($inventoryEntry ===
null){
487 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
488 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
489 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
491 $this->trackItemStack($inventoryEntry, $slot, $currentItem,
null);
492 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
495 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
498 unset($inventoryEntry->predictions[$slot]);
501 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
510 if($itemStackWrapper->getStackId() !== 0){
511 $this->session->sendDataPacket(InventorySlotPacket::create(
514 new FullContainerName($this->lastInventoryNetworkId),
515 new ItemStackWrapper(0, ItemStack::null()),
516 new ItemStackWrapper(0, ItemStack::null())
520 $this->session->sendDataPacket(InventorySlotPacket::create(
523 new FullContainerName($this->lastInventoryNetworkId),
524 new ItemStackWrapper(0, ItemStack::null()),
532 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
541 $this->session->sendDataPacket(InventoryContentPacket::create(
543 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
544 new FullContainerName($this->lastInventoryNetworkId),
545 new ItemStackWrapper(0, ItemStack::null())
548 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers,
new FullContainerName($this->lastInventoryNetworkId),
new ItemStackWrapper(0, ItemStack::null())));
551 public function syncSlot(Inventory $inventory,
int $slot, ItemStack $itemStack) : void{
552 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
554 throw new \LogicException(
"Cannot sync an untracked inventory");
556 $itemStackInfo = $entry->itemStackInfos[$slot];
557 if($itemStackInfo ===
null){
558 throw new \LogicException(
"Cannot sync an untracked inventory slot");
560 if($entry->complexSlotMap !==
null){
561 $windowId = ContainerIds::UI;
562 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
564 $windowId = $this->getWindowId($inventory) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
568 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
569 if($windowId === ContainerIds::OFFHAND){
575 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
577 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
579 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
582 public function syncContents(Inventory $inventory) : void{
583 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
589 if($entry->complexSlotMap !==
null){
590 $windowId = ContainerIds::UI;
592 $windowId = $this->getWindowId($inventory);
594 if($windowId !==
null){
595 $entry->predictions = [];
596 $entry->pendingSyncs = [];
598 $typeConverter = $this->session->getTypeConverter();
599 foreach($inventory->getContents(
true) as $slot => $item){
600 $itemStack = $typeConverter->coreItemStackToNet($item);
601 $info = $this->trackItemStack($entry, $slot, $itemStack,
null);
602 $contents[] =
new ItemStackWrapper($info->getStackId(), $itemStack);
604 if($entry->complexSlotMap !==
null){
605 foreach($contents as $slotId => $info){
606 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ??
null;
607 if($packetSlot ===
null){
610 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
613 $this->sendInventoryContentPackets($windowId, $contents);
618 public function syncAll() : void{
619 foreach($this->inventories as $entry){
620 $this->syncContents($entry->inventory);
624 public function requestSyncAll() : void{
625 $this->fullSyncRequested = true;
628 public function syncMismatchedPredictedSlotChanges() : void{
629 $typeConverter = $this->session->getTypeConverter();
630 foreach($this->inventories as $entry){
631 $inventory = $entry->inventory;
632 foreach($entry->predictions as $slot => $expectedItem){
633 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
638 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
639 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
642 $entry->predictions = [];
646 public function flushPendingUpdates() : void{
647 if($this->fullSyncRequested){
648 $this->fullSyncRequested =
false;
649 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->inventories) .
" inventories");
652 foreach($this->inventories as $entry){
653 if(count($entry->pendingSyncs) === 0){
656 $inventory = $entry->inventory;
657 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
658 foreach($entry->pendingSyncs as $slot => $itemStack){
659 $this->syncSlot($inventory, $slot, $itemStack);
661 $entry->pendingSyncs = [];
666 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
667 $windowId = $this->getWindowId($inventory);
668 if($windowId !==
null){
669 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
673 public function onClientSelectHotbarSlot(
int $slot) : void{
674 $this->clientSelectedHotbarSlot = $slot;
677 public function syncSelectedHotbarSlot() : void{
678 $playerInventory = $this->player->getInventory();
679 $selected = $playerInventory->getHeldItemIndex();
680 if($selected !== $this->clientSelectedHotbarSlot){
681 $inventoryEntry = $this->inventories[spl_object_id($playerInventory)] ??
null;
682 if($inventoryEntry ===
null){
683 throw new AssumptionFailedError(
"Player inventory should always be tracked");
685 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
686 if($itemStackInfo ===
null){
687 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
690 $this->session->sendDataPacket(MobEquipmentPacket::create(
691 $this->player->getId(),
692 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
695 ContainerIds::INVENTORY
697 $this->clientSelectedHotbarSlot = $selected;
701 public function syncCreative() : void{
702 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
710 $protocolOptions = [];
712 foreach($options as $index => $option){
713 $optionId = $this->nextEnchantingTableOptionId++;
714 $this->enchantingTableOptions[$optionId] = $index;
716 $protocolEnchantments = array_map(
718 $option->getEnchantments()
722 $protocolOptions[] =
new ProtocolEnchantOption(
723 $option->getRequiredXpLevel(),
724 0, $protocolEnchantments,
727 $option->getDisplayName(),
732 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
735 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
736 return $this->enchantingTableOptions[$recipeId] ?? null;
739 private function newItemStackId() : int{
740 return $this->nextItemStackId++;
743 public function getItemStackInfo(Inventory $inventory,
int $slot) : ?ItemStackInfo{
744 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
745 return $entry?->itemStackInfos[$slot] ??
null;
748 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
750 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
751 return $entry->itemStackInfos[$slotId] = $info;