3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #include "irrlichttypes.h"
25 #include <unordered_set>
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"
35 inline bool isGroupRecipeStr(const std::string &rec_name)
37 return str_starts_with(rec_name, std::string("group:"));
40 static bool hasGroupItem(const std::vector<std::string> &recipe)
42 for (const auto &item : recipe) {
43 if (isGroupRecipeStr(item))
49 inline u64 getHashForString(const std::string &recipe_str)
51 /*errorstream << "Hashing craft string \"" << recipe_str << '"';*/
52 return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef);
55 static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names)
58 case CRAFT_HASH_TYPE_ITEM_NAMES: {
59 std::ostringstream os;
61 for (const std::string &grid_name : grid_names) {
62 if (!grid_name.empty()) {
63 os << (is_first ? "" : "\n") << grid_name;
67 return getHashForString(os.str());
68 } case CRAFT_HASH_TYPE_COUNT: {
70 for (const std::string &grid_name : grid_names)
71 if (!grid_name.empty())
74 } case CRAFT_HASH_TYPE_UNHASHED:
77 // invalid CraftHashType
82 // Check if input matches recipe
83 // Takes recipe groups into account
84 static bool inputItemMatchesRecipe(const std::string &inp_name,
85 const std::string &rec_name, IItemDefManager *idef)
88 if (inp_name == rec_name)
92 if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) {
93 const struct ItemDefinition &def = idef->get(inp_name);
94 Strfnd f(rec_name.substr(6));
95 bool all_groups_match = true;
97 std::string check_group = f.next(",");
98 if (itemgroup_get(def.groups, check_group) == 0) {
99 all_groups_match = false;
102 } while (!f.at_end());
103 if (all_groups_match)
111 // Deserialize an itemstring then return the name of the item
112 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
115 item.deSerialize(itemstring, gamedef->idef());
119 // (mapcar craftGetItemName itemstrings)
120 static std::vector<std::string> craftGetItemNames(
121 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
123 std::vector<std::string> result;
124 result.reserve(itemstrings.size());
125 for (const auto &itemstring : itemstrings) {
126 result.push_back(craftGetItemName(itemstring, gamedef));
131 // Get name of each item, and return them as a new list.
132 static std::vector<std::string> craftGetItemNames(
133 const std::vector<ItemStack> &items, IGameDef *gamedef)
135 std::vector<std::string> result;
136 result.reserve(items.size());
137 for (const auto &item : items) {
138 result.push_back(item.name);
143 // convert a list of item names, to ItemStacks.
144 static std::vector<ItemStack> craftGetItems(
145 const std::vector<std::string> &items, IGameDef *gamedef)
147 std::vector<ItemStack> result;
148 result.reserve(items.size());
149 for (const auto &item : items) {
150 result.emplace_back(std::string(item), (u16)1,
151 (u16)0, gamedef->getItemDefManager());
156 // Compute bounding rectangle given a matrix of items
157 // Returns false if every item is ""
158 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
159 unsigned int &min_x, unsigned int &max_x,
160 unsigned int &min_y, unsigned int &max_y)
162 bool success = false;
165 for (const std::string &item : items) {
166 // Is this an actual item?
169 // This is the first nonempty item
174 if (x < min_x) min_x = x;
175 if (x > max_x) max_x = x;
176 if (y < min_y) min_y = y;
177 if (y > max_y) max_y = y;
191 // Removes 1 from each item stack
192 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
194 for (auto &item : input.items) {
200 // Removes 1 from each item stack with replacement support
201 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
202 // a water bucket will not be removed but replaced by an empty bucket.
203 static void craftDecrementOrReplaceInput(CraftInput &input,
204 std::vector<ItemStack> &output_replacements,
205 const CraftReplacements &replacements,
208 if (replacements.pairs.empty()) {
209 craftDecrementInput(input, gamedef);
213 // Make a copy of the replacements pair list
214 std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
216 for (auto &item : input.items) {
217 // Find an appropriate replacement
218 bool found_replacement = false;
219 for (auto j = pairs.begin(); j != pairs.end(); ++j) {
220 if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) {
221 if (item.count == 1) {
222 item.deSerialize(j->second, gamedef->idef());
223 found_replacement = true;
229 rep.deSerialize(j->second, gamedef->idef());
231 found_replacement = true;
233 output_replacements.push_back(rep);
238 // No replacement was found, simply decrement count by one
239 if (!found_replacement && item.count > 0)
244 // Dump an itemstring matrix
245 static std::string craftDumpMatrix(const std::vector<std::string> &items,
248 std::ostringstream os(std::ios::binary);
251 for(std::vector<std::string>::size_type i = 0;
252 i < items.size(); i++, x++) {
259 os << '"' << items[i] << '"';
265 // Dump an item matrix
266 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
269 std::ostringstream os(std::ios::binary);
272 for (std::vector<ItemStack>::size_type i = 0;
273 i < items.size(); i++, x++) {
280 os << '"' << (items[i].getItemString()) << '"';
291 bool CraftInput::empty() const
293 for (const auto &item : items) {
300 std::string CraftInput::dump() const
302 std::ostringstream os(std::ios::binary);
303 os << "(method=" << ((int)method) << ", items="
304 << craftDumpMatrix(items, width) << ")";
312 std::string CraftOutput::dump() const
314 std::ostringstream os(std::ios::binary);
315 os << "(item=\"" << item << "\", time=" << time << ")";
323 std::string CraftReplacements::dump() const
325 std::ostringstream os(std::ios::binary);
327 const char *sep = "";
328 for (const auto &repl_p : pairs) {
330 << '"' << (repl_p.first)
331 << "\"=>\"" << (repl_p.second) << '"';
339 CraftDefinitionShaped
342 CraftDefinitionShaped::CraftDefinitionShaped(
343 const std::string &output_,
345 const std::vector<std::string> &recipe_,
346 const CraftReplacements &replacements_):
347 output(output_), width(width_), recipe(recipe_), replacements(replacements_)
349 if (hasGroupItem(recipe))
350 priority = PRIORITY_SHAPED_AND_GROUPS;
352 priority = PRIORITY_SHAPED;
355 std::string CraftDefinitionShaped::getName() const
360 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
362 if (input.method != CRAFT_METHOD_NORMAL)
365 // Get input item matrix
366 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
367 unsigned int inp_width = input.width;
370 while (inp_names.size() % inp_width != 0)
371 inp_names.emplace_back("");
374 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
375 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
376 inp_min_y, inp_max_y))
377 return false; // it was empty
379 std::vector<std::string> rec_names;
381 rec_names = recipe_names;
383 rec_names = craftGetItemNames(recipe, gamedef);
385 // Get recipe item matrix
386 unsigned int rec_width = width;
389 while (rec_names.size() % rec_width != 0)
390 rec_names.emplace_back("");
393 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
394 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
395 rec_min_y, rec_max_y))
396 return false; // it was empty
399 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
400 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
403 // Verify that all item names in the bounding box are equal
404 unsigned int w = inp_max_x - inp_min_x + 1;
405 unsigned int h = inp_max_y - inp_min_y + 1;
407 for (unsigned int y=0; y < h; y++) {
408 unsigned int inp_y = (inp_min_y + y) * inp_width;
409 unsigned int rec_y = (rec_min_y + y) * rec_width;
411 for (unsigned int x=0; x < w; x++) {
412 unsigned int inp_x = inp_min_x + x;
413 unsigned int rec_x = rec_min_x + x;
415 if (!inputItemMatchesRecipe(
416 inp_names[inp_y + inp_x],
417 rec_names[rec_y + rec_x], gamedef->idef())) {
426 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
428 return CraftOutput(output, 0);
431 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
433 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
436 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
437 IGameDef *gamedef) const
439 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
442 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
444 assert(hash_inited); // Pre-condition
445 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
446 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
448 std::vector<std::string> rec_names = recipe_names;
449 std::sort(rec_names.begin(), rec_names.end());
450 return getHashForGrid(type, rec_names);
453 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
458 recipe_names = craftGetItemNames(recipe, gamedef);
460 if (hasGroupItem(recipe_names))
461 hash_type = CRAFT_HASH_TYPE_COUNT;
463 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
466 std::string CraftDefinitionShaped::dump() const
468 std::ostringstream os(std::ios::binary);
469 os << "(shaped, output=\"" << output
470 << "\", recipe=" << craftDumpMatrix(recipe, width)
471 << ", replacements=" << replacements.dump() << ")";
476 CraftDefinitionShapeless
479 CraftDefinitionShapeless::CraftDefinitionShapeless(
480 const std::string &output_,
481 const std::vector<std::string> &recipe_,
482 const CraftReplacements &replacements_):
483 output(output_), recipe(recipe_), replacements(replacements_)
485 if (hasGroupItem(recipe))
486 priority = PRIORITY_SHAPELESS_AND_GROUPS;
488 priority = PRIORITY_SHAPELESS;
491 std::string CraftDefinitionShapeless::getName() const
496 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
498 if (input.method != CRAFT_METHOD_NORMAL)
501 // Filter empty items out of input
502 std::vector<std::string> input_filtered;
503 for (const auto &item : input.items) {
504 if (!item.name.empty())
505 input_filtered.push_back(item.name);
508 // If there is a wrong number of items in input, no match
509 if (input_filtered.size() != recipe.size()) {
510 /*dstream<<"Number of input items ("<<input_filtered.size()
511 <<") does not match recipe size ("<<recipe.size()<<") "
512 <<"of recipe with output="<<output<<std::endl;*/
516 std::vector<std::string> recipe_copy;
518 recipe_copy = recipe_names;
520 recipe_copy = craftGetItemNames(recipe, gamedef);
521 std::sort(recipe_copy.begin(), recipe_copy.end());
524 // Try with all permutations of the recipe,
525 // start from the lexicographically first permutation (=sorted),
526 // recipe_names is pre-sorted
528 // If all items match, the recipe matches
529 bool all_match = true;
530 //dstream<<"Testing recipe (output="<<output<<"):";
531 for (size_t i=0; i<recipe.size(); i++) {
532 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
533 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
539 //dstream<<" -> match="<<all_match<<std::endl;
542 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
547 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
549 return CraftOutput(output, 0);
552 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
554 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
557 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
558 IGameDef *gamedef) const
560 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
563 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
565 assert(hash_inited); // Pre-condition
566 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
567 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
568 return getHashForGrid(type, recipe_names);
571 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
576 recipe_names = craftGetItemNames(recipe, gamedef);
577 std::sort(recipe_names.begin(), recipe_names.end());
579 if (hasGroupItem(recipe_names))
580 hash_type = CRAFT_HASH_TYPE_COUNT;
582 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
585 std::string CraftDefinitionShapeless::dump() const
587 std::ostringstream os(std::ios::binary);
588 os << "(shapeless, output=\"" << output
589 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
590 << ", replacements=" << replacements.dump() << ")";
595 CraftDefinitionToolRepair
598 CraftDefinitionToolRepair::CraftDefinitionToolRepair(float additional_wear_):
599 additional_wear(additional_wear_)
601 priority = PRIORITY_TOOLREPAIR;
604 static ItemStack craftToolRepair(
605 const ItemStack &item1,
606 const ItemStack &item2,
607 float additional_wear,
610 IItemDefManager *idef = gamedef->idef();
611 if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
612 || idef->get(item1.name).type != ITEM_TOOL
613 || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
618 s32 item1_uses = 65536 - (u32) item1.wear;
619 s32 item2_uses = 65536 - (u32) item2.wear;
620 s32 new_uses = item1_uses + item2_uses;
621 s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
622 if (new_wear >= 65536)
627 ItemStack repaired = item1;
628 repaired.wear = new_wear;
632 std::string CraftDefinitionToolRepair::getName() const
637 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
639 if (input.method != CRAFT_METHOD_NORMAL)
644 for (const auto &item : input.items) {
648 else if (item2.empty())
654 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
655 return !repaired.empty();
658 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
662 for (const auto &item : input.items) {
666 else if (item2.empty())
670 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
671 return CraftOutput(repaired.getItemString(), 0);
674 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
676 std::vector<ItemStack> stack;
677 stack.emplace_back();
678 return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
681 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
682 IGameDef *gamedef) const
684 craftDecrementInput(input, gamedef);
687 std::string CraftDefinitionToolRepair::dump() const
689 std::ostringstream os(std::ios::binary);
690 os << "(toolrepair, additional_wear=" << additional_wear << ")";
695 CraftDefinitionCooking
698 CraftDefinitionCooking::CraftDefinitionCooking(
699 const std::string &output_,
700 const std::string &recipe_,
702 const CraftReplacements &replacements_):
703 output(output_), recipe(recipe_), cooktime(cooktime_), replacements(replacements_)
705 if (isGroupRecipeStr(recipe))
706 priority = PRIORITY_SHAPELESS_AND_GROUPS;
708 priority = PRIORITY_SHAPELESS;
711 std::string CraftDefinitionCooking::getName() const
716 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
718 if (input.method != CRAFT_METHOD_COOKING)
721 // Filter empty items out of input
722 std::vector<std::string> input_filtered;
723 for (const auto &item : input.items) {
724 const std::string &name = item.name;
726 input_filtered.push_back(name);
729 // If there is a wrong number of items in input, no match
730 if (input_filtered.size() != 1) {
731 /*dstream<<"Number of input items ("<<input_filtered.size()
732 <<") does not match recipe size (1) "
733 <<"of cooking recipe with output="<<output<<std::endl;*/
737 // Check the single input item
738 std::string rec_name = craftGetItemName(recipe, gamedef);
739 return inputItemMatchesRecipe(input_filtered[0], rec_name, gamedef->idef());
742 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
744 return CraftOutput(output, cooktime);
747 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
749 std::vector<std::string> rec;
750 rec.push_back(recipe);
751 return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
754 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
755 IGameDef *gamedef) const
757 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
760 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
762 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
763 return getHashForString(recipe_name);
766 if (type == CRAFT_HASH_TYPE_COUNT) {
770 // illegal hash type for this CraftDefinition (pre-condition)
775 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
780 recipe_name = craftGetItemName(recipe, gamedef);
782 if (isGroupRecipeStr(recipe_name))
783 hash_type = CRAFT_HASH_TYPE_COUNT;
785 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
788 std::string CraftDefinitionCooking::dump() const
790 std::ostringstream os(std::ios::binary);
791 os << "(cooking, output=\"" << output
792 << "\", recipe=\"" << recipe
793 << "\", cooktime=" << cooktime << ")"
794 << ", replacements=" << replacements.dump() << ")";
802 CraftDefinitionFuel::CraftDefinitionFuel(
803 const std::string &recipe_,
805 const CraftReplacements &replacements_):
806 recipe(recipe_), burntime(burntime_), replacements(replacements_)
808 if (isGroupRecipeStr(recipe_name))
809 priority = PRIORITY_SHAPELESS_AND_GROUPS;
811 priority = PRIORITY_SHAPELESS;
814 std::string CraftDefinitionFuel::getName() const
819 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
821 if (input.method != CRAFT_METHOD_FUEL)
824 // Filter empty items out of input
825 std::vector<std::string> input_filtered;
826 for (const auto &item : input.items) {
827 const std::string &name = item.name;
829 input_filtered.push_back(name);
832 // If there is a wrong number of items in input, no match
833 if (input_filtered.size() != 1) {
834 /*dstream<<"Number of input items ("<<input_filtered.size()
835 <<") does not match recipe size (1) "
836 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
840 // Check the single input item
841 std::string rec_name = craftGetItemName(recipe, gamedef);
842 return inputItemMatchesRecipe(input_filtered[0], rec_name, gamedef->idef());
845 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
847 return CraftOutput("", burntime);
850 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
852 std::vector<std::string> rec;
853 rec.push_back(recipe);
854 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
857 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
858 IGameDef *gamedef) const
860 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
863 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
865 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
866 return getHashForString(recipe_name);
869 if (type == CRAFT_HASH_TYPE_COUNT) {
873 // illegal hash type for this CraftDefinition (pre-condition)
878 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
883 recipe_name = craftGetItemName(recipe, gamedef);
885 if (isGroupRecipeStr(recipe_name))
886 hash_type = CRAFT_HASH_TYPE_COUNT;
888 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
891 std::string CraftDefinitionFuel::dump() const
893 std::ostringstream os(std::ios::binary);
894 os << "(fuel, recipe=\"" << recipe
895 << "\", burntime=" << burntime << ")"
896 << ", replacements=" << replacements.dump() << ")";
901 Craft definition manager
904 class CCraftDefManager: public IWritableCraftDefManager
909 m_craft_defs.resize(craft_hash_type_max + 1);
912 virtual ~CCraftDefManager()
917 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
918 std::vector<ItemStack> &output_replacement, bool decrementInput,
919 IGameDef *gamedef) const
924 std::vector<std::string> input_names;
925 input_names = craftGetItemNames(input.items, gamedef);
926 std::sort(input_names.begin(), input_names.end());
928 // Try hash types with increasing collision rate
929 // while remembering the latest, highest priority recipe.
930 CraftDefinition::RecipePriority priority_best =
931 CraftDefinition::PRIORITY_NO_RECIPE;
932 CraftDefinition *def_best = nullptr;
933 for (int type = 0; type <= craft_hash_type_max; type++) {
934 u64 hash = getHashForGrid((CraftHashType) type, input_names);
936 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
938 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
939 // but that doesn't compile for some reason. This does.
940 auto col_iter = (m_craft_defs[type]).find(hash);
942 if (col_iter == (m_craft_defs[type]).end())
945 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
946 // Walk crafting definitions from back to front, so that later
947 // definitions can override earlier ones.
948 for (std::vector<CraftDefinition*>::size_type
949 i = hash_collisions.size(); i > 0; i--) {
950 CraftDefinition *def = hash_collisions[i - 1];
952 /*errorstream << "Checking " << input.dump() << std::endl
953 << " against " << def->dump() << std::endl;*/
955 CraftDefinition::RecipePriority priority = def->getPriority();
956 if (priority > priority_best
957 && def->check(input, gamedef)) {
958 // Check if the crafted node/item exists
959 CraftOutput out = def->getOutput(input, gamedef);
961 is.deSerialize(out.item, gamedef->idef());
962 if (!is.isKnown(gamedef->idef())) {
963 infostream << "trying to craft non-existent "
964 << out.item << ", ignoring recipe" << std::endl;
969 priority_best = priority;
974 if (priority_best == CraftDefinition::PRIORITY_NO_RECIPE)
977 def_best->decrementInput(input, output_replacement, gamedef);
981 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
982 IGameDef *gamedef, unsigned limit=0) const
984 std::vector<CraftDefinition*> recipes;
986 auto vec_iter = m_output_craft_definitions.find(output.item);
988 if (vec_iter == m_output_craft_definitions.end())
991 const std::vector<CraftDefinition*> &vec = vec_iter->second;
993 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
995 for (std::vector<CraftDefinition*>::size_type i = vec.size();
997 CraftDefinition *def = vec[i - 1];
998 if (limit && recipes.size() >= limit)
1000 recipes.push_back(def);
1006 virtual bool clearCraftsByOutput(const CraftOutput &output, IGameDef *gamedef)
1008 auto to_clear = m_output_craft_definitions.find(output.item);
1010 if (to_clear == m_output_craft_definitions.end())
1013 for (auto def : to_clear->second) {
1014 // Recipes are not yet hashed at this point
1015 std::vector<CraftDefinition *> &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0];
1016 defs.erase(std::remove(defs.begin(), defs.end(), def), defs.end());
1019 m_output_craft_definitions.erase(to_clear);
1023 virtual bool clearCraftsByInput(const CraftInput &input, IGameDef *gamedef)
1028 // Recipes are not yet hashed at this point
1029 std::vector<CraftDefinition *> &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0];
1030 std::unordered_set<const CraftDefinition *> defs_to_remove;
1031 std::vector<CraftDefinition *> new_defs;
1033 for (auto def : defs) {
1034 if (def->check(input, gamedef))
1035 defs_to_remove.insert(def);
1037 new_defs.push_back(def);
1040 if (!defs_to_remove.empty()) {
1041 for (auto def : defs_to_remove)
1044 defs.swap(new_defs);
1046 for (auto &output : m_output_craft_definitions) {
1047 std::vector<CraftDefinition *> &outdefs = output.second;
1048 outdefs.erase(std::remove_if(outdefs.begin(), outdefs.end(), [&](const CraftDefinition* def) {
1049 return defs_to_remove.find(def) != defs_to_remove.end();
1054 return !defs_to_remove.empty();
1057 virtual std::string dump() const
1059 std::ostringstream os(std::ios::binary);
1060 os << "Crafting definitions:\n";
1061 for (int type = 0; type <= craft_hash_type_max; ++type) {
1062 for (auto it = m_craft_defs[type].begin();
1063 it != m_craft_defs[type].end(); ++it) {
1064 for (std::vector<CraftDefinition*>::size_type i = 0;
1065 i < it->second.size(); i++) {
1066 os << "type " << type
1067 << " hash " << it->first
1068 << " def " << it->second[i]->dump()
1075 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1077 TRACESTREAM(<< "registerCraft: registering craft definition: "
1078 << def->dump() << std::endl);
1079 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1082 std::string output_name = craftGetItemName(
1083 def->getOutput(input, gamedef).item, gamedef);
1084 m_output_craft_definitions[output_name].push_back(def);
1086 virtual void clear()
1088 for (int type = 0; type <= craft_hash_type_max; ++type) {
1089 for (auto &it : m_craft_defs[type]) {
1090 for (auto &iit : it.second) {
1095 m_craft_defs[type].clear();
1097 m_output_craft_definitions.clear();
1099 virtual void initHashes(IGameDef *gamedef)
1101 // Move the CraftDefs from the unhashed layer into layers higher up.
1102 std::vector<CraftDefinition *> &unhashed =
1103 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1104 for (auto def : unhashed) {
1105 // Initialize and get the definition's hash
1106 def->initHash(gamedef);
1107 CraftHashType type = def->getHashType();
1108 u64 hash = def->getHash(type);
1110 // Enter the definition
1111 m_craft_defs[type][hash].push_back(def);
1116 std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > >
1118 std::unordered_map<std::string, std::vector<CraftDefinition*> >
1119 m_output_craft_definitions;
1122 IWritableCraftDefManager* createCraftDefManager()
1124 return new CCraftDefManager();