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"));
441 std::getline(is, line, '\n');
443 std::istringstream iss(line);
444 //iss.imbue(std::locale("C"));
447 std::getline(iss, name, ' ');
449 if (name == "EndInventoryList")
452 // This is a temporary backwards compatibility fix
456 if (name == "Width") {
459 throw SerializationError("incorrect width property");
461 else if(name == "Item")
463 if(item_i > getSize() - 1)
464 throw SerializationError("too many items");
466 item.deSerialize(iss, m_itemdef);
467 m_items[item_i++] = item;
469 else if(name == "Empty")
471 if(item_i > getSize() - 1)
472 throw SerializationError("too many items");
473 m_items[item_i++].clear();
477 // Contents given to deSerialize() were not terminated properly: throw error.
479 std::ostringstream ss;
480 ss << "Malformatted inventory list. list="
481 << m_name << ", read " << item_i << " of " << getSize()
482 << " ItemStacks." << std::endl;
483 throw SerializationError(ss.str());
486 InventoryList::InventoryList(const InventoryList &other)
491 InventoryList & InventoryList::operator = (const InventoryList &other)
493 m_items = other.m_items;
494 m_size = other.m_size;
495 m_width = other.m_width;
496 m_name = other.m_name;
497 m_itemdef = other.m_itemdef;
503 bool InventoryList::operator == (const InventoryList &other) const
505 if(m_size != other.m_size)
507 if(m_width != other.m_width)
509 if(m_name != other.m_name)
511 for(u32 i=0; i<m_items.size(); i++)
513 ItemStack s1 = m_items[i];
514 ItemStack s2 = other.m_items[i];
515 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
516 s1.metadata != s2.metadata)
523 const std::string &InventoryList::getName() const
528 u32 InventoryList::getSize() const
530 return m_items.size();
533 u32 InventoryList::getWidth() const
538 u32 InventoryList::getUsedSlots() const
541 for (const auto &m_item : m_items) {
548 u32 InventoryList::getFreeSlots() const
550 return getSize() - getUsedSlots();
553 const ItemStack& InventoryList::getItem(u32 i) const
555 assert(i < m_size); // Pre-condition
559 ItemStack& InventoryList::getItem(u32 i)
561 assert(i < m_size); // Pre-condition
565 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
567 if(i >= m_items.size())
570 ItemStack olditem = m_items[i];
571 m_items[i] = newitem;
576 void InventoryList::deleteItem(u32 i)
578 assert(i < m_items.size()); // Pre-condition
582 ItemStack InventoryList::addItem(const ItemStack &newitem_)
584 ItemStack newitem = newitem_;
590 First try to find if it could be added to some existing items
592 for(u32 i=0; i<m_items.size(); i++)
594 // Ignore empty slots
595 if(m_items[i].empty())
598 newitem = addItem(i, newitem);
600 return newitem; // All was eaten
604 Then try to add it to empty slots
606 for(u32 i=0; i<m_items.size(); i++)
608 // Ignore unempty slots
609 if(!m_items[i].empty())
612 newitem = addItem(i, newitem);
614 return newitem; // All was eaten
621 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
623 if(i >= m_items.size())
626 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
627 //if(leftover != newitem)
632 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
633 ItemStack *restitem) const
635 if(i >= m_items.size())
642 return m_items[i].itemFits(newitem, restitem, m_itemdef);
645 bool InventoryList::roomForItem(const ItemStack &item_) const
647 ItemStack item = item_;
649 for(u32 i=0; i<m_items.size(); i++)
651 if(itemFits(i, item, &leftover))
658 bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
660 u32 count = item.count;
664 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
667 if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
668 if (i->count >= count)
677 ItemStack InventoryList::removeItem(const ItemStack &item)
680 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
681 if (i->name == item.name) {
682 u32 still_to_remove = item.count - removed.count;
683 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
684 if (removed.count == item.count)
691 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
693 if(i >= m_items.size())
696 ItemStack taken = m_items[i].takeItem(takecount);
702 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
704 // Take item from source list
707 item1 = changeItem(i, ItemStack());
709 item1 = takeItem(i, count);
714 // Try to add the item to destination list
715 u32 dest_size = dest->getSize();
716 // First try all the non-empty slots
717 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
718 if (!m_items[dest_i].empty()) {
719 item1 = dest->addItem(dest_i, item1);
720 if (item1.empty()) return;
724 // Then try all the empty ones
725 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
726 if (m_items[dest_i].empty()) {
727 item1 = dest->addItem(dest_i, item1);
728 if (item1.empty()) return;
732 // If we reach this, the item was not fully added
733 // Add the remaining part back to the source item
737 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
738 u32 count, bool swap_if_needed, bool *did_swap)
740 if(this == dest && i == dest_i)
743 // Take item from source list
746 item1 = changeItem(i, ItemStack());
748 item1 = takeItem(i, count);
753 // Try to add the item to destination list
754 u32 oldcount = item1.count;
755 item1 = dest->addItem(dest_i, item1);
757 // If something is returned, the item was not fully added
760 // If olditem is returned, nothing was added.
761 bool nothing_added = (item1.count == oldcount);
763 // If something else is returned, part of the item was left unadded.
764 // Add the other part back to the source item
767 // If olditem is returned, nothing was added.
769 if (nothing_added && swap_if_needed) {
770 // Tell that we swapped
771 if (did_swap != NULL) {
774 // Take item from source list
775 item1 = changeItem(i, ItemStack());
776 // Adding was not possible, swap the items.
777 ItemStack item2 = dest->changeItem(dest_i, item1);
778 // Put item from destination list to the source list
779 changeItem(i, item2);
782 return (oldcount - item1.count);
789 Inventory::~Inventory()
794 void Inventory::clear()
797 for (auto &m_list : m_lists) {
803 void Inventory::clearContents()
806 for (InventoryList *list : m_lists) {
807 for (u32 j=0; j<list->getSize(); j++) {
813 Inventory::Inventory(IItemDefManager *itemdef)
819 Inventory::Inventory(const Inventory &other)
825 Inventory & Inventory::operator = (const Inventory &other)
827 // Gracefully handle self assignment
832 m_itemdef = other.m_itemdef;
833 for (InventoryList *list : other.m_lists) {
834 m_lists.push_back(new InventoryList(*list));
840 bool Inventory::operator == (const Inventory &other) const
842 if(m_lists.size() != other.m_lists.size())
845 for(u32 i=0; i<m_lists.size(); i++)
847 if(*m_lists[i] != *other.m_lists[i])
853 void Inventory::serialize(std::ostream &os) const
855 for (InventoryList *list : m_lists) {
856 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
860 os<<"EndInventory\n";
863 void Inventory::deSerialize(std::istream &is)
869 std::getline(is, line, '\n');
871 std::istringstream iss(line);
874 std::getline(iss, name, ' ');
876 if (name == "EndInventory")
879 // This is a temporary backwards compatibility fix
883 if (name == "List") {
884 std::string listname;
887 std::getline(iss, listname, ' ');
890 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
891 list->deSerialize(is);
893 m_lists.push_back(list);
897 throw SerializationError("invalid inventory specifier: " + name);
901 // Contents given to deSerialize() were not terminated properly: throw error.
903 std::ostringstream ss;
904 ss << "Malformatted inventory (damaged?). "
905 << m_lists.size() << " lists read." << std::endl;
906 throw SerializationError(ss.str());
909 InventoryList * Inventory::addList(const std::string &name, u32 size)
912 s32 i = getListIndex(name);
915 if(m_lists[i]->getSize() != size)
918 m_lists[i] = new InventoryList(name, size, m_itemdef);
924 //don't create list with invalid name
925 if (name.find(' ') != std::string::npos) return NULL;
927 InventoryList *list = new InventoryList(name, size, m_itemdef);
928 m_lists.push_back(list);
932 InventoryList * Inventory::getList(const std::string &name)
934 s32 i = getListIndex(name);
940 std::vector<const InventoryList*> Inventory::getLists()
942 std::vector<const InventoryList*> lists;
943 for (auto list : m_lists) {
944 lists.push_back(list);
949 bool Inventory::deleteList(const std::string &name)
951 s32 i = getListIndex(name);
956 m_lists.erase(m_lists.begin() + i);
960 const InventoryList * Inventory::getList(const std::string &name) const
962 s32 i = getListIndex(name);
968 const s32 Inventory::getListIndex(const std::string &name) const
970 for(u32 i=0; i<m_lists.size(); i++)
972 if(m_lists[i]->getName() == name)