inventory = new SimpleInventory(count(ChiseledBookshelfSlot::cases())); } public function getInventory() : SimpleInventory{ return $this->inventory; } public function getRealInventory() : SimpleInventory{ return $this->inventory; } public function getLastInteractedSlot() : ?ChiseledBookshelfSlot{ return $this->lastInteractedSlot; } public function setLastInteractedSlot(?ChiseledBookshelfSlot $lastInteractedSlot) : void{ $this->lastInteractedSlot = $lastInteractedSlot; } public function readSaveData(CompoundTag $nbt) : void{ $this->loadItems($nbt); $lastInteractedSlot = $nbt->getInt(self::TAG_LAST_INTERACTED_SLOT, 0); if($lastInteractedSlot !== 0){ $this->lastInteractedSlot = ChiseledBookshelfSlot::tryFrom($lastInteractedSlot - 1); } } protected function writeSaveData(CompoundTag $nbt) : void{ $this->saveItems($nbt); $nbt->setInt(self::TAG_LAST_INTERACTED_SLOT, $this->lastInteractedSlot !== null ? $this->lastInteractedSlot->value + 1 : 0 ); } protected function loadItems(CompoundTag $tag) : void{ if(($inventoryTag = $tag->getTag(ContainerTile::TAG_ITEMS)) instanceof ListTag && $inventoryTag->getTagType() === NBT::TAG_Compound){ $inventory = $this->getRealInventory(); $listeners = $inventory->getListeners()->toArray(); $inventory->getListeners()->remove(...$listeners); //prevent any events being fired by initialization $newContents = []; /** @var CompoundTag $itemNBT */ foreach($inventoryTag as $slot => $itemNBT){ try{ $count = $itemNBT->getByte(SavedItemStackData::TAG_COUNT); if($count === 0){ continue; } $newContents[$slot] = Item::nbtDeserialize($itemNBT); }catch(SavedDataLoadingException $e){ //TODO: not the best solution \GlobalLogger::get()->logException($e); continue; } } $inventory->setContents($newContents); $inventory->getListeners()->add(...$listeners); } if(($lockTag = $tag->getTag(ContainerTile::TAG_LOCK)) instanceof StringTag){ $this->lock = $lockTag->getValue(); } } protected function saveItems(CompoundTag $tag) : void{ $items = []; foreach($this->getRealInventory()->getContents(true) as $slot => $item){ if($item->isNull()){ $items[$slot] = CompoundTag::create() ->setByte(SavedItemStackData::TAG_COUNT, 0) ->setShort(SavedItemData::TAG_DAMAGE, 0) ->setString(SavedItemData::TAG_NAME, "") ->setByte(SavedItemStackData::TAG_WAS_PICKED_UP, 0); }else{ $items[$slot] = $item->nbtSerialize(); } } $tag->setTag(ContainerTile::TAG_ITEMS, new ListTag($items, NBT::TAG_Compound)); if($this->lock !== null){ $tag->setString(ContainerTile::TAG_LOCK, $this->lock); } } }