inventory.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "inventory.h"
  17. #include "serialization.h"
  18. #include "debug.h"
  19. #include <algorithm>
  20. #include <sstream>
  21. #include "log.h"
  22. #include "itemdef.h"
  23. #include "util/strfnd.h"
  24. #include "content_mapnode.h" // For loading legacy MaterialItems
  25. #include "nameidmapping.h" // For loading legacy MaterialItems
  26. #include "util/serialize.h"
  27. #include "util/string.h"
  28. /*
  29. ItemStack
  30. */
  31. static content_t content_translate_from_19_to_internal(content_t c_from)
  32. {
  33. for (const auto &tt : trans_table_19) {
  34. if(tt[1] == c_from) {
  35. return tt[0];
  36. }
  37. }
  38. return c_from;
  39. }
  40. ItemStack::ItemStack(const std::string &name_, u16 count_,
  41. u16 wear_, IItemDefManager *itemdef) :
  42. name(itemdef->getAlias(name_)),
  43. count(count_),
  44. wear(wear_)
  45. {
  46. if (name.empty() || count == 0)
  47. clear();
  48. else if (itemdef->get(name).type == ITEM_TOOL)
  49. count = 1;
  50. }
  51. void ItemStack::serialize(std::ostream &os, bool serialize_meta) const
  52. {
  53. if (empty())
  54. return;
  55. // Check how many parts of the itemstring are needed
  56. int parts = 1;
  57. if (!metadata.empty())
  58. parts = 4;
  59. else if (wear != 0)
  60. parts = 3;
  61. else if (count != 1)
  62. parts = 2;
  63. os << serializeJsonStringIfNeeded(name);
  64. if (parts >= 2)
  65. os << " " << count;
  66. if (parts >= 3)
  67. os << " " << wear;
  68. if (parts >= 4) {
  69. os << " ";
  70. if (serialize_meta)
  71. metadata.serialize(os);
  72. else
  73. os << "<metadata size=" << metadata.size() << ">";
  74. }
  75. }
  76. void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
  77. {
  78. clear();
  79. // Read name
  80. name = deSerializeJsonStringIfNeeded(is);
  81. // Skip space
  82. std::string tmp;
  83. std::getline(is, tmp, ' ');
  84. if(!tmp.empty())
  85. throw SerializationError("Unexpected text after item name");
  86. if(name == "MaterialItem")
  87. {
  88. // Obsoleted on 2011-07-30
  89. u16 material;
  90. is>>material;
  91. u16 materialcount;
  92. is>>materialcount;
  93. // Convert old materials
  94. if(material <= 0xff)
  95. material = content_translate_from_19_to_internal(material);
  96. if(material > 0xfff)
  97. throw SerializationError("Too large material number");
  98. // Convert old id to name
  99. NameIdMapping legacy_nimap;
  100. content_mapnode_get_name_id_mapping(&legacy_nimap);
  101. legacy_nimap.getName(material, name);
  102. if(name.empty())
  103. name = "unknown_block";
  104. if (itemdef)
  105. name = itemdef->getAlias(name);
  106. count = materialcount;
  107. }
  108. else if(name == "MaterialItem2")
  109. {
  110. // Obsoleted on 2011-11-16
  111. u16 material;
  112. is>>material;
  113. u16 materialcount;
  114. is>>materialcount;
  115. if(material > 0xfff)
  116. throw SerializationError("Too large material number");
  117. // Convert old id to name
  118. NameIdMapping legacy_nimap;
  119. content_mapnode_get_name_id_mapping(&legacy_nimap);
  120. legacy_nimap.getName(material, name);
  121. if(name.empty())
  122. name = "unknown_block";
  123. if (itemdef)
  124. name = itemdef->getAlias(name);
  125. count = materialcount;
  126. }
  127. else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
  128. || name == "craft" || name == "CraftItem")
  129. {
  130. // Obsoleted on 2012-01-07
  131. std::string all;
  132. std::getline(is, all, '\n');
  133. // First attempt to read inside ""
  134. Strfnd fnd(all);
  135. fnd.next("\"");
  136. // If didn't skip to end, we have ""s
  137. if(!fnd.at_end()){
  138. name = fnd.next("\"");
  139. } else { // No luck, just read a word then
  140. fnd.start(all);
  141. name = fnd.next(" ");
  142. }
  143. fnd.skip_over(" ");
  144. if (itemdef)
  145. name = itemdef->getAlias(name);
  146. count = stoi(trim(fnd.next("")));
  147. if(count == 0)
  148. count = 1;
  149. }
  150. else if(name == "MBOItem")
  151. {
  152. // Obsoleted on 2011-10-14
  153. throw SerializationError("MBOItem not supported anymore");
  154. }
  155. else if(name == "tool" || name == "ToolItem")
  156. {
  157. // Obsoleted on 2012-01-07
  158. std::string all;
  159. std::getline(is, all, '\n');
  160. // First attempt to read inside ""
  161. Strfnd fnd(all);
  162. fnd.next("\"");
  163. // If didn't skip to end, we have ""s
  164. if(!fnd.at_end()){
  165. name = fnd.next("\"");
  166. } else { // No luck, just read a word then
  167. fnd.start(all);
  168. name = fnd.next(" ");
  169. }
  170. count = 1;
  171. // Then read wear
  172. fnd.skip_over(" ");
  173. if (itemdef)
  174. name = itemdef->getAlias(name);
  175. wear = stoi(trim(fnd.next("")));
  176. }
  177. else
  178. {
  179. do // This loop is just to allow "break;"
  180. {
  181. // The real thing
  182. // Apply item aliases
  183. if (itemdef)
  184. name = itemdef->getAlias(name);
  185. // Read the count
  186. std::string count_str;
  187. std::getline(is, count_str, ' ');
  188. if (count_str.empty()) {
  189. count = 1;
  190. break;
  191. }
  192. count = stoi(count_str);
  193. // Read the wear
  194. std::string wear_str;
  195. std::getline(is, wear_str, ' ');
  196. if(wear_str.empty())
  197. break;
  198. wear = stoi(wear_str);
  199. // Read metadata
  200. metadata.deSerialize(is);
  201. // In case fields are added after metadata, skip space here:
  202. //std::getline(is, tmp, ' ');
  203. //if(!tmp.empty())
  204. // throw SerializationError("Unexpected text after metadata");
  205. } while(false);
  206. }
  207. if (name.empty() || count == 0)
  208. clear();
  209. else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
  210. count = 1;
  211. }
  212. void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
  213. {
  214. std::istringstream is(str, std::ios::binary);
  215. deSerialize(is, itemdef);
  216. }
  217. std::string ItemStack::getItemString(bool include_meta) const
  218. {
  219. std::ostringstream os(std::ios::binary);
  220. serialize(os, include_meta);
  221. return os.str();
  222. }
  223. std::string ItemStack::getDescription(const IItemDefManager *itemdef) const
  224. {
  225. std::string desc = metadata.getString("description");
  226. if (desc.empty())
  227. desc = getDefinition(itemdef).description;
  228. return desc.empty() ? name : desc;
  229. }
  230. std::string ItemStack::getShortDescription(const IItemDefManager *itemdef) const
  231. {
  232. std::string desc = metadata.getString("short_description");
  233. if (desc.empty())
  234. desc = getDefinition(itemdef).short_description;
  235. if (!desc.empty())
  236. return desc;
  237. // no short_description because of old server version or modified builtin
  238. // return first line of description
  239. std::stringstream sstr(getDescription(itemdef));
  240. std::getline(sstr, desc, '\n');
  241. return desc;
  242. }
  243. ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
  244. {
  245. // If the item is empty or the position invalid, bail out
  246. if(newitem.empty())
  247. {
  248. // nothing can be added trivially
  249. }
  250. // If this is an empty item, it's an easy job.
  251. else if(empty())
  252. {
  253. *this = newitem;
  254. newitem.clear();
  255. }
  256. // If item name or metadata differs, bail out
  257. else if (name != newitem.name
  258. || metadata != newitem.metadata)
  259. {
  260. // cannot be added
  261. }
  262. // If the item fits fully, add counter and delete it
  263. else if(newitem.count <= freeSpace(itemdef))
  264. {
  265. add(newitem.count);
  266. newitem.clear();
  267. }
  268. // Else the item does not fit fully. Add all that fits and return
  269. // the rest.
  270. else
  271. {
  272. u16 freespace = freeSpace(itemdef);
  273. add(freespace);
  274. newitem.remove(freespace);
  275. }
  276. return newitem;
  277. }
  278. bool ItemStack::itemFits(ItemStack newitem,
  279. ItemStack *restitem,
  280. IItemDefManager *itemdef) const
  281. {
  282. // If the item is empty or the position invalid, bail out
  283. if(newitem.empty())
  284. {
  285. // nothing can be added trivially
  286. }
  287. // If this is an empty item, it's an easy job.
  288. else if(empty())
  289. {
  290. newitem.clear();
  291. }
  292. // If item name or metadata differs, bail out
  293. else if (name != newitem.name
  294. || metadata != newitem.metadata)
  295. {
  296. // cannot be added
  297. }
  298. // If the item fits fully, delete it
  299. else if(newitem.count <= freeSpace(itemdef))
  300. {
  301. newitem.clear();
  302. }
  303. // Else the item does not fit fully. Return the rest.
  304. else
  305. {
  306. u16 freespace = freeSpace(itemdef);
  307. newitem.remove(freespace);
  308. }
  309. if(restitem)
  310. *restitem = newitem;
  311. return newitem.empty();
  312. }
  313. ItemStack ItemStack::takeItem(u32 takecount)
  314. {
  315. if(takecount == 0 || count == 0)
  316. return ItemStack();
  317. ItemStack result = *this;
  318. if(takecount >= count)
  319. {
  320. // Take all
  321. clear();
  322. }
  323. else
  324. {
  325. // Take part
  326. remove(takecount);
  327. result.count = takecount;
  328. }
  329. return result;
  330. }
  331. ItemStack ItemStack::peekItem(u32 peekcount) const
  332. {
  333. if(peekcount == 0 || count == 0)
  334. return ItemStack();
  335. ItemStack result = *this;
  336. if(peekcount < count)
  337. result.count = peekcount;
  338. return result;
  339. }
  340. /*
  341. Inventory
  342. */
  343. InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
  344. m_name(name),
  345. m_size(size),
  346. m_itemdef(itemdef)
  347. {
  348. clearItems();
  349. }
  350. void InventoryList::clearItems()
  351. {
  352. m_items.clear();
  353. for (u32 i=0; i < m_size; i++) {
  354. m_items.emplace_back();
  355. }
  356. setModified();
  357. }
  358. void InventoryList::setSize(u32 newsize)
  359. {
  360. if (newsize == m_items.size())
  361. return;
  362. m_items.resize(newsize);
  363. m_size = newsize;
  364. setModified();
  365. }
  366. void InventoryList::setWidth(u32 newwidth)
  367. {
  368. m_width = newwidth;
  369. setModified();
  370. }
  371. void InventoryList::setName(const std::string &name)
  372. {
  373. m_name = name;
  374. setModified();
  375. }
  376. void InventoryList::serialize(std::ostream &os, bool incremental) const
  377. {
  378. //os.imbue(std::locale("C"));
  379. os<<"Width "<<m_width<<"\n";
  380. for (const auto &item : m_items) {
  381. if (item.empty()) {
  382. os<<"Empty";
  383. } else {
  384. os<<"Item ";
  385. item.serialize(os);
  386. }
  387. // TODO: Implement this:
  388. // if (!incremental || item.checkModified())
  389. // os << "Keep";
  390. os<<"\n";
  391. }
  392. os<<"EndInventoryList\n";
  393. }
  394. void InventoryList::deSerialize(std::istream &is)
  395. {
  396. //is.imbue(std::locale("C"));
  397. setModified();
  398. u32 item_i = 0;
  399. m_width = 0;
  400. while (is.good()) {
  401. std::string line;
  402. std::getline(is, line, '\n');
  403. std::istringstream iss(line);
  404. std::string name;
  405. std::getline(iss, name, ' ');
  406. if (name == "EndInventoryList" || name == "end") {
  407. // If partial incremental: Clear leftover items (should not happen!)
  408. for (size_t i = item_i; i < m_items.size(); ++i)
  409. m_items[i].clear();
  410. return;
  411. }
  412. if (name == "Width") {
  413. iss >> m_width;
  414. if (iss.fail())
  415. throw SerializationError("incorrect width property");
  416. }
  417. else if(name == "Item")
  418. {
  419. if(item_i > getSize() - 1)
  420. throw SerializationError("too many items");
  421. ItemStack item;
  422. item.deSerialize(iss, m_itemdef);
  423. m_items[item_i++] = item;
  424. }
  425. else if(name == "Empty")
  426. {
  427. if(item_i > getSize() - 1)
  428. throw SerializationError("too many items");
  429. m_items[item_i++].clear();
  430. } else if (name == "Keep") {
  431. ++item_i; // Unmodified item
  432. }
  433. }
  434. // Contents given to deSerialize() were not terminated properly: throw error.
  435. std::ostringstream ss;
  436. ss << "Malformatted inventory list. list="
  437. << m_name << ", read " << item_i << " of " << getSize()
  438. << " ItemStacks." << std::endl;
  439. throw SerializationError(ss.str());
  440. }
  441. InventoryList & InventoryList::operator = (const InventoryList &other)
  442. {
  443. m_items = other.m_items;
  444. m_size = other.m_size;
  445. m_width = other.m_width;
  446. m_name = other.m_name;
  447. m_itemdef = other.m_itemdef;
  448. //setDirty(true);
  449. return *this;
  450. }
  451. bool InventoryList::operator == (const InventoryList &other) const
  452. {
  453. if(m_size != other.m_size)
  454. return false;
  455. if(m_width != other.m_width)
  456. return false;
  457. if(m_name != other.m_name)
  458. return false;
  459. for (u32 i = 0; i < m_items.size(); i++)
  460. if (m_items[i] != other.m_items[i])
  461. return false;
  462. return true;
  463. }
  464. u32 InventoryList::getUsedSlots() const
  465. {
  466. u32 num = 0;
  467. for (const auto &m_item : m_items) {
  468. if (!m_item.empty())
  469. num++;
  470. }
  471. return num;
  472. }
  473. ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
  474. {
  475. if(i >= m_items.size())
  476. return newitem;
  477. ItemStack olditem = m_items[i];
  478. m_items[i] = newitem;
  479. setModified();
  480. return olditem;
  481. }
  482. void InventoryList::deleteItem(u32 i)
  483. {
  484. assert(i < m_items.size()); // Pre-condition
  485. m_items[i].clear();
  486. setModified();
  487. }
  488. ItemStack InventoryList::addItem(const ItemStack &newitem_)
  489. {
  490. ItemStack newitem = newitem_;
  491. if(newitem.empty())
  492. return newitem;
  493. /*
  494. First try to find if it could be added to some existing items
  495. */
  496. for(u32 i=0; i<m_items.size(); i++)
  497. {
  498. // Ignore empty slots
  499. if(m_items[i].empty())
  500. continue;
  501. // Try adding
  502. newitem = addItem(i, newitem);
  503. if(newitem.empty())
  504. return newitem; // All was eaten
  505. }
  506. /*
  507. Then try to add it to empty slots
  508. */
  509. for(u32 i=0; i<m_items.size(); i++)
  510. {
  511. // Ignore unempty slots
  512. if(!m_items[i].empty())
  513. continue;
  514. // Try adding
  515. newitem = addItem(i, newitem);
  516. if(newitem.empty())
  517. return newitem; // All was eaten
  518. }
  519. // Return leftover
  520. return newitem;
  521. }
  522. ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
  523. {
  524. if(i >= m_items.size())
  525. return newitem;
  526. ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
  527. if (leftover != newitem)
  528. setModified();
  529. return leftover;
  530. }
  531. bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
  532. ItemStack *restitem) const
  533. {
  534. if(i >= m_items.size())
  535. {
  536. if(restitem)
  537. *restitem = newitem;
  538. return false;
  539. }
  540. return m_items[i].itemFits(newitem, restitem, m_itemdef);
  541. }
  542. bool InventoryList::roomForItem(const ItemStack &item_) const
  543. {
  544. ItemStack item = item_;
  545. ItemStack leftover;
  546. for(u32 i=0; i<m_items.size(); i++)
  547. {
  548. if(itemFits(i, item, &leftover))
  549. return true;
  550. item = leftover;
  551. }
  552. return false;
  553. }
  554. bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
  555. {
  556. u32 count = item.count;
  557. if (count == 0)
  558. return true;
  559. for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
  560. if (count == 0)
  561. break;
  562. if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
  563. if (i->count >= count)
  564. return true;
  565. count -= i->count;
  566. }
  567. }
  568. return false;
  569. }
  570. ItemStack InventoryList::removeItem(const ItemStack &item)
  571. {
  572. ItemStack removed;
  573. for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
  574. if (i->name == item.name) {
  575. u32 still_to_remove = item.count - removed.count;
  576. ItemStack leftover = removed.addItem(i->takeItem(still_to_remove),
  577. m_itemdef);
  578. // Allow oversized stacks
  579. removed.count += leftover.count;
  580. if (removed.count == item.count)
  581. break;
  582. }
  583. }
  584. if (!removed.empty())
  585. setModified();
  586. return removed;
  587. }
  588. ItemStack InventoryList::takeItem(u32 i, u32 takecount)
  589. {
  590. if(i >= m_items.size())
  591. return ItemStack();
  592. ItemStack taken = m_items[i].takeItem(takecount);
  593. if (!taken.empty())
  594. setModified();
  595. return taken;
  596. }
  597. void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
  598. {
  599. // Take item from source list
  600. ItemStack item1;
  601. if (count == 0)
  602. item1 = changeItem(i, ItemStack());
  603. else
  604. item1 = takeItem(i, count);
  605. if (item1.empty())
  606. return;
  607. ItemStack leftover;
  608. leftover = dest->addItem(item1);
  609. if (!leftover.empty()) {
  610. // Add the remaining part back to the source item
  611. addItem(i, leftover);
  612. }
  613. }
  614. u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
  615. u32 count, bool swap_if_needed, bool *did_swap)
  616. {
  617. if (this == dest && i == dest_i)
  618. return count;
  619. // Take item from source list
  620. ItemStack item1;
  621. if (count == 0)
  622. item1 = changeItem(i, ItemStack());
  623. else
  624. item1 = takeItem(i, count);
  625. if (item1.empty())
  626. return 0;
  627. // Try to add the item to destination list
  628. u32 oldcount = item1.count;
  629. item1 = dest->addItem(dest_i, item1);
  630. // If something is returned, the item was not fully added
  631. if (!item1.empty()) {
  632. // If olditem is returned, nothing was added.
  633. bool nothing_added = (item1.count == oldcount);
  634. // If something else is returned, part of the item was left unadded.
  635. // Add the other part back to the source item
  636. addItem(i, item1);
  637. // If olditem is returned, nothing was added.
  638. // Swap the items
  639. if (nothing_added && swap_if_needed) {
  640. // Tell that we swapped
  641. if (did_swap != NULL) {
  642. *did_swap = true;
  643. }
  644. // Take item from source list
  645. item1 = changeItem(i, ItemStack());
  646. // Adding was not possible, swap the items.
  647. ItemStack item2 = dest->changeItem(dest_i, item1);
  648. // Put item from destination list to the source list
  649. changeItem(i, item2);
  650. }
  651. }
  652. return (oldcount - item1.count);
  653. }
  654. /*
  655. Inventory
  656. */
  657. Inventory::~Inventory()
  658. {
  659. clear();
  660. }
  661. void Inventory::clear()
  662. {
  663. for (auto &m_list : m_lists) {
  664. delete m_list;
  665. }
  666. m_lists.clear();
  667. setModified();
  668. }
  669. Inventory::Inventory(IItemDefManager *itemdef)
  670. {
  671. m_itemdef = itemdef;
  672. setModified();
  673. }
  674. Inventory::Inventory(const Inventory &other)
  675. {
  676. *this = other;
  677. }
  678. Inventory & Inventory::operator = (const Inventory &other)
  679. {
  680. // Gracefully handle self assignment
  681. if(this != &other)
  682. {
  683. clear();
  684. m_itemdef = other.m_itemdef;
  685. for (InventoryList *list : other.m_lists) {
  686. m_lists.push_back(new InventoryList(*list));
  687. }
  688. setModified();
  689. }
  690. return *this;
  691. }
  692. bool Inventory::operator == (const Inventory &other) const
  693. {
  694. if(m_lists.size() != other.m_lists.size())
  695. return false;
  696. for(u32 i=0; i<m_lists.size(); i++)
  697. {
  698. if(*m_lists[i] != *other.m_lists[i])
  699. return false;
  700. }
  701. return true;
  702. }
  703. void Inventory::serialize(std::ostream &os, bool incremental) const
  704. {
  705. //std::cout << "Serialize " << (int)incremental << ", n=" << m_lists.size() << std::endl;
  706. for (const InventoryList *list : m_lists) {
  707. if (!incremental || list->checkModified()) {
  708. os << "List " << list->getName() << " " << list->getSize() << "\n";
  709. list->serialize(os, incremental);
  710. } else {
  711. os << "KeepList " << list->getName() << "\n";
  712. }
  713. }
  714. os<<"EndInventory\n";
  715. }
  716. void Inventory::deSerialize(std::istream &is)
  717. {
  718. std::vector<InventoryList *> new_lists;
  719. new_lists.reserve(m_lists.size());
  720. while (is.good()) {
  721. std::string line;
  722. std::getline(is, line, '\n');
  723. std::istringstream iss(line);
  724. std::string name;
  725. std::getline(iss, name, ' ');
  726. if (name == "EndInventory" || name == "end") {
  727. // Remove all lists that were not sent
  728. for (auto &list : m_lists) {
  729. if (std::find(new_lists.begin(), new_lists.end(), list) != new_lists.end())
  730. continue;
  731. delete list;
  732. list = nullptr;
  733. setModified();
  734. }
  735. m_lists.erase(std::remove(m_lists.begin(), m_lists.end(),
  736. nullptr), m_lists.end());
  737. return;
  738. }
  739. if (name == "List") {
  740. std::string listname;
  741. u32 listsize;
  742. std::getline(iss, listname, ' ');
  743. iss>>listsize;
  744. InventoryList *list = getList(listname);
  745. bool create_new = !list;
  746. if (create_new)
  747. list = new InventoryList(listname, listsize, m_itemdef);
  748. else
  749. list->setSize(listsize);
  750. list->deSerialize(is);
  751. new_lists.push_back(list);
  752. if (create_new)
  753. m_lists.push_back(list);
  754. } else if (name == "KeepList") {
  755. // Incrementally sent list
  756. std::string listname;
  757. std::getline(iss, listname, ' ');
  758. InventoryList *list = getList(listname);
  759. if (list) {
  760. new_lists.push_back(list);
  761. } else {
  762. errorstream << "Inventory::deSerialize(): Tried to keep list '" <<
  763. listname << "' which is non-existent." << std::endl;
  764. }
  765. }
  766. // Any additional fields will throw errors when received by a client
  767. // older than PROTOCOL_VERSION 38
  768. }
  769. // Contents given to deSerialize() were not terminated properly: throw error.
  770. std::ostringstream ss;
  771. ss << "Malformatted inventory (damaged?). "
  772. << m_lists.size() << " lists read." << std::endl;
  773. throw SerializationError(ss.str());
  774. }
  775. InventoryList * Inventory::addList(const std::string &name, u32 size)
  776. {
  777. setModified();
  778. // Remove existing lists
  779. s32 i = getListIndex(name);
  780. if (i != -1) {
  781. delete m_lists[i];
  782. m_lists[i] = new InventoryList(name, size, m_itemdef);
  783. m_lists[i]->setModified();
  784. return m_lists[i];
  785. }
  786. //don't create list with invalid name
  787. if (name.find(' ') != std::string::npos)
  788. return nullptr;
  789. InventoryList *list = new InventoryList(name, size, m_itemdef);
  790. list->setModified();
  791. m_lists.push_back(list);
  792. return list;
  793. }
  794. InventoryList * Inventory::getList(const std::string &name)
  795. {
  796. s32 i = getListIndex(name);
  797. if(i == -1)
  798. return nullptr;
  799. return m_lists[i];
  800. }
  801. bool Inventory::deleteList(const std::string &name)
  802. {
  803. s32 i = getListIndex(name);
  804. if(i == -1)
  805. return false;
  806. setModified();
  807. delete m_lists[i];
  808. m_lists.erase(m_lists.begin() + i);
  809. return true;
  810. }
  811. const InventoryList *Inventory::getList(const std::string &name) const
  812. {
  813. s32 i = getListIndex(name);
  814. if(i == -1)
  815. return nullptr;
  816. return m_lists[i];
  817. }
  818. s32 Inventory::getListIndex(const std::string &name) const
  819. {
  820. for(u32 i=0; i<m_lists.size(); i++)
  821. {
  822. if(m_lists[i]->getName() == name)
  823. return i;
  824. }
  825. return -1;
  826. }
  827. //END