PocketMine-MP 5.15.1 git-be6754494fdbbb9dd57c058ba0e33a4a78c4581f
Item.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
27namespace pocketmine\item;
28
52use function base64_decode;
53use function base64_encode;
54use function count;
55use function gettype;
56use function hex2bin;
57use function is_string;
58use function morton2d_encode;
59
60class Item implements \JsonSerializable{
62
63 public const TAG_ENCH = "ench";
64 private const TAG_ENCH_ID = "id"; //TAG_Short
65 private const TAG_ENCH_LVL = "lvl"; //TAG_Short
66
67 public const TAG_DISPLAY = "display";
68 public const TAG_BLOCK_ENTITY_TAG = "BlockEntityTag";
69
70 public const TAG_DISPLAY_NAME = "Name";
71 public const TAG_DISPLAY_LORE = "Lore";
72
73 public const TAG_KEEP_ON_DEATH = "minecraft:keep_on_death";
74
75 private const TAG_CAN_PLACE_ON = "CanPlaceOn"; //TAG_List<TAG_String>
76 private const TAG_CAN_DESTROY = "CanDestroy"; //TAG_List<TAG_String>
77
78 private CompoundTag $nbt;
79
80 protected int $count = 1;
81
82 //TODO: this stuff should be moved to itemstack properties, not mushed in with type properties
83
84 protected string $customName = "";
86 protected array $lore = [];
88 protected ?CompoundTag $blockEntityTag = null;
89
94 protected array $canPlaceOn = [];
99 protected array $canDestroy = [];
100
101 protected bool $keepOnDeath = false;
102
113 public function __construct(
114 private ItemIdentifier $identifier,
115 protected string $name = "Unknown",
116 private array $enchantmentTags = []
117 ){
118 $this->nbt = new CompoundTag();
119 }
120
121 public function hasCustomBlockData() : bool{
122 return $this->blockEntityTag !== null;
123 }
124
128 public function clearCustomBlockData(){
129 $this->blockEntityTag = null;
130 return $this;
131 }
132
136 public function setCustomBlockData(CompoundTag $compound) : Item{
137 $this->blockEntityTag = clone $compound;
138
139 return $this;
140 }
141
142 public function getCustomBlockData() : ?CompoundTag{
143 return $this->blockEntityTag;
144 }
145
146 public function hasCustomName() : bool{
147 return $this->customName !== "";
148 }
149
150 public function getCustomName() : string{
151 return $this->customName;
152 }
153
157 public function setCustomName(string $name) : Item{
158 Utils::checkUTF8($name);
159 $this->customName = $name;
160 return $this;
161 }
162
166 public function clearCustomName() : Item{
167 $this->setCustomName("");
168 return $this;
169 }
170
174 public function getLore() : array{
175 return $this->lore;
176 }
177
183 public function setLore(array $lines) : Item{
184 foreach($lines as $line){
185 if(!is_string($line)){
186 throw new \TypeError("Expected string[], but found " . gettype($line) . " in given array");
187 }
188 Utils::checkUTF8($line);
189 }
190 $this->lore = $lines;
191 return $this;
192 }
193
198 public function getCanPlaceOn() : array{
199 return $this->canPlaceOn;
200 }
201
205 public function setCanPlaceOn(array $canPlaceOn) : void{
206 $this->canPlaceOn = [];
207 foreach($canPlaceOn as $value){
208 $this->canPlaceOn[$value] = $value;
209 }
210 }
211
216 public function getCanDestroy() : array{
217 return $this->canDestroy;
218 }
219
223 public function setCanDestroy(array $canDestroy) : void{
224 $this->canDestroy = [];
225 foreach($canDestroy as $value){
226 $this->canDestroy[$value] = $value;
227 }
228 }
229
233 public function keepOnDeath() : bool{
234 return $this->keepOnDeath;
235 }
236
237 public function setKeepOnDeath(bool $keepOnDeath) : void{
238 $this->keepOnDeath = $keepOnDeath;
239 }
240
244 public function hasNamedTag() : bool{
245 return $this->getNamedTag()->count() > 0;
246 }
247
252 public function getNamedTag() : CompoundTag{
253 $this->serializeCompoundTag($this->nbt);
254 return $this->nbt;
255 }
256
263 public function setNamedTag(CompoundTag $tag) : Item{
264 if($tag->getCount() === 0){
265 return $this->clearNamedTag();
266 }
267
268 $this->nbt = clone $tag;
269 $this->deserializeCompoundTag($this->nbt);
270
271 return $this;
272 }
273
279 public function clearNamedTag() : Item{
280 $this->nbt = new CompoundTag();
281 $this->deserializeCompoundTag($this->nbt);
282 return $this;
283 }
284
288 protected function deserializeCompoundTag(CompoundTag $tag) : void{
289 $this->customName = "";
290 $this->lore = [];
291
292 $display = $tag->getCompoundTag(self::TAG_DISPLAY);
293 if($display !== null){
294 $this->customName = $display->getString(self::TAG_DISPLAY_NAME, $this->customName);
295 $lore = $display->getListTag(self::TAG_DISPLAY_LORE);
296 if($lore !== null && $lore->getTagType() === NBT::TAG_String){
298 foreach($lore as $t){
299 $this->lore[] = $t->getValue();
300 }
301 }
302 }
303
304 $this->removeEnchantments();
305 $enchantments = $tag->getListTag(self::TAG_ENCH);
306 if($enchantments !== null && $enchantments->getTagType() === NBT::TAG_Compound){
308 foreach($enchantments as $enchantment){
309 $magicNumber = $enchantment->getShort(self::TAG_ENCH_ID, -1);
310 $level = $enchantment->getShort(self::TAG_ENCH_LVL, 0);
311 if($level <= 0){
312 continue;
313 }
314 $type = EnchantmentIdMap::getInstance()->fromId($magicNumber);
315 if($type !== null){
316 $this->addEnchantment(new EnchantmentInstance($type, $level));
317 }
318 }
319 }
320
321 $this->blockEntityTag = $tag->getCompoundTag(self::TAG_BLOCK_ENTITY_TAG);
322
323 $this->canPlaceOn = [];
324 $canPlaceOn = $tag->getListTag(self::TAG_CAN_PLACE_ON);
325 if($canPlaceOn !== null && $canPlaceOn->getTagType() === NBT::TAG_String){
327 foreach($canPlaceOn as $entry){
328 $this->canPlaceOn[$entry->getValue()] = $entry->getValue();
329 }
330 }
331 $this->canDestroy = [];
332 $canDestroy = $tag->getListTag(self::TAG_CAN_DESTROY);
333 if($canDestroy !== null && $canDestroy->getTagType() === NBT::TAG_String){
335 foreach($canDestroy as $entry){
336 $this->canDestroy[$entry->getValue()] = $entry->getValue();
337 }
338 }
339
340 $this->keepOnDeath = $tag->getByte(self::TAG_KEEP_ON_DEATH, 0) !== 0;
341 }
342
343 protected function serializeCompoundTag(CompoundTag $tag) : void{
344 $display = $tag->getCompoundTag(self::TAG_DISPLAY);
345
346 if($this->customName !== ""){
347 $display ??= new CompoundTag();
348 $display->setString(self::TAG_DISPLAY_NAME, $this->customName);
349 }else{
350 $display?->removeTag(self::TAG_DISPLAY_NAME);
351 }
352
353 if(count($this->lore) > 0){
354 $loreTag = new ListTag();
355 foreach($this->lore as $line){
356 $loreTag->push(new StringTag($line));
357 }
358 $display ??= new CompoundTag();
359 $display->setTag(self::TAG_DISPLAY_LORE, $loreTag);
360 }else{
361 $display?->removeTag(self::TAG_DISPLAY_LORE);
362 }
363 $display !== null && $display->count() > 0 ?
364 $tag->setTag(self::TAG_DISPLAY, $display) :
365 $tag->removeTag(self::TAG_DISPLAY);
366
367 if(count($this->enchantments) > 0){
368 $ench = new ListTag();
369 $enchantmentIdMap = EnchantmentIdMap::getInstance();
370 foreach($this->enchantments as $enchantmentInstance){
371 $ench->push(CompoundTag::create()
372 ->setShort(self::TAG_ENCH_ID, $enchantmentIdMap->toId($enchantmentInstance->getType()))
373 ->setShort(self::TAG_ENCH_LVL, $enchantmentInstance->getLevel())
374 );
375 }
376 $tag->setTag(self::TAG_ENCH, $ench);
377 }else{
378 $tag->removeTag(self::TAG_ENCH);
379 }
380
381 $this->blockEntityTag !== null ?
382 $tag->setTag(self::TAG_BLOCK_ENTITY_TAG, clone $this->blockEntityTag) :
383 $tag->removeTag(self::TAG_BLOCK_ENTITY_TAG);
384
385 if(count($this->canPlaceOn) > 0){
386 $canPlaceOn = new ListTag();
387 foreach($this->canPlaceOn as $item){
388 $canPlaceOn->push(new StringTag($item));
389 }
390 $tag->setTag(self::TAG_CAN_PLACE_ON, $canPlaceOn);
391 }else{
392 $tag->removeTag(self::TAG_CAN_PLACE_ON);
393 }
394 if(count($this->canDestroy) > 0){
395 $canDestroy = new ListTag();
396 foreach($this->canDestroy as $item){
397 $canDestroy->push(new StringTag($item));
398 }
399 $tag->setTag(self::TAG_CAN_DESTROY, $canDestroy);
400 }else{
401 $tag->removeTag(self::TAG_CAN_DESTROY);
402 }
403
404 if($this->keepOnDeath){
405 $tag->setByte(self::TAG_KEEP_ON_DEATH, 1);
406 }else{
407 $tag->removeTag(self::TAG_KEEP_ON_DEATH);
408 }
409 }
410
411 public function getCount() : int{
412 return $this->count;
413 }
414
418 public function setCount(int $count) : Item{
419 $this->count = $count;
420
421 return $this;
422 }
423
430 public function pop(int $count = 1) : Item{
431 if($count > $this->count){
432 throw new \InvalidArgumentException("Cannot pop $count items from a stack of $this->count");
433 }
434
435 $item = clone $this;
436 $item->count = $count;
437
438 $this->count -= $count;
439
440 return $item;
441 }
442
443 public function isNull() : bool{
444 return $this->count <= 0;
445 }
446
450 final public function getName() : string{
451 return $this->hasCustomName() ? $this->getCustomName() : $this->getVanillaName();
452 }
453
457 public function getVanillaName() : string{
458 return $this->name;
459 }
460
470 public function getEnchantmentTags() : array{
471 return $this->enchantmentTags;
472 }
473
480 public function getEnchantability() : int{
481 return 1;
482 }
483
484 final public function canBePlaced() : bool{
485 return $this->getBlock()->canBePlaced();
486 }
487
491 public function getBlock(?int $clickedFace = null) : Block{
492 return VanillaBlocks::AIR();
493 }
494
495 final public function getTypeId() : int{
496 return $this->identifier->getTypeId();
497 }
498
499 final public function getStateId() : int{
500 return morton2d_encode($this->identifier->getTypeId(), $this->computeStateData());
501 }
502
503 private function computeStateData() : int{
504 $writer = new RuntimeDataWriter(16); //TODO: max bits should be a constant instead of being hardcoded all over the place
505 $this->describeState($writer);
506 return $writer->getValue();
507 }
508
513 protected function describeState(RuntimeDataDescriber $w) : void{
514 //NOOP
515 }
516
520 public function getMaxStackSize() : int{
521 return 64;
522 }
523
527 public function getFuelTime() : int{
528 return 0;
529 }
530
534 public function getFuelResidue() : Item{
535 $item = clone $this;
536 $item->pop();
537
538 return $item;
539 }
540
544 public function isFireProof() : bool{
545 return false;
546 }
547
551 public function getAttackPoints() : int{
552 return 1;
553 }
554
558 public function getDefensePoints() : int{
559 return 0;
560 }
561
566 public function getBlockToolType() : int{
567 return BlockToolType::NONE;
568 }
569
577 public function getBlockToolHarvestLevel() : int{
578 return 0;
579 }
580
581 public function getMiningEfficiency(bool $isCorrectTool) : float{
582 return 1;
583 }
584
590 public function onInteractBlock(Player $player, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, array &$returnedItems) : ItemUseResult{
591 return ItemUseResult::NONE;
592 }
593
600 public function onClickAir(Player $player, Vector3 $directionVector, array &$returnedItems) : ItemUseResult{
601 return ItemUseResult::NONE;
602 }
603
610 public function onReleaseUsing(Player $player, array &$returnedItems) : ItemUseResult{
611 return ItemUseResult::NONE;
612 }
613
619 public function onDestroyBlock(Block $block, array &$returnedItems) : bool{
620 return false;
621 }
622
628 public function onAttackEntity(Entity $victim, array &$returnedItems) : bool{
629 return false;
630 }
631
636 public function onTickWorn(Living $entity) : bool{
637 return false;
638 }
639
646 public function onInteractEntity(Player $player, Entity $entity, Vector3 $clickVector) : bool{
647 return false;
648 }
649
653 public function getCooldownTicks() : int{
654 return 0;
655 }
656
663 final public function equals(Item $item, bool $checkDamage = true, bool $checkCompound = true) : bool{
664 return $this->getStateId() === $item->getStateId() &&
665 (!$checkCompound || $this->getNamedTag()->equals($item->getNamedTag()));
666 }
667
671 final public function canStackWith(Item $other) : bool{
672 return $this->equals($other, true, true);
673 }
674
678 final public function equalsExact(Item $other) : bool{
679 return $this->canStackWith($other) && $this->count === $other->count;
680 }
681
682 final public function __toString() : string{
683 return "Item " . $this->name . " (" . $this->getTypeId() . ":" . $this->computeStateData() . ")x" . $this->count . ($this->hasNamedTag() ? " tags:0x" . base64_encode((new LittleEndianNbtSerializer())->write(new TreeRoot($this->getNamedTag()))) : "");
684 }
685
689 public function jsonSerialize() : array{
690 throw new \LogicException("json_encode()ing Item instances is no longer supported. Make your own method to convert the item to an array or stdClass.");
691 }
692
701 final public static function legacyJsonDeserialize(array $data) : Item{
702 $nbt = "";
703
704 //Backwards compatibility
705 if(isset($data["nbt"])){
706 $nbt = $data["nbt"];
707 }elseif(isset($data["nbt_hex"])){
708 $nbt = hex2bin($data["nbt_hex"]);
709 }elseif(isset($data["nbt_b64"])){
710 $nbt = base64_decode($data["nbt_b64"], true);
711 }
712
713 $itemStackData = GlobalItemDataHandlers::getUpgrader()->upgradeItemTypeDataInt(
714 (int) $data["id"],
715 (int) ($data["damage"] ?? 0),
716 (int) ($data["count"] ?? 1),
717 $nbt !== "" ? (new LittleEndianNbtSerializer())->read($nbt)->mustGetCompoundTag() : null
718 );
719
720 try{
721 return GlobalItemDataHandlers::getDeserializer()->deserializeStack($itemStackData);
722 }catch(ItemTypeDeserializeException $e){
723 throw new SavedDataLoadingException($e->getMessage(), 0, $e);
724 }
725 }
726
732 public function nbtSerialize(int $slot = -1) : CompoundTag{
733 return GlobalItemDataHandlers::getSerializer()->serializeStack($this, $slot !== -1 ? $slot : null)->toNbt();
734 }
735
740 public static function nbtDeserialize(CompoundTag $tag) : Item{
741 $itemData = GlobalItemDataHandlers::getUpgrader()->upgradeItemStackNbt($tag);
742 if($itemData === null){
743 return VanillaItems::AIR();
744 }
745
746 try{
747 return GlobalItemDataHandlers::getDeserializer()->deserializeStack($itemData);
748 }catch(ItemTypeDeserializeException $e){
749 throw new SavedDataLoadingException($e->getMessage(), 0, $e);
750 }
751 }
752
753 public function __clone(){
754 $this->nbt = clone $this->nbt;
755 if($this->blockEntityTag !== null){
756 $this->blockEntityTag = clone $this->blockEntityTag;
757 }
758 }
759}
static legacyJsonDeserialize(array $data)
Definition: Item.php:701
getBlock(?int $clickedFace=null)
Definition: Item.php:491
describeState(RuntimeDataDescriber $w)
Definition: Item.php:513
nbtSerialize(int $slot=-1)
Definition: Item.php:732
onAttackEntity(Entity $victim, array &$returnedItems)
Definition: Item.php:628
getBlockToolHarvestLevel()
Definition: Item.php:577
setCustomBlockData(CompoundTag $compound)
Definition: Item.php:136
canStackWith(Item $other)
Definition: Item.php:671
equals(Item $item, bool $checkDamage=true, bool $checkCompound=true)
Definition: Item.php:663
deserializeCompoundTag(CompoundTag $tag)
Definition: Item.php:288
CompoundTag $blockEntityTag
Definition: Item.php:88
pop(int $count=1)
Definition: Item.php:430
onReleaseUsing(Player $player, array &$returnedItems)
Definition: Item.php:610
setNamedTag(CompoundTag $tag)
Definition: Item.php:263
static nbtDeserialize(CompoundTag $tag)
Definition: Item.php:740
setCount(int $count)
Definition: Item.php:418
setLore(array $lines)
Definition: Item.php:183
onClickAir(Player $player, Vector3 $directionVector, array &$returnedItems)
Definition: Item.php:600
setCanPlaceOn(array $canPlaceOn)
Definition: Item.php:205
onTickWorn(Living $entity)
Definition: Item.php:636
__construct(private ItemIdentifier $identifier, protected string $name="Unknown", private array $enchantmentTags=[])
Definition: Item.php:113
onInteractBlock(Player $player, Block $blockReplace, Block $blockClicked, int $face, Vector3 $clickVector, array &$returnedItems)
Definition: Item.php:590
setCanDestroy(array $canDestroy)
Definition: Item.php:223
onDestroyBlock(Block $block, array &$returnedItems)
Definition: Item.php:619
setCustomName(string $name)
Definition: Item.php:157
equalsExact(Item $other)
Definition: Item.php:678
onInteractEntity(Player $player, Entity $entity, Vector3 $clickVector)
Definition: Item.php:646