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