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(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 ItemStack::ItemStack(const std::string &name_, u16 count_,
49 u16 wear_, IItemDefManager *itemdef) :
50 name(itemdef->getAlias(name_)),
54 if (name.empty() || count == 0)
56 else if (itemdef->get(name).type == ITEM_TOOL)
60 void ItemStack::serialize(std::ostream &os) const
62 DSTACK(FUNCTION_NAME);
67 // Check how many parts of the itemstring are needed
73 if (!metadata.empty())
76 os<<serializeJsonStringIfNeeded(name);
83 metadata.serialize(os);
87 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
89 DSTACK(FUNCTION_NAME);
94 name = deSerializeJsonStringIfNeeded(is);
98 std::getline(is, tmp, ' ');
100 throw SerializationError("Unexpected text after item name");
102 if(name == "MaterialItem")
104 // Obsoleted on 2011-07-30
110 // Convert old materials
112 material = content_translate_from_19_to_internal(material);
114 throw SerializationError("Too large material number");
115 // Convert old id to name
116 NameIdMapping legacy_nimap;
117 content_mapnode_get_name_id_mapping(&legacy_nimap);
118 legacy_nimap.getName(material, name);
120 name = "unknown_block";
122 name = itemdef->getAlias(name);
123 count = materialcount;
125 else if(name == "MaterialItem2")
127 // Obsoleted on 2011-11-16
134 throw SerializationError("Too large material number");
135 // Convert old id to name
136 NameIdMapping legacy_nimap;
137 content_mapnode_get_name_id_mapping(&legacy_nimap);
138 legacy_nimap.getName(material, name);
140 name = "unknown_block";
142 name = itemdef->getAlias(name);
143 count = materialcount;
145 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
146 || name == "craft" || name == "CraftItem")
148 // Obsoleted on 2012-01-07
151 std::getline(is, all, '\n');
152 // First attempt to read inside ""
155 // If didn't skip to end, we have ""s
157 name = fnd.next("\"");
158 } else { // No luck, just read a word then
160 name = fnd.next(" ");
164 name = itemdef->getAlias(name);
165 count = stoi(trim(fnd.next("")));
169 else if(name == "MBOItem")
171 // Obsoleted on 2011-10-14
172 throw SerializationError("MBOItem not supported anymore");
174 else if(name == "tool" || name == "ToolItem")
176 // Obsoleted on 2012-01-07
179 std::getline(is, all, '\n');
180 // First attempt to read inside ""
183 // If didn't skip to end, we have ""s
185 name = fnd.next("\"");
186 } else { // No luck, just read a word then
188 name = fnd.next(" ");
194 name = itemdef->getAlias(name);
195 wear = stoi(trim(fnd.next("")));
199 do // This loop is just to allow "break;"
203 // Apply item aliases
205 name = itemdef->getAlias(name);
208 std::string count_str;
209 std::getline(is, count_str, ' ');
210 if(count_str.empty())
216 count = stoi(count_str);
219 std::string wear_str;
220 std::getline(is, wear_str, ' ');
224 wear = stoi(wear_str);
227 metadata.deSerialize(is);
229 // In case fields are added after metadata, skip space here:
230 //std::getline(is, tmp, ' ');
232 // throw SerializationError("Unexpected text after metadata");
237 if (name.empty() || count == 0)
239 else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
243 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
245 std::istringstream is(str, std::ios::binary);
246 deSerialize(is, itemdef);
249 std::string ItemStack::getItemString() const
251 std::ostringstream os(std::ios::binary);
257 ItemStack ItemStack::addItem(const ItemStack &newitem_,
258 IItemDefManager *itemdef)
260 ItemStack newitem = newitem_;
262 // If the item is empty or the position invalid, bail out
265 // nothing can be added trivially
267 // If this is an empty item, it's an easy job.
273 // If item name or metadata differs, bail out
274 else if (name != newitem.name
275 || metadata != newitem.metadata)
279 // If the item fits fully, add counter and delete it
280 else if(newitem.count <= freeSpace(itemdef))
285 // Else the item does not fit fully. Add all that fits and return
289 u16 freespace = freeSpace(itemdef);
291 newitem.remove(freespace);
297 bool ItemStack::itemFits(const ItemStack &newitem_,
299 IItemDefManager *itemdef) const
301 ItemStack newitem = newitem_;
303 // If the item is empty or the position invalid, bail out
306 // nothing can be added trivially
308 // If this is an empty item, it's an easy job.
313 // If item name or metadata differs, bail out
314 else if (name != newitem.name
315 || metadata != newitem.metadata)
319 // If the item fits fully, delete it
320 else if(newitem.count <= freeSpace(itemdef))
324 // Else the item does not fit fully. Return the rest.
328 u16 freespace = freeSpace(itemdef);
329 newitem.remove(freespace);
334 return newitem.empty();
337 ItemStack ItemStack::takeItem(u32 takecount)
339 if(takecount == 0 || count == 0)
342 ItemStack result = *this;
343 if(takecount >= count)
352 result.count = takecount;
357 ItemStack ItemStack::peekItem(u32 peekcount) const
359 if(peekcount == 0 || count == 0)
362 ItemStack result = *this;
363 if(peekcount < count)
364 result.count = peekcount;
372 InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
380 InventoryList::~InventoryList()
384 void InventoryList::clearItems()
388 for(u32 i=0; i<m_size; i++)
390 m_items.push_back(ItemStack());
396 void InventoryList::setSize(u32 newsize)
398 if(newsize != m_items.size())
399 m_items.resize(newsize);
403 void InventoryList::setWidth(u32 newwidth)
408 void InventoryList::setName(const std::string &name)
413 void InventoryList::serialize(std::ostream &os) const
415 //os.imbue(std::locale("C"));
417 os<<"Width "<<m_width<<"\n";
419 for(u32 i=0; i<m_items.size(); i++)
421 const ItemStack &item = m_items[i];
434 os<<"EndInventoryList\n";
437 void InventoryList::deSerialize(std::istream &is)
439 //is.imbue(std::locale("C"));
448 std::getline(is, line, '\n');
450 std::istringstream iss(line);
451 //iss.imbue(std::locale("C"));
454 std::getline(iss, name, ' ');
456 if(name == "EndInventoryList")
460 // This is a temporary backwards compatibility fix
461 else if(name == "end")
465 else if(name == "Width")
469 throw SerializationError("incorrect width property");
471 else if(name == "Item")
473 if(item_i > getSize() - 1)
474 throw SerializationError("too many items");
476 item.deSerialize(iss, m_itemdef);
477 m_items[item_i++] = item;
479 else if(name == "Empty")
481 if(item_i > getSize() - 1)
482 throw SerializationError("too many items");
483 m_items[item_i++].clear();
488 InventoryList::InventoryList(const InventoryList &other)
493 InventoryList & InventoryList::operator = (const InventoryList &other)
495 m_items = other.m_items;
496 m_size = other.m_size;
497 m_width = other.m_width;
498 m_name = other.m_name;
499 m_itemdef = other.m_itemdef;
505 bool InventoryList::operator == (const InventoryList &other) const
507 if(m_size != other.m_size)
509 if(m_width != other.m_width)
511 if(m_name != other.m_name)
513 for(u32 i=0; i<m_items.size(); i++)
515 ItemStack s1 = m_items[i];
516 ItemStack s2 = other.m_items[i];
517 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
518 s1.metadata != s2.metadata)
525 const std::string &InventoryList::getName() const
530 u32 InventoryList::getSize() const
532 return m_items.size();
535 u32 InventoryList::getWidth() const
540 u32 InventoryList::getUsedSlots() const
543 for(u32 i=0; i<m_items.size(); i++)
545 if(!m_items[i].empty())
551 u32 InventoryList::getFreeSlots() const
553 return getSize() - getUsedSlots();
556 const ItemStack& InventoryList::getItem(u32 i) const
558 assert(i < m_size); // Pre-condition
562 ItemStack& InventoryList::getItem(u32 i)
564 assert(i < m_size); // Pre-condition
568 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
570 if(i >= m_items.size())
573 ItemStack olditem = m_items[i];
574 m_items[i] = newitem;
579 void InventoryList::deleteItem(u32 i)
581 assert(i < m_items.size()); // Pre-condition
585 ItemStack InventoryList::addItem(const ItemStack &newitem_)
587 ItemStack newitem = newitem_;
593 First try to find if it could be added to some existing items
595 for(u32 i=0; i<m_items.size(); i++)
597 // Ignore empty slots
598 if(m_items[i].empty())
601 newitem = addItem(i, newitem);
603 return newitem; // All was eaten
607 Then try to add it to empty slots
609 for(u32 i=0; i<m_items.size(); i++)
611 // Ignore unempty slots
612 if(!m_items[i].empty())
615 newitem = addItem(i, newitem);
617 return newitem; // All was eaten
624 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
626 if(i >= m_items.size())
629 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
630 //if(leftover != newitem)
635 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
636 ItemStack *restitem) const
638 if(i >= m_items.size())
645 return m_items[i].itemFits(newitem, restitem, m_itemdef);
648 bool InventoryList::roomForItem(const ItemStack &item_) const
650 ItemStack item = item_;
652 for(u32 i=0; i<m_items.size(); i++)
654 if(itemFits(i, item, &leftover))
661 bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
663 u32 count = item.count;
666 for(std::vector<ItemStack>::const_reverse_iterator
667 i = m_items.rbegin();
668 i != m_items.rend(); ++i)
672 if (i->name == item.name
673 && (!match_meta || (i->metadata == item.metadata))) {
674 if (i->count >= count)
683 ItemStack InventoryList::removeItem(const ItemStack &item)
686 for(std::vector<ItemStack>::reverse_iterator
687 i = m_items.rbegin();
688 i != m_items.rend(); ++i)
690 if(i->name == item.name)
692 u32 still_to_remove = item.count - removed.count;
693 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
694 if(removed.count == item.count)
701 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
703 if(i >= m_items.size())
706 ItemStack taken = m_items[i].takeItem(takecount);
712 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
714 // Take item from source list
717 item1 = changeItem(i, ItemStack());
719 item1 = takeItem(i, count);
724 // Try to add the item to destination list
725 u32 dest_size = dest->getSize();
726 // First try all the non-empty slots
727 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
728 if (!m_items[dest_i].empty()) {
729 item1 = dest->addItem(dest_i, item1);
730 if (item1.empty()) return;
734 // Then try all the empty ones
735 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
736 if (m_items[dest_i].empty()) {
737 item1 = dest->addItem(dest_i, item1);
738 if (item1.empty()) return;
742 // If we reach this, the item was not fully added
743 // Add the remaining part back to the source item
747 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
748 u32 count, bool swap_if_needed, bool *did_swap)
750 if(this == dest && i == dest_i)
753 // Take item from source list
756 item1 = changeItem(i, ItemStack());
758 item1 = takeItem(i, count);
763 // Try to add the item to destination list
764 u32 oldcount = item1.count;
765 item1 = dest->addItem(dest_i, item1);
767 // If something is returned, the item was not fully added
770 // If olditem is returned, nothing was added.
771 bool nothing_added = (item1.count == oldcount);
773 // If something else is returned, part of the item was left unadded.
774 // Add the other part back to the source item
777 // If olditem is returned, nothing was added.
779 if (nothing_added && swap_if_needed) {
780 // Tell that we swapped
781 if (did_swap != NULL) {
784 // Take item from source list
785 item1 = changeItem(i, ItemStack());
786 // Adding was not possible, swap the items.
787 ItemStack item2 = dest->changeItem(dest_i, item1);
788 // Put item from destination list to the source list
789 changeItem(i, item2);
792 return (oldcount - item1.count);
799 Inventory::~Inventory()
804 void Inventory::clear()
807 for(u32 i=0; i<m_lists.size(); i++)
814 void Inventory::clearContents()
817 for(u32 i=0; i<m_lists.size(); i++)
819 InventoryList *list = m_lists[i];
820 for(u32 j=0; j<list->getSize(); j++)
827 Inventory::Inventory(IItemDefManager *itemdef)
833 Inventory::Inventory(const Inventory &other)
839 Inventory & Inventory::operator = (const Inventory &other)
841 // Gracefully handle self assignment
846 m_itemdef = other.m_itemdef;
847 for(u32 i=0; i<other.m_lists.size(); i++)
849 m_lists.push_back(new InventoryList(*other.m_lists[i]));
855 bool Inventory::operator == (const Inventory &other) const
857 if(m_lists.size() != other.m_lists.size())
860 for(u32 i=0; i<m_lists.size(); i++)
862 if(*m_lists[i] != *other.m_lists[i])
868 void Inventory::serialize(std::ostream &os) const
870 for(u32 i=0; i<m_lists.size(); i++)
872 InventoryList *list = m_lists[i];
873 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
877 os<<"EndInventory\n";
880 void Inventory::deSerialize(std::istream &is)
887 std::getline(is, line, '\n');
889 std::istringstream iss(line);
892 std::getline(iss, name, ' ');
894 if(name == "EndInventory")
898 // This is a temporary backwards compatibility fix
899 else if(name == "end")
903 else if(name == "List")
905 std::string listname;
908 std::getline(iss, listname, ' ');
911 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
912 list->deSerialize(is);
914 m_lists.push_back(list);
918 throw SerializationError("invalid inventory specifier: " + name);
923 InventoryList * Inventory::addList(const std::string &name, u32 size)
926 s32 i = getListIndex(name);
929 if(m_lists[i]->getSize() != size)
932 m_lists[i] = new InventoryList(name, size, m_itemdef);
938 //don't create list with invalid name
939 if (name.find(" ") != std::string::npos) return NULL;
941 InventoryList *list = new InventoryList(name, size, m_itemdef);
942 m_lists.push_back(list);
947 InventoryList * Inventory::getList(const std::string &name)
949 s32 i = getListIndex(name);
955 std::vector<const InventoryList*> Inventory::getLists()
957 std::vector<const InventoryList*> lists;
958 for(u32 i=0; i<m_lists.size(); i++)
960 InventoryList *list = m_lists[i];
961 lists.push_back(list);
966 bool Inventory::deleteList(const std::string &name)
968 s32 i = getListIndex(name);
973 m_lists.erase(m_lists.begin() + i);
977 const InventoryList * Inventory::getList(const std::string &name) const
979 s32 i = getListIndex(name);
985 const s32 Inventory::getListIndex(const std::string &name) const
987 for(u32 i=0; i<m_lists.size(); i++)
989 if(m_lists[i]->getName() == name)