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):
381 InventoryList::~InventoryList()
385 void InventoryList::clearItems()
389 for(u32 i=0; i<m_size; i++)
391 m_items.push_back(ItemStack());
397 void InventoryList::setSize(u32 newsize)
399 if(newsize != m_items.size())
400 m_items.resize(newsize);
404 void InventoryList::setWidth(u32 newwidth)
409 void InventoryList::setName(const std::string &name)
414 void InventoryList::serialize(std::ostream &os) const
416 //os.imbue(std::locale("C"));
418 os<<"Width "<<m_width<<"\n";
420 for(u32 i=0; i<m_items.size(); i++)
422 const ItemStack &item = m_items[i];
435 os<<"EndInventoryList\n";
438 void InventoryList::deSerialize(std::istream &is)
440 //is.imbue(std::locale("C"));
449 std::getline(is, line, '\n');
451 std::istringstream iss(line);
452 //iss.imbue(std::locale("C"));
455 std::getline(iss, name, ' ');
457 if(name == "EndInventoryList")
461 // This is a temporary backwards compatibility fix
462 else if(name == "end")
466 else if(name == "Width")
470 throw SerializationError("incorrect width property");
472 else if(name == "Item")
474 if(item_i > getSize() - 1)
475 throw SerializationError("too many items");
477 item.deSerialize(iss, m_itemdef);
478 m_items[item_i++] = item;
480 else if(name == "Empty")
482 if(item_i > getSize() - 1)
483 throw SerializationError("too many items");
484 m_items[item_i++].clear();
489 InventoryList::InventoryList(const InventoryList &other)
494 InventoryList & InventoryList::operator = (const InventoryList &other)
496 m_items = other.m_items;
497 m_size = other.m_size;
498 m_width = other.m_width;
499 m_name = other.m_name;
500 m_itemdef = other.m_itemdef;
506 bool InventoryList::operator == (const InventoryList &other) const
508 if(m_size != other.m_size)
510 if(m_width != other.m_width)
512 if(m_name != other.m_name)
514 for(u32 i=0; i<m_items.size(); i++)
516 ItemStack s1 = m_items[i];
517 ItemStack s2 = other.m_items[i];
518 if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count ||
519 s1.metadata != s2.metadata)
526 const std::string &InventoryList::getName() const
531 u32 InventoryList::getSize() const
533 return m_items.size();
536 u32 InventoryList::getWidth() const
541 u32 InventoryList::getUsedSlots() const
544 for(u32 i=0; i<m_items.size(); i++)
546 if(!m_items[i].empty())
552 u32 InventoryList::getFreeSlots() const
554 return getSize() - getUsedSlots();
557 const ItemStack& InventoryList::getItem(u32 i) const
559 assert(i < m_size); // Pre-condition
563 ItemStack& InventoryList::getItem(u32 i)
565 assert(i < m_size); // Pre-condition
569 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
571 if(i >= m_items.size())
574 ItemStack olditem = m_items[i];
575 m_items[i] = newitem;
580 void InventoryList::deleteItem(u32 i)
582 assert(i < m_items.size()); // Pre-condition
586 ItemStack InventoryList::addItem(const ItemStack &newitem_)
588 ItemStack newitem = newitem_;
594 First try to find if it could be added to some existing items
596 for(u32 i=0; i<m_items.size(); i++)
598 // Ignore empty slots
599 if(m_items[i].empty())
602 newitem = addItem(i, newitem);
604 return newitem; // All was eaten
608 Then try to add it to empty slots
610 for(u32 i=0; i<m_items.size(); i++)
612 // Ignore unempty slots
613 if(!m_items[i].empty())
616 newitem = addItem(i, newitem);
618 return newitem; // All was eaten
625 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
627 if(i >= m_items.size())
630 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
631 //if(leftover != newitem)
636 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
637 ItemStack *restitem) const
639 if(i >= m_items.size())
646 return m_items[i].itemFits(newitem, restitem, m_itemdef);
649 bool InventoryList::roomForItem(const ItemStack &item_) const
651 ItemStack item = item_;
653 for(u32 i=0; i<m_items.size(); i++)
655 if(itemFits(i, item, &leftover))
662 bool InventoryList::containsItem(const ItemStack &item) const
664 u32 count = item.count;
667 for(std::vector<ItemStack>::const_reverse_iterator
668 i = m_items.rbegin();
669 i != m_items.rend(); ++i)
673 if(i->name == item.name)
675 if(i->count >= count)
684 ItemStack InventoryList::removeItem(const ItemStack &item)
687 for(std::vector<ItemStack>::reverse_iterator
688 i = m_items.rbegin();
689 i != m_items.rend(); ++i)
691 if(i->name == item.name)
693 u32 still_to_remove = item.count - removed.count;
694 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
695 if(removed.count == item.count)
702 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
704 if(i >= m_items.size())
707 ItemStack taken = m_items[i].takeItem(takecount);
713 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
715 // Take item from source list
718 item1 = changeItem(i, ItemStack());
720 item1 = takeItem(i, count);
725 // Try to add the item to destination list
726 u32 dest_size = dest->getSize();
727 // First try all the non-empty slots
728 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
729 if (!m_items[dest_i].empty()) {
730 item1 = dest->addItem(dest_i, item1);
731 if (item1.empty()) return;
735 // Then try all the empty ones
736 for (u32 dest_i = 0; dest_i < dest_size; dest_i++) {
737 if (m_items[dest_i].empty()) {
738 item1 = dest->addItem(dest_i, item1);
739 if (item1.empty()) return;
743 // If we reach this, the item was not fully added
744 // Add the remaining part back to the source item
748 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
749 u32 count, bool swap_if_needed, bool *did_swap)
751 if(this == dest && i == dest_i)
754 // Take item from source list
757 item1 = changeItem(i, ItemStack());
759 item1 = takeItem(i, count);
764 // Try to add the item to destination list
765 u32 oldcount = item1.count;
766 item1 = dest->addItem(dest_i, item1);
768 // If something is returned, the item was not fully added
771 // If olditem is returned, nothing was added.
772 bool nothing_added = (item1.count == oldcount);
774 // If something else is returned, part of the item was left unadded.
775 // Add the other part back to the source item
778 // If olditem is returned, nothing was added.
780 if (nothing_added && swap_if_needed) {
781 // Tell that we swapped
782 if (did_swap != NULL) {
785 // Take item from source list
786 item1 = changeItem(i, ItemStack());
787 // Adding was not possible, swap the items.
788 ItemStack item2 = dest->changeItem(dest_i, item1);
789 // Put item from destination list to the source list
790 changeItem(i, item2);
793 return (oldcount - item1.count);
800 Inventory::~Inventory()
805 void Inventory::clear()
808 for(u32 i=0; i<m_lists.size(); i++)
815 void Inventory::clearContents()
818 for(u32 i=0; i<m_lists.size(); i++)
820 InventoryList *list = m_lists[i];
821 for(u32 j=0; j<list->getSize(); j++)
828 Inventory::Inventory(IItemDefManager *itemdef)
834 Inventory::Inventory(const Inventory &other)
840 Inventory & Inventory::operator = (const Inventory &other)
842 // Gracefully handle self assignment
847 m_itemdef = other.m_itemdef;
848 for(u32 i=0; i<other.m_lists.size(); i++)
850 m_lists.push_back(new InventoryList(*other.m_lists[i]));
856 bool Inventory::operator == (const Inventory &other) const
858 if(m_lists.size() != other.m_lists.size())
861 for(u32 i=0; i<m_lists.size(); i++)
863 if(*m_lists[i] != *other.m_lists[i])
869 void Inventory::serialize(std::ostream &os) const
871 for(u32 i=0; i<m_lists.size(); i++)
873 InventoryList *list = m_lists[i];
874 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
878 os<<"EndInventory\n";
881 void Inventory::deSerialize(std::istream &is)
888 std::getline(is, line, '\n');
890 std::istringstream iss(line);
893 std::getline(iss, name, ' ');
895 if(name == "EndInventory")
899 // This is a temporary backwards compatibility fix
900 else if(name == "end")
904 else if(name == "List")
906 std::string listname;
909 std::getline(iss, listname, ' ');
912 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
913 list->deSerialize(is);
915 m_lists.push_back(list);
919 throw SerializationError("invalid inventory specifier: " + name);
924 InventoryList * Inventory::addList(const std::string &name, u32 size)
927 s32 i = getListIndex(name);
930 if(m_lists[i]->getSize() != size)
933 m_lists[i] = new InventoryList(name, size, m_itemdef);
939 //don't create list with invalid name
940 if (name.find(" ") != std::string::npos) return NULL;
942 InventoryList *list = new InventoryList(name, size, m_itemdef);
943 m_lists.push_back(list);
948 InventoryList * Inventory::getList(const std::string &name)
950 s32 i = getListIndex(name);
956 std::vector<const InventoryList*> Inventory::getLists()
958 std::vector<const InventoryList*> lists;
959 for(u32 i=0; i<m_lists.size(); i++)
961 InventoryList *list = m_lists[i];
962 lists.push_back(list);
967 bool Inventory::deleteList(const std::string &name)
969 s32 i = getListIndex(name);
974 m_lists.erase(m_lists.begin() + i);
978 const InventoryList * Inventory::getList(const std::string &name) const
980 s32 i = getListIndex(name);
986 const s32 Inventory::getListIndex(const std::string &name) const
988 for(u32 i=0; i<m_lists.size(); i++)
990 if(m_lists[i]->getName() == name)