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"
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;
232 output_replacements.push_back(rep);
237 // No replacement was found, simply decrement count by one
238 if (!found_replacement && item.count > 0)
243 // Dump an itemstring matrix
244 static std::string craftDumpMatrix(const std::vector<std::string> &items,
247 std::ostringstream os(std::ios::binary);
250 for(std::vector<std::string>::size_type i = 0;
251 i < items.size(); i++, x++) {
258 os << '"' << items[i] << '"';
264 // Dump an item matrix
265 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
268 std::ostringstream os(std::ios::binary);
271 for (std::vector<ItemStack>::size_type i = 0;
272 i < items.size(); i++, x++) {
279 os << '"' << (items[i].getItemString()) << '"';
290 std::string CraftInput::dump() const
292 std::ostringstream os(std::ios::binary);
293 os << "(method=" << ((int)method) << ", items="
294 << craftDumpMatrix(items, width) << ")";
302 std::string CraftOutput::dump() const
304 std::ostringstream os(std::ios::binary);
305 os << "(item=\"" << item << "\", time=" << time << ")";
313 std::string CraftReplacements::dump() const
315 std::ostringstream os(std::ios::binary);
317 const char *sep = "";
318 for (const auto &repl_p : pairs) {
320 << '"' << (repl_p.first)
321 << "\"=>\"" << (repl_p.second) << '"';
329 CraftDefinitionShaped
332 CraftDefinitionShaped::CraftDefinitionShaped(
333 const std::string &output_,
335 const std::vector<std::string> &recipe_,
336 const CraftReplacements &replacements_):
337 output(output_), width(width_), recipe(recipe_), replacements(replacements_)
339 if (hasGroupItem(recipe))
340 priority = PRIORITY_SHAPED_AND_GROUPS;
342 priority = PRIORITY_SHAPED;
345 std::string CraftDefinitionShaped::getName() const
350 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
352 if (input.method != CRAFT_METHOD_NORMAL)
355 // Get input item matrix
356 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
357 unsigned int inp_width = input.width;
360 while (inp_names.size() % inp_width != 0)
361 inp_names.emplace_back("");
364 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
365 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
366 inp_min_y, inp_max_y))
367 return false; // it was empty
369 std::vector<std::string> rec_names;
371 rec_names = recipe_names;
373 rec_names = craftGetItemNames(recipe, gamedef);
375 // Get recipe item matrix
376 unsigned int rec_width = width;
379 while (rec_names.size() % rec_width != 0)
380 rec_names.emplace_back("");
383 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
384 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
385 rec_min_y, rec_max_y))
386 return false; // it was empty
389 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
390 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
393 // Verify that all item names in the bounding box are equal
394 unsigned int w = inp_max_x - inp_min_x + 1;
395 unsigned int h = inp_max_y - inp_min_y + 1;
397 for (unsigned int y=0; y < h; y++) {
398 unsigned int inp_y = (inp_min_y + y) * inp_width;
399 unsigned int rec_y = (rec_min_y + y) * rec_width;
401 for (unsigned int x=0; x < w; x++) {
402 unsigned int inp_x = inp_min_x + x;
403 unsigned int rec_x = rec_min_x + x;
405 if (!inputItemMatchesRecipe(
406 inp_names[inp_y + inp_x],
407 rec_names[rec_y + rec_x], gamedef->idef())) {
416 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
418 return CraftOutput(output, 0);
421 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
423 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
426 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
427 IGameDef *gamedef) const
429 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
432 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
434 assert(hash_inited); // Pre-condition
435 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
436 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
438 std::vector<std::string> rec_names = recipe_names;
439 std::sort(rec_names.begin(), rec_names.end());
440 return getHashForGrid(type, rec_names);
443 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
448 recipe_names = craftGetItemNames(recipe, gamedef);
450 if (hasGroupItem(recipe_names))
451 hash_type = CRAFT_HASH_TYPE_COUNT;
453 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
456 std::string CraftDefinitionShaped::dump() const
458 std::ostringstream os(std::ios::binary);
459 os << "(shaped, output=\"" << output
460 << "\", recipe=" << craftDumpMatrix(recipe, width)
461 << ", replacements=" << replacements.dump() << ")";
466 CraftDefinitionShapeless
469 CraftDefinitionShapeless::CraftDefinitionShapeless(
470 const std::string &output_,
471 const std::vector<std::string> &recipe_,
472 const CraftReplacements &replacements_):
473 output(output_), recipe(recipe_), replacements(replacements_)
475 if (hasGroupItem(recipe))
476 priority = PRIORITY_SHAPELESS_AND_GROUPS;
478 priority = PRIORITY_SHAPELESS;
481 std::string CraftDefinitionShapeless::getName() const
486 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
488 if (input.method != CRAFT_METHOD_NORMAL)
491 // Filter empty items out of input
492 std::vector<std::string> input_filtered;
493 for (const auto &item : input.items) {
494 if (!item.name.empty())
495 input_filtered.push_back(item.name);
498 // If there is a wrong number of items in input, no match
499 if (input_filtered.size() != recipe.size()) {
500 /*dstream<<"Number of input items ("<<input_filtered.size()
501 <<") does not match recipe size ("<<recipe.size()<<") "
502 <<"of recipe with output="<<output<<std::endl;*/
506 std::vector<std::string> recipe_copy;
508 recipe_copy = recipe_names;
510 recipe_copy = craftGetItemNames(recipe, gamedef);
511 std::sort(recipe_copy.begin(), recipe_copy.end());
514 // Try with all permutations of the recipe,
515 // start from the lexicographically first permutation (=sorted),
516 // recipe_names is pre-sorted
518 // If all items match, the recipe matches
519 bool all_match = true;
520 //dstream<<"Testing recipe (output="<<output<<"):";
521 for (size_t i=0; i<recipe.size(); i++) {
522 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
523 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
529 //dstream<<" -> match="<<all_match<<std::endl;
532 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
537 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
539 return CraftOutput(output, 0);
542 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
544 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
547 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
548 IGameDef *gamedef) const
550 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
553 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
555 assert(hash_inited); // Pre-condition
556 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
557 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
558 return getHashForGrid(type, recipe_names);
561 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
566 recipe_names = craftGetItemNames(recipe, gamedef);
567 std::sort(recipe_names.begin(), recipe_names.end());
569 if (hasGroupItem(recipe_names))
570 hash_type = CRAFT_HASH_TYPE_COUNT;
572 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
575 std::string CraftDefinitionShapeless::dump() const
577 std::ostringstream os(std::ios::binary);
578 os << "(shapeless, output=\"" << output
579 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
580 << ", replacements=" << replacements.dump() << ")";
585 CraftDefinitionToolRepair
588 CraftDefinitionToolRepair::CraftDefinitionToolRepair(float additional_wear_):
589 additional_wear(additional_wear_)
591 priority = PRIORITY_TOOLREPAIR;
594 static ItemStack craftToolRepair(
595 const ItemStack &item1,
596 const ItemStack &item2,
597 float additional_wear,
600 IItemDefManager *idef = gamedef->idef();
601 if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
602 || idef->get(item1.name).type != ITEM_TOOL
603 || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
608 s32 item1_uses = 65536 - (u32) item1.wear;
609 s32 item2_uses = 65536 - (u32) item2.wear;
610 s32 new_uses = item1_uses + item2_uses;
611 s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
612 if (new_wear >= 65536)
617 ItemStack repaired = item1;
618 repaired.wear = new_wear;
622 std::string CraftDefinitionToolRepair::getName() const
627 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
629 if (input.method != CRAFT_METHOD_NORMAL)
634 for (const auto &item : input.items) {
638 else if (item2.empty())
644 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
645 return !repaired.empty();
648 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
652 for (const auto &item : input.items) {
656 else if (item2.empty())
660 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
661 return CraftOutput(repaired.getItemString(), 0);
664 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
666 std::vector<ItemStack> stack;
667 stack.emplace_back();
668 return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
671 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
672 IGameDef *gamedef) const
674 craftDecrementInput(input, gamedef);
677 std::string CraftDefinitionToolRepair::dump() const
679 std::ostringstream os(std::ios::binary);
680 os << "(toolrepair, additional_wear=" << additional_wear << ")";
685 CraftDefinitionCooking
688 CraftDefinitionCooking::CraftDefinitionCooking(
689 const std::string &output_,
690 const std::string &recipe_,
692 const CraftReplacements &replacements_):
693 output(output_), recipe(recipe_), cooktime(cooktime_), replacements(replacements_)
695 if (isGroupRecipeStr(recipe))
696 priority = PRIORITY_SHAPELESS_AND_GROUPS;
698 priority = PRIORITY_SHAPELESS;
701 std::string CraftDefinitionCooking::getName() const
706 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
708 if (input.method != CRAFT_METHOD_COOKING)
711 // Filter empty items out of input
712 std::vector<std::string> input_filtered;
713 for (const auto &item : input.items) {
714 const std::string &name = item.name;
716 input_filtered.push_back(name);
719 // If there is a wrong number of items in input, no match
720 if (input_filtered.size() != 1) {
721 /*dstream<<"Number of input items ("<<input_filtered.size()
722 <<") does not match recipe size (1) "
723 <<"of cooking recipe with output="<<output<<std::endl;*/
727 // Check the single input item
728 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
731 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
733 return CraftOutput(output, cooktime);
736 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
738 std::vector<std::string> rec;
739 rec.push_back(recipe);
740 return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
743 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
744 IGameDef *gamedef) const
746 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
749 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
751 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
752 return getHashForString(recipe_name);
755 if (type == CRAFT_HASH_TYPE_COUNT) {
759 // illegal hash type for this CraftDefinition (pre-condition)
764 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
769 recipe_name = craftGetItemName(recipe, gamedef);
771 if (isGroupRecipeStr(recipe_name))
772 hash_type = CRAFT_HASH_TYPE_COUNT;
774 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
777 std::string CraftDefinitionCooking::dump() const
779 std::ostringstream os(std::ios::binary);
780 os << "(cooking, output=\"" << output
781 << "\", recipe=\"" << recipe
782 << "\", cooktime=" << cooktime << ")"
783 << ", replacements=" << replacements.dump() << ")";
791 CraftDefinitionFuel::CraftDefinitionFuel(
792 const std::string &recipe_,
794 const CraftReplacements &replacements_):
795 recipe(recipe_), burntime(burntime_), replacements(replacements_)
797 if (isGroupRecipeStr(recipe_name))
798 priority = PRIORITY_SHAPELESS_AND_GROUPS;
800 priority = PRIORITY_SHAPELESS;
803 std::string CraftDefinitionFuel::getName() const
808 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
810 if (input.method != CRAFT_METHOD_FUEL)
813 // Filter empty items out of input
814 std::vector<std::string> input_filtered;
815 for (const auto &item : input.items) {
816 const std::string &name = item.name;
818 input_filtered.push_back(name);
821 // If there is a wrong number of items in input, no match
822 if (input_filtered.size() != 1) {
823 /*dstream<<"Number of input items ("<<input_filtered.size()
824 <<") does not match recipe size (1) "
825 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
829 // Check the single input item
830 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
833 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
835 return CraftOutput("", burntime);
838 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
840 std::vector<std::string> rec;
841 rec.push_back(recipe);
842 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
845 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
846 IGameDef *gamedef) const
848 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
851 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
853 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
854 return getHashForString(recipe_name);
857 if (type == CRAFT_HASH_TYPE_COUNT) {
861 // illegal hash type for this CraftDefinition (pre-condition)
866 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
871 recipe_name = craftGetItemName(recipe, gamedef);
873 if (isGroupRecipeStr(recipe_name))
874 hash_type = CRAFT_HASH_TYPE_COUNT;
876 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
879 std::string CraftDefinitionFuel::dump() const
881 std::ostringstream os(std::ios::binary);
882 os << "(fuel, recipe=\"" << recipe
883 << "\", burntime=" << burntime << ")"
884 << ", replacements=" << replacements.dump() << ")";
889 Craft definition manager
892 class CCraftDefManager: public IWritableCraftDefManager
897 m_craft_defs.resize(craft_hash_type_max + 1);
900 virtual ~CCraftDefManager()
905 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
906 std::vector<ItemStack> &output_replacement, bool decrementInput,
907 IGameDef *gamedef) const
912 // If all input items are empty, abort.
913 bool all_empty = true;
914 for (const auto &item : input.items) {
923 std::vector<std::string> input_names;
924 input_names = craftGetItemNames(input.items, gamedef);
925 std::sort(input_names.begin(), input_names.end());
927 // Try hash types with increasing collision rate
928 // while remembering the latest, highest priority recipe.
929 CraftDefinition::RecipePriority priority_best =
930 CraftDefinition::PRIORITY_NO_RECIPE;
931 CraftDefinition *def_best = nullptr;
932 for (int type = 0; type <= craft_hash_type_max; type++) {
933 u64 hash = getHashForGrid((CraftHashType) type, input_names);
935 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
937 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
938 // but that doesn't compile for some reason. This does.
939 auto col_iter = (m_craft_defs[type]).find(hash);
941 if (col_iter == (m_craft_defs[type]).end())
944 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
945 // Walk crafting definitions from back to front, so that later
946 // definitions can override earlier ones.
947 for (std::vector<CraftDefinition*>::size_type
948 i = hash_collisions.size(); i > 0; i--) {
949 CraftDefinition *def = hash_collisions[i - 1];
951 /*errorstream << "Checking " << input.dump() << std::endl
952 << " against " << def->dump() << std::endl;*/
954 CraftDefinition::RecipePriority priority = def->getPriority();
955 if (priority > priority_best
956 && def->check(input, gamedef)) {
957 // Check if the crafted node/item exists
958 CraftOutput out = def->getOutput(input, gamedef);
960 is.deSerialize(out.item, gamedef->idef());
961 if (!is.isKnown(gamedef->idef())) {
962 infostream << "trying to craft non-existent "
963 << out.item << ", ignoring recipe" << std::endl;
968 priority_best = priority;
973 if (priority_best == CraftDefinition::PRIORITY_NO_RECIPE)
976 def_best->decrementInput(input, output_replacement, gamedef);
980 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
981 IGameDef *gamedef, unsigned limit=0) const
983 std::vector<CraftDefinition*> recipes;
985 auto vec_iter = m_output_craft_definitions.find(output.item);
987 if (vec_iter == m_output_craft_definitions.end())
990 const std::vector<CraftDefinition*> &vec = vec_iter->second;
992 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
994 for (std::vector<CraftDefinition*>::size_type i = vec.size();
996 CraftDefinition *def = vec[i - 1];
997 if (limit && recipes.size() >= limit)
999 recipes.push_back(def);
1005 virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef)
1007 auto vec_iter = m_output_craft_definitions.find(output.item);
1009 if (vec_iter == m_output_craft_definitions.end())
1012 std::vector<CraftDefinition*> &vec = vec_iter->second;
1013 for (auto def : vec) {
1014 // Recipes are not yet hashed at this point
1015 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1016 std::vector<CraftDefinition*> new_vec_by_input;
1017 /* We will preallocate necessary memory addresses, so we don't need to reallocate them later.
1018 This would save us some performance. */
1019 new_vec_by_input.reserve(unhashed_inputs_vec.size());
1020 for (auto &i2 : unhashed_inputs_vec) {
1022 new_vec_by_input.push_back(i2);
1025 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1027 m_output_craft_definitions.erase(output.item);
1031 virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width,
1032 const std::vector<std::string> &recipe, IGameDef *gamedef)
1034 bool all_empty = true;
1035 for (const auto &i : recipe) {
1044 CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef));
1045 // Recipes are not yet hashed at this point
1046 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1047 std::vector<CraftDefinition*> new_vec_by_input;
1048 bool got_hit = false;
1049 for (std::vector<CraftDefinition*>::size_type
1050 i = unhashed_inputs_vec.size(); i > 0; i--) {
1051 CraftDefinition *def = unhashed_inputs_vec[i - 1];
1052 /* If the input doesn't match the recipe definition, this recipe definition later
1053 will be added back in source map. */
1054 if (!def->check(input, gamedef)) {
1055 new_vec_by_input.push_back(def);
1058 CraftOutput output = def->getOutput(input, gamedef);
1060 auto vec_iter = m_output_craft_definitions.find(output.item);
1061 if (vec_iter == m_output_craft_definitions.end())
1063 std::vector<CraftDefinition*> &vec = vec_iter->second;
1064 std::vector<CraftDefinition*> new_vec_by_output;
1065 /* We will preallocate necessary memory addresses, so we don't need
1066 to reallocate them later. This would save us some performance. */
1067 new_vec_by_output.reserve(vec.size());
1068 for (auto &vec_i : vec) {
1069 /* If pointers from map by input and output are not same,
1070 we will add 'CraftDefinition*' to a new vector. */
1072 /* Adding dereferenced iterator value (which are
1073 'CraftDefinition' reference) to a new vector. */
1074 new_vec_by_output.push_back(vec_i);
1077 // Swaps assigned to current key value with new vector for output map.
1078 m_output_craft_definitions[output.item].swap(new_vec_by_output);
1081 // Swaps value with new vector for input map.
1082 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1087 virtual std::string dump() const
1089 std::ostringstream os(std::ios::binary);
1090 os << "Crafting definitions:\n";
1091 for (int type = 0; type <= craft_hash_type_max; ++type) {
1092 for (auto it = m_craft_defs[type].begin();
1093 it != m_craft_defs[type].end(); ++it) {
1094 for (std::vector<CraftDefinition*>::size_type i = 0;
1095 i < it->second.size(); i++) {
1096 os << "type " << type
1097 << " hash " << it->first
1098 << " def " << it->second[i]->dump()
1105 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1107 verbosestream << "registerCraft: registering craft definition: "
1108 << def->dump() << std::endl;
1109 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1112 std::string output_name = craftGetItemName(
1113 def->getOutput(input, gamedef).item, gamedef);
1114 m_output_craft_definitions[output_name].push_back(def);
1116 virtual void clear()
1118 for (int type = 0; type <= craft_hash_type_max; ++type) {
1119 for (auto &it : m_craft_defs[type]) {
1120 for (auto &iit : it.second) {
1125 m_craft_defs[type].clear();
1127 m_output_craft_definitions.clear();
1129 virtual void initHashes(IGameDef *gamedef)
1131 // Move the CraftDefs from the unhashed layer into layers higher up.
1132 std::vector<CraftDefinition *> &unhashed =
1133 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1134 for (auto def : unhashed) {
1135 // Initialize and get the definition's hash
1136 def->initHash(gamedef);
1137 CraftHashType type = def->getHashType();
1138 u64 hash = def->getHash(type);
1140 // Enter the definition
1141 m_craft_defs[type][hash].push_back(def);
1146 std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > >
1148 std::unordered_map<std::string, std::vector<CraftDefinition*> >
1149 m_output_craft_definitions;
1152 IWritableCraftDefManager* createCraftDefManager()
1154 return new CCraftDefManager();