3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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"
28 #include "content_mapnode.h" // For loading legacy MaterialItems
29 #include "nameidmapping.h" // For loading legacy MaterialItems
35 static content_t content_translate_from_19_to_internal(content_t c_from)
37 for(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
39 if(trans_table_19[i][1] == c_from)
41 return trans_table_19[i][0];
47 // If the string contains spaces, quotes or control characters, encodes as JSON.
48 // Else returns the string unmodified.
49 static std::string serializeJsonStringIfNeeded(const std::string &s)
51 for(size_t i = 0; i < s.size(); ++i)
53 if(s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
54 return serializeJsonString(s);
59 // Parses a string serialized by serializeJsonStringIfNeeded.
60 static std::string deSerializeJsonStringIfNeeded(std::istream &is)
62 std::ostringstream tmp_os;
63 bool expect_initial_quote = true;
65 bool was_backslash = false;
71 if(expect_initial_quote && c == '"')
80 was_backslash = false;
84 break; // Found end of string
99 expect_initial_quote = false;
103 std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
104 return deSerializeJsonString(tmp_is);
111 ItemStack::ItemStack(std::string name_, u16 count_,
112 u16 wear_, std::string metadata_,
113 IItemDefManager *itemdef)
115 name = itemdef->getAlias(name_);
118 metadata = metadata_;
120 if(name.empty() || count == 0)
122 else if(itemdef->get(name).type == ITEM_TOOL)
126 void ItemStack::serialize(std::ostream &os) const
128 DSTACK(__FUNCTION_NAME);
133 // Check how many parts of the itemstring are needed
142 os<<serializeJsonStringIfNeeded(name);
148 os<<" "<<serializeJsonStringIfNeeded(metadata);
151 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
153 DSTACK(__FUNCTION_NAME);
158 name = deSerializeJsonStringIfNeeded(is);
162 std::getline(is, tmp, ' ');
164 throw SerializationError("Unexpected text after item name");
166 if(name == "MaterialItem")
168 // Obsoleted on 2011-07-30
174 // Convert old materials
176 material = content_translate_from_19_to_internal(material);
177 if(material > MAX_CONTENT)
178 throw SerializationError("Too large material number");
179 // Convert old id to name
180 NameIdMapping legacy_nimap;
181 content_mapnode_get_name_id_mapping(&legacy_nimap);
182 legacy_nimap.getName(material, name);
184 name = "unknown_block";
185 name = itemdef->getAlias(name);
186 count = materialcount;
188 else if(name == "MaterialItem2")
190 // Obsoleted on 2011-11-16
196 if(material > MAX_CONTENT)
197 throw SerializationError("Too large material number");
198 // Convert old id to name
199 NameIdMapping legacy_nimap;
200 content_mapnode_get_name_id_mapping(&legacy_nimap);
201 legacy_nimap.getName(material, name);
203 name = "unknown_block";
204 name = itemdef->getAlias(name);
205 count = materialcount;
207 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
208 || name == "craft" || name == "CraftItem")
210 // Obsoleted on 2012-01-07
213 std::getline(is, all, '\n');
214 // First attempt to read inside ""
217 // If didn't skip to end, we have ""s
219 name = fnd.next("\"");
220 } else { // No luck, just read a word then
222 name = fnd.next(" ");
225 name = itemdef->getAlias(name);
226 count = stoi(trim(fnd.next("")));
230 else if(name == "MBOItem")
232 // Obsoleted on 2011-10-14
233 throw SerializationError("MBOItem not supported anymore");
235 else if(name == "tool" || name == "ToolItem")
237 // Obsoleted on 2012-01-07
240 std::getline(is, all, '\n');
241 // First attempt to read inside ""
244 // If didn't skip to end, we have ""s
246 name = fnd.next("\"");
247 } else { // No luck, just read a word then
249 name = fnd.next(" ");
254 wear = stoi(trim(fnd.next("")));
258 do // This loop is just to allow "break;"
262 // Apply item aliases
263 name = itemdef->getAlias(name);
266 std::string count_str;
267 std::getline(is, count_str, ' ');
268 if(count_str.empty())
274 count = stoi(count_str);
277 std::string wear_str;
278 std::getline(is, wear_str, ' ');
282 wear = stoi(wear_str);
285 metadata = deSerializeJsonStringIfNeeded(is);
287 // In case fields are added after metadata, skip space here:
288 //std::getline(is, tmp, ' ');
290 // throw SerializationError("Unexpected text after metadata");
295 if(name.empty() || count == 0)
297 else if(itemdef->get(name).type == ITEM_TOOL)
301 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
303 std::istringstream is(str, std::ios::binary);
304 deSerialize(is, itemdef);
307 std::string ItemStack::getItemString() const
310 std::ostringstream os(std::ios::binary);
315 ItemStack ItemStack::addItem(const ItemStack &newitem_,
316 IItemDefManager *itemdef)
318 ItemStack newitem = newitem_;
320 // If the item is empty or the position invalid, bail out
323 // nothing can be added trivially
325 // If this is an empty item, it's an easy job.
331 // If item name differs, bail out
332 else if(name != newitem.name)
336 // If the item fits fully, add counter and delete it
337 else if(newitem.count <= freeSpace(itemdef))
342 // Else the item does not fit fully. Add all that fits and return
346 u16 freespace = freeSpace(itemdef);
348 newitem.remove(freespace);
354 bool ItemStack::itemFits(const ItemStack &newitem_,
356 IItemDefManager *itemdef) const
358 ItemStack newitem = newitem_;
360 // If the item is empty or the position invalid, bail out
363 // nothing can be added trivially
365 // If this is an empty item, it's an easy job.
370 // If item name differs, bail out
371 else if(name != newitem.name)
375 // If the item fits fully, delete it
376 else if(newitem.count <= freeSpace(itemdef))
380 // Else the item does not fit fully. Return the rest.
384 u16 freespace = freeSpace(itemdef);
385 newitem.remove(freespace);
390 return newitem.empty();
393 ItemStack ItemStack::takeItem(u32 takecount)
395 if(takecount == 0 || count == 0)
398 ItemStack result = *this;
399 if(takecount >= count)
408 result.count = takecount;
413 ItemStack ItemStack::peekItem(u32 peekcount) const
415 if(peekcount == 0 || count == 0)
418 ItemStack result = *this;
419 if(peekcount < count)
420 result.count = peekcount;
428 InventoryList::InventoryList(std::string name, u32 size, IItemDefManager *itemdef)
437 InventoryList::~InventoryList()
441 void InventoryList::clearItems()
445 for(u32 i=0; i<m_size; i++)
447 m_items.push_back(ItemStack());
453 void InventoryList::setSize(u32 newsize)
455 if(newsize != m_items.size())
456 m_items.resize(newsize);
460 void InventoryList::serialize(std::ostream &os) const
462 //os.imbue(std::locale("C"));
464 for(u32 i=0; i<m_items.size(); i++)
466 const ItemStack &item = m_items[i];
479 os<<"EndInventoryList\n";
482 void InventoryList::deSerialize(std::istream &is)
484 //is.imbue(std::locale("C"));
492 std::getline(is, line, '\n');
494 std::istringstream iss(line);
495 //iss.imbue(std::locale("C"));
498 std::getline(iss, name, ' ');
500 if(name == "EndInventoryList")
504 // This is a temporary backwards compatibility fix
505 else if(name == "end")
509 else if(name == "Item")
511 if(item_i > getSize() - 1)
512 throw SerializationError("too many items");
514 item.deSerialize(iss, m_itemdef);
515 m_items[item_i++] = item;
517 else if(name == "Empty")
519 if(item_i > getSize() - 1)
520 throw SerializationError("too many items");
521 m_items[item_i++].clear();
525 throw SerializationError("Unknown inventory identifier");
530 InventoryList::InventoryList(const InventoryList &other)
535 InventoryList & InventoryList::operator = (const InventoryList &other)
537 m_items = other.m_items;
538 m_size = other.m_size;
539 m_name = other.m_name;
540 m_itemdef = other.m_itemdef;
546 const std::string &InventoryList::getName() const
551 u32 InventoryList::getSize() const
553 return m_items.size();
556 u32 InventoryList::getUsedSlots() const
559 for(u32 i=0; i<m_items.size(); i++)
561 if(!m_items[i].empty())
567 u32 InventoryList::getFreeSlots() const
569 return getSize() - getUsedSlots();
572 const ItemStack& InventoryList::getItem(u32 i) const
578 ItemStack& InventoryList::getItem(u32 i)
584 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
586 if(i >= m_items.size())
589 ItemStack olditem = m_items[i];
590 m_items[i] = newitem;
595 void InventoryList::deleteItem(u32 i)
597 assert(i < m_items.size());
601 ItemStack InventoryList::addItem(const ItemStack &newitem_)
603 ItemStack newitem = newitem_;
609 First try to find if it could be added to some existing items
611 for(u32 i=0; i<m_items.size(); i++)
613 // Ignore empty slots
614 if(m_items[i].empty())
617 newitem = addItem(i, newitem);
619 return newitem; // All was eaten
623 Then try to add it to empty slots
625 for(u32 i=0; i<m_items.size(); i++)
627 // Ignore unempty slots
628 if(!m_items[i].empty())
631 newitem = addItem(i, newitem);
633 return newitem; // All was eaten
640 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
642 if(i >= m_items.size())
645 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
646 //if(leftover != newitem)
651 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
652 ItemStack *restitem) const
654 if(i >= m_items.size())
661 return m_items[i].itemFits(newitem, restitem, m_itemdef);
664 bool InventoryList::roomForItem(const ItemStack &item_) const
666 ItemStack item = item_;
668 for(u32 i=0; i<m_items.size(); i++)
670 if(itemFits(i, item, &leftover))
677 bool InventoryList::containsItem(const ItemStack &item) const
679 u32 count = item.count;
682 for(std::vector<ItemStack>::const_reverse_iterator
683 i = m_items.rbegin();
684 i != m_items.rend(); i++)
688 if(i->name == item.name)
690 if(i->count >= count)
699 ItemStack InventoryList::removeItem(const ItemStack &item)
702 for(std::vector<ItemStack>::reverse_iterator
703 i = m_items.rbegin();
704 i != m_items.rend(); i++)
706 if(i->name == item.name)
708 u32 still_to_remove = item.count - removed.count;
709 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
710 if(removed.count == item.count)
717 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
719 if(i >= m_items.size())
722 ItemStack taken = m_items[i].takeItem(takecount);
728 ItemStack InventoryList::peekItem(u32 i, u32 peekcount) const
730 if(i >= m_items.size())
733 return m_items[i].peekItem(peekcount);
736 void InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count)
738 if(this == dest && i == dest_i)
741 // Take item from source list
744 item1 = changeItem(i, ItemStack());
746 item1 = takeItem(i, count);
751 // Try to add the item to destination list
752 u32 oldcount = item1.count;
753 item1 = dest->addItem(dest_i, item1);
755 // If something is returned, the item was not fully added
758 // If olditem is returned, nothing was added.
759 bool nothing_added = (item1.count == oldcount);
761 // If something else is returned, part of the item was left unadded.
762 // Add the other part back to the source item
765 // If olditem is returned, nothing was added.
769 // Take item from source list
770 item1 = changeItem(i, ItemStack());
771 // Adding was not possible, swap the items.
772 ItemStack item2 = dest->changeItem(dest_i, item1);
773 // Put item from destination list to the source list
774 changeItem(i, item2);
783 Inventory::~Inventory()
788 void Inventory::clear()
790 for(u32 i=0; i<m_lists.size(); i++)
797 Inventory::Inventory(IItemDefManager *itemdef)
802 Inventory::Inventory(const Inventory &other)
807 Inventory & Inventory::operator = (const Inventory &other)
809 // Gracefully handle self assignment
813 m_itemdef = other.m_itemdef;
814 for(u32 i=0; i<other.m_lists.size(); i++)
816 m_lists.push_back(new InventoryList(*other.m_lists[i]));
822 void Inventory::serialize(std::ostream &os) const
824 for(u32 i=0; i<m_lists.size(); i++)
826 InventoryList *list = m_lists[i];
827 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
831 os<<"EndInventory\n";
834 void Inventory::deSerialize(std::istream &is)
841 std::getline(is, line, '\n');
843 std::istringstream iss(line);
846 std::getline(iss, name, ' ');
848 if(name == "EndInventory")
852 // This is a temporary backwards compatibility fix
853 else if(name == "end")
857 else if(name == "List")
859 std::string listname;
862 std::getline(iss, listname, ' ');
865 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
866 list->deSerialize(is);
868 m_lists.push_back(list);
872 throw SerializationError("Unknown inventory identifier");
877 InventoryList * Inventory::addList(const std::string &name, u32 size)
879 s32 i = getListIndex(name);
882 if(m_lists[i]->getSize() != size)
885 m_lists[i] = new InventoryList(name, size, m_itemdef);
891 InventoryList *list = new InventoryList(name, size, m_itemdef);
892 m_lists.push_back(list);
897 InventoryList * Inventory::getList(const std::string &name)
899 s32 i = getListIndex(name);
905 bool Inventory::deleteList(const std::string &name)
907 s32 i = getListIndex(name);
911 m_lists.erase(m_lists.begin() + i);
915 const InventoryList * Inventory::getList(const std::string &name) const
917 s32 i = getListIndex(name);
923 const s32 Inventory::getListIndex(const std::string &name) const
925 for(u32 i=0; i<m_lists.size(); i++)
927 if(m_lists[i]->getName() == name)