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