PocketMine-MP 5.21.3 git-fcef015f32c0b0709cfd4d6f1b3c32f484b25bde
Loading...
Searching...
No Matches
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
667 public function getCooldownTag() : ?string{
668 return null;
669 }
670
677 final public function equals(Item $item, bool $checkDamage = true, bool $checkCompound = true) : bool{
678 return $this->getStateId() === $item->getStateId() &&
679 (!$checkCompound || $this->getNamedTag()->equals($item->getNamedTag()));
680 }
681
685 final public function canStackWith(Item $other) : bool{
686 return $this->equals($other, true, true);
687 }
688
692 final public function equalsExact(Item $other) : bool{
693 return $this->canStackWith($other) && $this->count === $other->count;
694 }
695
696 final public function __toString() : string{
697 return "Item " . $this->name . " (" . $this->getTypeId() . ":" . $this->computeStateData() . ")x" . $this->count . ($this->hasNamedTag() ? " tags:0x" . base64_encode((new LittleEndianNbtSerializer())->write(new TreeRoot($this->getNamedTag()))) : "");
698 }
699
703 public function jsonSerialize() : array{
704 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.");
705 }
706
715 final public static function legacyJsonDeserialize(array $data) : Item{
716 $nbt = "";
717
718 //Backwards compatibility
719 if(isset($data["nbt"])){
720 $nbt = $data["nbt"];
721 }elseif(isset($data["nbt_hex"])){
722 $nbt = hex2bin($data["nbt_hex"]);
723 }elseif(isset($data["nbt_b64"])){
724 $nbt = base64_decode($data["nbt_b64"], true);
725 }
726
727 $itemStackData = GlobalItemDataHandlers::getUpgrader()->upgradeItemTypeDataInt(
728 (int) $data["id"],
729 (int) ($data["damage"] ?? 0),
730 (int) ($data["count"] ?? 1),
731 $nbt !== "" ? (new LittleEndianNbtSerializer())->read($nbt)->mustGetCompoundTag() : null
732 );
733
734 try{
735 return GlobalItemDataHandlers::getDeserializer()->deserializeStack($itemStackData);
736 }catch(ItemTypeDeserializeException $e){
737 throw new SavedDataLoadingException($e->getMessage(), 0, $e);
738 }
739 }
740
746 public function nbtSerialize(int $slot = -1) : CompoundTag{
747 return GlobalItemDataHandlers::getSerializer()->serializeStack($this, $slot !== -1 ? $slot : null)->toNbt();
748 }
749
754 public static function nbtDeserialize(CompoundTag $tag) : Item{
755 $itemData = GlobalItemDataHandlers::getUpgrader()->upgradeItemStackNbt($tag);
756 if($itemData === null){
757 return VanillaItems::AIR();
758 }
759
760 try{
761 return GlobalItemDataHandlers::getDeserializer()->deserializeStack($itemData);
762 }catch(ItemTypeDeserializeException $e){
763 throw new SavedDataLoadingException($e->getMessage(), 0, $e);
764 }
765 }
766
767 public function __clone(){
768 $this->nbt = clone $this->nbt;
769 if($this->blockEntityTag !== null){
770 $this->blockEntityTag = clone $this->blockEntityTag;
771 }
772 }
773}
static legacyJsonDeserialize(array $data)
Definition Item.php:715
getBlock(?int $clickedFace=null)
Definition Item.php:491
describeState(RuntimeDataDescriber $w)
Definition Item.php:513
nbtSerialize(int $slot=-1)
Definition Item.php:746
onAttackEntity(Entity $victim, array &$returnedItems)
Definition Item.php:628
setCustomBlockData(CompoundTag $compound)
Definition Item.php:136
canStackWith(Item $other)
Definition Item.php:685
equals(Item $item, bool $checkDamage=true, bool $checkCompound=true)
Definition Item.php:677
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:754
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:692
onInteractEntity(Player $player, Entity $entity, Vector3 $clickVector)
Definition Item.php:646