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){
296 if(match($action->windowId){
297 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
300 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
302 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
307 [$window, $slot] = $info;
308 $this->addPredictedSlotChangeInternal($window, $slot, $action->newItem->getItemStack());
312 public function setCurrentItemStackRequestId(?
int $id) : void{
313 $this->currentItemStackRequestId = $id;
330 private function openWindowDeferred(\Closure $func) : void{
331 if($this->pendingCloseWindowId !== null){
332 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
333 $this->pendingOpenWindowCallback = $func;
343 private function createComplexSlotMapping(InventoryWindow $inventory) : ?array{
346 $inventory instanceof AnvilInventoryWindow => UIInventorySlotOffset::ANVIL,
347 $inventory instanceof EnchantingTableInventoryWindow => UIInventorySlotOffset::ENCHANTING_TABLE,
348 $inventory instanceof LoomInventoryWindow => UIInventorySlotOffset::LOOM,
349 $inventory instanceof StonecutterInventoryWindow => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventoryWindow::SLOT_INPUT],
350 $inventory instanceof CraftingTableInventoryWindow => UIInventorySlotOffset::CRAFTING3X3_INPUT,
351 $inventory instanceof CartographyTableInventoryWindow => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
352 $inventory instanceof SmithingTableInventoryWindow => UIInventorySlotOffset::SMITHING_TABLE,
357 public function onCurrentWindowChange(InventoryWindow $window) : void{
358 $this->onCurrentWindowRemove();
360 $this->openWindowDeferred(
function() use ($window) :
void{
361 if(($slotMap = $this->createComplexSlotMapping($window)) !==
null){
362 $windowId = $this->addComplexDynamic($slotMap, $window);
364 $windowId = $this->addDynamic($window);
367 foreach($this->containerOpenCallbacks as $callback){
368 $pks = $callback($windowId, $window);
371 foreach($pks as $pk){
372 if($pk instanceof ContainerOpenPacket){
374 $windowType = $pk->windowType;
376 $this->session->sendDataPacket($pk);
378 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
379 $this->syncContents($window);
383 throw new \LogicException(
"Unsupported inventory type");
398 $blockPosition = BlockPosition::fromVector3($window->getHolder());
399 $windowType = match(
true){
402 FurnaceType::FURNACE => WindowTypes::FURNACE,
403 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
404 FurnaceType::SMOKER => WindowTypes::SMOKER,
405 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE =>
throw new \LogicException(
"Campfire inventory cannot be displayed to a player")
415 default => WindowTypes::CONTAINER
417 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
422 public function onClientOpenMainInventory() : void{
423 $this->onCurrentWindowRemove();
425 $this->openWindowDeferred(
function() :
void{
426 $windowId = $this->getNewWindowId();
427 $window = $this->getInventoryWindow($this->player->getInventory()) ??
throw new AssumptionFailedError(
"This should never be null");
428 $this->associateIdWithInventory($windowId, $window);
429 $this->currentWindowType = WindowTypes::INVENTORY;
431 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
433 $this->currentWindowType,
434 $this->player->getId()
439 public function onCurrentWindowRemove() : void{
440 if(isset($this->networkIdToWindowMap[$this->lastWindowNetworkId])){
441 $this->
remove($this->lastWindowNetworkId);
442 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastWindowNetworkId, $this->currentWindowType,
true));
443 if($this->pendingCloseWindowId !==
null){
444 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
446 $this->pendingCloseWindowId = $this->lastWindowNetworkId;
447 $this->enchantingTableOptions = [];
451 public function onClientRemoveWindow(
int $id) : void{
452 if(Binary::signByte($id) === ContainerIds::NONE){
458 $this->session->getLogger()->debug(
"Client rejected opening of a window, assuming it was $this->lastWindowNetworkId");
459 $id = $this->lastWindowNetworkId;
461 if($id === $this->lastWindowNetworkId){
462 if(isset($this->networkIdToWindowMap[$id]) && $id !== $this->pendingCloseWindowId){
464 $this->player->removeCurrentWindow();
467 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastWindowNetworkId");
472 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
474 if($this->pendingCloseWindowId === $id){
475 $this->pendingCloseWindowId =
null;
476 if($this->pendingOpenWindowCallback !==
null){
477 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
478 ($this->pendingOpenWindowCallback)();
479 $this->pendingOpenWindowCallback =
null;
491 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
492 if($left->getRawExtraData() === $right->getRawExtraData()){
496 $typeConverter = $this->session->getTypeConverter();
497 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
498 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
500 $leftNbt = $leftExtraData->getNbt();
501 $rightNbt = $rightExtraData->getNbt();
503 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
504 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
505 $leftNbt === $rightNbt ||
506 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
510 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
512 $left->getId() === $right->getId() &&
513 $left->getMeta() === $right->getMeta() &&
514 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
515 $left->getCount() === $right->getCount() &&
516 $this->itemStackExtraDataEqual($left, $right);
519 public function onSlotChange(Inventory $inventory,
int $slot, Item $oldItem) : void{
520 $window = $this->getInventoryWindow($inventory);
521 if($window ===
null){
526 $this->requestSyncSlot($window, $slot);
529 public function requestSyncSlot(InventoryWindow $window,
int $slot) : void{
530 $inventoryEntry = $this->getEntryByWindow($window);
531 if($inventoryEntry ===
null){
537 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($window->getInventory()->getItem($slot));
538 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
539 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
541 $this->trackItemStack($inventoryEntry, $slot, $currentItem, null);
542 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
545 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
548 unset($inventoryEntry->predictions[$slot]);
551 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
560 if($itemStackWrapper->getStackId() !== 0){
561 $this->session->sendDataPacket(InventorySlotPacket::create(
564 new FullContainerName($this->lastWindowNetworkId),
565 new ItemStackWrapper(0, ItemStack::null()),
566 new ItemStackWrapper(0, ItemStack::null())
570 $this->session->sendDataPacket(InventorySlotPacket::create(
573 new FullContainerName($this->lastWindowNetworkId),
574 new ItemStackWrapper(0, ItemStack::null()),
582 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
591 $this->session->sendDataPacket(InventoryContentPacket::create(
593 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
594 new FullContainerName($this->lastWindowNetworkId),
595 new ItemStackWrapper(0, ItemStack::null())
598 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers,
new FullContainerName($this->lastWindowNetworkId),
new ItemStackWrapper(0, ItemStack::null())));
601 private function syncSlot(InventoryWindow $window,
int $slot, ItemStack $itemStack) : void{
602 $entry = $this->getEntryByWindow($window) ?? throw new \LogicException(
"Cannot sync an untracked inventory");
603 $itemStackInfo = $entry->itemStackInfos[$slot];
604 if($itemStackInfo ===
null){
605 throw new \LogicException(
"Cannot sync an untracked inventory slot");
607 if($entry->complexSlotMap !==
null){
608 $windowId = ContainerIds::UI;
609 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ?? throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
611 $windowId = $this->getWindowId($window) ?? throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
615 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
616 if($windowId === ContainerIds::OFFHAND){
622 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
624 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
626 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
632 $window = $this->getInventoryWindow($inventory);
633 if($window !==
null){
634 $this->syncContents($window);
638 private function syncContents(InventoryWindow $window) : void{
639 $entry = $this->getEntryByWindow($window);
645 if($entry->complexSlotMap !==
null){
646 $windowId = ContainerIds::UI;
648 $windowId = $this->getWindowId($window);
650 if($windowId !==
null){
651 $entry->predictions = [];
652 $entry->pendingSyncs = [];
654 $typeConverter = $this->session->getTypeConverter();
655 foreach($window->getInventory()->getContents(true) as $slot => $item){
656 $itemStack = $typeConverter->coreItemStackToNet($item);
657 $info = $this->trackItemStack($entry, $slot, $itemStack, null);
658 $contents[] = new ItemStackWrapper($info->getStackId(), $itemStack);
660 if($entry->complexSlotMap !==
null){
661 foreach($contents as $slotId => $info){
662 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ?? null;
663 if($packetSlot === null){
666 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
669 $this->sendInventoryContentPackets($windowId, $contents);
674 public function syncAll() : void{
675 foreach($this->entries as $entry){
676 $this->syncContents($entry->window);
680 public function requestSyncAll() : void{
681 $this->fullSyncRequested = true;
684 public function syncMismatchedPredictedSlotChanges() : void{
685 $typeConverter = $this->session->getTypeConverter();
686 foreach($this->entries as $entry){
687 $inventory = $entry->window->getInventory();
688 foreach($entry->predictions as $slot => $expectedItem){
689 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
694 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
695 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
698 $entry->predictions = [];
702 public function flushPendingUpdates() : void{
703 if($this->fullSyncRequested){
704 $this->fullSyncRequested =
false;
705 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->entries) .
" inventories");
708 foreach($this->entries as $entry){
709 if(count($entry->pendingSyncs) === 0){
712 $inventory = $entry->window;
713 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
714 foreach($entry->pendingSyncs as $slot => $itemStack){
715 $this->syncSlot($inventory, $slot, $itemStack);
717 $entry->pendingSyncs = [];
722 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
725 $window = $this->getInventoryWindow($inventory);
726 if($window ===
null){
729 $windowId = $this->getWindowId($window);
730 if($windowId !==
null){
731 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
735 public function onClientSelectHotbarSlot(
int $slot) : void{
736 $this->clientSelectedHotbarSlot = $slot;
739 public function syncSelectedHotbarSlot() : void{
740 $playerInventory = $this->player->getInventory();
741 $selected = $this->player->getHotbar()->getSelectedIndex();
742 if($selected !== $this->clientSelectedHotbarSlot){
743 $inventoryEntry = $this->getEntry($playerInventory) ??
throw new AssumptionFailedError(
"Player inventory should always be tracked");
744 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
745 if($itemStackInfo ===
null){
746 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
749 $this->session->sendDataPacket(MobEquipmentPacket::create(
750 $this->player->getId(),
751 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItem($selected))),
754 ContainerIds::INVENTORY
756 $this->clientSelectedHotbarSlot = $selected;
760 public function syncCreative() : void{
761 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
769 $protocolOptions = [];
771 foreach($options as $index => $option){
772 $optionId = $this->nextEnchantingTableOptionId++;
773 $this->enchantingTableOptions[$optionId] = $index;
775 $protocolEnchantments = array_map(
777 $option->getEnchantments()
781 $protocolOptions[] =
new ProtocolEnchantOption(
782 $option->getRequiredXpLevel(),
783 0, $protocolEnchantments,
786 $option->getDisplayName(),
791 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
794 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
795 return $this->enchantingTableOptions[$recipeId] ?? null;
798 private function newItemStackId() : int{
799 return $this->nextItemStackId++;
802 public function getItemStackInfo(InventoryWindow $window,
int $slot) : ?ItemStackInfo{
803 return $this->getEntryByWindow($window)?->itemStackInfos[$slot] ?? null;
806 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
808 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
809 return $entry->itemStackInfos[$slotId] = $info;