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"
25 #include "main.h" // For tsrc, g_toolmanager
26 #include "serverobject.h"
27 #include "content_mapnode.h"
28 #include "content_inventory.h"
29 #include "content_sao.h"
41 InventoryItem::InventoryItem(IGameDef *gamedef, u16 count):
48 InventoryItem::~InventoryItem()
52 content_t content_translate_from_19_to_internal(content_t c_from)
54 for(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
56 if(trans_table_19[i][1] == c_from)
58 return trans_table_19[i][0];
64 InventoryItem* InventoryItem::deSerialize(std::istream &is, IGameDef *gamedef)
66 DSTACK(__FUNCTION_NAME);
68 //is.imbue(std::locale("C"));
71 std::getline(is, name, ' ');
73 if(name == "MaterialItem")
75 // u16 reads directly as a number (u8 doesn't)
80 // Convert old materials
82 material = content_translate_from_19_to_internal(material);
83 if(material > MAX_CONTENT)
84 throw SerializationError("Too large material number");
85 return new MaterialItem(gamedef, material, count);
87 else if(name == "MaterialItem2")
93 if(material > MAX_CONTENT)
94 throw SerializationError("Too large material number");
95 return new MaterialItem(gamedef, material, count);
97 else if(name == "NodeItem" || name == "MaterialItem3")
100 std::getline(is, all, '\n');
101 std::string nodename;
102 // First attempt to read inside ""
105 // If didn't skip to end, we have ""s
107 nodename = fnd.next("\"");
108 } else { // No luck, just read a word then
110 nodename = fnd.next(" ");
113 u16 count = stoi(trim(fnd.next("")));
114 return new MaterialItem(gamedef, nodename, count);
116 else if(name == "MBOItem")
118 std::string inventorystring;
119 std::getline(is, inventorystring, '|');
120 throw SerializationError("MBOItem not supported anymore");
122 else if(name == "CraftItem")
125 std::getline(is, all, '\n');
127 // First attempt to read inside ""
130 // If didn't skip to end, we have ""s
132 subname = fnd.next("\"");
133 } else { // No luck, just read a word then
135 subname = fnd.next(" ");
139 u16 count = stoi(trim(fnd.next("")));
140 return new CraftItem(gamedef, subname, count);
142 else if(name == "ToolItem")
145 std::getline(is, all, '\n');
146 std::string toolname;
147 // First attempt to read inside ""
150 // If didn't skip to end, we have ""s
152 toolname = fnd.next("\"");
153 } else { // No luck, just read a word then
155 toolname = fnd.next(" ");
159 u16 wear = stoi(trim(fnd.next("")));
160 return new ToolItem(gamedef, toolname, wear);
164 infostream<<"Unknown InventoryItem name=\""<<name<<"\""<<std::endl;
165 throw SerializationError("Unknown InventoryItem name");
169 std::string InventoryItem::getItemString() {
171 std::ostringstream os(std::ios_base::binary);
176 ServerActiveObject* InventoryItem::createSAO(ServerEnvironment *env, u16 id, v3f pos)
181 pos.Y -= BS*0.25; // let it drop a bit
183 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
184 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
186 ServerActiveObject *obj = new ItemSAO(env, pos, getItemString());
194 MaterialItem::MaterialItem(IGameDef *gamedef, std::string nodename, u16 count):
195 InventoryItem(gamedef, count)
198 nodename = "unknown_block";
199 m_nodename = nodename;
201 // Legacy constructor
202 MaterialItem::MaterialItem(IGameDef *gamedef, content_t content, u16 count):
203 InventoryItem(gamedef, count)
205 INodeDefManager *ndef = m_gamedef->ndef();
206 std::string nodename = ndef->get(content).name;
208 nodename = "unknown_block";
209 m_nodename = nodename;
213 video::ITexture * MaterialItem::getImage() const
215 return m_gamedef->getNodeDefManager()->get(m_nodename).inventory_texture;
219 bool MaterialItem::isCookable() const
221 INodeDefManager *ndef = m_gamedef->ndef();
222 const ContentFeatures &f = ndef->get(m_nodename);
223 return (f.cookresult_item != "");
226 InventoryItem *MaterialItem::createCookResult() const
228 INodeDefManager *ndef = m_gamedef->ndef();
229 const ContentFeatures &f = ndef->get(m_nodename);
230 std::istringstream is(f.cookresult_item, std::ios::binary);
231 return InventoryItem::deSerialize(is, m_gamedef);
234 float MaterialItem::getCookTime() const
236 INodeDefManager *ndef = m_gamedef->ndef();
237 const ContentFeatures &f = ndef->get(m_nodename);
238 return f.furnace_cooktime;
241 float MaterialItem::getBurnTime() const
243 INodeDefManager *ndef = m_gamedef->ndef();
244 const ContentFeatures &f = ndef->get(m_nodename);
245 return f.furnace_burntime;
248 content_t MaterialItem::getMaterial() const
250 INodeDefManager *ndef = m_gamedef->ndef();
251 content_t id = CONTENT_IGNORE;
252 ndef->getId(m_nodename, id);
260 std::string ToolItem::getImageBasename() const
262 return m_gamedef->getToolDefManager()->getImagename(m_toolname);
266 video::ITexture * ToolItem::getImage() const
268 ITextureSource *tsrc = m_gamedef->tsrc();
270 std::string basename = getImageBasename();
273 Calculate a progress value with sane amount of
276 u32 maxprogress = 30;
277 u32 toolprogress = (65535-m_wear)/(65535/maxprogress);
279 float value_f = (float)toolprogress / (float)maxprogress;
280 std::ostringstream os;
281 os<<basename<<"^[progressbar"<<value_f;
283 return tsrc->getTextureRaw(os.str());
286 video::ITexture * ToolItem::getImageRaw() const
288 ITextureSource *tsrc = m_gamedef->tsrc();
290 return tsrc->getTextureRaw(getImageBasename());
299 video::ITexture * CraftItem::getImage() const
301 ITextureSource *tsrc = m_gamedef->tsrc();
303 std::string name = item_craft_get_image_name(m_subname, m_gamedef);
305 // Get such a texture
306 return tsrc->getTextureRaw(name);
310 ServerActiveObject* CraftItem::createSAO(ServerEnvironment *env, u16 id, v3f pos)
313 ServerActiveObject *obj = item_craft_create_object(m_subname, env, pos);
317 return InventoryItem::createSAO(env, id, pos);
320 u16 CraftItem::getDropCount() const
323 s16 dc = item_craft_get_drop_count(m_subname, m_gamedef);
327 return InventoryItem::getDropCount();
330 bool CraftItem::isCookable() const
332 return item_craft_is_cookable(m_subname, m_gamedef);
335 InventoryItem *CraftItem::createCookResult() const
337 return item_craft_create_cook_result(m_subname, m_gamedef);
340 float CraftItem::getCookTime() const
345 float CraftItem::getBurnTime() const
347 if(m_subname == "lump_of_coal")
352 bool CraftItem::use(ServerEnvironment *env, ServerActiveObject *user)
354 if(!item_craft_is_eatable(m_subname, m_gamedef))
357 u16 result_count = getCount() - 1; // Eat one at a time
358 s16 hp_change = item_craft_eat_hp_change(m_subname, m_gamedef);
359 s16 hp = user->getHP();
368 setCount(result_count);
376 InventoryList::InventoryList(std::string name, u32 size)
384 InventoryList::~InventoryList()
386 for(u32 i=0; i<m_items.size(); i++)
393 void InventoryList::clearItems()
395 for(u32 i=0; i<m_items.size(); i++)
403 for(u32 i=0; i<m_size; i++)
405 m_items.push_back(NULL);
411 void InventoryList::serialize(std::ostream &os) const
413 //os.imbue(std::locale("C"));
415 for(u32 i=0; i<m_items.size(); i++)
417 InventoryItem *item = m_items[i];
430 os<<"EndInventoryList\n";
433 void InventoryList::deSerialize(std::istream &is, IGameDef *gamedef)
435 //is.imbue(std::locale("C"));
443 std::getline(is, line, '\n');
445 std::istringstream iss(line);
446 //iss.imbue(std::locale("C"));
449 std::getline(iss, name, ' ');
451 if(name == "EndInventoryList")
455 // This is a temporary backwards compatibility fix
456 else if(name == "end")
460 else if(name == "Item")
462 if(item_i > getSize() - 1)
463 throw SerializationError("too many items");
464 InventoryItem *item = InventoryItem::deSerialize(iss, gamedef);
465 m_items[item_i++] = item;
467 else if(name == "Empty")
469 if(item_i > getSize() - 1)
470 throw SerializationError("too many items");
471 m_items[item_i++] = NULL;
475 throw SerializationError("Unknown inventory identifier");
480 InventoryList::InventoryList(const InventoryList &other)
483 Do this so that the items get cloned. Otherwise the pointers
484 in the array will just get copied.
489 InventoryList & InventoryList::operator = (const InventoryList &other)
491 m_name = other.m_name;
492 m_size = other.m_size;
494 for(u32 i=0; i<other.m_items.size(); i++)
496 InventoryItem *item = other.m_items[i];
499 m_items[i] = item->clone();
507 const std::string &InventoryList::getName() const
512 u32 InventoryList::getSize()
514 return m_items.size();
517 u32 InventoryList::getUsedSlots()
520 for(u32 i=0; i<m_items.size(); i++)
522 InventoryItem *item = m_items[i];
529 u32 InventoryList::getFreeSlots()
531 return getSize() - getUsedSlots();
534 const InventoryItem * InventoryList::getItem(u32 i) const
536 if(i > m_items.size() - 1)
541 InventoryItem * InventoryList::getItem(u32 i)
543 if(i > m_items.size() - 1)
548 InventoryItem * InventoryList::changeItem(u32 i, InventoryItem *newitem)
550 assert(i < m_items.size());
552 InventoryItem *olditem = m_items[i];
553 m_items[i] = newitem;
558 void InventoryList::deleteItem(u32 i)
560 assert(i < m_items.size());
561 InventoryItem *item = changeItem(i, NULL);
566 InventoryItem * InventoryList::addItem(InventoryItem *newitem)
572 First try to find if it could be added to some existing items
574 for(u32 i=0; i<m_items.size(); i++)
576 // Ignore empty slots
577 if(m_items[i] == NULL)
580 newitem = addItem(i, newitem);
582 return NULL; // All was eaten
586 Then try to add it to empty slots
588 for(u32 i=0; i<m_items.size(); i++)
590 // Ignore unempty slots
591 if(m_items[i] != NULL)
594 newitem = addItem(i, newitem);
596 return NULL; // All was eaten
603 InventoryItem * InventoryList::addItem(u32 i, InventoryItem *newitem)
610 // If it is an empty position, it's an easy job.
611 InventoryItem *to_item = getItem(i);
614 m_items[i] = newitem;
618 // If not addable, return the item
619 if(newitem->addableTo(to_item) == false)
622 // If the item fits fully in the slot, add counter and delete it
623 if(newitem->getCount() <= to_item->freeSpace())
625 to_item->add(newitem->getCount());
629 // Else the item does not fit fully. Add all that fits and return
633 u16 freespace = to_item->freeSpace();
634 to_item->add(freespace);
635 newitem->remove(freespace);
640 bool InventoryList::itemFits(const u32 i, const InventoryItem *newitem)
642 // If it is an empty position, it's an easy job.
643 const InventoryItem *to_item = getItem(i);
649 // If not addable, fail
650 if(newitem->addableTo(to_item) == false)
653 // If the item fits fully in the slot, pass
654 if(newitem->getCount() <= to_item->freeSpace())
662 bool InventoryList::roomForItem(const InventoryItem *item)
664 for(u32 i=0; i<m_items.size(); i++)
665 if(itemFits(i, item))
670 bool InventoryList::roomForCookedItem(const InventoryItem *item)
674 const InventoryItem *cook = item->createCookResult();
677 bool room = roomForItem(cook);
682 InventoryItem * InventoryList::takeItem(u32 i, u32 count)
689 InventoryItem *item = getItem(i);
690 // If it is an empty position, return NULL
694 if(count >= item->getCount())
696 // Get the item by swapping NULL to its place
697 return changeItem(i, NULL);
701 InventoryItem *item2 = item->clone();
703 item2->setCount(count);
710 void InventoryList::decrementMaterials(u16 count)
712 for(u32 i=0; i<m_items.size(); i++)
714 InventoryItem *item = takeItem(i, count);
720 void InventoryList::print(std::ostream &o)
722 o<<"InventoryList:"<<std::endl;
723 for(u32 i=0; i<m_items.size(); i++)
725 InventoryItem *item = m_items[i];
739 Inventory::~Inventory()
744 void Inventory::clear()
746 for(u32 i=0; i<m_lists.size(); i++)
753 Inventory::Inventory()
757 Inventory::Inventory(const Inventory &other)
762 Inventory & Inventory::operator = (const Inventory &other)
765 for(u32 i=0; i<other.m_lists.size(); i++)
767 m_lists.push_back(new InventoryList(*other.m_lists[i]));
772 void Inventory::serialize(std::ostream &os) const
774 for(u32 i=0; i<m_lists.size(); i++)
776 InventoryList *list = m_lists[i];
777 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
781 os<<"EndInventory\n";
784 void Inventory::deSerialize(std::istream &is, IGameDef *gamedef)
791 std::getline(is, line, '\n');
793 std::istringstream iss(line);
796 std::getline(iss, name, ' ');
798 if(name == "EndInventory")
802 // This is a temporary backwards compatibility fix
803 else if(name == "end")
807 else if(name == "List")
809 std::string listname;
812 std::getline(iss, listname, ' ');
815 InventoryList *list = new InventoryList(listname, listsize);
816 list->deSerialize(is, gamedef);
818 m_lists.push_back(list);
822 throw SerializationError("Unknown inventory identifier");
827 InventoryList * Inventory::addList(const std::string &name, u32 size)
829 s32 i = getListIndex(name);
832 if(m_lists[i]->getSize() != size)
835 m_lists[i] = new InventoryList(name, size);
841 m_lists.push_back(new InventoryList(name, size));
842 return m_lists.getLast();
846 InventoryList * Inventory::getList(const std::string &name)
848 s32 i = getListIndex(name);
854 const InventoryList * Inventory::getList(const std::string &name) const
856 s32 i = getListIndex(name);
862 const s32 Inventory::getListIndex(const std::string &name) const
864 for(u32 i=0; i<m_lists.size(); i++)
866 if(m_lists[i]->getName() == name)
876 InventoryAction * InventoryAction::deSerialize(std::istream &is)
879 std::getline(is, type, ' ');
881 InventoryAction *a = NULL;
885 a = new IMoveAction(is);
891 static std::string describeC(const struct InventoryContext *c)
893 if(c->current_player == NULL)
894 return "current_player=NULL";
896 return std::string("current_player=") + c->current_player->getName();
899 IMoveAction::IMoveAction(std::istream &is)
903 std::getline(is, ts, ' ');
906 std::getline(is, from_inv, ' ');
908 std::getline(is, from_list, ' ');
910 std::getline(is, ts, ' ');
913 std::getline(is, to_inv, ' ');
915 std::getline(is, to_list, ' ');
917 std::getline(is, ts, ' ');
921 void IMoveAction::apply(InventoryContext *c, InventoryManager *mgr)
923 Inventory *inv_from = mgr->getInventory(c, from_inv);
924 Inventory *inv_to = mgr->getInventory(c, to_inv);
927 infostream<<"IMoveAction::apply(): FAIL: source inventory not found: "
928 <<"context=["<<describeC(c)<<"], from_inv=\""<<from_inv<<"\""
929 <<", to_inv=\""<<to_inv<<"\""<<std::endl;
933 infostream<<"IMoveAction::apply(): FAIL: destination inventory not found: "
934 "context=["<<describeC(c)<<"], from_inv=\""<<from_inv<<"\""
935 <<", to_inv=\""<<to_inv<<"\""<<std::endl;
939 InventoryList *list_from = inv_from->getList(from_list);
940 InventoryList *list_to = inv_to->getList(to_list);
943 If a list doesn't exist or the source item doesn't exist
946 infostream<<"IMoveAction::apply(): FAIL: source list not found: "
947 <<"context=["<<describeC(c)<<"], from_inv=\""<<from_inv<<"\""
948 <<", from_list=\""<<from_list<<"\""<<std::endl;
952 infostream<<"IMoveAction::apply(): FAIL: destination list not found: "
953 <<"context=["<<describeC(c)<<"], to_inv=\""<<to_inv<<"\""
954 <<", to_list=\""<<to_list<<"\""<<std::endl;
957 if(list_from->getItem(from_i) == NULL)
959 infostream<<"IMoveAction::apply(): FAIL: source item not found: "
960 <<"context=["<<describeC(c)<<"], from_inv=\""<<from_inv<<"\""
961 <<", from_list=\""<<from_list<<"\""
962 <<" from_i="<<from_i<<std::endl;
966 If the source and the destination slots are the same
968 if(inv_from == inv_to && list_from == list_to && from_i == to_i)
970 infostream<<"IMoveAction::apply(): FAIL: source and destination slots "
971 <<"are the same: inv=\""<<from_inv<<"\" list=\""<<from_list
972 <<"\" i="<<from_i<<std::endl;
976 // Take item from source list
977 InventoryItem *item1 = NULL;
979 item1 = list_from->changeItem(from_i, NULL);
981 item1 = list_from->takeItem(from_i, count);
983 // Try to add the item to destination list
984 InventoryItem *olditem = item1;
985 item1 = list_to->addItem(to_i, item1);
987 // If something is returned, the item was not fully added
990 // If olditem is returned, nothing was added.
991 bool nothing_added = (item1 == olditem);
993 // If something else is returned, part of the item was left unadded.
994 // Add the other part back to the source item
995 list_from->addItem(from_i, item1);
997 // If olditem is returned, nothing was added.
1001 // Take item from source list
1002 item1 = list_from->changeItem(from_i, NULL);
1003 // Adding was not possible, swap the items.
1004 InventoryItem *item2 = list_to->changeItem(to_i, item1);
1005 // Put item from destination list to the source list
1006 list_from->changeItem(from_i, item2);
1010 mgr->inventoryModified(c, from_inv);
1011 if(from_inv != to_inv)
1012 mgr->inventoryModified(c, to_inv);
1014 infostream<<"IMoveAction::apply(): moved at "
1015 <<"["<<describeC(c)<<"]"
1016 <<" from inv=\""<<from_inv<<"\""
1017 <<" list=\""<<from_list<<"\""
1019 <<" to inv=\""<<to_inv<<"\""
1020 <<" list=\""<<to_list<<"\""
1026 Craft checking system
1029 bool ItemSpec::checkItem(const InventoryItem *item) const
1031 if(type == ITEM_NONE)
1033 // Has to be no item
1039 // There should be an item
1043 std::string itemname = item->getName();
1045 if(type == ITEM_MATERIAL)
1047 if(itemname != "MaterialItem")
1049 MaterialItem *mitem = (MaterialItem*)item;
1051 if(mitem->getMaterial() != num)
1054 if(mitem->getNodeName() != name)
1058 else if(type == ITEM_CRAFT)
1060 if(itemname != "CraftItem")
1062 CraftItem *mitem = (CraftItem*)item;
1063 if(mitem->getSubName() != name)
1066 else if(type == ITEM_TOOL)
1068 // Not supported yet
1071 else if(type == ITEM_MBO)
1073 // Not supported yet
1078 // Not supported yet
1084 bool checkItemCombination(InventoryItem const * const *items, const ItemSpec *specs)
1086 u16 items_min_x = 100;
1087 u16 items_max_x = 100;
1088 u16 items_min_y = 100;
1089 u16 items_max_y = 100;
1090 for(u16 y=0; y<3; y++)
1091 for(u16 x=0; x<3; x++)
1093 if(items[y*3 + x] == NULL)
1095 if(items_min_x == 100 || x < items_min_x)
1097 if(items_min_y == 100 || y < items_min_y)
1099 if(items_max_x == 100 || x > items_max_x)
1101 if(items_max_y == 100 || y > items_max_y)
1104 // No items at all, just return false
1105 if(items_min_x == 100)
1108 u16 items_w = items_max_x - items_min_x + 1;
1109 u16 items_h = items_max_y - items_min_y + 1;
1111 u16 specs_min_x = 100;
1112 u16 specs_max_x = 100;
1113 u16 specs_min_y = 100;
1114 u16 specs_max_y = 100;
1115 for(u16 y=0; y<3; y++)
1116 for(u16 x=0; x<3; x++)
1118 if(specs[y*3 + x].type == ITEM_NONE)
1120 if(specs_min_x == 100 || x < specs_min_x)
1122 if(specs_min_y == 100 || y < specs_min_y)
1124 if(specs_max_x == 100 || x > specs_max_x)
1126 if(specs_max_y == 100 || y > specs_max_y)
1129 // No specs at all, just return false
1130 if(specs_min_x == 100)
1133 u16 specs_w = specs_max_x - specs_min_x + 1;
1134 u16 specs_h = specs_max_y - specs_min_y + 1;
1137 if(items_w != specs_w || items_h != specs_h)
1140 for(u16 y=0; y<specs_h; y++)
1141 for(u16 x=0; x<specs_w; x++)
1143 u16 items_x = items_min_x + x;
1144 u16 items_y = items_min_y + y;
1145 u16 specs_x = specs_min_x + x;
1146 u16 specs_y = specs_min_y + y;
1147 const InventoryItem *item = items[items_y * 3 + items_x];
1148 const ItemSpec &spec = specs[specs_y * 3 + specs_x];
1150 if(spec.checkItem(item) == false)