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"
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(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
40 if(trans_table_19[i][1] == c_from)
42 return trans_table_19[i][0];
48 // If the string contains spaces, quotes or control characters, encodes as JSON.
49 // Else returns the string unmodified.
50 static std::string serializeJsonStringIfNeeded(const std::string &s)
52 for(size_t i = 0; i < s.size(); ++i)
54 if(s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
55 return serializeJsonString(s);
60 // Parses a string serialized by serializeJsonStringIfNeeded.
61 static std::string deSerializeJsonStringIfNeeded(std::istream &is)
63 std::ostringstream tmp_os;
64 bool expect_initial_quote = true;
66 bool was_backslash = false;
72 if(expect_initial_quote && c == '"')
81 was_backslash = false;
85 break; // Found end of string
100 expect_initial_quote = false;
104 std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
105 return deSerializeJsonString(tmp_is);
112 ItemStack::ItemStack(std::string name_, u16 count_,
113 u16 wear_, std::string metadata_,
114 IItemDefManager *itemdef)
116 name = itemdef->getAlias(name_);
119 metadata = metadata_;
121 if(name.empty() || count == 0)
123 else if(itemdef->get(name).type == ITEM_TOOL)
127 void ItemStack::serialize(std::ostream &os) const
129 DSTACK(__FUNCTION_NAME);
134 // Check how many parts of the itemstring are needed
143 os<<serializeJsonStringIfNeeded(name);
149 os<<" "<<serializeJsonStringIfNeeded(metadata);
152 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
154 DSTACK(__FUNCTION_NAME);
159 name = deSerializeJsonStringIfNeeded(is);
163 std::getline(is, tmp, ' ');
165 throw SerializationError("Unexpected text after item name");
167 if(name == "MaterialItem")
169 // Obsoleted on 2011-07-30
175 // Convert old materials
177 material = content_translate_from_19_to_internal(material);
179 throw SerializationError("Too large material number");
180 // Convert old id to name
181 NameIdMapping legacy_nimap;
182 content_mapnode_get_name_id_mapping(&legacy_nimap);
183 legacy_nimap.getName(material, name);
185 name = "unknown_block";
187 name = itemdef->getAlias(name);
188 count = materialcount;
190 else if(name == "MaterialItem2")
192 // Obsoleted on 2011-11-16
199 throw SerializationError("Too large material number");
200 // Convert old id to name
201 NameIdMapping legacy_nimap;
202 content_mapnode_get_name_id_mapping(&legacy_nimap);
203 legacy_nimap.getName(material, name);
205 name = "unknown_block";
207 name = itemdef->getAlias(name);
208 count = materialcount;
210 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
211 || name == "craft" || name == "CraftItem")
213 // Obsoleted on 2012-01-07
216 std::getline(is, all, '\n');
217 // First attempt to read inside ""
220 // If didn't skip to end, we have ""s
222 name = fnd.next("\"");
223 } else { // No luck, just read a word then
225 name = fnd.next(" ");
229 name = itemdef->getAlias(name);
230 count = stoi(trim(fnd.next("")));
234 else if(name == "MBOItem")
236 // Obsoleted on 2011-10-14
237 throw SerializationError("MBOItem not supported anymore");
239 else if(name == "tool" || name == "ToolItem")
241 // Obsoleted on 2012-01-07
244 std::getline(is, all, '\n');
245 // First attempt to read inside ""
248 // If didn't skip to end, we have ""s
250 name = fnd.next("\"");
251 } else { // No luck, just read a word then
253 name = fnd.next(" ");
259 name = itemdef->getAlias(name);
260 wear = stoi(trim(fnd.next("")));
264 do // This loop is just to allow "break;"
268 // Apply item aliases
270 name = itemdef->getAlias(name);
273 std::string count_str;
274 std::getline(is, count_str, ' ');
275 if(count_str.empty())
281 count = stoi(count_str);
284 std::string wear_str;
285 std::getline(is, wear_str, ' ');
289 wear = stoi(wear_str);
292 metadata = deSerializeJsonStringIfNeeded(is);
294 // In case fields are added after metadata, skip space here:
295 //std::getline(is, tmp, ' ');
297 // throw SerializationError("Unexpected text after metadata");
302 if (name.empty() || count == 0)
304 else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
308 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
310 std::istringstream is(str, std::ios::binary);
311 deSerialize(is, itemdef);
314 std::string ItemStack::getItemString() const
316 std::ostringstream os(std::ios::binary);
322 ItemStack ItemStack::addItem(const ItemStack &newitem_,
323 IItemDefManager *itemdef)
325 ItemStack newitem = newitem_;
327 // If the item is empty or the position invalid, bail out
330 // nothing can be added trivially
332 // If this is an empty item, it's an easy job.
338 // If item name differs, bail out
339 else if(name != newitem.name)
343 // If the item fits fully, add counter and delete it
344 else if(newitem.count <= freeSpace(itemdef))
349 // Else the item does not fit fully. Add all that fits and return
353 u16 freespace = freeSpace(itemdef);
355 newitem.remove(freespace);
361 bool ItemStack::itemFits(const ItemStack &newitem_,
363 IItemDefManager *itemdef) const
365 ItemStack newitem = newitem_;
367 // If the item is empty or the position invalid, bail out
370 // nothing can be added trivially
372 // If this is an empty item, it's an easy job.
377 // If item name differs, bail out
378 else if(name != newitem.name)
382 // If the item fits fully, delete it
383 else if(newitem.count <= freeSpace(itemdef))
387 // Else the item does not fit fully. Return the rest.
391 u16 freespace = freeSpace(itemdef);
392 newitem.remove(freespace);
397 return newitem.empty();
400 ItemStack ItemStack::takeItem(u32 takecount)
402 if(takecount == 0 || count == 0)
405 ItemStack result = *this;
406 if(takecount >= count)
415 result.count = takecount;
420 ItemStack ItemStack::peekItem(u32 peekcount) const
422 if(peekcount == 0 || count == 0)
425 ItemStack result = *this;
426 if(peekcount < count)
427 result.count = peekcount;
435 InventoryList::InventoryList(std::string name, u32 size, IItemDefManager *itemdef)
445 InventoryList::~InventoryList()
449 void InventoryList::clearItems()
453 for(u32 i=0; i<m_size; i++)
455 m_items.push_back(ItemStack());
461 void InventoryList::setSize(u32 newsize)
463 if(newsize != m_items.size())
464 m_items.resize(newsize);
468 void InventoryList::setWidth(u32 newwidth)
473 void InventoryList::setName(const std::string &name)
478 void InventoryList::serialize(std::ostream &os) const
480 //os.imbue(std::locale("C"));
482 os<<"Width "<<m_width<<"\n";
484 for(u32 i=0; i<m_items.size(); i++)
486 const ItemStack &item = m_items[i];
499 os<<"EndInventoryList\n";
502 void InventoryList::deSerialize(std::istream &is)
504 //is.imbue(std::locale("C"));
513 std::getline(is, line, '\n');
515 std::istringstream iss(line);
516 //iss.imbue(std::locale("C"));
519 std::getline(iss, name, ' ');
521 if(name == "EndInventoryList")
525 // This is a temporary backwards compatibility fix
526 else if(name == "end")
530 else if(name == "Width")
534 throw SerializationError("incorrect width property");
536 else if(name == "Item")
538 if(item_i > getSize() - 1)
539 throw SerializationError("too many items");
541 item.deSerialize(iss, m_itemdef);
542 m_items[item_i++] = item;
544 else if(name == "Empty")
546 if(item_i > getSize() - 1)
547 throw SerializationError("too many items");
548 m_items[item_i++].clear();
553 InventoryList::InventoryList(const InventoryList &other)
558 InventoryList & InventoryList::operator = (const InventoryList &other)
560 m_items = other.m_items;
561 m_size = other.m_size;
562 m_width = other.m_width;
563 m_name = other.m_name;
564 m_itemdef = other.m_itemdef;
570 bool InventoryList::operator == (const InventoryList &other) const
572 if(m_size != other.m_size)
574 if(m_width != other.m_width)
576 if(m_name != other.m_name)
578 for(u32 i=0; i<m_items.size(); i++)
580 ItemStack s1 = m_items[i];
581 ItemStack s2 = other.m_items[i];
582 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
583 s1.metadata != s2.metadata)
590 const std::string &InventoryList::getName() const
595 u32 InventoryList::getSize() const
597 return m_items.size();
600 u32 InventoryList::getWidth() const
605 u32 InventoryList::getUsedSlots() const
608 for(u32 i=0; i<m_items.size(); i++)
610 if(!m_items[i].empty())
616 u32 InventoryList::getFreeSlots() const
618 return getSize() - getUsedSlots();
621 const ItemStack& InventoryList::getItem(u32 i) const
623 assert(i < m_size); // Pre-condition
627 ItemStack& InventoryList::getItem(u32 i)
629 assert(i < m_size); // Pre-condition
633 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
635 if(i >= m_items.size())
638 ItemStack olditem = m_items[i];
639 m_items[i] = newitem;
644 void InventoryList::deleteItem(u32 i)
646 assert(i < m_items.size()); // Pre-condition
650 ItemStack InventoryList::addItem(const ItemStack &newitem_)
652 ItemStack newitem = newitem_;
658 First try to find if it could be added to some existing items
660 for(u32 i=0; i<m_items.size(); i++)
662 // Ignore empty slots
663 if(m_items[i].empty())
666 newitem = addItem(i, newitem);
668 return newitem; // All was eaten
672 Then try to add it to empty slots
674 for(u32 i=0; i<m_items.size(); i++)
676 // Ignore unempty slots
677 if(!m_items[i].empty())
680 newitem = addItem(i, newitem);
682 return newitem; // All was eaten
689 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
691 if(i >= m_items.size())
694 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
695 //if(leftover != newitem)
700 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
701 ItemStack *restitem) const
703 if(i >= m_items.size())
710 return m_items[i].itemFits(newitem, restitem, m_itemdef);
713 bool InventoryList::roomForItem(const ItemStack &item_) const
715 ItemStack item = item_;
717 for(u32 i=0; i<m_items.size(); i++)
719 if(itemFits(i, item, &leftover))
726 bool InventoryList::containsItem(const ItemStack &item) const
728 u32 count = item.count;
731 for(std::vector<ItemStack>::const_reverse_iterator
732 i = m_items.rbegin();
733 i != m_items.rend(); i++)
737 if(i->name == item.name)
739 if(i->count >= count)
748 ItemStack InventoryList::removeItem(const ItemStack &item)
751 for(std::vector<ItemStack>::reverse_iterator
752 i = m_items.rbegin();
753 i != m_items.rend(); i++)
755 if(i->name == item.name)
757 u32 still_to_remove = item.count - removed.count;
758 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
759 if(removed.count == item.count)
766 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
768 if(i >= m_items.size())
771 ItemStack taken = m_items[i].takeItem(takecount);
777 ItemStack InventoryList::peekItem(u32 i, u32 peekcount) const
779 if(i >= m_items.size())
782 return m_items[i].peekItem(peekcount);
785 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
787 // Take item from source list
790 item1 = changeItem(i, ItemStack());
792 item1 = takeItem(i, count);
797 // Try to add the item to destination list
798 u32 dest_size = dest->getSize();
799 // First try all the non-empty slots
800 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
801 if (!m_items[dest_i].empty()) {
802 item1 = dest->addItem(dest_i, item1);
803 if (item1.empty()) return;
807 // Then try all the empty ones
808 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
809 if (m_items[dest_i].empty()) {
810 item1 = dest->addItem(dest_i, item1);
811 if (item1.empty()) return;
815 // If we reach this, the item was not fully added
816 // Add the remaining part back to the source item
820 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
821 u32 count, bool swap_if_needed)
823 if(this == dest && i == dest_i)
826 // Take item from source list
829 item1 = changeItem(i, ItemStack());
831 item1 = takeItem(i, count);
836 // Try to add the item to destination list
837 u32 oldcount = item1.count;
838 item1 = dest->addItem(dest_i, item1);
840 // If something is returned, the item was not fully added
843 // If olditem is returned, nothing was added.
844 bool nothing_added = (item1.count == oldcount);
846 // If something else is returned, part of the item was left unadded.
847 // Add the other part back to the source item
850 // If olditem is returned, nothing was added.
852 if (nothing_added && swap_if_needed) {
853 // Take item from source list
854 item1 = changeItem(i, ItemStack());
855 // Adding was not possible, swap the items.
856 ItemStack item2 = dest->changeItem(dest_i, item1);
857 // Put item from destination list to the source list
858 changeItem(i, item2);
861 return (oldcount - item1.count);
868 Inventory::~Inventory()
873 void Inventory::clear()
876 for(u32 i=0; i<m_lists.size(); i++)
883 void Inventory::clearContents()
886 for(u32 i=0; i<m_lists.size(); i++)
888 InventoryList *list = m_lists[i];
889 for(u32 j=0; j<list->getSize(); j++)
896 Inventory::Inventory(IItemDefManager *itemdef)
902 Inventory::Inventory(const Inventory &other)
908 Inventory & Inventory::operator = (const Inventory &other)
910 // Gracefully handle self assignment
915 m_itemdef = other.m_itemdef;
916 for(u32 i=0; i<other.m_lists.size(); i++)
918 m_lists.push_back(new InventoryList(*other.m_lists[i]));
924 bool Inventory::operator == (const Inventory &other) const
926 if(m_lists.size() != other.m_lists.size())
929 for(u32 i=0; i<m_lists.size(); i++)
931 if(*m_lists[i] != *other.m_lists[i])
937 void Inventory::serialize(std::ostream &os) const
939 for(u32 i=0; i<m_lists.size(); i++)
941 InventoryList *list = m_lists[i];
942 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
946 os<<"EndInventory\n";
949 void Inventory::deSerialize(std::istream &is)
956 std::getline(is, line, '\n');
958 std::istringstream iss(line);
961 std::getline(iss, name, ' ');
963 if(name == "EndInventory")
967 // This is a temporary backwards compatibility fix
968 else if(name == "end")
972 else if(name == "List")
974 std::string listname;
977 std::getline(iss, listname, ' ');
980 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
981 list->deSerialize(is);
983 m_lists.push_back(list);
987 throw SerializationError("invalid inventory specifier: " + name);
992 InventoryList * Inventory::addList(const std::string &name, u32 size)
995 s32 i = getListIndex(name);
998 if(m_lists[i]->getSize() != size)
1001 m_lists[i] = new InventoryList(name, size, m_itemdef);
1007 //don't create list with invalid name
1008 if (name.find(" ") != std::string::npos) return NULL;
1010 InventoryList *list = new InventoryList(name, size, m_itemdef);
1011 m_lists.push_back(list);
1016 InventoryList * Inventory::getList(const std::string &name)
1018 s32 i = getListIndex(name);
1024 std::vector<const InventoryList*> Inventory::getLists()
1026 std::vector<const InventoryList*> lists;
1027 for(u32 i=0; i<m_lists.size(); i++)
1029 InventoryList *list = m_lists[i];
1030 lists.push_back(list);
1035 bool Inventory::deleteList(const std::string &name)
1037 s32 i = getListIndex(name);
1042 m_lists.erase(m_lists.begin() + i);
1046 const InventoryList * Inventory::getList(const std::string &name) const
1048 s32 i = getListIndex(name);
1054 const s32 Inventory::getListIndex(const std::string &name) const
1056 for(u32 i=0; i<m_lists.size(); i++)
1058 if(m_lists[i]->getName() == name)