3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "inventory.h"
21 #include "serialization.h"
26 #include "util/strfnd.h"
27 #include "content_mapnode.h" // For loading legacy MaterialItems
28 #include "nameidmapping.h" // For loading legacy MaterialItems
29 #include "util/serialize.h"
30 #include "util/string.h"
36 static content_t content_translate_from_19_to_internal(content_t c_from)
38 for (const auto &tt : trans_table_19) {
46 ItemStack::ItemStack(const std::string &name_, u16 count_,
47 u16 wear_, IItemDefManager *itemdef) :
48 name(itemdef->getAlias(name_)),
52 if (name.empty() || count == 0)
54 else if (itemdef->get(name).type == ITEM_TOOL)
58 void ItemStack::serialize(std::ostream &os) const
63 // Check how many parts of the itemstring are needed
69 if (!metadata.empty())
72 os<<serializeJsonStringIfNeeded(name);
79 metadata.serialize(os);
83 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
88 name = deSerializeJsonStringIfNeeded(is);
92 std::getline(is, tmp, ' ');
94 throw SerializationError("Unexpected text after item name");
96 if(name == "MaterialItem")
98 // Obsoleted on 2011-07-30
104 // Convert old materials
106 material = content_translate_from_19_to_internal(material);
108 throw SerializationError("Too large material number");
109 // Convert old id to name
110 NameIdMapping legacy_nimap;
111 content_mapnode_get_name_id_mapping(&legacy_nimap);
112 legacy_nimap.getName(material, name);
114 name = "unknown_block";
116 name = itemdef->getAlias(name);
117 count = materialcount;
119 else if(name == "MaterialItem2")
121 // Obsoleted on 2011-11-16
128 throw SerializationError("Too large material number");
129 // Convert old id to name
130 NameIdMapping legacy_nimap;
131 content_mapnode_get_name_id_mapping(&legacy_nimap);
132 legacy_nimap.getName(material, name);
134 name = "unknown_block";
136 name = itemdef->getAlias(name);
137 count = materialcount;
139 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
140 || name == "craft" || name == "CraftItem")
142 // Obsoleted on 2012-01-07
145 std::getline(is, all, '\n');
146 // First attempt to read inside ""
149 // If didn't skip to end, we have ""s
151 name = fnd.next("\"");
152 } else { // No luck, just read a word then
154 name = fnd.next(" ");
158 name = itemdef->getAlias(name);
159 count = stoi(trim(fnd.next("")));
163 else if(name == "MBOItem")
165 // Obsoleted on 2011-10-14
166 throw SerializationError("MBOItem not supported anymore");
168 else if(name == "tool" || name == "ToolItem")
170 // Obsoleted on 2012-01-07
173 std::getline(is, all, '\n');
174 // First attempt to read inside ""
177 // If didn't skip to end, we have ""s
179 name = fnd.next("\"");
180 } else { // No luck, just read a word then
182 name = fnd.next(" ");
188 name = itemdef->getAlias(name);
189 wear = stoi(trim(fnd.next("")));
193 do // This loop is just to allow "break;"
197 // Apply item aliases
199 name = itemdef->getAlias(name);
202 std::string count_str;
203 std::getline(is, count_str, ' ');
204 if (count_str.empty()) {
209 count = stoi(count_str);
212 std::string wear_str;
213 std::getline(is, wear_str, ' ');
217 wear = stoi(wear_str);
220 metadata.deSerialize(is);
222 // In case fields are added after metadata, skip space here:
223 //std::getline(is, tmp, ' ');
225 // throw SerializationError("Unexpected text after metadata");
230 if (name.empty() || count == 0)
232 else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
236 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
238 std::istringstream is(str, std::ios::binary);
239 deSerialize(is, itemdef);
242 std::string ItemStack::getItemString() const
244 std::ostringstream os(std::ios::binary);
250 ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
252 // If the item is empty or the position invalid, bail out
255 // nothing can be added trivially
257 // If this is an empty item, it's an easy job.
260 const u16 stackMax = newitem.getStackMax(itemdef);
264 // If the item fits fully, delete it
265 if (count <= stackMax) {
267 } else { // Else the item does not fit fully. Return the rest.
269 newitem.remove(count);
272 // If item name or metadata differs, bail out
273 else if (name != newitem.name
274 || metadata != newitem.metadata)
278 // If the item fits fully, add counter and delete it
279 else if(newitem.count <= freeSpace(itemdef))
284 // Else the item does not fit fully. Add all that fits and return
288 u16 freespace = freeSpace(itemdef);
290 newitem.remove(freespace);
296 bool ItemStack::itemFits(ItemStack newitem,
298 IItemDefManager *itemdef) const
301 // If the item is empty or the position invalid, bail out
304 // nothing can be added trivially
306 // If this is an empty item, it's an easy job.
309 const u16 stackMax = newitem.getStackMax(itemdef);
311 // If the item fits fully, delete it
312 if (newitem.count <= stackMax) {
314 } else { // Else the item does not fit fully. Return the rest.
315 newitem.remove(stackMax);
318 // If item name or metadata differs, bail out
319 else if (name != newitem.name
320 || metadata != newitem.metadata)
324 // If the item fits fully, delete it
325 else if(newitem.count <= freeSpace(itemdef))
329 // Else the item does not fit fully. Return the rest.
332 u16 freespace = freeSpace(itemdef);
333 newitem.remove(freespace);
338 return newitem.empty();
341 ItemStack ItemStack::takeItem(u32 takecount)
343 if(takecount == 0 || count == 0)
346 ItemStack result = *this;
347 if(takecount >= count)
356 result.count = takecount;
361 ItemStack ItemStack::peekItem(u32 peekcount) const
363 if(peekcount == 0 || count == 0)
366 ItemStack result = *this;
367 if(peekcount < count)
368 result.count = peekcount;
376 InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
384 void InventoryList::clearItems()
388 for (u32 i=0; i < m_size; i++) {
389 m_items.emplace_back();
395 void InventoryList::setSize(u32 newsize)
397 if(newsize != m_items.size())
398 m_items.resize(newsize);
402 void InventoryList::setWidth(u32 newwidth)
407 void InventoryList::setName(const std::string &name)
412 void InventoryList::serialize(std::ostream &os) const
414 //os.imbue(std::locale("C"));
416 os<<"Width "<<m_width<<"\n";
418 for (const auto &item : m_items) {
428 os<<"EndInventoryList\n";
431 void InventoryList::deSerialize(std::istream &is)
433 //is.imbue(std::locale("C"));
442 std::getline(is, line, '\n');
444 std::istringstream iss(line);
445 //iss.imbue(std::locale("C"));
448 std::getline(iss, name, ' ');
450 if (name == "EndInventoryList") {
454 // This is a temporary backwards compatibility fix
459 if (name == "Width") {
462 throw SerializationError("incorrect width property");
464 else if(name == "Item")
466 if(item_i > getSize() - 1)
467 throw SerializationError("too many items");
469 item.deSerialize(iss, m_itemdef);
470 m_items[item_i++] = item;
472 else if(name == "Empty")
474 if(item_i > getSize() - 1)
475 throw SerializationError("too many items");
476 m_items[item_i++].clear();
481 InventoryList::InventoryList(const InventoryList &other)
486 InventoryList & InventoryList::operator = (const InventoryList &other)
488 m_items = other.m_items;
489 m_size = other.m_size;
490 m_width = other.m_width;
491 m_name = other.m_name;
492 m_itemdef = other.m_itemdef;
498 bool InventoryList::operator == (const InventoryList &other) const
500 if(m_size != other.m_size)
502 if(m_width != other.m_width)
504 if(m_name != other.m_name)
506 for(u32 i=0; i<m_items.size(); i++)
508 ItemStack s1 = m_items[i];
509 ItemStack s2 = other.m_items[i];
510 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
511 s1.metadata != s2.metadata)
518 const std::string &InventoryList::getName() const
523 u32 InventoryList::getSize() const
525 return m_items.size();
528 u32 InventoryList::getWidth() const
533 u32 InventoryList::getUsedSlots() const
536 for (const auto &m_item : m_items) {
543 u32 InventoryList::getFreeSlots() const
545 return getSize() - getUsedSlots();
548 const ItemStack& InventoryList::getItem(u32 i) const
550 assert(i < m_size); // Pre-condition
554 ItemStack& InventoryList::getItem(u32 i)
556 assert(i < m_size); // Pre-condition
560 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
562 if(i >= m_items.size())
565 ItemStack olditem = m_items[i];
566 m_items[i] = newitem;
571 void InventoryList::deleteItem(u32 i)
573 assert(i < m_items.size()); // Pre-condition
577 ItemStack InventoryList::addItem(const ItemStack &newitem_)
579 ItemStack newitem = newitem_;
585 First try to find if it could be added to some existing items
587 for(u32 i=0; i<m_items.size(); i++)
589 // Ignore empty slots
590 if(m_items[i].empty())
593 newitem = addItem(i, newitem);
595 return newitem; // All was eaten
599 Then try to add it to empty slots
601 for(u32 i=0; i<m_items.size(); i++)
603 // Ignore unempty slots
604 if(!m_items[i].empty())
607 newitem = addItem(i, newitem);
609 return newitem; // All was eaten
616 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
618 if(i >= m_items.size())
621 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
622 //if(leftover != newitem)
627 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
628 ItemStack *restitem) const
630 if(i >= m_items.size())
637 return m_items[i].itemFits(newitem, restitem, m_itemdef);
640 bool InventoryList::roomForItem(const ItemStack &item_) const
642 ItemStack item = item_;
644 for(u32 i=0; i<m_items.size(); i++)
646 if(itemFits(i, item, &leftover))
653 bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
655 u32 count = item.count;
659 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
662 if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
663 if (i->count >= count)
672 ItemStack InventoryList::removeItem(const ItemStack &item)
675 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
676 if (i->name == item.name) {
677 u32 still_to_remove = item.count - removed.count;
678 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
679 if (removed.count == item.count)
686 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
688 if(i >= m_items.size())
691 ItemStack taken = m_items[i].takeItem(takecount);
697 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
699 // Take item from source list
702 item1 = changeItem(i, ItemStack());
704 item1 = takeItem(i, count);
709 // Try to add the item to destination list
710 u32 dest_size = dest->getSize();
711 // First try all the non-empty slots
712 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
713 if (!m_items[dest_i].empty()) {
714 item1 = dest->addItem(dest_i, item1);
715 if (item1.empty()) return;
719 // Then try all the empty ones
720 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
721 if (m_items[dest_i].empty()) {
722 item1 = dest->addItem(dest_i, item1);
723 if (item1.empty()) return;
727 // If we reach this, the item was not fully added
728 // Add the remaining part back to the source item
732 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
733 u32 count, bool swap_if_needed, bool *did_swap)
735 if(this == dest && i == dest_i)
738 // Take item from source list
741 item1 = changeItem(i, ItemStack());
743 item1 = takeItem(i, count);
748 // Try to add the item to destination list
749 u32 oldcount = item1.count;
750 item1 = dest->addItem(dest_i, item1);
752 // If something is returned, the item was not fully added
755 // If olditem is returned, nothing was added.
756 bool nothing_added = (item1.count == oldcount);
758 // If something else is returned, part of the item was left unadded.
759 // Add the other part back to the source item
762 // If olditem is returned, nothing was added.
764 if (nothing_added && swap_if_needed) {
765 // Tell that we swapped
766 if (did_swap != NULL) {
769 // Take item from source list
770 item1 = changeItem(i, ItemStack());
771 // Adding was not possible, swap the items.
772 ItemStack item2 = dest->changeItem(dest_i, item1);
773 // Put item from destination list to the source list
774 changeItem(i, item2);
777 return (oldcount - item1.count);
784 Inventory::~Inventory()
789 void Inventory::clear()
792 for (auto &m_list : m_lists) {
798 void Inventory::clearContents()
801 for (InventoryList *list : m_lists) {
802 for (u32 j=0; j<list->getSize(); j++) {
808 Inventory::Inventory(IItemDefManager *itemdef)
814 Inventory::Inventory(const Inventory &other)
820 Inventory & Inventory::operator = (const Inventory &other)
822 // Gracefully handle self assignment
827 m_itemdef = other.m_itemdef;
828 for (InventoryList *list : other.m_lists) {
829 m_lists.push_back(new InventoryList(*list));
835 bool Inventory::operator == (const Inventory &other) const
837 if(m_lists.size() != other.m_lists.size())
840 for(u32 i=0; i<m_lists.size(); i++)
842 if(*m_lists[i] != *other.m_lists[i])
848 void Inventory::serialize(std::ostream &os) const
850 for (InventoryList *list : m_lists) {
851 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
855 os<<"EndInventory\n";
858 void Inventory::deSerialize(std::istream &is)
865 std::getline(is, line, '\n');
867 std::istringstream iss(line);
870 std::getline(iss, name, ' ');
872 if (name == "EndInventory") {
876 // This is a temporary backwards compatibility fix
881 if (name == "List") {
882 std::string listname;
885 std::getline(iss, listname, ' ');
888 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
889 list->deSerialize(is);
891 m_lists.push_back(list);
895 throw SerializationError("invalid inventory specifier: " + name);
900 InventoryList * Inventory::addList(const std::string &name, u32 size)
903 s32 i = getListIndex(name);
906 if(m_lists[i]->getSize() != size)
909 m_lists[i] = new InventoryList(name, size, m_itemdef);
915 //don't create list with invalid name
916 if (name.find(' ') != std::string::npos) return NULL;
918 InventoryList *list = new InventoryList(name, size, m_itemdef);
919 m_lists.push_back(list);
923 InventoryList * Inventory::getList(const std::string &name)
925 s32 i = getListIndex(name);
931 std::vector<const InventoryList*> Inventory::getLists()
933 std::vector<const InventoryList*> lists;
934 for (auto list : m_lists) {
935 lists.push_back(list);
940 bool Inventory::deleteList(const std::string &name)
942 s32 i = getListIndex(name);
947 m_lists.erase(m_lists.begin() + i);
951 const InventoryList * Inventory::getList(const std::string &name) const
953 s32 i = getListIndex(name);
959 const s32 Inventory::getListIndex(const std::string &name) const
961 for(u32 i=0; i<m_lists.size(); i++)
963 if(m_lists[i]->getName() == name)