91 private array $entries = [];
97 private array $networkIdToWindowMap = [];
102 private array $complexSlotToWindowMap = [];
104 private int $lastWindowNetworkId = ContainerIds::FIRST;
105 private int $currentWindowType = WindowTypes::CONTAINER;
107 private int $clientSelectedHotbarSlot = -1;
110 private ObjectSet $containerOpenCallbacks;
112 private ?
int $pendingCloseWindowId =
null;
114 private ?\Closure $pendingOpenWindowCallback =
null;
116 private int $nextItemStackId = 1;
117 private ?
int $currentItemStackRequestId =
null;
119 private bool $fullSyncRequested =
false;
122 private array $enchantingTableOptions = [];
125 private int $nextEnchantingTableOptionId = 100000;
127 public function __construct(
131 $this->containerOpenCallbacks =
new ObjectSet();
132 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
134 foreach($this->player->getPermanentWindows() as $window){
135 match($window->getType()){
136 PlayerInventoryWindow::TYPE_INVENTORY => $this->add(ContainerIds::INVENTORY, $window),
137 PlayerInventoryWindow::TYPE_OFFHAND => $this->add(ContainerIds::OFFHAND, $window),
138 PlayerInventoryWindow::TYPE_ARMOR => $this->add(ContainerIds::ARMOR, $window),
139 PlayerInventoryWindow::TYPE_CURSOR => $this->addComplex(UIInventorySlotOffset::CURSOR, $window),
140 PlayerInventoryWindow::TYPE_CRAFTING => $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $window),
145 $this->player->getHotbar()->getSelectedIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
148 private function associateIdWithInventory(
int $id,
InventoryWindow $window) :
void{
149 $this->networkIdToWindowMap[$id] = $window;
152 private function getNewWindowId() :
int{
153 $this->lastWindowNetworkId = max(ContainerIds::FIRST, ($this->lastWindowNetworkId + 1) % ContainerIds::LAST);
154 return $this->lastWindowNetworkId;
158 return $this->entries[spl_object_id($inventory)] ??
null;
162 return $this->getEntry($window->getInventory());
166 return $this->getEntry($inventory)?->window;
170 $k = spl_object_id($window->getInventory());
171 if(isset($this->entries[$k])){
172 throw new \InvalidArgumentException(
"Inventory " . get_class($window->getInventory()) .
" is already tracked (open in two different windows?)");
175 $window->getInventory()->getListeners()->add($this);
176 $this->associateIdWithInventory($id, $window);
180 $id = $this->getNewWindowId();
181 $this->add($id, $inventory);
189 private function addComplex(array|
int $slotMap,
InventoryWindow $window) :
void{
190 $k = spl_object_id($window->getInventory());
191 if(isset($this->entries[$k])){
192 throw new \InvalidArgumentException(
"Inventory " . get_class($window) .
" is already tracked");
199 $window->getInventory()->getListeners()->add($this);
200 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
201 $this->complexSlotToWindowMap[$netSlot] = $complexSlotMap;
209 private function addComplexDynamic(array|
int $slotMap,
InventoryWindow $inventory) :
int{
210 $this->addComplex($slotMap, $inventory);
211 $id = $this->getNewWindowId();
212 $this->associateIdWithInventory($id, $inventory);
216 private function remove(
int $id) :
void{
217 $window = $this->networkIdToWindowMap[$id];
218 $inventory = $window->getInventory();
219 unset($this->networkIdToWindowMap[$id]);
220 if($this->getWindowId($window) ===
null){
222 unset($this->entries[spl_object_id($inventory)]);
223 foreach($this->complexSlotToWindowMap as $netSlot => $entry){
224 if($entry->getWindow() === $window){
225 unset($this->complexSlotToWindowMap[$netSlot]);
232 return ($id = array_search($window, $this->networkIdToWindowMap,
true)) !==
false ? $id :
null;
235 public function getCurrentWindowId() :
int{
236 return $this->lastWindowNetworkId;
244 $entry = $this->complexSlotToWindowMap[$netSlotId] ??
null;
248 $window = $entry->getWindow();
249 $coreSlotId = $entry->mapNetToCore($netSlotId);
250 return $coreSlotId !==
null && $window->getInventory()->slotExists($coreSlotId) ? [$window, $coreSlotId] :
null;
252 $window = $this->networkIdToWindowMap[$windowId] ??
null;
253 if($window !==
null && $window->getInventory()->slotExists($netSlotId)){
254 return [$window, $netSlotId];
259 private function addPredictedSlotChangeInternal(InventoryWindow $window,
int $slot, ItemStack $item) : void{
261 $entry = $this->getEntryByWindow($window) ?? throw new
AssumptionFailedError(
"Assume this should never be null");
262 $entry->predictions[$slot] = $item;
265 public function addPredictedSlotChange(InventoryWindow $window,
int $slot, Item $item) : void{
266 $typeConverter = $this->session->getTypeConverter();
267 $itemStack = $typeConverter->coreItemStackToNet($item);
268 $this->addPredictedSlotChangeInternal($window, $slot, $itemStack);
271 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
272 foreach($tx->getActions() as $action){
273 if($action instanceof SlotChangeAction){
275 $this->addPredictedSlotChange(
276 $action->getInventoryWindow(),
278 $action->getTargetItem()
289 foreach($networkInventoryActions as $action){
290 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
293 if($action->windowId ===
null){
294 throw new PacketHandlingException(
"Window ID should always be set for SOURCE_CONTAINER");
299 if(match($action->windowId){
300 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
303 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
305 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
310 [$window, $slot] = $info;
311 $this->addPredictedSlotChangeInternal($window, $slot, $action->newItem->getItemStack());
315 public function setCurrentItemStackRequestId(?
int $id) : void{
316 $this->currentItemStackRequestId = $id;
333 private function openWindowDeferred(\Closure $func) : void{
334 if($this->pendingCloseWindowId !== null){
335 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
336 $this->pendingOpenWindowCallback = $func;
346 private function createComplexSlotMapping(InventoryWindow $inventory) : ?array{
349 $inventory instanceof AnvilInventoryWindow => UIInventorySlotOffset::ANVIL,
350 $inventory instanceof EnchantingTableInventoryWindow => UIInventorySlotOffset::ENCHANTING_TABLE,
351 $inventory instanceof LoomInventoryWindow => UIInventorySlotOffset::LOOM,
352 $inventory instanceof StonecutterInventoryWindow => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventoryWindow::SLOT_INPUT],
353 $inventory instanceof CraftingTableInventoryWindow => UIInventorySlotOffset::CRAFTING3X3_INPUT,
354 $inventory instanceof CartographyTableInventoryWindow => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
355 $inventory instanceof SmithingTableInventoryWindow => UIInventorySlotOffset::SMITHING_TABLE,
360 public function onCurrentWindowChange(InventoryWindow $window) : void{
361 $this->onCurrentWindowRemove();
363 $this->openWindowDeferred(
function() use ($window) :
void{
364 if(($slotMap = $this->createComplexSlotMapping($window)) !==
null){
365 $windowId = $this->addComplexDynamic($slotMap, $window);
367 $windowId = $this->addDynamic($window);
370 foreach($this->containerOpenCallbacks as $callback){
371 $pks = $callback($windowId, $window);
374 foreach($pks as $pk){
375 if($pk instanceof ContainerOpenPacket){
377 $windowType = $pk->windowType;
379 $this->session->sendDataPacket($pk);
381 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
382 $this->syncContents($window);
386 throw new \LogicException(
"Unsupported inventory type");
401 $blockPosition = BlockPosition::fromVector3($window->getHolder());
402 $windowType = match(
true){
405 FurnaceType::FURNACE => WindowTypes::FURNACE,
406 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
407 FurnaceType::SMOKER => WindowTypes::SMOKER,
408 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE =>
throw new \LogicException(
"Campfire inventory cannot be displayed to a player")
418 default => WindowTypes::CONTAINER
420 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
425 public function onClientOpenMainInventory() : void{
426 $this->onCurrentWindowRemove();
428 $this->openWindowDeferred(
function() :
void{
429 $windowId = $this->getNewWindowId();
430 $window = $this->getInventoryWindow($this->player->getInventory()) ??
throw new AssumptionFailedError(
"This should never be null");
431 $this->associateIdWithInventory($windowId, $window);
432 $this->currentWindowType = WindowTypes::INVENTORY;
434 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
436 $this->currentWindowType,
437 $this->player->getId()
442 public function onCurrentWindowRemove() : void{
443 if(isset($this->networkIdToWindowMap[$this->lastWindowNetworkId])){
444 $this->
remove($this->lastWindowNetworkId);
445 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastWindowNetworkId, $this->currentWindowType,
true));
446 if($this->pendingCloseWindowId !==
null){
447 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
449 $this->pendingCloseWindowId = $this->lastWindowNetworkId;
450 $this->enchantingTableOptions = [];
454 public function onClientRemoveWindow(
int $id) : void{
455 if(Binary::signByte($id) === ContainerIds::NONE){
461 $this->session->getLogger()->debug(
"Client rejected opening of a window, assuming it was $this->lastWindowNetworkId");
462 $id = $this->lastWindowNetworkId;
464 if($id === $this->lastWindowNetworkId){
465 if(isset($this->networkIdToWindowMap[$id]) && $id !== $this->pendingCloseWindowId){
467 $this->player->removeCurrentWindow();
470 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastWindowNetworkId");
475 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
477 if($this->pendingCloseWindowId === $id){
478 $this->pendingCloseWindowId =
null;
479 if($this->pendingOpenWindowCallback !==
null){
480 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
481 ($this->pendingOpenWindowCallback)();
482 $this->pendingOpenWindowCallback =
null;
494 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
495 if($left->getRawExtraData() === $right->getRawExtraData()){
499 $typeConverter = $this->session->getTypeConverter();
500 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
501 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
503 $leftNbt = $leftExtraData->getNbt();
504 $rightNbt = $rightExtraData->getNbt();
506 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
507 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
508 $leftNbt === $rightNbt ||
509 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
513 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
515 $left->getId() === $right->getId() &&
516 $left->getMeta() === $right->getMeta() &&
517 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
518 $left->getCount() === $right->getCount() &&
519 $this->itemStackExtraDataEqual($left, $right);
522 public function onSlotChange(Inventory $inventory,
int $slot, Item $oldItem) : void{
523 $window = $this->getInventoryWindow($inventory);
524 if($window ===
null){
529 $this->requestSyncSlot($window, $slot);
532 public function requestSyncSlot(InventoryWindow $window,
int $slot) : void{
533 $inventoryEntry = $this->getEntryByWindow($window);
534 if($inventoryEntry ===
null){
540 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($window->getInventory()->getItem($slot));
541 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
542 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
544 $this->trackItemStack($inventoryEntry, $slot, $currentItem, null);
545 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
548 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
551 unset($inventoryEntry->predictions[$slot]);
554 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
563 if($itemStackWrapper->getStackId() !== 0){
564 $this->session->sendDataPacket(InventorySlotPacket::create(
569 new ItemStackWrapper(0, ItemStack::null())
573 $this->session->sendDataPacket(InventorySlotPacket::create(
585 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
594 $this->session->sendDataPacket(InventoryContentPacket::create(
596 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
597 new FullContainerName(0, null),
598 new ItemStackWrapper(0, ItemStack::null())
601 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers,
new FullContainerName(0,
null),
new ItemStackWrapper(0, ItemStack::null())));
604 private function syncSlot(InventoryWindow $window,
int $slot, ItemStack $itemStack) : void{
605 $entry = $this->getEntryByWindow($window) ?? throw new \LogicException(
"Cannot sync an untracked inventory");
606 $itemStackInfo = $entry->itemStackInfos[$slot];
607 if($itemStackInfo ===
null){
608 throw new \LogicException(
"Cannot sync an untracked inventory slot");
610 if($entry->complexSlotMap !==
null){
611 $windowId = ContainerIds::UI;
612 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ?? throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
614 $windowId = $this->getWindowId($window) ?? throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
618 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
619 if($windowId === ContainerIds::OFFHAND){
625 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
627 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
629 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
635 $window = $this->getInventoryWindow($inventory);
636 if($window !==
null){
637 $this->syncContents($window);
641 private function syncContents(InventoryWindow $window) : void{
642 $entry = $this->getEntryByWindow($window);
648 if($entry->complexSlotMap !==
null){
649 $windowId = ContainerIds::UI;
651 $windowId = $this->getWindowId($window);
653 if($windowId !==
null){
654 $entry->predictions = [];
655 $entry->pendingSyncs = [];
657 $typeConverter = $this->session->getTypeConverter();
658 foreach($window->getInventory()->getContents(true) as $slot => $item){
659 $itemStack = $typeConverter->coreItemStackToNet($item);
660 $info = $this->trackItemStack($entry, $slot, $itemStack, null);
661 $contents[] = new ItemStackWrapper($info->getStackId(), $itemStack);
663 if($entry->complexSlotMap !==
null){
664 foreach($contents as $slotId => $info){
665 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ?? null;
666 if($packetSlot === null){
669 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
672 $this->sendInventoryContentPackets($windowId, $contents);
677 public function syncAll() : void{
678 foreach($this->entries as $entry){
679 $this->syncContents($entry->window);
683 public function requestSyncAll() : void{
684 $this->fullSyncRequested = true;
687 public function syncMismatchedPredictedSlotChanges() : void{
688 $typeConverter = $this->session->getTypeConverter();
689 foreach($this->entries as $entry){
690 $inventory = $entry->window->getInventory();
691 foreach($entry->predictions as $slot => $expectedItem){
692 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
697 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
698 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
701 $entry->predictions = [];
705 public function flushPendingUpdates() : void{
706 if($this->fullSyncRequested){
707 $this->fullSyncRequested =
false;
708 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->entries) .
" inventories");
711 foreach($this->entries as $entry){
712 if(count($entry->pendingSyncs) === 0){
715 $inventory = $entry->window;
716 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
717 foreach($entry->pendingSyncs as $slot => $itemStack){
718 $this->syncSlot($inventory, $slot, $itemStack);
720 $entry->pendingSyncs = [];
725 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
728 $window = $this->getInventoryWindow($inventory);
729 if($window ===
null){
732 $windowId = $this->getWindowId($window);
733 if($windowId !==
null){
734 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
738 public function onClientSelectHotbarSlot(
int $slot) : void{
739 $this->clientSelectedHotbarSlot = $slot;
742 public function syncSelectedHotbarSlot() : void{
743 $playerInventory = $this->player->getInventory();
744 $selected = $this->player->getHotbar()->getSelectedIndex();
745 if($selected !== $this->clientSelectedHotbarSlot){
746 $inventoryEntry = $this->getEntry($playerInventory) ??
throw new AssumptionFailedError(
"Player inventory should always be tracked");
747 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
748 if($itemStackInfo ===
null){
749 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
752 $this->session->sendDataPacket(MobEquipmentPacket::create(
753 $this->player->getId(),
754 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItem($selected))),
757 ContainerIds::INVENTORY
759 $this->clientSelectedHotbarSlot = $selected;
763 public function syncCreative() : void{
764 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
772 $protocolOptions = [];
774 foreach($options as $index => $option){
775 $optionId = $this->nextEnchantingTableOptionId++;
776 $this->enchantingTableOptions[$optionId] = $index;
778 $protocolEnchantments = array_map(
780 $option->getEnchantments()
784 $protocolOptions[] =
new ProtocolEnchantOption(
785 $option->getRequiredXpLevel(),
786 0, $protocolEnchantments,
789 $option->getDisplayName(),
794 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
797 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
798 return $this->enchantingTableOptions[$recipeId] ?? null;
801 private function newItemStackId() : int{
802 return $this->nextItemStackId++;
805 public function getItemStackInfo(InventoryWindow $window,
int $slot) : ?ItemStackInfo{
806 return $this->getEntryByWindow($window)?->itemStackInfos[$slot] ?? null;
809 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
811 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
812 return $entry->itemStackInfos[$slotId] = $info;