]> git.lizzy.rs Git - minetest.git/blob - src/craftdef.cpp
Test crafting hash type only once for a recipe
[minetest.git] / src / craftdef.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "craftdef.h"
21
22 #include "irrlichttypes.h"
23 #include "log.h"
24 #include <sstream>
25 #include <set>
26 #include <algorithm>
27 #include "gamedef.h"
28 #include "inventory.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
31 #include "util/numeric.h"
32 #include "util/strfnd.h"
33 #include "exceptions.h"
34
35 inline bool isGroupRecipeStr(const std::string &rec_name)
36 {
37         return str_starts_with(rec_name, std::string("group:"));
38 }
39
40 inline u64 getHashForString(const std::string &recipe_str)
41 {
42         /*errorstream << "Hashing craft string  \"" << recipe_str << '"';*/
43         return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef);
44 }
45
46 static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names)
47 {
48         switch (type) {
49                 case CRAFT_HASH_TYPE_ITEM_NAMES: {
50                         std::ostringstream os;
51                         bool is_first = true;
52                         for (const std::string &grid_name : grid_names) {
53                                 if (!grid_name.empty()) {
54                                         os << (is_first ? "" : "\n") << grid_name;
55                                         is_first = false;
56                                 }
57                         }
58                         return getHashForString(os.str());
59                 } case CRAFT_HASH_TYPE_COUNT: {
60                         u64 cnt = 0;
61                         for (const std::string &grid_name : grid_names)
62                                 if (!grid_name.empty())
63                                         cnt++;
64                         return cnt;
65                 } case CRAFT_HASH_TYPE_UNHASHED:
66                         return 0;
67         }
68         // invalid CraftHashType
69         assert(false);
70         return 0;
71 }
72
73 // Check if input matches recipe
74 // Takes recipe groups into account
75 static bool inputItemMatchesRecipe(const std::string &inp_name,
76                 const std::string &rec_name, IItemDefManager *idef)
77 {
78         // Exact name
79         if (inp_name == rec_name)
80                 return true;
81
82         // Group
83         if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) {
84                 const struct ItemDefinition &def = idef->get(inp_name);
85                 Strfnd f(rec_name.substr(6));
86                 bool all_groups_match = true;
87                 do {
88                         std::string check_group = f.next(",");
89                         if (itemgroup_get(def.groups, check_group) == 0) {
90                                 all_groups_match = false;
91                                 break;
92                         }
93                 } while (!f.at_end());
94                 if (all_groups_match)
95                         return true;
96         }
97
98         // Didn't match
99         return false;
100 }
101
102 // Deserialize an itemstring then return the name of the item
103 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
104 {
105         ItemStack item;
106         item.deSerialize(itemstring, gamedef->idef());
107         return item.name;
108 }
109
110 // (mapcar craftGetItemName itemstrings)
111 static std::vector<std::string> craftGetItemNames(
112                 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
113 {
114         std::vector<std::string> result;
115         result.reserve(itemstrings.size());
116         for (const auto &itemstring : itemstrings) {
117                 result.push_back(craftGetItemName(itemstring, gamedef));
118         }
119         return result;
120 }
121
122 // Get name of each item, and return them as a new list.
123 static std::vector<std::string> craftGetItemNames(
124                 const std::vector<ItemStack> &items, IGameDef *gamedef)
125 {
126         std::vector<std::string> result;
127         result.reserve(items.size());
128         for (const auto &item : items) {
129                 result.push_back(item.name);
130         }
131         return result;
132 }
133
134 // convert a list of item names, to ItemStacks.
135 static std::vector<ItemStack> craftGetItems(
136                 const std::vector<std::string> &items, IGameDef *gamedef)
137 {
138         std::vector<ItemStack> result;
139         result.reserve(items.size());
140         for (const auto &item : items) {
141                 result.emplace_back(std::string(item), (u16)1,
142                         (u16)0, gamedef->getItemDefManager());
143         }
144         return result;
145 }
146
147 // Compute bounding rectangle given a matrix of items
148 // Returns false if every item is ""
149 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
150                 unsigned int &min_x, unsigned int &max_x,
151                 unsigned int &min_y, unsigned int &max_y)
152 {
153         bool success = false;
154         unsigned int x = 0;
155         unsigned int y = 0;
156         for (const std::string &item : items) {
157                 // Is this an actual item?
158                 if (!item.empty()) {
159                         if (!success) {
160                                 // This is the first nonempty item
161                                 min_x = max_x = x;
162                                 min_y = max_y = y;
163                                 success = true;
164                         } else {
165                                 if (x < min_x) min_x = x;
166                                 if (x > max_x) max_x = x;
167                                 if (y < min_y) min_y = y;
168                                 if (y > max_y) max_y = y;
169                         }
170                 }
171
172                 // Step coordinate
173                 x++;
174                 if (x == width) {
175                         x = 0;
176                         y++;
177                 }
178         }
179         return success;
180 }
181
182 // Removes 1 from each item stack
183 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
184 {
185         for (auto &item : input.items) {
186                 if (item.count != 0)
187                         item.remove(1);
188         }
189 }
190
191 // Removes 1 from each item stack with replacement support
192 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
193 //   a water bucket will not be removed but replaced by an empty bucket.
194 static void craftDecrementOrReplaceInput(CraftInput &input,
195                 std::vector<ItemStack> &output_replacements,
196                 const CraftReplacements &replacements,
197                 IGameDef *gamedef)
198 {
199         if (replacements.pairs.empty()) {
200                 craftDecrementInput(input, gamedef);
201                 return;
202         }
203
204         // Make a copy of the replacements pair list
205         std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
206
207         for (auto &item : input.items) {
208                 // Find an appropriate replacement
209                 bool found_replacement = false;
210                 for (auto j = pairs.begin(); j != pairs.end(); ++j) {
211                         if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) {
212                                 if (item.count == 1) {
213                                         item.deSerialize(j->second, gamedef->idef());
214                                         found_replacement = true;
215                                         pairs.erase(j);
216                                         break;
217                                 }
218
219                                 ItemStack rep;
220                                 rep.deSerialize(j->second, gamedef->idef());
221                                 item.remove(1);
222                                 found_replacement = true;
223                                 output_replacements.push_back(rep);
224                                 break;
225
226                         }
227                 }
228                 // No replacement was found, simply decrement count by one
229                 if (!found_replacement && item.count > 0)
230                         item.remove(1);
231         }
232 }
233
234 // Dump an itemstring matrix
235 static std::string craftDumpMatrix(const std::vector<std::string> &items,
236                 unsigned int width)
237 {
238         std::ostringstream os(std::ios::binary);
239         os << "{ ";
240         unsigned int x = 0;
241         for(std::vector<std::string>::size_type i = 0;
242                         i < items.size(); i++, x++) {
243                 if (x == width) {
244                         os << "; ";
245                         x = 0;
246                 } else if (x != 0) {
247                         os << ",";
248                 }
249                 os << '"' << items[i] << '"';
250         }
251         os << " }";
252         return os.str();
253 }
254
255 // Dump an item matrix
256 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
257                 unsigned int width)
258 {
259         std::ostringstream os(std::ios::binary);
260         os << "{ ";
261         unsigned int x = 0;
262         for (std::vector<ItemStack>::size_type i = 0;
263                         i < items.size(); i++, x++) {
264                 if (x == width) {
265                         os << "; ";
266                         x = 0;
267                 } else if (x != 0) {
268                         os << ",";
269                 }
270                 os << '"' << (items[i].getItemString()) << '"';
271         }
272         os << " }";
273         return os.str();
274 }
275
276
277 /*
278         CraftInput
279 */
280
281 std::string CraftInput::dump() const
282 {
283         std::ostringstream os(std::ios::binary);
284         os << "(method=" << ((int)method) << ", items="
285                 << craftDumpMatrix(items, width) << ")";
286         return os.str();
287 }
288
289 /*
290         CraftOutput
291 */
292
293 std::string CraftOutput::dump() const
294 {
295         std::ostringstream os(std::ios::binary);
296         os << "(item=\"" << item << "\", time=" << time << ")";
297         return os.str();
298 }
299
300 /*
301         CraftReplacements
302 */
303
304 std::string CraftReplacements::dump() const
305 {
306         std::ostringstream os(std::ios::binary);
307         os<<"{";
308         const char *sep = "";
309         for (const auto &repl_p : pairs) {
310                 os << sep
311                         << '"' << (repl_p.first)
312                         << "\"=>\"" << (repl_p.second) << '"';
313                 sep = ",";
314         }
315         os << "}";
316         return os.str();
317 }
318
319 /*
320         CraftDefinitionShaped
321 */
322
323 std::string CraftDefinitionShaped::getName() const
324 {
325         return "shaped";
326 }
327
328 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
329 {
330         if (input.method != CRAFT_METHOD_NORMAL)
331                 return false;
332
333         // Get input item matrix
334         std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
335         unsigned int inp_width = input.width;
336         if (inp_width == 0)
337                 return false;
338         while (inp_names.size() % inp_width != 0)
339                 inp_names.emplace_back("");
340
341         // Get input bounds
342         unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
343         if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
344                         inp_min_y, inp_max_y))
345                 return false;  // it was empty
346
347         std::vector<std::string> rec_names;
348         if (hash_inited)
349                 rec_names = recipe_names;
350         else
351                 rec_names = craftGetItemNames(recipe, gamedef);
352
353         // Get recipe item matrix
354         unsigned int rec_width = width;
355         if (rec_width == 0)
356                 return false;
357         while (rec_names.size() % rec_width != 0)
358                 rec_names.emplace_back("");
359
360         // Get recipe bounds
361         unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
362         if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
363                         rec_min_y, rec_max_y))
364                 return false;  // it was empty
365
366         // Different sizes?
367         if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
368                         inp_max_y - inp_min_y != rec_max_y - rec_min_y)
369                 return false;
370
371         // Verify that all item names in the bounding box are equal
372         unsigned int w = inp_max_x - inp_min_x + 1;
373         unsigned int h = inp_max_y - inp_min_y + 1;
374
375         for (unsigned int y=0; y < h; y++) {
376                 unsigned int inp_y = (inp_min_y + y) * inp_width;
377                 unsigned int rec_y = (rec_min_y + y) * rec_width;
378
379                 for (unsigned int x=0; x < w; x++) {
380                         unsigned int inp_x = inp_min_x + x;
381                         unsigned int rec_x = rec_min_x + x;
382
383                         if (!inputItemMatchesRecipe(
384                                         inp_names[inp_y + inp_x],
385                                         rec_names[rec_y + rec_x], gamedef->idef())) {
386                                 return false;
387                         }
388                 }
389         }
390
391         return true;
392 }
393
394 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
395 {
396         return CraftOutput(output, 0);
397 }
398
399 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
400 {
401         return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
402 }
403
404 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
405          IGameDef *gamedef) const
406 {
407         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
408 }
409
410 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
411 {
412         assert(hash_inited); // Pre-condition
413         assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
414                 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
415
416         std::vector<std::string> rec_names = recipe_names;
417         std::sort(rec_names.begin(), rec_names.end());
418         return getHashForGrid(type, rec_names);
419 }
420
421 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
422 {
423         if (hash_inited)
424                 return;
425         hash_inited = true;
426         recipe_names = craftGetItemNames(recipe, gamedef);
427
428         bool has_group = false;
429         for (const auto &recipe_name : recipe_names) {
430                 if (isGroupRecipeStr(recipe_name)) {
431                         has_group = true;
432                         break;
433                 }
434         }
435         hash_type = has_group ? CRAFT_HASH_TYPE_COUNT : CRAFT_HASH_TYPE_ITEM_NAMES;
436 }
437
438 std::string CraftDefinitionShaped::dump() const
439 {
440         std::ostringstream os(std::ios::binary);
441         os << "(shaped, output=\"" << output
442                 << "\", recipe=" << craftDumpMatrix(recipe, width)
443                 << ", replacements=" << replacements.dump() << ")";
444         return os.str();
445 }
446
447 /*
448         CraftDefinitionShapeless
449 */
450
451 std::string CraftDefinitionShapeless::getName() const
452 {
453         return "shapeless";
454 }
455
456 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
457 {
458         if (input.method != CRAFT_METHOD_NORMAL)
459                 return false;
460
461         // Filter empty items out of input
462         std::vector<std::string> input_filtered;
463         for (const auto &item : input.items) {
464                 if (!item.name.empty())
465                         input_filtered.push_back(item.name);
466         }
467
468         // If there is a wrong number of items in input, no match
469         if (input_filtered.size() != recipe.size()) {
470                 /*dstream<<"Number of input items ("<<input_filtered.size()
471                                 <<") does not match recipe size ("<<recipe.size()<<") "
472                                 <<"of recipe with output="<<output<<std::endl;*/
473                 return false;
474         }
475
476         std::vector<std::string> recipe_copy;
477         if (hash_inited)
478                 recipe_copy = recipe_names;
479         else {
480                 recipe_copy = craftGetItemNames(recipe, gamedef);
481                 std::sort(recipe_copy.begin(), recipe_copy.end());
482         }
483
484         // Try with all permutations of the recipe,
485         // start from the lexicographically first permutation (=sorted),
486         // recipe_names is pre-sorted
487         do {
488                 // If all items match, the recipe matches
489                 bool all_match = true;
490                 //dstream<<"Testing recipe (output="<<output<<"):";
491                 for (size_t i=0; i<recipe.size(); i++) {
492                         //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
493                         if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
494                                         gamedef->idef())) {
495                                 all_match = false;
496                                 break;
497                         }
498                 }
499                 //dstream<<" -> match="<<all_match<<std::endl;
500                 if (all_match)
501                         return true;
502         } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
503
504         return false;
505 }
506
507 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
508 {
509         return CraftOutput(output, 0);
510 }
511
512 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
513 {
514         return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
515 }
516
517 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
518         IGameDef *gamedef) const
519 {
520         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
521 }
522
523 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
524 {
525         assert(hash_inited); // Pre-condition
526         assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
527                 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
528         return getHashForGrid(type, recipe_names);
529 }
530
531 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
532 {
533         if (hash_inited)
534                 return;
535         hash_inited = true;
536         recipe_names = craftGetItemNames(recipe, gamedef);
537         std::sort(recipe_names.begin(), recipe_names.end());
538
539         bool has_group = false;
540         for (const auto &recipe_name : recipe_names) {
541                 if (isGroupRecipeStr(recipe_name)) {
542                         has_group = true;
543                         break;
544                 }
545         }
546         hash_type = has_group ? CRAFT_HASH_TYPE_COUNT : CRAFT_HASH_TYPE_ITEM_NAMES;
547 }
548
549 std::string CraftDefinitionShapeless::dump() const
550 {
551         std::ostringstream os(std::ios::binary);
552         os << "(shapeless, output=\"" << output
553                 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
554                 << ", replacements=" << replacements.dump() << ")";
555         return os.str();
556 }
557
558 /*
559         CraftDefinitionToolRepair
560 */
561
562 static ItemStack craftToolRepair(
563                 const ItemStack &item1,
564                 const ItemStack &item2,
565                 float additional_wear,
566                 IGameDef *gamedef)
567 {
568         IItemDefManager *idef = gamedef->idef();
569         if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
570                         || idef->get(item1.name).type != ITEM_TOOL
571                         || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
572                 // Failure
573                 return ItemStack();
574         }
575
576         s32 item1_uses = 65536 - (u32) item1.wear;
577         s32 item2_uses = 65536 - (u32) item2.wear;
578         s32 new_uses = item1_uses + item2_uses;
579         s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
580         if (new_wear >= 65536)
581                 return ItemStack();
582         if (new_wear < 0)
583                 new_wear = 0;
584
585         ItemStack repaired = item1;
586         repaired.wear = new_wear;
587         return repaired;
588 }
589
590 std::string CraftDefinitionToolRepair::getName() const
591 {
592         return "toolrepair";
593 }
594
595 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
596 {
597         if (input.method != CRAFT_METHOD_NORMAL)
598                 return false;
599
600         ItemStack item1;
601         ItemStack item2;
602         for (const auto &item : input.items) {
603                 if (!item.empty()) {
604                         if (item1.empty())
605                                 item1 = item;
606                         else if (item2.empty())
607                                 item2 = item;
608                         else
609                                 return false;
610                 }
611         }
612         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
613         return !repaired.empty();
614 }
615
616 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
617 {
618         ItemStack item1;
619         ItemStack item2;
620         for (const auto &item : input.items) {
621                 if (!item.empty()) {
622                         if (item1.empty())
623                                 item1 = item;
624                         else if (item2.empty())
625                                 item2 = item;
626                 }
627         }
628         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
629         return CraftOutput(repaired.getItemString(), 0);
630 }
631
632 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
633 {
634         std::vector<ItemStack> stack;
635         stack.emplace_back();
636         return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
637 }
638
639 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
640         IGameDef *gamedef) const
641 {
642         craftDecrementInput(input, gamedef);
643 }
644
645 std::string CraftDefinitionToolRepair::dump() const
646 {
647         std::ostringstream os(std::ios::binary);
648         os << "(toolrepair, additional_wear=" << additional_wear << ")";
649         return os.str();
650 }
651
652 /*
653         CraftDefinitionCooking
654 */
655
656 std::string CraftDefinitionCooking::getName() const
657 {
658         return "cooking";
659 }
660
661 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
662 {
663         if (input.method != CRAFT_METHOD_COOKING)
664                 return false;
665
666         // Filter empty items out of input
667         std::vector<std::string> input_filtered;
668         for (const auto &item : input.items) {
669                 const std::string &name = item.name;
670                 if (!name.empty())
671                         input_filtered.push_back(name);
672         }
673
674         // If there is a wrong number of items in input, no match
675         if (input_filtered.size() != 1) {
676                 /*dstream<<"Number of input items ("<<input_filtered.size()
677                                 <<") does not match recipe size (1) "
678                                 <<"of cooking recipe with output="<<output<<std::endl;*/
679                 return false;
680         }
681
682         // Check the single input item
683         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
684 }
685
686 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
687 {
688         return CraftOutput(output, cooktime);
689 }
690
691 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
692 {
693         std::vector<std::string> rec;
694         rec.push_back(recipe);
695         return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
696 }
697
698 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
699         IGameDef *gamedef) const
700 {
701         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
702 }
703
704 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
705 {
706         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
707                 return getHashForString(recipe_name);
708         }
709
710         if (type == CRAFT_HASH_TYPE_COUNT) {
711                 return 1;
712         }
713
714         // illegal hash type for this CraftDefinition (pre-condition)
715         assert(false);
716         return 0;
717 }
718
719 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
720 {
721         if (hash_inited)
722                 return;
723         hash_inited = true;
724         recipe_name = craftGetItemName(recipe, gamedef);
725
726         if (isGroupRecipeStr(recipe_name))
727                 hash_type = CRAFT_HASH_TYPE_COUNT;
728         else
729                 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
730 }
731
732 std::string CraftDefinitionCooking::dump() const
733 {
734         std::ostringstream os(std::ios::binary);
735         os << "(cooking, output=\"" << output
736                 << "\", recipe=\"" << recipe
737                 << "\", cooktime=" << cooktime << ")"
738                 << ", replacements=" << replacements.dump() << ")";
739         return os.str();
740 }
741
742 /*
743         CraftDefinitionFuel
744 */
745
746 std::string CraftDefinitionFuel::getName() const
747 {
748         return "fuel";
749 }
750
751 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
752 {
753         if (input.method != CRAFT_METHOD_FUEL)
754                 return false;
755
756         // Filter empty items out of input
757         std::vector<std::string> input_filtered;
758         for (const auto &item : input.items) {
759                 const std::string &name = item.name;
760                 if (!name.empty())
761                         input_filtered.push_back(name);
762         }
763
764         // If there is a wrong number of items in input, no match
765         if (input_filtered.size() != 1) {
766                 /*dstream<<"Number of input items ("<<input_filtered.size()
767                                 <<") does not match recipe size (1) "
768                                 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
769                 return false;
770         }
771
772         // Check the single input item
773         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
774 }
775
776 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
777 {
778         return CraftOutput("", burntime);
779 }
780
781 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
782 {
783         std::vector<std::string> rec;
784         rec.push_back(recipe);
785         return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
786 }
787
788 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
789         IGameDef *gamedef) const
790 {
791         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
792 }
793
794 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
795 {
796         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
797                 return getHashForString(recipe_name);
798         }
799
800         if (type == CRAFT_HASH_TYPE_COUNT) {
801                 return 1;
802         }
803
804         // illegal hash type for this CraftDefinition (pre-condition)
805         assert(false);
806         return 0;
807 }
808
809 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
810 {
811         if (hash_inited)
812                 return;
813         hash_inited = true;
814         recipe_name = craftGetItemName(recipe, gamedef);
815
816         if (isGroupRecipeStr(recipe_name))
817                 hash_type = CRAFT_HASH_TYPE_COUNT;
818         else
819                 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
820 }
821
822 std::string CraftDefinitionFuel::dump() const
823 {
824         std::ostringstream os(std::ios::binary);
825         os << "(fuel, recipe=\"" << recipe
826                 << "\", burntime=" << burntime << ")"
827                 << ", replacements=" << replacements.dump() << ")";
828         return os.str();
829 }
830
831 /*
832         Craft definition manager
833 */
834
835 class CCraftDefManager: public IWritableCraftDefManager
836 {
837 public:
838         CCraftDefManager()
839         {
840                 m_craft_defs.resize(craft_hash_type_max + 1);
841         }
842
843         virtual ~CCraftDefManager()
844         {
845                 clear();
846         }
847
848         virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
849                         std::vector<ItemStack> &output_replacement, bool decrementInput,
850                         IGameDef *gamedef) const
851         {
852                 output.item = "";
853                 output.time = 0;
854
855                 // If all input items are empty, abort.
856                 bool all_empty = true;
857                 for (const auto &item : input.items) {
858                         if (!item.empty()) {
859                                 all_empty = false;
860                                 break;
861                         }
862                 }
863                 if (all_empty)
864                         return false;
865
866                 std::vector<std::string> input_names;
867                 input_names = craftGetItemNames(input.items, gamedef);
868                 std::sort(input_names.begin(), input_names.end());
869
870                 // Try hash types with increasing collision rate, and return if found.
871                 for (int type = 0; type <= craft_hash_type_max; type++) {
872                         u64 hash = getHashForGrid((CraftHashType) type, input_names);
873
874                         /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
875
876                         // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
877                         // but that doesn't compile for some reason. This does.
878                         auto col_iter = (m_craft_defs[type]).find(hash);
879
880                         if (col_iter == (m_craft_defs[type]).end())
881                                 continue;
882
883                         const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
884                         // Walk crafting definitions from back to front, so that later
885                         // definitions can override earlier ones.
886                         for (std::vector<CraftDefinition*>::size_type
887                                         i = hash_collisions.size(); i > 0; i--) {
888                                 CraftDefinition *def = hash_collisions[i - 1];
889
890                                 /*errorstream << "Checking " << input.dump() << std::endl
891                                         << " against " << def->dump() << std::endl;*/
892
893                                 if (def->check(input, gamedef)) {
894                                         // Check if the crafted node/item exists
895                                         CraftOutput out = def->getOutput(input, gamedef);
896                                         ItemStack is;
897                                         is.deSerialize(out.item, gamedef->idef());
898                                         if (!is.isKnown(gamedef->idef())) {
899                                                 infostream << "trying to craft non-existent "
900                                                         << out.item << ", ignoring recipe" << std::endl;
901                                                 continue;
902                                         }
903
904                                         // Get output, then decrement input (if requested)
905                                         output = out;
906
907                                         if (decrementInput)
908                                                 def->decrementInput(input, output_replacement, gamedef);
909                                         /*errorstream << "Check RETURNS TRUE" << std::endl;*/
910                                         return true;
911                                 }
912                         }
913                 }
914                 return false;
915         }
916
917         virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
918                         IGameDef *gamedef, unsigned limit=0) const
919         {
920                 std::vector<CraftDefinition*> recipes;
921
922                 auto vec_iter = m_output_craft_definitions.find(output.item);
923
924                 if (vec_iter == m_output_craft_definitions.end())
925                         return recipes;
926
927                 const std::vector<CraftDefinition*> &vec = vec_iter->second;
928
929                 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
930
931                 for (std::vector<CraftDefinition*>::size_type i = vec.size();
932                                 i > 0; i--) {
933                         CraftDefinition *def = vec[i - 1];
934                         if (limit && recipes.size() >= limit)
935                                 break;
936                         recipes.push_back(def);
937                 }
938
939                 return recipes;
940         }
941
942         virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef)
943         {
944                 auto vec_iter = m_output_craft_definitions.find(output.item);
945
946                 if (vec_iter == m_output_craft_definitions.end())
947                         return false;
948
949                 std::vector<CraftDefinition*> &vec = vec_iter->second;
950                 for (auto def : vec) {
951                         // Recipes are not yet hashed at this point
952                         std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
953                         std::vector<CraftDefinition*> new_vec_by_input;
954                         /* We will preallocate necessary memory addresses, so we don't need to reallocate them later.
955                                 This would save us some performance. */
956                         new_vec_by_input.reserve(unhashed_inputs_vec.size());
957                         for (auto &i2 : unhashed_inputs_vec) {
958                                 if (def != i2) {
959                                         new_vec_by_input.push_back(i2);
960                                 }
961                         }
962                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
963                 }
964                 m_output_craft_definitions.erase(output.item);
965                 return true;
966         }
967
968         virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width,
969                 const std::vector<std::string> &recipe, IGameDef *gamedef)
970         {
971                 bool all_empty = true;
972                 for (const auto &i : recipe) {
973                         if (!i.empty()) {
974                                 all_empty = false;
975                                 break;
976                         }
977                 }
978                 if (all_empty)
979                         return false;
980
981                 CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef));
982                 // Recipes are not yet hashed at this point
983                 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
984                 std::vector<CraftDefinition*> new_vec_by_input;
985                 bool got_hit = false;
986                 for (std::vector<CraftDefinition*>::size_type
987                                 i = unhashed_inputs_vec.size(); i > 0; i--) {
988                         CraftDefinition *def = unhashed_inputs_vec[i - 1];
989                         /* If the input doesn't match the recipe definition, this recipe definition later
990                                 will be added back in source map. */
991                         if (!def->check(input, gamedef)) {
992                                 new_vec_by_input.push_back(def);
993                                 continue;
994                         }
995                         CraftOutput output = def->getOutput(input, gamedef);
996                         got_hit = true;
997                         auto vec_iter = m_output_craft_definitions.find(output.item);
998                         if (vec_iter == m_output_craft_definitions.end())
999                                 continue;
1000                         std::vector<CraftDefinition*> &vec = vec_iter->second;
1001                         std::vector<CraftDefinition*> new_vec_by_output;
1002                         /* We will preallocate necessary memory addresses, so we don't need
1003                                 to reallocate them later. This would save us some performance. */
1004                         new_vec_by_output.reserve(vec.size());
1005                         for (auto &vec_i : vec) {
1006                                 /* If pointers from map by input and output are not same,
1007                                         we will add 'CraftDefinition*' to a new vector. */
1008                                 if (def != vec_i) {
1009                                         /* Adding dereferenced iterator value (which are
1010                                                 'CraftDefinition' reference) to a new vector. */
1011                                         new_vec_by_output.push_back(vec_i);
1012                                 }
1013                         }
1014                         // Swaps assigned to current key value with new vector for output map.
1015                         m_output_craft_definitions[output.item].swap(new_vec_by_output);
1016                 }
1017                 if (got_hit)
1018                         // Swaps value with new vector for input map.
1019                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1020
1021                 return got_hit;
1022         }
1023
1024         virtual std::string dump() const
1025         {
1026                 std::ostringstream os(std::ios::binary);
1027                 os << "Crafting definitions:\n";
1028                 for (int type = 0; type <= craft_hash_type_max; ++type) {
1029                         for (auto it = m_craft_defs[type].begin();
1030                                         it != m_craft_defs[type].end(); ++it) {
1031                                 for (std::vector<CraftDefinition*>::size_type i = 0;
1032                                                 i < it->second.size(); i++) {
1033                                         os << "type " << type
1034                                                 << " hash " << it->first
1035                                                 << " def " << it->second[i]->dump()
1036                                                 << "\n";
1037                                 }
1038                         }
1039                 }
1040                 return os.str();
1041         }
1042         virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1043         {
1044                 verbosestream << "registerCraft: registering craft definition: "
1045                                 << def->dump() << std::endl;
1046                 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1047
1048                 CraftInput input;
1049                 std::string output_name = craftGetItemName(
1050                                 def->getOutput(input, gamedef).item, gamedef);
1051                 m_output_craft_definitions[output_name].push_back(def);
1052         }
1053         virtual void clear()
1054         {
1055                 for (int type = 0; type <= craft_hash_type_max; ++type) {
1056                         for (auto &it : m_craft_defs[type]) {
1057                                 for (auto &iit : it.second) {
1058                                         delete iit;
1059                                 }
1060                                 it.second.clear();
1061                         }
1062                         m_craft_defs[type].clear();
1063                 }
1064                 m_output_craft_definitions.clear();
1065         }
1066         virtual void initHashes(IGameDef *gamedef)
1067         {
1068                 // Move the CraftDefs from the unhashed layer into layers higher up.
1069                 std::vector<CraftDefinition *> &unhashed =
1070                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1071                 for (auto def : unhashed) {
1072                         // Initialize and get the definition's hash
1073                         def->initHash(gamedef);
1074                         CraftHashType type = def->getHashType();
1075                         u64 hash = def->getHash(type);
1076
1077                         // Enter the definition
1078                         m_craft_defs[type][hash].push_back(def);
1079                 }
1080                 unhashed.clear();
1081         }
1082 private:
1083         std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > >
1084                 m_craft_defs;
1085         std::unordered_map<std::string, std::vector<CraftDefinition*> >
1086                 m_output_craft_definitions;
1087 };
1088
1089 IWritableCraftDefManager* createCraftDefManager()
1090 {
1091         return new CCraftDefManager();
1092 }