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";
186 name = itemdef->getAlias(name);
187 count = materialcount;
189 else if(name == "MaterialItem2")
191 // Obsoleted on 2011-11-16
198 throw SerializationError("Too large material number");
199 // Convert old id to name
200 NameIdMapping legacy_nimap;
201 content_mapnode_get_name_id_mapping(&legacy_nimap);
202 legacy_nimap.getName(material, name);
204 name = "unknown_block";
205 name = itemdef->getAlias(name);
206 count = materialcount;
208 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
209 || name == "craft" || name == "CraftItem")
211 // Obsoleted on 2012-01-07
214 std::getline(is, all, '\n');
215 // First attempt to read inside ""
218 // If didn't skip to end, we have ""s
220 name = fnd.next("\"");
221 } else { // No luck, just read a word then
223 name = fnd.next(" ");
226 name = itemdef->getAlias(name);
227 count = stoi(trim(fnd.next("")));
231 else if(name == "MBOItem")
233 // Obsoleted on 2011-10-14
234 throw SerializationError("MBOItem not supported anymore");
236 else if(name == "tool" || name == "ToolItem")
238 // Obsoleted on 2012-01-07
241 std::getline(is, all, '\n');
242 // First attempt to read inside ""
245 // If didn't skip to end, we have ""s
247 name = fnd.next("\"");
248 } else { // No luck, just read a word then
250 name = fnd.next(" ");
255 name = itemdef->getAlias(name);
256 wear = stoi(trim(fnd.next("")));
260 do // This loop is just to allow "break;"
264 // Apply item aliases
265 name = itemdef->getAlias(name);
268 std::string count_str;
269 std::getline(is, count_str, ' ');
270 if(count_str.empty())
276 count = stoi(count_str);
279 std::string wear_str;
280 std::getline(is, wear_str, ' ');
284 wear = stoi(wear_str);
287 metadata = deSerializeJsonStringIfNeeded(is);
289 // In case fields are added after metadata, skip space here:
290 //std::getline(is, tmp, ' ');
292 // throw SerializationError("Unexpected text after metadata");
297 if(name.empty() || count == 0)
299 else if(itemdef->get(name).type == ITEM_TOOL)
303 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
305 std::istringstream is(str, std::ios::binary);
306 deSerialize(is, itemdef);
309 std::string ItemStack::getItemString() const
312 std::ostringstream os(std::ios::binary);
317 ItemStack ItemStack::addItem(const ItemStack &newitem_,
318 IItemDefManager *itemdef)
320 ItemStack newitem = newitem_;
322 // If the item is empty or the position invalid, bail out
325 // nothing can be added trivially
327 // If this is an empty item, it's an easy job.
333 // If item name differs, bail out
334 else if(name != newitem.name)
338 // If the item fits fully, add counter and delete it
339 else if(newitem.count <= freeSpace(itemdef))
344 // Else the item does not fit fully. Add all that fits and return
348 u16 freespace = freeSpace(itemdef);
350 newitem.remove(freespace);
356 bool ItemStack::itemFits(const ItemStack &newitem_,
358 IItemDefManager *itemdef) const
360 ItemStack newitem = newitem_;
362 // If the item is empty or the position invalid, bail out
365 // nothing can be added trivially
367 // If this is an empty item, it's an easy job.
372 // If item name differs, bail out
373 else if(name != newitem.name)
377 // If the item fits fully, delete it
378 else if(newitem.count <= freeSpace(itemdef))
382 // Else the item does not fit fully. Return the rest.
386 u16 freespace = freeSpace(itemdef);
387 newitem.remove(freespace);
392 return newitem.empty();
395 ItemStack ItemStack::takeItem(u32 takecount)
397 if(takecount == 0 || count == 0)
400 ItemStack result = *this;
401 if(takecount >= count)
410 result.count = takecount;
415 ItemStack ItemStack::peekItem(u32 peekcount) const
417 if(peekcount == 0 || count == 0)
420 ItemStack result = *this;
421 if(peekcount < count)
422 result.count = peekcount;
430 InventoryList::InventoryList(std::string name, u32 size, IItemDefManager *itemdef)
440 InventoryList::~InventoryList()
444 void InventoryList::clearItems()
448 for(u32 i=0; i<m_size; i++)
450 m_items.push_back(ItemStack());
456 void InventoryList::setSize(u32 newsize)
458 if(newsize != m_items.size())
459 m_items.resize(newsize);
463 void InventoryList::setWidth(u32 newwidth)
468 void InventoryList::setName(const std::string &name)
473 void InventoryList::serialize(std::ostream &os) const
475 //os.imbue(std::locale("C"));
477 os<<"Width "<<m_width<<"\n";
479 for(u32 i=0; i<m_items.size(); i++)
481 const ItemStack &item = m_items[i];
494 os<<"EndInventoryList\n";
497 void InventoryList::deSerialize(std::istream &is)
499 //is.imbue(std::locale("C"));
508 std::getline(is, line, '\n');
510 std::istringstream iss(line);
511 //iss.imbue(std::locale("C"));
514 std::getline(iss, name, ' ');
516 if(name == "EndInventoryList")
520 // This is a temporary backwards compatibility fix
521 else if(name == "end")
525 else if(name == "Width")
529 throw SerializationError("incorrect width property");
531 else if(name == "Item")
533 if(item_i > getSize() - 1)
534 throw SerializationError("too many items");
536 item.deSerialize(iss, m_itemdef);
537 m_items[item_i++] = item;
539 else if(name == "Empty")
541 if(item_i > getSize() - 1)
542 throw SerializationError("too many items");
543 m_items[item_i++].clear();
548 InventoryList::InventoryList(const InventoryList &other)
553 InventoryList & InventoryList::operator = (const InventoryList &other)
555 m_items = other.m_items;
556 m_size = other.m_size;
557 m_width = other.m_width;
558 m_name = other.m_name;
559 m_itemdef = other.m_itemdef;
565 bool InventoryList::operator == (const InventoryList &other)
567 if(m_size != other.m_size)
569 if(m_width != other.m_width)
571 if(m_name != other.m_name)
573 for(u32 i=0; i<m_items.size(); i++)
575 ItemStack s1 = m_items[i];
576 ItemStack s2 = other.m_items[i];
577 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
578 s1.metadata != s2.metadata)
585 const std::string &InventoryList::getName() const
590 u32 InventoryList::getSize() const
592 return m_items.size();
595 u32 InventoryList::getWidth() const
600 u32 InventoryList::getUsedSlots() const
603 for(u32 i=0; i<m_items.size(); i++)
605 if(!m_items[i].empty())
611 u32 InventoryList::getFreeSlots() const
613 return getSize() - getUsedSlots();
616 const ItemStack& InventoryList::getItem(u32 i) const
622 ItemStack& InventoryList::getItem(u32 i)
628 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
630 if(i >= m_items.size())
633 ItemStack olditem = m_items[i];
634 m_items[i] = newitem;
639 void InventoryList::deleteItem(u32 i)
641 assert(i < m_items.size());
645 ItemStack InventoryList::addItem(const ItemStack &newitem_)
647 ItemStack newitem = newitem_;
653 First try to find if it could be added to some existing items
655 for(u32 i=0; i<m_items.size(); i++)
657 // Ignore empty slots
658 if(m_items[i].empty())
661 newitem = addItem(i, newitem);
663 return newitem; // All was eaten
667 Then try to add it to empty slots
669 for(u32 i=0; i<m_items.size(); i++)
671 // Ignore unempty slots
672 if(!m_items[i].empty())
675 newitem = addItem(i, newitem);
677 return newitem; // All was eaten
684 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
686 if(i >= m_items.size())
689 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
690 //if(leftover != newitem)
695 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
696 ItemStack *restitem) const
698 if(i >= m_items.size())
705 return m_items[i].itemFits(newitem, restitem, m_itemdef);
708 bool InventoryList::roomForItem(const ItemStack &item_) const
710 ItemStack item = item_;
712 for(u32 i=0; i<m_items.size(); i++)
714 if(itemFits(i, item, &leftover))
721 bool InventoryList::containsItem(const ItemStack &item) const
723 u32 count = item.count;
726 for(std::vector<ItemStack>::const_reverse_iterator
727 i = m_items.rbegin();
728 i != m_items.rend(); i++)
732 if(i->name == item.name)
734 if(i->count >= count)
743 ItemStack InventoryList::removeItem(const ItemStack &item)
746 for(std::vector<ItemStack>::reverse_iterator
747 i = m_items.rbegin();
748 i != m_items.rend(); i++)
750 if(i->name == item.name)
752 u32 still_to_remove = item.count - removed.count;
753 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
754 if(removed.count == item.count)
761 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
763 if(i >= m_items.size())
766 ItemStack taken = m_items[i].takeItem(takecount);
772 ItemStack InventoryList::peekItem(u32 i, u32 peekcount) const
774 if(i >= m_items.size())
777 return m_items[i].peekItem(peekcount);
780 void InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count)
782 if(this == dest && i == dest_i)
785 // Take item from source list
788 item1 = changeItem(i, ItemStack());
790 item1 = takeItem(i, count);
795 // Try to add the item to destination list
796 u32 oldcount = item1.count;
797 item1 = dest->addItem(dest_i, item1);
799 // If something is returned, the item was not fully added
802 // If olditem is returned, nothing was added.
803 bool nothing_added = (item1.count == oldcount);
805 // If something else is returned, part of the item was left unadded.
806 // Add the other part back to the source item
809 // If olditem is returned, nothing was added.
813 // Take item from source list
814 item1 = changeItem(i, ItemStack());
815 // Adding was not possible, swap the items.
816 ItemStack item2 = dest->changeItem(dest_i, item1);
817 // Put item from destination list to the source list
818 changeItem(i, item2);
827 Inventory::~Inventory()
832 void Inventory::clear()
834 for(u32 i=0; i<m_lists.size(); i++)
841 void Inventory::clearContents()
843 for(u32 i=0; i<m_lists.size(); i++)
845 InventoryList *list = m_lists[i];
846 for(u32 j=0; j<list->getSize(); j++)
853 Inventory::Inventory(IItemDefManager *itemdef)
858 Inventory::Inventory(const Inventory &other)
863 Inventory & Inventory::operator = (const Inventory &other)
865 // Gracefully handle self assignment
869 m_itemdef = other.m_itemdef;
870 for(u32 i=0; i<other.m_lists.size(); i++)
872 m_lists.push_back(new InventoryList(*other.m_lists[i]));
878 bool Inventory::operator == (const Inventory &other)
880 if(m_lists.size() != other.m_lists.size())
883 for(u32 i=0; i<m_lists.size(); i++)
885 if(m_lists[i] != other.m_lists[i])
891 void Inventory::serialize(std::ostream &os) const
893 for(u32 i=0; i<m_lists.size(); i++)
895 InventoryList *list = m_lists[i];
896 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
900 os<<"EndInventory\n";
903 void Inventory::deSerialize(std::istream &is)
910 std::getline(is, line, '\n');
912 std::istringstream iss(line);
915 std::getline(iss, name, ' ');
917 if(name == "EndInventory")
921 // This is a temporary backwards compatibility fix
922 else if(name == "end")
926 else if(name == "List")
928 std::string listname;
931 std::getline(iss, listname, ' ');
934 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
935 list->deSerialize(is);
937 m_lists.push_back(list);
941 throw SerializationError("invalid inventory specifier");
946 InventoryList * Inventory::addList(const std::string &name, u32 size)
948 s32 i = getListIndex(name);
951 if(m_lists[i]->getSize() != size)
954 m_lists[i] = new InventoryList(name, size, m_itemdef);
960 InventoryList *list = new InventoryList(name, size, m_itemdef);
961 m_lists.push_back(list);
966 InventoryList * Inventory::getList(const std::string &name)
968 s32 i = getListIndex(name);
974 std::vector<const InventoryList*> Inventory::getLists()
976 std::vector<const InventoryList*> lists;
977 for(u32 i=0; i<m_lists.size(); i++)
979 InventoryList *list = m_lists[i];
980 lists.push_back(list);
985 bool Inventory::deleteList(const std::string &name)
987 s32 i = getListIndex(name);
991 m_lists.erase(m_lists.begin() + i);
995 const InventoryList * Inventory::getList(const std::string &name) const
997 s32 i = getListIndex(name);
1003 const s32 Inventory::getListIndex(const std::string &name) const
1005 for(u32 i=0; i<m_lists.size(); i++)
1007 if(m_lists[i]->getName() == name)