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