88 private array $inventories = [];
94 private array $networkIdToInventoryMap = [];
99 private array $complexSlotToInventoryMap = [];
101 private int $lastInventoryNetworkId = ContainerIds::FIRST;
102 private int $currentWindowType = WindowTypes::CONTAINER;
104 private int $clientSelectedHotbarSlot = -1;
107 private ObjectSet $containerOpenCallbacks;
109 private ?
int $pendingCloseWindowId =
null;
111 private ?\Closure $pendingOpenWindowCallback =
null;
113 private int $nextItemStackId = 1;
114 private ?
int $currentItemStackRequestId =
null;
116 private bool $fullSyncRequested =
false;
119 private array $enchantingTableOptions = [];
122 private int $nextEnchantingTableOptionId = 100000;
124 public function __construct(
128 $this->containerOpenCallbacks =
new ObjectSet();
129 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
131 $this->add(ContainerIds::INVENTORY, $this->player->getInventory());
132 $this->add(ContainerIds::OFFHAND, $this->player->getOffHandInventory());
133 $this->add(ContainerIds::ARMOR, $this->player->getArmorInventory());
134 $this->addComplex(UIInventorySlotOffset::CURSOR, $this->player->getCursorInventory());
135 $this->addComplex(UIInventorySlotOffset::CRAFTING2X2_INPUT, $this->player->getCraftingGrid());
137 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
140 private function associateIdWithInventory(
int $id,
Inventory $inventory) :
void{
141 $this->networkIdToInventoryMap[$id] = $inventory;
144 private function getNewWindowId() :
int{
145 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
146 return $this->lastInventoryNetworkId;
149 private function add(
int $id,
Inventory $inventory) :
void{
150 if(isset($this->inventories[spl_object_id($inventory)])){
151 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
154 $this->associateIdWithInventory($id, $inventory);
157 private function addDynamic(
Inventory $inventory) :
int{
158 $id = $this->getNewWindowId();
159 $this->add($id, $inventory);
167 private function addComplex(array|
int $slotMap,
Inventory $inventory) :
void{
168 if(isset($this->inventories[spl_object_id($inventory)])){
169 throw new \InvalidArgumentException(
"Inventory " . get_class($inventory) .
" is already tracked");
176 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
177 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
185 private function addComplexDynamic(array|
int $slotMap,
Inventory $inventory) :
int{
186 $this->addComplex($slotMap, $inventory);
187 $id = $this->getNewWindowId();
188 $this->associateIdWithInventory($id, $inventory);
192 private function remove(
int $id) :
void{
193 $inventory = $this->networkIdToInventoryMap[$id];
194 unset($this->networkIdToInventoryMap[$id]);
195 if($this->getWindowId($inventory) ===
null){
196 unset($this->inventories[spl_object_id($inventory)]);
197 foreach($this->complexSlotToInventoryMap as $netSlot => $entry){
198 if($entry->getInventory() === $inventory){
199 unset($this->complexSlotToInventoryMap[$netSlot]);
205 public function getWindowId(
Inventory $inventory) : ?
int{
206 return ($id = array_search($inventory, $this->networkIdToInventoryMap,
true)) !==
false ? $id :
null;
209 public function getCurrentWindowId() :
int{
210 return $this->lastInventoryNetworkId;
218 $entry = $this->complexSlotToInventoryMap[$netSlotId] ??
null;
222 $inventory = $entry->getInventory();
223 $coreSlotId = $entry->mapNetToCore($netSlotId);
224 return $coreSlotId !==
null && $inventory->
slotExists($coreSlotId) ? [$inventory, $coreSlotId] :
null;
226 $inventory = $this->networkIdToInventoryMap[$windowId] ??
null;
227 if($inventory !==
null && $inventory->
slotExists($netSlotId)){
228 return [$inventory, $netSlotId];
233 private function addPredictedSlotChangeInternal(Inventory $inventory,
int $slot, ItemStack $item) : void{
234 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
237 public function addPredictedSlotChange(Inventory $inventory,
int $slot, Item $item) : void{
238 $typeConverter = $this->session->getTypeConverter();
239 $itemStack = $typeConverter->coreItemStackToNet($item);
240 $this->addPredictedSlotChangeInternal($inventory, $slot, $itemStack);
243 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
244 foreach($tx->getActions() as $action){
245 if($action instanceof SlotChangeAction){
247 $this->addPredictedSlotChange(
248 $action->getInventory(),
250 $action->getTargetItem()
261 foreach($networkInventoryActions as $action){
262 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
265 if($action->windowId ===
null){
266 throw new PacketHandlingException(
"Window ID should always be set for SOURCE_CONTAINER");
271 if(match($action->windowId){
272 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
275 throw new PacketHandlingException(
"Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
277 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
282 [$inventory, $slot] = $info;
283 $this->addPredictedSlotChangeInternal($inventory, $slot, $action->newItem->getItemStack());
287 public function setCurrentItemStackRequestId(?
int $id) : void{
288 $this->currentItemStackRequestId = $id;
305 private function openWindowDeferred(\Closure $func) : void{
306 if($this->pendingCloseWindowId !== null){
307 $this->session->getLogger()->debug(
"Deferring opening of new window, waiting for close ack of window $this->pendingCloseWindowId");
308 $this->pendingOpenWindowCallback = $func;
318 private function createComplexSlotMapping(Inventory $inventory) : ?array{
321 $inventory instanceof AnvilInventory => UIInventorySlotOffset::ANVIL,
322 $inventory instanceof EnchantInventory => UIInventorySlotOffset::ENCHANTING_TABLE,
323 $inventory instanceof LoomInventory => UIInventorySlotOffset::LOOM,
324 $inventory instanceof StonecutterInventory => [UIInventorySlotOffset::STONE_CUTTER_INPUT => StonecutterInventory::SLOT_INPUT],
325 $inventory instanceof CraftingTableInventory => UIInventorySlotOffset::CRAFTING3X3_INPUT,
326 $inventory instanceof CartographyTableInventory => UIInventorySlotOffset::CARTOGRAPHY_TABLE,
327 $inventory instanceof SmithingTableInventory => UIInventorySlotOffset::SMITHING_TABLE,
332 public function onCurrentWindowChange(Inventory $inventory) : void{
333 $this->onCurrentWindowRemove();
335 $this->openWindowDeferred(
function() use ($inventory) :
void{
336 if(($slotMap = $this->createComplexSlotMapping($inventory)) !==
null){
337 $windowId = $this->addComplexDynamic($slotMap, $inventory);
339 $windowId = $this->addDynamic($inventory);
342 foreach($this->containerOpenCallbacks as $callback){
343 $pks = $callback($windowId, $inventory);
346 foreach($pks as $pk){
347 if($pk instanceof ContainerOpenPacket){
349 $windowType = $pk->windowType;
351 $this->session->sendDataPacket($pk);
353 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
354 $this->syncContents($inventory);
358 throw new \LogicException(
"Unsupported inventory type");
373 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
374 $windowType = match(
true){
377 FurnaceType::FURNACE => WindowTypes::FURNACE,
378 FurnaceType::BLAST_FURNACE => WindowTypes::BLAST_FURNACE,
379 FurnaceType::SMOKER => WindowTypes::SMOKER,
380 FurnaceType::CAMPFIRE, FurnaceType::SOUL_CAMPFIRE =>
throw new \LogicException(
"Campfire inventory cannot be displayed to a player")
390 default => WindowTypes::CONTAINER
392 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
397 public function onClientOpenMainInventory() : void{
398 $this->onCurrentWindowRemove();
400 $this->openWindowDeferred(
function() :
void{
401 $windowId = $this->getNewWindowId();
402 $this->associateIdWithInventory($windowId, $this->player->getInventory());
403 $this->currentWindowType = WindowTypes::INVENTORY;
405 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
407 $this->currentWindowType,
408 $this->player->getId()
413 public function onCurrentWindowRemove() : void{
414 if(isset($this->networkIdToInventoryMap[$this->lastInventoryNetworkId])){
415 $this->
remove($this->lastInventoryNetworkId);
416 $this->session->sendDataPacket(ContainerClosePacket::create($this->lastInventoryNetworkId, $this->currentWindowType,
true));
417 if($this->pendingCloseWindowId !==
null){
418 throw new AssumptionFailedError(
"We should not have opened a new window while a window was waiting to be closed");
420 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
421 $this->enchantingTableOptions = [];
425 public function onClientRemoveWindow(
int $id) : void{
426 if(Binary::signByte($id) === ContainerIds::NONE){
432 $this->session->getLogger()->debug(
"Client rejected opening of a window, assuming it was $this->lastInventoryNetworkId");
433 $id = $this->lastInventoryNetworkId;
435 if($id === $this->lastInventoryNetworkId){
436 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
438 $this->player->removeCurrentWindow();
441 $this->session->getLogger()->debug(
"Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
446 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType,
false));
448 if($this->pendingCloseWindowId === $id){
449 $this->pendingCloseWindowId =
null;
450 if($this->pendingOpenWindowCallback !==
null){
451 $this->session->getLogger()->debug(
"Opening deferred window after close ack of window $id");
452 ($this->pendingOpenWindowCallback)();
453 $this->pendingOpenWindowCallback =
null;
465 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
466 if($left->getRawExtraData() === $right->getRawExtraData()){
470 $typeConverter = $this->session->getTypeConverter();
471 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
472 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
474 $leftNbt = $leftExtraData->getNbt();
475 $rightNbt = $rightExtraData->getNbt();
477 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
478 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
479 $leftNbt === $rightNbt ||
480 ($leftNbt !==
null && $rightNbt !==
null && $leftNbt->equals($rightNbt))
484 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
486 $left->getId() === $right->getId() &&
487 $left->getMeta() === $right->getMeta() &&
488 $left->getBlockRuntimeId() === $right->getBlockRuntimeId() &&
489 $left->getCount() === $right->getCount() &&
490 $this->itemStackExtraDataEqual($left, $right);
493 public function onSlotChange(Inventory $inventory,
int $slot) : void{
494 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
495 if($inventoryEntry ===
null){
500 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
501 $clientSideItem = $inventoryEntry->predictions[$slot] ??
null;
502 if($clientSideItem ===
null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
504 $this->trackItemStack($inventoryEntry, $slot, $currentItem,
null);
505 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
508 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
511 unset($inventoryEntry->predictions[$slot]);
514 private function sendInventorySlotPackets(
int $windowId,
int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
523 if($itemStackWrapper->getStackId() !== 0){
524 $this->session->sendDataPacket(InventorySlotPacket::create(
529 new ItemStackWrapper(0, ItemStack::null())
533 $this->session->sendDataPacket(InventorySlotPacket::create(
545 private function sendInventoryContentPackets(
int $windowId, array $itemStackWrappers) : void{
554 $this->session->sendDataPacket(InventoryContentPacket::create(
556 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
557 new FullContainerName(0, null),
558 new ItemStackWrapper(0, ItemStack::null())
561 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers,
new FullContainerName(0,
null),
new ItemStackWrapper(0, ItemStack::null())));
564 public function syncSlot(Inventory $inventory,
int $slot, ItemStack $itemStack) : void{
565 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
567 throw new \LogicException(
"Cannot sync an untracked inventory");
569 $itemStackInfo = $entry->itemStackInfos[$slot];
570 if($itemStackInfo ===
null){
571 throw new \LogicException(
"Cannot sync an untracked inventory slot");
573 if($entry->complexSlotMap !==
null){
574 $windowId = ContainerIds::UI;
575 $netSlot = $entry->complexSlotMap->mapCoreToNet($slot) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
577 $windowId = $this->getWindowId($inventory) ??
throw new AssumptionFailedError(
"We already have an ItemStackInfo, so this should not be null");
581 $itemStackWrapper =
new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
582 if($windowId === ContainerIds::OFFHAND){
588 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
590 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
592 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
595 public function syncContents(Inventory $inventory) : void{
596 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
602 if($entry->complexSlotMap !==
null){
603 $windowId = ContainerIds::UI;
605 $windowId = $this->getWindowId($inventory);
607 if($windowId !==
null){
608 $entry->predictions = [];
609 $entry->pendingSyncs = [];
611 $typeConverter = $this->session->getTypeConverter();
612 foreach($inventory->getContents(
true) as $slot => $item){
613 $itemStack = $typeConverter->coreItemStackToNet($item);
614 $info = $this->trackItemStack($entry, $slot, $itemStack,
null);
615 $contents[] =
new ItemStackWrapper($info->getStackId(), $itemStack);
617 if($entry->complexSlotMap !==
null){
618 foreach($contents as $slotId => $info){
619 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ??
null;
620 if($packetSlot ===
null){
623 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
626 $this->sendInventoryContentPackets($windowId, $contents);
631 public function syncAll() : void{
632 foreach($this->inventories as $entry){
633 $this->syncContents($entry->inventory);
637 public function requestSyncAll() : void{
638 $this->fullSyncRequested = true;
641 public function syncMismatchedPredictedSlotChanges() : void{
642 $typeConverter = $this->session->getTypeConverter();
643 foreach($this->inventories as $entry){
644 $inventory = $entry->inventory;
645 foreach($entry->predictions as $slot => $expectedItem){
646 if(!$inventory->slotExists($slot) || $entry->itemStackInfos[$slot] ===
null){
651 $this->session->getLogger()->debug(
"Detected prediction mismatch in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory) .
" slot $slot");
652 $entry->pendingSyncs[$slot] = $typeConverter->coreItemStackToNet($inventory->getItem($slot));
655 $entry->predictions = [];
659 public function flushPendingUpdates() : void{
660 if($this->fullSyncRequested){
661 $this->fullSyncRequested =
false;
662 $this->session->getLogger()->debug(
"Full inventory sync requested, sending contents of " . count($this->inventories) .
" inventories");
665 foreach($this->inventories as $entry){
666 if(count($entry->pendingSyncs) === 0){
669 $inventory = $entry->inventory;
670 $this->session->getLogger()->debug(
"Syncing slots " . implode(
", ", array_keys($entry->pendingSyncs)) .
" in inventory " . get_class($inventory) .
"#" . spl_object_id($inventory));
671 foreach($entry->pendingSyncs as $slot => $itemStack){
672 $this->syncSlot($inventory, $slot, $itemStack);
674 $entry->pendingSyncs = [];
679 public function syncData(Inventory $inventory,
int $propertyId,
int $value) : void{
680 $windowId = $this->getWindowId($inventory);
681 if($windowId !==
null){
682 $this->session->sendDataPacket(ContainerSetDataPacket::create($windowId, $propertyId, $value));
686 public function onClientSelectHotbarSlot(
int $slot) : void{
687 $this->clientSelectedHotbarSlot = $slot;
690 public function syncSelectedHotbarSlot() : void{
691 $playerInventory = $this->player->getInventory();
692 $selected = $playerInventory->getHeldItemIndex();
693 if($selected !== $this->clientSelectedHotbarSlot){
694 $inventoryEntry = $this->inventories[spl_object_id($playerInventory)] ??
null;
695 if($inventoryEntry ===
null){
696 throw new AssumptionFailedError(
"Player inventory should always be tracked");
698 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ??
null;
699 if($itemStackInfo ===
null){
700 throw new AssumptionFailedError(
"Untracked player inventory slot $selected");
703 $this->session->sendDataPacket(MobEquipmentPacket::create(
704 $this->player->getId(),
705 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
708 ContainerIds::INVENTORY
710 $this->clientSelectedHotbarSlot = $selected;
714 public function syncCreative() : void{
715 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
723 $protocolOptions = [];
725 foreach($options as $index => $option){
726 $optionId = $this->nextEnchantingTableOptionId++;
727 $this->enchantingTableOptions[$optionId] = $index;
729 $protocolEnchantments = array_map(
731 $option->getEnchantments()
735 $protocolOptions[] =
new ProtocolEnchantOption(
736 $option->getRequiredXpLevel(),
737 0, $protocolEnchantments,
740 $option->getDisplayName(),
745 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
748 public function getEnchantingTableOptionIndex(
int $recipeId) : ?int{
749 return $this->enchantingTableOptions[$recipeId] ?? null;
752 private function newItemStackId() : int{
753 return $this->nextItemStackId++;
756 public function getItemStackInfo(Inventory $inventory,
int $slot) : ?ItemStackInfo{
757 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
758 return $entry?->itemStackInfos[$slot] ??
null;
761 private function trackItemStack(InventoryManagerEntry $entry,
int $slotId, ItemStack $itemStack, ?
int $itemStackRequestId) : ItemStackInfo{
763 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
764 return $entry->itemStackInfos[$slotId] = $info;