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