PocketMine-MP 5.44.4 git-6a7cc02e9dff59b69241aa0bcffdb9903ce86beb
Loading...
Searching...
No Matches
InventoryManager.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\network\mcpe;
25
37use pocketmine\crafting\FurnaceType;
69use function array_fill_keys;
70use function array_keys;
71use function array_map;
72use function array_search;
73use function count;
74use function get_class;
75use function implode;
76use function is_int;
77use function max;
78use function spl_object_id;
79
88 private array $inventories = [];
89
94 private array $networkIdToInventoryMap = [];
99 private array $complexSlotToInventoryMap = [];
100
101 private int $lastInventoryNetworkId = ContainerIds::FIRST;
102 private int $currentWindowType = WindowTypes::CONTAINER;
103
104 private int $clientSelectedHotbarSlot = -1;
105
107 private ObjectSet $containerOpenCallbacks;
108
109 private ?int $pendingCloseWindowId = null;
111 private ?\Closure $pendingOpenWindowCallback = null;
112
113 private int $nextItemStackId = 1;
114 private ?int $currentItemStackRequestId = null;
115
116 private bool $fullSyncRequested = false;
117
119 private array $enchantingTableOptions = [];
120 //TODO: this should be based on the total number of crafting recipes - if there are ever 100k recipes, this will
121 //conflict with regular recipes
122 private int $nextEnchantingTableOptionId = 100000;
123
124 public function __construct(
125 private Player $player,
126 private NetworkSession $session
127 ){
128 $this->containerOpenCallbacks = new ObjectSet();
129 $this->containerOpenCallbacks->add(self::createContainerOpen(...));
130
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());
136
137 $this->player->getInventory()->getHeldItemIndexChangeListeners()->add($this->syncSelectedHotbarSlot(...));
138 }
139
140 private function associateIdWithInventory(int $id, Inventory $inventory) : void{
141 $this->networkIdToInventoryMap[$id] = $inventory;
142 }
143
144 private function getNewWindowId() : int{
145 $this->lastInventoryNetworkId = max(ContainerIds::FIRST, ($this->lastInventoryNetworkId + 1) % ContainerIds::LAST);
146 return $this->lastInventoryNetworkId;
147 }
148
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");
152 }
153 $this->inventories[spl_object_id($inventory)] = new InventoryManagerEntry($inventory);
154 $this->associateIdWithInventory($id, $inventory);
155 }
156
157 private function addDynamic(Inventory $inventory) : int{
158 $id = $this->getNewWindowId();
159 $this->add($id, $inventory);
160 return $id;
161 }
162
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");
170 }
171 $complexSlotMap = new ComplexInventoryMapEntry($inventory, is_int($slotMap) ? [$slotMap => 0] : $slotMap);
172 $this->inventories[spl_object_id($inventory)] = new InventoryManagerEntry(
173 $inventory,
174 $complexSlotMap
175 );
176 foreach($complexSlotMap->getSlotMap() as $netSlot => $coreSlot){
177 $this->complexSlotToInventoryMap[$netSlot] = $complexSlotMap;
178 }
179 }
180
185 private function addComplexDynamic(array|int $slotMap, Inventory $inventory) : int{
186 $this->addComplex($slotMap, $inventory);
187 $id = $this->getNewWindowId();
188 $this->associateIdWithInventory($id, $inventory);
189 return $id;
190 }
191
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]);
200 }
201 }
202 }
203 }
204
205 public function getWindowId(Inventory $inventory) : ?int{
206 return ($id = array_search($inventory, $this->networkIdToInventoryMap, true)) !== false ? $id : null;
207 }
208
209 public function getCurrentWindowId() : int{
210 return $this->lastInventoryNetworkId;
211 }
212
216 public function locateWindowAndSlot(int $windowId, int $netSlotId) : ?array{
217 if($windowId === ContainerIds::UI){
218 $entry = $this->complexSlotToInventoryMap[$netSlotId] ?? null;
219 if($entry === null){
220 return null;
221 }
222 $inventory = $entry->getInventory();
223 $coreSlotId = $entry->mapNetToCore($netSlotId);
224 return $coreSlotId !== null && $inventory->slotExists($coreSlotId) ? [$inventory, $coreSlotId] : null;
225 }
226 $inventory = $this->networkIdToInventoryMap[$windowId] ?? null;
227 if($inventory !== null && $inventory->slotExists($netSlotId)){
228 return [$inventory, $netSlotId];
229 }
230 return null;
231 }
232
233 private function addPredictedSlotChangeInternal(Inventory $inventory, int $slot, ItemStack $item) : void{
234 $this->inventories[spl_object_id($inventory)]->predictions[$slot] = $item;
235 }
236
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);
241 }
242
243 public function addTransactionPredictedSlotChanges(InventoryTransaction $tx) : void{
244 foreach($tx->getActions() as $action){
245 if($action instanceof SlotChangeAction){
246 //TODO: ItemStackRequestExecutor can probably build these predictions with much lower overhead
247 $this->addPredictedSlotChange(
248 $action->getInventory(),
249 $action->getSlot(),
250 $action->getTargetItem()
251 );
252 }
253 }
254 }
255
260 public function addRawPredictedSlotChanges(array $networkInventoryActions) : void{
261 foreach($networkInventoryActions as $action){
262 if($action->sourceType !== NetworkInventoryAction::SOURCE_CONTAINER){
263 continue;
264 }
265 if($action->windowId === null){
266 throw new PacketHandlingException("Window ID should always be set for SOURCE_CONTAINER");
267 }
268
269 //legacy transactions should not modify or predict anything other than these inventories, since these are
270 //the only ones accessible when not in-game (ItemStackRequest is used for everything else)
271 if(match($action->windowId){
272 ContainerIds::INVENTORY, ContainerIds::OFFHAND, ContainerIds::ARMOR => false,
273 default => true
274 }){
275 throw new PacketHandlingException("Legacy transactions cannot predict changes to inventory with ID " . $action->windowId);
276 }
277 $info = $this->locateWindowAndSlot($action->windowId, $action->inventorySlot);
278 if($info === null){
279 continue;
280 }
281
282 [$inventory, $slot] = $info;
283 $this->addPredictedSlotChangeInternal($inventory, $slot, $action->newItem->getItemStack());
284 }
285 }
286
287 public function setCurrentItemStackRequestId(?int $id) : void{
288 $this->currentItemStackRequestId = $id;
289 }
290
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;
309 }else{
310 $func();
311 }
312 }
313
318 private function createComplexSlotMapping(Inventory $inventory) : ?array{
319 //TODO: make this dynamic so plugins can add mappings for stuff not implemented by PM
320 return match(true){
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,
328 default => null,
329 };
330 }
331
332 public function onCurrentWindowChange(Inventory $inventory) : void{
333 $this->onCurrentWindowRemove();
334
335 $this->openWindowDeferred(function() use ($inventory) : void{
336 if(($slotMap = $this->createComplexSlotMapping($inventory)) !== null){
337 $windowId = $this->addComplexDynamic($slotMap, $inventory);
338 }else{
339 $windowId = $this->addDynamic($inventory);
340 }
341
342 foreach($this->containerOpenCallbacks as $callback){
343 $pks = $callback($windowId, $inventory);
344 if($pks !== null){
345 $windowType = null;
346 foreach($pks as $pk){
347 if($pk instanceof ContainerOpenPacket){
348 //workaround useless bullshit in 1.21 - ContainerClose requires a type now for some reason
349 $windowType = $pk->windowType;
350 }
351 $this->session->sendDataPacket($pk);
352 }
353 $this->currentWindowType = $windowType ?? WindowTypes::CONTAINER;
354 $this->syncContents($inventory);
355 return;
356 }
357 }
358 throw new \LogicException("Unsupported inventory type");
359 });
360 }
361
363 public function getContainerOpenCallbacks() : ObjectSet{ return $this->containerOpenCallbacks; }
364
369 protected static function createContainerOpen(int $id, Inventory $inv) : ?array{
370 //TODO: we should be using some kind of tagging system to identify the types. Instanceof is flaky especially
371 //if the class isn't final, not to mention being inflexible.
372 if($inv instanceof BlockInventory){
373 $blockPosition = BlockPosition::fromVector3($inv->getHolder());
374 $windowType = match(true){
375 $inv instanceof LoomInventory => WindowTypes::LOOM,
376 $inv instanceof FurnaceInventory => match($inv->getFurnaceType()){
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")
381 },
382 $inv instanceof EnchantInventory => WindowTypes::ENCHANTMENT,
383 $inv instanceof BrewingStandInventory => WindowTypes::BREWING_STAND,
384 $inv instanceof AnvilInventory => WindowTypes::ANVIL,
385 $inv instanceof HopperInventory => WindowTypes::HOPPER,
386 $inv instanceof CraftingTableInventory => WindowTypes::WORKBENCH,
387 $inv instanceof StonecutterInventory => WindowTypes::STONECUTTER,
388 $inv instanceof CartographyTableInventory => WindowTypes::CARTOGRAPHY,
389 $inv instanceof SmithingTableInventory => WindowTypes::SMITHING_TABLE,
390 default => WindowTypes::CONTAINER
391 };
392 return [ContainerOpenPacket::blockInv($id, $windowType, $blockPosition)];
393 }
394 return null;
395 }
396
397 public function onClientOpenMainInventory() : void{
398 $this->onCurrentWindowRemove();
399
400 $this->openWindowDeferred(function() : void{
401 $windowId = $this->getNewWindowId();
402 $this->associateIdWithInventory($windowId, $this->player->getInventory());
403 $this->currentWindowType = WindowTypes::INVENTORY;
404
405 $this->session->sendDataPacket(ContainerOpenPacket::entityInv(
406 $windowId,
407 $this->currentWindowType,
408 $this->player->getId()
409 ));
410 });
411 }
412
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");
419 }
420 $this->pendingCloseWindowId = $this->lastInventoryNetworkId;
421 $this->enchantingTableOptions = [];
422 }
423 }
424
425 public function onClientRemoveWindow(int $id) : void{
426 if(Binary::signByte($id) === ContainerIds::NONE){ //TODO: REMOVE signByte() once BedrockProtocol + ext-encoding are implemented
427 //TODO: HACK! Since 1.21.100 (and probably earlier), the client will send -1 to close windows that it can't
428 //view for some reason, e.g. if the chat window was already open. This is pretty awkward, since it means
429 //that we can only assume it refers to the most recently sent window, and if we don't handle it,
430 //InventoryManager will never get the green light to send subsequent windows, which breaks inventory UIs.
431 //Fortunately, we already wait for close acks anyway, so the window ID is technically useless...?
432 $this->session->getLogger()->debug("Client rejected opening of a window, assuming it was $this->lastInventoryNetworkId");
433 $id = $this->lastInventoryNetworkId;
434 }
435 if($id === $this->lastInventoryNetworkId){
436 if(isset($this->networkIdToInventoryMap[$id]) && $id !== $this->pendingCloseWindowId){
437 $this->remove($id);
438 $this->player->removeCurrentWindow();
439 }
440 }else{
441 $this->session->getLogger()->debug("Attempted to close inventory with network ID $id, but current is $this->lastInventoryNetworkId");
442 }
443
444 //Always send this, even if no window matches. If we told the client to close a window, it will behave as if it
445 //initiated the close and expect an ack.
446 $this->session->sendDataPacket(ContainerClosePacket::create($id, $this->currentWindowType, false));
447
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;
454 }
455 }
456 }
457
465 private function itemStackExtraDataEqual(ItemStack $left, ItemStack $right) : bool{
466 if($left->getRawExtraData() === $right->getRawExtraData()){
467 return true;
468 }
469
470 $typeConverter = $this->session->getTypeConverter();
471 $leftExtraData = $typeConverter->deserializeItemStackExtraData($left->getRawExtraData(), $left->getId());
472 $rightExtraData = $typeConverter->deserializeItemStackExtraData($right->getRawExtraData(), $right->getId());
473
474 $leftNbt = $leftExtraData->getNbt();
475 $rightNbt = $rightExtraData->getNbt();
476 return
477 $leftExtraData->getCanPlaceOn() === $rightExtraData->getCanPlaceOn() &&
478 $leftExtraData->getCanDestroy() === $rightExtraData->getCanDestroy() && (
479 $leftNbt === $rightNbt || //this covers null === null and fast object identity
480 ($leftNbt !== null && $rightNbt !== null && $leftNbt->equals($rightNbt))
481 );
482 }
483
484 private function itemStacksEqual(ItemStack $left, ItemStack $right) : bool{
485 return
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);
491 }
492
493 public function onSlotChange(Inventory $inventory, int $slot) : void{
494 $inventoryEntry = $this->inventories[spl_object_id($inventory)] ?? null;
495 if($inventoryEntry === null){
496 //this can happen when an inventory changed during InventoryCloseEvent, or when a temporary inventory
497 //is cleared before removal.
498 return;
499 }
500 $currentItem = $this->session->getTypeConverter()->coreItemStackToNet($inventory->getItem($slot));
501 $clientSideItem = $inventoryEntry->predictions[$slot] ?? null;
502 if($clientSideItem === null || !$this->itemStacksEqual($currentItem, $clientSideItem)){
503 //no prediction or incorrect - do not associate this with the currently active itemstack request
504 $this->trackItemStack($inventoryEntry, $slot, $currentItem, null);
505 $inventoryEntry->pendingSyncs[$slot] = $currentItem;
506 }else{
507 //correctly predicted - associate the change with the currently active itemstack request
508 $this->trackItemStack($inventoryEntry, $slot, $currentItem, $this->currentItemStackRequestId);
509 }
510
511 unset($inventoryEntry->predictions[$slot]);
512 }
513
514 private function sendInventorySlotPackets(int $windowId, int $netSlot, ItemStackWrapper $itemStackWrapper) : void{
515 /*
516 * TODO: HACK!
517 * As of 1.20.12, the client ignores change of itemstackID in some cases when the old item == the new item.
518 * Notably, this happens with armor, offhand and enchanting tables, but not with main inventory.
519 * While we could track the items previously sent to the client, that's a waste of memory and would
520 * cost performance. Instead, clear the slot(s) first, then send the new item(s).
521 * The network cost of doing this is fortunately minimal, as an air itemstack is only 1 byte.
522 */
523 if($itemStackWrapper->getStackId() !== 0){
524 $this->session->sendDataPacket(InventorySlotPacket::create(
525 $windowId,
526 $netSlot,
527 null,
528 null,
529 new ItemStackWrapper(0, ItemStack::null())
530 ));
531 }
532 //now send the real contents
533 $this->session->sendDataPacket(InventorySlotPacket::create(
534 $windowId,
535 $netSlot,
536 null,
537 null,
538 $itemStackWrapper
539 ));
540 }
541
545 private function sendInventoryContentPackets(int $windowId, array $itemStackWrappers) : void{
546 /*
547 * TODO: HACK!
548 * As of 1.20.12, the client ignores change of itemstackID in some cases when the old item == the new item.
549 * Notably, this happens with armor, offhand and enchanting tables, but not with main inventory.
550 * While we could track the items previously sent to the client, that's a waste of memory and would
551 * cost performance. Instead, clear the slot(s) first, then send the new item(s).
552 * The network cost of doing this is fortunately minimal, as an air itemstack is only 1 byte.
553 */
554 $this->session->sendDataPacket(InventoryContentPacket::create(
555 $windowId,
556 array_fill_keys(array_keys($itemStackWrappers), new ItemStackWrapper(0, ItemStack::null())),
557 new FullContainerName(0, null),
558 new ItemStackWrapper(0, ItemStack::null())
559 ));
560 //now send the real contents
561 $this->session->sendDataPacket(InventoryContentPacket::create($windowId, $itemStackWrappers, new FullContainerName(0, null), new ItemStackWrapper(0, ItemStack::null())));
562 }
563
564 public function syncSlot(Inventory $inventory, int $slot, ItemStack $itemStack) : void{
565 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
566 if($entry === null){
567 throw new \LogicException("Cannot sync an untracked inventory");
568 }
569 $itemStackInfo = $entry->itemStackInfos[$slot];
570 if($itemStackInfo === null){
571 throw new \LogicException("Cannot sync an untracked inventory slot");
572 }
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");
576 }else{
577 $windowId = $this->getWindowId($inventory) ?? throw new AssumptionFailedError("We already have an ItemStackInfo, so this should not be null");
578 $netSlot = $slot;
579 }
580
581 $itemStackWrapper = new ItemStackWrapper($itemStackInfo->getStackId(), $itemStack);
582 if($windowId === ContainerIds::OFFHAND){
583 //TODO: HACK!
584 //The client may sometimes ignore the InventorySlotPacket for the offhand slot.
585 //This can cause a lot of problems (totems, arrows, and more...).
586 //The workaround is to send an InventoryContentPacket instead
587 //BDS (Bedrock Dedicated Server) also seems to work this way.
588 $this->sendInventoryContentPackets($windowId, [$itemStackWrapper]);
589 }else{
590 $this->sendInventorySlotPackets($windowId, $netSlot, $itemStackWrapper);
591 }
592 unset($entry->predictions[$slot], $entry->pendingSyncs[$slot]);
593 }
594
595 public function syncContents(Inventory $inventory) : void{
596 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
597 if($entry === null){
598 //this can happen when an inventory changed during InventoryCloseEvent, or when a temporary inventory
599 //is cleared before removal.
600 return;
601 }
602 if($entry->complexSlotMap !== null){
603 $windowId = ContainerIds::UI;
604 }else{
605 $windowId = $this->getWindowId($inventory);
606 }
607 if($windowId !== null){
608 $entry->predictions = [];
609 $entry->pendingSyncs = [];
610 $contents = [];
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);
616 }
617 if($entry->complexSlotMap !== null){
618 foreach($contents as $slotId => $info){
619 $packetSlot = $entry->complexSlotMap->mapCoreToNet($slotId) ?? null;
620 if($packetSlot === null){
621 continue;
622 }
623 $this->sendInventorySlotPackets($windowId, $packetSlot, $info);
624 }
625 }else{
626 $this->sendInventoryContentPackets($windowId, $contents);
627 }
628 }
629 }
630
631 public function syncAll() : void{
632 foreach($this->inventories as $entry){
633 $this->syncContents($entry->inventory);
634 }
635 }
636
637 public function requestSyncAll() : void{
638 $this->fullSyncRequested = true;
639 }
640
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){
647 continue; //TODO: size desync ???
648 }
649
650 //any prediction that still exists at this point is a slot that was predicted to change but didn't
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));
653 }
654
655 $entry->predictions = [];
656 }
657 }
658
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");
663 $this->syncAll();
664 }else{
665 foreach($this->inventories as $entry){
666 if(count($entry->pendingSyncs) === 0){
667 continue;
668 }
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);
673 }
674 $entry->pendingSyncs = [];
675 }
676 }
677 }
678
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));
683 }
684 }
685
686 public function onClientSelectHotbarSlot(int $slot) : void{
687 $this->clientSelectedHotbarSlot = $slot;
688 }
689
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");
697 }
698 $itemStackInfo = $inventoryEntry->itemStackInfos[$selected] ?? null;
699 if($itemStackInfo === null){
700 throw new AssumptionFailedError("Untracked player inventory slot $selected");
701 }
702
703 $this->session->sendDataPacket(MobEquipmentPacket::create(
704 $this->player->getId(),
705 new ItemStackWrapper($itemStackInfo->getStackId(), $this->session->getTypeConverter()->coreItemStackToNet($playerInventory->getItemInHand())),
706 $selected,
707 $selected,
708 ContainerIds::INVENTORY
709 ));
710 $this->clientSelectedHotbarSlot = $selected;
711 }
712 }
713
714 public function syncCreative() : void{
715 $this->session->sendDataPacket(CreativeInventoryCache::getInstance()->buildPacket($this->player->getCreativeInventory(), $this->session));
716 }
717
722 public function syncEnchantingTableOptions(array $options) : void{
723 $protocolOptions = [];
724
725 foreach($options as $index => $option){
726 $optionId = $this->nextEnchantingTableOptionId++;
727 $this->enchantingTableOptions[$optionId] = $index;
728
729 $protocolEnchantments = array_map(
730 fn(EnchantmentInstance $e) => new Enchant(EnchantmentIdMap::getInstance()->toId($e->getType()), $e->getLevel()),
731 $option->getEnchantments()
732 );
733 // We don't pay attention to the $slotFlags, $heldActivatedEnchantments and $selfActivatedEnchantments
734 // as everything works fine without them (perhaps these values are used somehow in the BDS).
735 $protocolOptions[] = new ProtocolEnchantOption(
736 $option->getRequiredXpLevel(),
737 0, $protocolEnchantments,
738 [],
739 [],
740 $option->getDisplayName(),
741 $optionId
742 );
743 }
744
745 $this->session->sendDataPacket(PlayerEnchantOptionsPacket::create($protocolOptions));
746 }
747
748 public function getEnchantingTableOptionIndex(int $recipeId) : ?int{
749 return $this->enchantingTableOptions[$recipeId] ?? null;
750 }
751
752 private function newItemStackId() : int{
753 return $this->nextItemStackId++;
754 }
755
756 public function getItemStackInfo(Inventory $inventory, int $slot) : ?ItemStackInfo{
757 $entry = $this->inventories[spl_object_id($inventory)] ?? null;
758 return $entry?->itemStackInfos[$slot] ?? null;
759 }
760
761 private function trackItemStack(InventoryManagerEntry $entry, int $slotId, ItemStack $itemStack, ?int $itemStackRequestId) : ItemStackInfo{
762 //TODO: ItemStack->isNull() would be nice to have here
763 $info = new ItemStackInfo($itemStackRequestId, $itemStack->getId() === 0 ? 0 : $this->newItemStackId());
764 return $entry->itemStackInfos[$slotId] = $info;
765 }
766}
locateWindowAndSlot(int $windowId, int $netSlotId)
static createContainerOpen(int $id, Inventory $inv)
addRawPredictedSlotChanges(array $networkInventoryActions)