inventory.cpp 20 KB

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