86 private array $inventories = [];
92 private array $networkIdToInventoryMap = [];
97 private array $complexSlotToInventoryMap = [];
99 private int $lastInventoryNetworkId = ContainerIds::FIRST;
100 private int $currentWindowType = WindowTypes::CONTAINER;
102 private int $clientSelectedHotbarSlot = -1;
105 private ObjectSet $containerOpenCallbacks;
107 private ?
int $pendingCloseWindowId =
null;
109 private ?\Closure $pendingOpenWindowCallback =
null;
111 private int $nextItemStackId = 1;
112 private ?
int $currentItemStackRequestId =
null;
114 private bool $fullSyncRequested =
false;
117 private array $enchantingTableOptions = [];
120 private int $nextEnchantingTableOptionId = 100000;
122 public function __construct(
126 $this->containerOpenCallbacks =
new ObjectSet();
127 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
129 $this->add(ContainerIds::INVENTORY, $this->player->getInventory());
130 $this->add(ContainerIds::OFFHAND, $this->player->getOffHandInventory());
131 $this->add(ContainerIds::ARMOR, $this->player->getArmorInventory());
132 $this->addComplex(UIInventorySlotOffset::CURSOR, $this->player->getCursorInventory());
133 $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $this->player->getCraftingGrid());
135 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
138 private function associateIdWithInventory(
int $id,
Inventory $inventory) :
void{
139 $this->networkIdToInventoryMap[$id] = $inventory;
142 private function getNewWindowId() :
int{
143 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
144 return $this->lastInventoryNetworkId;
147 private function add(
int $id,
Inventory $inventory) :
void{
148 if(isset($this->inventories[spl_object_id($inventory)])){
149 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
152 $this->associateIdWithInventory($id, $inventory);
155 private function addDynamic(
Inventory $inventory) :
int{
156 $id = $this->getNewWindowId();
157 $this->add($id, $inventory);
165 private function addComplex(array|
int $slotMap,
Inventory $inventory) :
void{
166 if(isset($this->inventories[spl_object_id($inventory)])){
167 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
174 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
175 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
183 private function addComplexDynamic(array|
int $slotMap,
Inventory $inventory) :
int{
184 $this->addComplex($slotMap, $inventory);
185 $id = $this->getNewWindowId();
186 $this->associateIdWithInventory($id, $inventory);
190 private function remove(
int $id) :
void{
191 $inventory = $this->networkIdToInventoryMap[$id];
192 unset($this->networkIdToInventoryMap[$id]);
193 if($this->getWindowId($inventory) ===
null){
194 unset($this->inventories[spl_object_id($inventory)]);
195 foreach($this->complexSlotToInventoryMap as $netSlot => $entry){
196 if($entry->getInventory() === $inventory){
197 unset($this->complexSlotToInventoryMap[$netSlot]);
203 public function getWindowId(
Inventory $inventory) : ?
int{
204 return ($id = array_search($inventory, $this->networkIdToInventoryMap,
true)) !==
false ? $id :
null;
207 public function getCurrentWindowId() :
int{
208 return $this->lastInventoryNetworkId;
216 $entry = $this->complexSlotToInventoryMap[$netSlotId] ??
null;
220 $inventory = $entry->getInventory();
221 $coreSlotId = $entry->mapNetToCore($netSlotId);
222 return $coreSlotId !==
null && $inventory->
slotExists($coreSlotId) ? [$inventory, $coreSlotId] :
null;
224 $inventory = $this->networkIdToInventoryMap[$windowId] ??
null;
225 if($inventory !==
null && $inventory->
slotExists($netSlotId)){
226 return [$inventory, $netSlotId];
231 private function addPredictedSlotChange(Inventory $inventory,
int $slot, ItemStack $item) : void{
232 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
235 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
236 $typeConverter = $this->session->getTypeConverter();
237 foreach($tx->getActions() as $action){
238 if($action instanceof SlotChangeAction){
240 $itemStack = $typeConverter->coreItemStackToNet($action->getTargetItem());
241 $this->addPredictedSlotChange($action->getInventory(), $action->getSlot(), $itemStack);
251 foreach($networkInventoryActions as $action){
252 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
258 if(match($action->windowId){
259 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
262 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
264 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
269 [$inventory, $slot] = $info;
270 $this->addPredictedSlotChange($inventory, $slot, $action->newItem->getItemStack());
274 public function setCurrentItemStackRequestId(?
int $id) : void{
275 $this->currentItemStackRequestId = $id;
292 private function openWindowDeferred(\Closure $func) : void{
293 if($this->pendingCloseWindowId !== null){
294 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
295 $this->pendingOpenWindowCallback = $func;
305 private function createComplexSlotMapping(Inventory $inventory) : ?array{
308 $inventory instanceof AnvilInventory => UIInventorySlotOffset::ANVIL,
309 $inventory instanceof EnchantInventory => UIInventorySlotOffset::ENCHANTING_TABLE,
310 $inventory instanceof LoomInventory => UIInventorySlotOffset::LOOM,
311 $inventory instanceof StonecutterInventory => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventory::SLOT_INPUT],
312 $inventory instanceof CraftingTableInventory => UIInventorySlotOffset::CRAFTING3X3_INPUT,
313 $inventory instanceof CartographyTableInventory => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
314 $inventory instanceof SmithingTableInventory => UIInventorySlotOffset::SMITHING_TABLE,
319 public function onCurrentWindowChange(Inventory $inventory) : void{
320 $this->onCurrentWindowRemove();
322 $this->openWindowDeferred(
function() use ($inventory) :
void{
323 if(($slotMap = $this->createComplexSlotMapping($inventory)) !==
null){
324 $windowId = $this->addComplexDynamic($slotMap, $inventory);
326 $windowId = $this->addDynamic($inventory);
329 foreach($this->containerOpenCallbacks as $callback){
330 $pks = $callback($windowId, $inventory);
333 foreach($pks as $pk){
334 if($pk instanceof ContainerOpenPacket){
336 $windowType = $pk->windowType;
338 $this->session->sendDataPacket($pk);
340 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
341 $this->syncContents($inventory);
345 throw new \LogicException(
"Unsupported inventory type");
360 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
361 $windowType = match(
true){
364 FurnaceType::FURNACE => WindowTypes::FURNACE,
365 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
366 FurnaceType::SMOKER => WindowTypes::SMOKER,
367 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE =>
throw new \LogicException(
"Campfire inventory cannot be displayed to a player")
377 default => WindowTypes::CONTAINER
379 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
384 public function onClientOpenMainInventory() : void{
385 $this->onCurrentWindowRemove();
387 $this->openWindowDeferred(
function() :
void{
388 $windowId = $this->getNewWindowId();
389 $this->associateIdWithInventory($windowId, $this->player->getInventory());
390 $this->currentWindowType = WindowTypes::INVENTORY;
392 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
394 $this->currentWindowType,
395 $this->player->getId()
400 public function onCurrentWindowRemove() : void{
401 if(isset($this->networkIdToInventoryMap[$this->lastInventoryNetworkId])){
402 $this->
remove($this->lastInventoryNetworkId);
403 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastInventoryNetworkId, $this->currentWindowType,
true));
404 if($this->pendingCloseWindowId !==
null){
405 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
407 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
408 $this->enchantingTableOptions = [];
412 public function onClientRemoveWindow(
int $id) : void{
413 if($id === $this->lastInventoryNetworkId){
414 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
416 $this->player->removeCurrentWindow();
419 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
424 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
426 if($this->pendingCloseWindowId === $id){
427 $this->pendingCloseWindowId =
null;
428 if($this->pendingOpenWindowCallback !==
null){
429 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
430 ($this->pendingOpenWindowCallback)();
431 $this->pendingOpenWindowCallback =
null;
443 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
444 if($left->getRawExtraData() === $right->getRawExtraData()){
448 $typeConverter = $this->session->getTypeConverter();
449 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
450 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
452 $leftNbt = $leftExtraData->getNbt();
453 $rightNbt = $rightExtraData->getNbt();
455 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
456 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
457 $leftNbt === $rightNbt ||
458 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
462 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
464 $left->getId() === $right->getId() &&
465 $left->getMeta() === $right->getMeta() &&
466 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
467 $left->getCount() === $right->getCount() &&
468 $this->itemStackExtraDataEqual($left, $right);
471 public function onSlotChange(Inventory $inventory,
int $slot) : void{
472 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
473 if($inventoryEntry ===
null){
478 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
479 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
480 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
482 $this->trackItemStack($inventoryEntry, $slot, $currentItem,
null);
483 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
486 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
489 unset($inventoryEntry->predictions[$slot]);
492 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
501 if($itemStackWrapper->getStackId() !== 0){
502 $this->session->sendDataPacket(InventorySlotPacket::create(
505 new FullContainerName($this->lastInventoryNetworkId),
506 new ItemStackWrapper(0, ItemStack::null()),
507 new ItemStackWrapper(0, ItemStack::null())
511 $this->session->sendDataPacket(InventorySlotPacket::create(
514 new FullContainerName($this->lastInventoryNetworkId),
515 new ItemStackWrapper(0, ItemStack::null()),
523 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
532 $this->session->sendDataPacket(InventoryContentPacket::create(
534 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
535 new FullContainerName($this->lastInventoryNetworkId),
536 new ItemStackWrapper(0, ItemStack::null())
539 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers,
new FullContainerName($this->lastInventoryNetworkId),
new ItemStackWrapper(0, ItemStack::null())));
542 public function syncSlot(Inventory $inventory,
int $slot, ItemStack $itemStack) : void{
543 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
545 throw new \LogicException(
"Cannot sync an untracked inventory");
547 $itemStackInfo = $entry->itemStackInfos[$slot];
548 if($itemStackInfo ===
null){
549 throw new \LogicException(
"Cannot sync an untracked inventory slot");
551 if($entry->complexSlotMap !==
null){
552 $windowId = ContainerIds::UI;
553 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
555 $windowId = $this->getWindowId($inventory) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
559 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
560 if($windowId === ContainerIds::OFFHAND){
566 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
568 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
570 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
573 public function syncContents(Inventory $inventory) : void{
574 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
580 if($entry->complexSlotMap !==
null){
581 $windowId = ContainerIds::UI;
583 $windowId = $this->getWindowId($inventory);
585 if($windowId !==
null){
586 $entry->predictions = [];
587 $entry->pendingSyncs = [];
589 $typeConverter = $this->session->getTypeConverter();
590 foreach($inventory->getContents(
true) as $slot => $item){
591 $itemStack = $typeConverter->coreItemStackToNet($item);
592 $info = $this->trackItemStack($entry, $slot, $itemStack,
null);
593 $contents[] =
new ItemStackWrapper($info->getStackId(), $itemStack);
595 $clearSlotWrapper =
new ItemStackWrapper(0, ItemStack::null());
596 if($entry->complexSlotMap !==
null){
597 foreach($contents as $slotId => $info){
598 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ??
null;
599 if($packetSlot ===
null){
602 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
605 $this->sendInventoryContentPackets($windowId, $contents);
610 public function syncAll() : void{
611 foreach($this->inventories as $entry){
612 $this->syncContents($entry->inventory);
616 public function requestSyncAll() : void{
617 $this->fullSyncRequested = true;
620 public function syncMismatchedPredictedSlotChanges() : void{
621 $typeConverter = $this->session->getTypeConverter();
622 foreach($this->inventories as $entry){
623 $inventory = $entry->inventory;
624 foreach($entry->predictions as $slot => $expectedItem){
625 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
630 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
631 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
634 $entry->predictions = [];
638 public function flushPendingUpdates() : void{
639 if($this->fullSyncRequested){
640 $this->fullSyncRequested =
false;
641 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->inventories) .
" inventories");
644 foreach($this->inventories as $entry){
645 if(count($entry->pendingSyncs) === 0){
648 $inventory = $entry->inventory;
649 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
650 foreach($entry->pendingSyncs as $slot => $itemStack){
651 $this->syncSlot($inventory, $slot, $itemStack);
653 $entry->pendingSyncs = [];
658 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
659 $windowId = $this->getWindowId($inventory);
660 if($windowId !==
null){
661 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
665 public function onClientSelectHotbarSlot(
int $slot) : void{
666 $this->clientSelectedHotbarSlot = $slot;
669 public function syncSelectedHotbarSlot() : void{
670 $playerInventory = $this->player->getInventory();
671 $selected = $playerInventory->getHeldItemIndex();
672 if($selected !== $this->clientSelectedHotbarSlot){
673 $inventoryEntry = $this->inventories[spl_object_id($playerInventory)] ??
null;
674 if($inventoryEntry ===
null){
675 throw new AssumptionFailedError(
"Player inventory should always be tracked");
677 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
678 if($itemStackInfo ===
null){
679 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
682 $this->session->sendDataPacket(MobEquipmentPacket::create(
683 $this->player->getId(),
684 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
687 ContainerIds::INVENTORY
689 $this->clientSelectedHotbarSlot = $selected;
693 public function syncCreative() : void{
694 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->getCache($this->player->getCreativeInventory()));
701 $protocolOptions = [];
703 foreach($options as $index => $option){
704 $optionId = $this->nextEnchantingTableOptionId++;
705 $this->enchantingTableOptions[$optionId] = $index;
707 $protocolEnchantments = array_map(
709 $option->getEnchantments()
713 $protocolOptions[] =
new ProtocolEnchantOption(
714 $option->getRequiredXpLevel(),
715 0, $protocolEnchantments,
718 $option->getDisplayName(),
723 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
726 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
727 return $this->enchantingTableOptions[$recipeId] ?? null;
730 private function newItemStackId() : int{
731 return $this->nextItemStackId++;
734 public function getItemStackInfo(Inventory $inventory,
int $slot) : ?ItemStackInfo{
735 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
736 return $entry?->itemStackInfos[$slot] ??
null;
739 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
741 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
742 return $entry->itemStackInfos[$slotId] = $info;