Use warningstream for log messages with WARNING
[oweals/minetest.git] / src / nodedef.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 "nodedef.h"
21
22 #include "itemdef.h"
23 #ifndef SERVER
24 #include "client/tile.h"
25 #include "mesh.h"
26 #include <IMeshManipulator.h>
27 #endif
28 #include "log.h"
29 #include "settings.h"
30 #include "nameidmapping.h"
31 #include "util/numeric.h"
32 #include "util/serialize.h"
33 #include "exceptions.h"
34 #include "debug.h"
35 #include "gamedef.h"
36 #include <fstream> // Used in applyTextureOverrides()
37
38 /*
39         NodeBox
40 */
41
42 void NodeBox::reset()
43 {
44         type = NODEBOX_REGULAR;
45         // default is empty
46         fixed.clear();
47         // default is sign/ladder-like
48         wall_top = aabb3f(-BS/2, BS/2-BS/16., -BS/2, BS/2, BS/2, BS/2);
49         wall_bottom = aabb3f(-BS/2, -BS/2, -BS/2, BS/2, -BS/2+BS/16., BS/2);
50         wall_side = aabb3f(-BS/2, -BS/2, -BS/2, -BS/2+BS/16., BS/2, BS/2);
51 }
52
53 void NodeBox::serialize(std::ostream &os, u16 protocol_version) const
54 {
55         int version = protocol_version >= 21 ? 2 : 1;
56         writeU8(os, version);
57
58         if (version == 1 && type == NODEBOX_LEVELED)
59                 writeU8(os, NODEBOX_FIXED);
60         else
61                 writeU8(os, type);
62
63         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
64         {
65                 writeU16(os, fixed.size());
66                 for(std::vector<aabb3f>::const_iterator
67                                 i = fixed.begin();
68                                 i != fixed.end(); ++i)
69                 {
70                         writeV3F1000(os, i->MinEdge);
71                         writeV3F1000(os, i->MaxEdge);
72                 }
73         }
74         else if(type == NODEBOX_WALLMOUNTED)
75         {
76                 writeV3F1000(os, wall_top.MinEdge);
77                 writeV3F1000(os, wall_top.MaxEdge);
78                 writeV3F1000(os, wall_bottom.MinEdge);
79                 writeV3F1000(os, wall_bottom.MaxEdge);
80                 writeV3F1000(os, wall_side.MinEdge);
81                 writeV3F1000(os, wall_side.MaxEdge);
82         }
83 }
84
85 void NodeBox::deSerialize(std::istream &is)
86 {
87         int version = readU8(is);
88         if(version < 1 || version > 2)
89                 throw SerializationError("unsupported NodeBox version");
90
91         reset();
92
93         type = (enum NodeBoxType)readU8(is);
94
95         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
96         {
97                 u16 fixed_count = readU16(is);
98                 while(fixed_count--)
99                 {
100                         aabb3f box;
101                         box.MinEdge = readV3F1000(is);
102                         box.MaxEdge = readV3F1000(is);
103                         fixed.push_back(box);
104                 }
105         }
106         else if(type == NODEBOX_WALLMOUNTED)
107         {
108                 wall_top.MinEdge = readV3F1000(is);
109                 wall_top.MaxEdge = readV3F1000(is);
110                 wall_bottom.MinEdge = readV3F1000(is);
111                 wall_bottom.MaxEdge = readV3F1000(is);
112                 wall_side.MinEdge = readV3F1000(is);
113                 wall_side.MaxEdge = readV3F1000(is);
114         }
115 }
116
117 /*
118         TileDef
119 */
120
121 void TileDef::serialize(std::ostream &os, u16 protocol_version) const
122 {
123         if (protocol_version >= 26)
124                 writeU8(os, 2);
125         else if (protocol_version >= 17)
126                 writeU8(os, 1);
127         else
128                 writeU8(os, 0);
129         os<<serializeString(name);
130         writeU8(os, animation.type);
131         writeU16(os, animation.aspect_w);
132         writeU16(os, animation.aspect_h);
133         writeF1000(os, animation.length);
134         if (protocol_version >= 17)
135                 writeU8(os, backface_culling);
136         if (protocol_version >= 26) {
137                 writeU8(os, tileable_horizontal);
138                 writeU8(os, tileable_vertical);
139         }
140 }
141
142 void TileDef::deSerialize(std::istream &is)
143 {
144         int version = readU8(is);
145         name = deSerializeString(is);
146         animation.type = (TileAnimationType)readU8(is);
147         animation.aspect_w = readU16(is);
148         animation.aspect_h = readU16(is);
149         animation.length = readF1000(is);
150         if (version >= 1)
151                 backface_culling = readU8(is);
152         if (version >= 2) {
153                 tileable_horizontal = readU8(is);
154                 tileable_vertical = readU8(is);
155         }
156 }
157
158
159 /*
160         SimpleSoundSpec serialization
161 */
162
163 static void serializeSimpleSoundSpec(const SimpleSoundSpec &ss,
164                 std::ostream &os)
165 {
166         os<<serializeString(ss.name);
167         writeF1000(os, ss.gain);
168 }
169 static void deSerializeSimpleSoundSpec(SimpleSoundSpec &ss, std::istream &is)
170 {
171         ss.name = deSerializeString(is);
172         ss.gain = readF1000(is);
173 }
174
175 /*
176         ContentFeatures
177 */
178
179 ContentFeatures::ContentFeatures()
180 {
181         reset();
182 }
183
184 ContentFeatures::~ContentFeatures()
185 {
186 }
187
188 void ContentFeatures::reset()
189 {
190         /*
191                 Cached stuff
192         */
193 #ifndef SERVER
194         solidness = 2;
195         visual_solidness = 0;
196         backface_culling = true;
197
198 #endif
199         has_on_construct = false;
200         has_on_destruct = false;
201         has_after_destruct = false;
202         /*
203                 Actual data
204
205                 NOTE: Most of this is always overridden by the default values given
206                       in builtin.lua
207         */
208         name = "";
209         groups.clear();
210         // Unknown nodes can be dug
211         groups["dig_immediate"] = 2;
212         drawtype = NDT_NORMAL;
213         mesh = "";
214 #ifndef SERVER
215         for(u32 i = 0; i < 24; i++)
216                 mesh_ptr[i] = NULL;
217         minimap_color = video::SColor(0, 0, 0, 0);
218 #endif
219         visual_scale = 1.0;
220         for(u32 i = 0; i < 6; i++)
221                 tiledef[i] = TileDef();
222         for(u16 j = 0; j < CF_SPECIAL_COUNT; j++)
223                 tiledef_special[j] = TileDef();
224         alpha = 255;
225         post_effect_color = video::SColor(0, 0, 0, 0);
226         param_type = CPT_NONE;
227         param_type_2 = CPT2_NONE;
228         is_ground_content = false;
229         light_propagates = false;
230         sunlight_propagates = false;
231         walkable = true;
232         pointable = true;
233         diggable = true;
234         climbable = false;
235         buildable_to = false;
236         rightclickable = true;
237         leveled = 0;
238         liquid_type = LIQUID_NONE;
239         liquid_alternative_flowing = "";
240         liquid_alternative_source = "";
241         liquid_viscosity = 0;
242         liquid_renewable = true;
243         liquid_range = LIQUID_LEVEL_MAX+1;
244         drowning = 0;
245         light_source = 0;
246         damage_per_second = 0;
247         node_box = NodeBox();
248         selection_box = NodeBox();
249         collision_box = NodeBox();
250         waving = 0;
251         legacy_facedir_simple = false;
252         legacy_wallmounted = false;
253         sound_footstep = SimpleSoundSpec();
254         sound_dig = SimpleSoundSpec("__group");
255         sound_dug = SimpleSoundSpec();
256 }
257
258 void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const
259 {
260         if(protocol_version < 24){
261                 serializeOld(os, protocol_version);
262                 return;
263         }
264
265         writeU8(os, 7); // version
266         os<<serializeString(name);
267         writeU16(os, groups.size());
268         for(ItemGroupList::const_iterator
269                         i = groups.begin(); i != groups.end(); ++i){
270                 os<<serializeString(i->first);
271                 writeS16(os, i->second);
272         }
273         writeU8(os, drawtype);
274         writeF1000(os, visual_scale);
275         writeU8(os, 6);
276         for(u32 i = 0; i < 6; i++)
277                 tiledef[i].serialize(os, protocol_version);
278         writeU8(os, CF_SPECIAL_COUNT);
279         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++){
280                 tiledef_special[i].serialize(os, protocol_version);
281         }
282         writeU8(os, alpha);
283         writeU8(os, post_effect_color.getAlpha());
284         writeU8(os, post_effect_color.getRed());
285         writeU8(os, post_effect_color.getGreen());
286         writeU8(os, post_effect_color.getBlue());
287         writeU8(os, param_type);
288         writeU8(os, param_type_2);
289         writeU8(os, is_ground_content);
290         writeU8(os, light_propagates);
291         writeU8(os, sunlight_propagates);
292         writeU8(os, walkable);
293         writeU8(os, pointable);
294         writeU8(os, diggable);
295         writeU8(os, climbable);
296         writeU8(os, buildable_to);
297         os<<serializeString(""); // legacy: used to be metadata_name
298         writeU8(os, liquid_type);
299         os<<serializeString(liquid_alternative_flowing);
300         os<<serializeString(liquid_alternative_source);
301         writeU8(os, liquid_viscosity);
302         writeU8(os, liquid_renewable);
303         writeU8(os, light_source);
304         writeU32(os, damage_per_second);
305         node_box.serialize(os, protocol_version);
306         selection_box.serialize(os, protocol_version);
307         writeU8(os, legacy_facedir_simple);
308         writeU8(os, legacy_wallmounted);
309         serializeSimpleSoundSpec(sound_footstep, os);
310         serializeSimpleSoundSpec(sound_dig, os);
311         serializeSimpleSoundSpec(sound_dug, os);
312         writeU8(os, rightclickable);
313         writeU8(os, drowning);
314         writeU8(os, leveled);
315         writeU8(os, liquid_range);
316         writeU8(os, waving);
317         // Stuff below should be moved to correct place in a version that otherwise changes
318         // the protocol version
319         os<<serializeString(mesh);
320         collision_box.serialize(os, protocol_version);
321 }
322
323 void ContentFeatures::deSerialize(std::istream &is)
324 {
325         int version = readU8(is);
326         if(version != 7){
327                 deSerializeOld(is, version);
328                 return;
329         }
330
331         name = deSerializeString(is);
332         groups.clear();
333         u32 groups_size = readU16(is);
334         for(u32 i = 0; i < groups_size; i++){
335                 std::string name = deSerializeString(is);
336                 int value = readS16(is);
337                 groups[name] = value;
338         }
339         drawtype = (enum NodeDrawType)readU8(is);
340         visual_scale = readF1000(is);
341         if(readU8(is) != 6)
342                 throw SerializationError("unsupported tile count");
343         for(u32 i = 0; i < 6; i++)
344                 tiledef[i].deSerialize(is);
345         if(readU8(is) != CF_SPECIAL_COUNT)
346                 throw SerializationError("unsupported CF_SPECIAL_COUNT");
347         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++)
348                 tiledef_special[i].deSerialize(is);
349         alpha = readU8(is);
350         post_effect_color.setAlpha(readU8(is));
351         post_effect_color.setRed(readU8(is));
352         post_effect_color.setGreen(readU8(is));
353         post_effect_color.setBlue(readU8(is));
354         param_type = (enum ContentParamType)readU8(is);
355         param_type_2 = (enum ContentParamType2)readU8(is);
356         is_ground_content = readU8(is);
357         light_propagates = readU8(is);
358         sunlight_propagates = readU8(is);
359         walkable = readU8(is);
360         pointable = readU8(is);
361         diggable = readU8(is);
362         climbable = readU8(is);
363         buildable_to = readU8(is);
364         deSerializeString(is); // legacy: used to be metadata_name
365         liquid_type = (enum LiquidType)readU8(is);
366         liquid_alternative_flowing = deSerializeString(is);
367         liquid_alternative_source = deSerializeString(is);
368         liquid_viscosity = readU8(is);
369         liquid_renewable = readU8(is);
370         light_source = readU8(is);
371         damage_per_second = readU32(is);
372         node_box.deSerialize(is);
373         selection_box.deSerialize(is);
374         legacy_facedir_simple = readU8(is);
375         legacy_wallmounted = readU8(is);
376         deSerializeSimpleSoundSpec(sound_footstep, is);
377         deSerializeSimpleSoundSpec(sound_dig, is);
378         deSerializeSimpleSoundSpec(sound_dug, is);
379         rightclickable = readU8(is);
380         drowning = readU8(is);
381         leveled = readU8(is);
382         liquid_range = readU8(is);
383         waving = readU8(is);
384         // If you add anything here, insert it primarily inside the try-catch
385         // block to not need to increase the version.
386         try{
387                 // Stuff below should be moved to correct place in a version that
388                 // otherwise changes the protocol version
389         mesh = deSerializeString(is);
390         collision_box.deSerialize(is);
391         }catch(SerializationError &e) {};
392 }
393
394 /*
395         CNodeDefManager
396 */
397
398 class CNodeDefManager: public IWritableNodeDefManager {
399 public:
400         CNodeDefManager();
401         virtual ~CNodeDefManager();
402         void clear();
403         virtual IWritableNodeDefManager *clone();
404         inline virtual const ContentFeatures& get(content_t c) const;
405         inline virtual const ContentFeatures& get(const MapNode &n) const;
406         virtual bool getId(const std::string &name, content_t &result) const;
407         virtual content_t getId(const std::string &name) const;
408         virtual void getIds(const std::string &name, std::set<content_t> &result) const;
409         virtual const ContentFeatures& get(const std::string &name) const;
410         content_t allocateId();
411         virtual content_t set(const std::string &name, const ContentFeatures &def);
412         virtual content_t allocateDummy(const std::string &name);
413         virtual void updateAliases(IItemDefManager *idef);
414         virtual void applyTextureOverrides(const std::string &override_filepath);
415         virtual void updateTextures(IGameDef *gamedef,
416                 void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress),
417                 void *progress_cbk_args);
418         void serialize(std::ostream &os, u16 protocol_version) const;
419         void deSerialize(std::istream &is);
420
421         inline virtual bool getNodeRegistrationStatus() const;
422         inline virtual void setNodeRegistrationStatus(bool completed);
423
424         virtual void pendNodeResolve(NodeResolver *nr);
425         virtual bool cancelNodeResolveCallback(NodeResolver *nr);
426         virtual void runNodeResolveCallbacks();
427         virtual void resetNodeResolveState();
428
429 private:
430         void addNameIdMapping(content_t i, std::string name);
431 #ifndef SERVER
432         void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef,
433                 u32 shader_id, bool use_normal_texture, bool backface_culling,
434                 u8 alpha, u8 material_type);
435 #endif
436
437         // Features indexed by id
438         std::vector<ContentFeatures> m_content_features;
439
440         // A mapping for fast converting back and forth between names and ids
441         NameIdMapping m_name_id_mapping;
442
443         // Like m_name_id_mapping, but only from names to ids, and includes
444         // item aliases too. Updated by updateAliases()
445         // Note: Not serialized.
446
447         std::map<std::string, content_t> m_name_id_mapping_with_aliases;
448
449         // A mapping from groups to a list of content_ts (and their levels)
450         // that belong to it.  Necessary for a direct lookup in getIds().
451         // Note: Not serialized.
452         std::map<std::string, GroupItems> m_group_to_items;
453
454         // Next possibly free id
455         content_t m_next_id;
456
457         // NodeResolvers to callback once node registration has ended
458         std::vector<NodeResolver *> m_pending_resolve_callbacks;
459
460         // True when all nodes have been registered
461         bool m_node_registration_complete;
462 };
463
464
465 CNodeDefManager::CNodeDefManager()
466 {
467         clear();
468 }
469
470
471 CNodeDefManager::~CNodeDefManager()
472 {
473 #ifndef SERVER
474         for (u32 i = 0; i < m_content_features.size(); i++) {
475                 ContentFeatures *f = &m_content_features[i];
476                 for (u32 j = 0; j < 24; j++) {
477                         if (f->mesh_ptr[j])
478                                 f->mesh_ptr[j]->drop();
479                 }
480         }
481 #endif
482 }
483
484
485 void CNodeDefManager::clear()
486 {
487         m_content_features.clear();
488         m_name_id_mapping.clear();
489         m_name_id_mapping_with_aliases.clear();
490         m_group_to_items.clear();
491         m_next_id = 0;
492
493         resetNodeResolveState();
494
495         u32 initial_length = 0;
496         initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1);
497         initial_length = MYMAX(initial_length, CONTENT_AIR + 1);
498         initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1);
499         m_content_features.resize(initial_length);
500
501         // Set CONTENT_UNKNOWN
502         {
503                 ContentFeatures f;
504                 f.name = "unknown";
505                 // Insert directly into containers
506                 content_t c = CONTENT_UNKNOWN;
507                 m_content_features[c] = f;
508                 addNameIdMapping(c, f.name);
509         }
510
511         // Set CONTENT_AIR
512         {
513                 ContentFeatures f;
514                 f.name                = "air";
515                 f.drawtype            = NDT_AIRLIKE;
516                 f.param_type          = CPT_LIGHT;
517                 f.light_propagates    = true;
518                 f.sunlight_propagates = true;
519                 f.walkable            = false;
520                 f.pointable           = false;
521                 f.diggable            = false;
522                 f.buildable_to        = true;
523                 f.is_ground_content   = true;
524                 // Insert directly into containers
525                 content_t c = CONTENT_AIR;
526                 m_content_features[c] = f;
527                 addNameIdMapping(c, f.name);
528         }
529
530         // Set CONTENT_IGNORE
531         {
532                 ContentFeatures f;
533                 f.name                = "ignore";
534                 f.drawtype            = NDT_AIRLIKE;
535                 f.param_type          = CPT_NONE;
536                 f.light_propagates    = false;
537                 f.sunlight_propagates = false;
538                 f.walkable            = false;
539                 f.pointable           = false;
540                 f.diggable            = false;
541                 f.buildable_to        = true; // A way to remove accidental CONTENT_IGNOREs
542                 f.is_ground_content   = true;
543                 // Insert directly into containers
544                 content_t c = CONTENT_IGNORE;
545                 m_content_features[c] = f;
546                 addNameIdMapping(c, f.name);
547         }
548 }
549
550
551 IWritableNodeDefManager *CNodeDefManager::clone()
552 {
553         CNodeDefManager *mgr = new CNodeDefManager();
554         *mgr = *this;
555         return mgr;
556 }
557
558
559 inline const ContentFeatures& CNodeDefManager::get(content_t c) const
560 {
561         return c < m_content_features.size()
562                         ? m_content_features[c] : m_content_features[CONTENT_UNKNOWN];
563 }
564
565
566 inline const ContentFeatures& CNodeDefManager::get(const MapNode &n) const
567 {
568         return get(n.getContent());
569 }
570
571
572 bool CNodeDefManager::getId(const std::string &name, content_t &result) const
573 {
574         std::map<std::string, content_t>::const_iterator
575                 i = m_name_id_mapping_with_aliases.find(name);
576         if(i == m_name_id_mapping_with_aliases.end())
577                 return false;
578         result = i->second;
579         return true;
580 }
581
582
583 content_t CNodeDefManager::getId(const std::string &name) const
584 {
585         content_t id = CONTENT_IGNORE;
586         getId(name, id);
587         return id;
588 }
589
590
591 void CNodeDefManager::getIds(const std::string &name,
592                 std::set<content_t> &result) const
593 {
594         //TimeTaker t("getIds", NULL, PRECISION_MICRO);
595         if (name.substr(0,6) != "group:") {
596                 content_t id = CONTENT_IGNORE;
597                 if(getId(name, id))
598                         result.insert(id);
599                 return;
600         }
601         std::string group = name.substr(6);
602
603         std::map<std::string, GroupItems>::const_iterator
604                 i = m_group_to_items.find(group);
605         if (i == m_group_to_items.end())
606                 return;
607
608         const GroupItems &items = i->second;
609         for (GroupItems::const_iterator j = items.begin();
610                 j != items.end(); ++j) {
611                 if ((*j).second != 0)
612                         result.insert((*j).first);
613         }
614         //printf("getIds: %dus\n", t.stop());
615 }
616
617
618 const ContentFeatures& CNodeDefManager::get(const std::string &name) const
619 {
620         content_t id = CONTENT_UNKNOWN;
621         getId(name, id);
622         return get(id);
623 }
624
625
626 // returns CONTENT_IGNORE if no free ID found
627 content_t CNodeDefManager::allocateId()
628 {
629         for (content_t id = m_next_id;
630                         id >= m_next_id; // overflow?
631                         ++id) {
632                 while (id >= m_content_features.size()) {
633                         m_content_features.push_back(ContentFeatures());
634                 }
635                 const ContentFeatures &f = m_content_features[id];
636                 if (f.name == "") {
637                         m_next_id = id + 1;
638                         return id;
639                 }
640         }
641         // If we arrive here, an overflow occurred in id.
642         // That means no ID was found
643         return CONTENT_IGNORE;
644 }
645
646
647 // IWritableNodeDefManager
648 content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
649 {
650         // Pre-conditions
651         assert(name != "");
652         assert(name == def.name);
653
654         // Don't allow redefining ignore (but allow air and unknown)
655         if (name == "ignore") {
656                 warningstream << "NodeDefManager: Ignoring "
657                         "CONTENT_IGNORE redefinition"<<std::endl;
658                 return CONTENT_IGNORE;
659         }
660
661         content_t id = CONTENT_IGNORE;
662         if (!m_name_id_mapping.getId(name, id)) { // ignore aliases
663                 // Get new id
664                 id = allocateId();
665                 if (id == CONTENT_IGNORE) {
666                         warningstream << "NodeDefManager: Absolute "
667                                 "limit reached" << std::endl;
668                         return CONTENT_IGNORE;
669                 }
670                 assert(id != CONTENT_IGNORE);
671                 addNameIdMapping(id, name);
672         }
673         m_content_features[id] = def;
674         verbosestream << "NodeDefManager: registering content id \"" << id
675                 << "\": name=\"" << def.name << "\""<<std::endl;
676
677         // Add this content to the list of all groups it belongs to
678         // FIXME: This should remove a node from groups it no longer
679         // belongs to when a node is re-registered
680         for (ItemGroupList::const_iterator i = def.groups.begin();
681                 i != def.groups.end(); ++i) {
682                 std::string group_name = i->first;
683
684                 std::map<std::string, GroupItems>::iterator
685                         j = m_group_to_items.find(group_name);
686                 if (j == m_group_to_items.end()) {
687                         m_group_to_items[group_name].push_back(
688                                 std::make_pair(id, i->second));
689                 } else {
690                         GroupItems &items = j->second;
691                         items.push_back(std::make_pair(id, i->second));
692                 }
693         }
694         return id;
695 }
696
697
698 content_t CNodeDefManager::allocateDummy(const std::string &name)
699 {
700         assert(name != "");     // Pre-condition
701         ContentFeatures f;
702         f.name = name;
703         return set(name, f);
704 }
705
706
707 void CNodeDefManager::updateAliases(IItemDefManager *idef)
708 {
709         std::set<std::string> all = idef->getAll();
710         m_name_id_mapping_with_aliases.clear();
711         for (std::set<std::string>::iterator
712                         i = all.begin(); i != all.end(); ++i) {
713                 std::string name = *i;
714                 std::string convert_to = idef->getAlias(name);
715                 content_t id;
716                 if (m_name_id_mapping.getId(convert_to, id)) {
717                         m_name_id_mapping_with_aliases.insert(
718                                 std::make_pair(name, id));
719                 }
720         }
721 }
722
723 void CNodeDefManager::applyTextureOverrides(const std::string &override_filepath)
724 {
725         infostream << "CNodeDefManager::applyTextureOverrides(): Applying "
726                 "overrides to textures from " << override_filepath << std::endl;
727
728         std::ifstream infile(override_filepath.c_str());
729         std::string line;
730         int line_c = 0;
731         while (std::getline(infile, line)) {
732                 line_c++;
733                 if (trim(line) == "")
734                         continue;
735                 std::vector<std::string> splitted = str_split(line, ' ');
736                 if (splitted.size() != 3) {
737                         errorstream << override_filepath
738                                 << ":" << line_c << " Could not apply texture override \""
739                                 << line << "\": Syntax error" << std::endl;
740                         continue;
741                 }
742
743                 content_t id;
744                 if (!getId(splitted[0], id)) {
745                         errorstream << override_filepath
746                                 << ":" << line_c << " Could not apply texture override \""
747                                 << line << "\": Unknown node \""
748                                 << splitted[0] << "\"" << std::endl;
749                         continue;
750                 }
751
752                 ContentFeatures &nodedef = m_content_features[id];
753
754                 if (splitted[1] == "top")
755                         nodedef.tiledef[0].name = splitted[2];
756                 else if (splitted[1] == "bottom")
757                         nodedef.tiledef[1].name = splitted[2];
758                 else if (splitted[1] == "right")
759                         nodedef.tiledef[2].name = splitted[2];
760                 else if (splitted[1] == "left")
761                         nodedef.tiledef[3].name = splitted[2];
762                 else if (splitted[1] == "back")
763                         nodedef.tiledef[4].name = splitted[2];
764                 else if (splitted[1] == "front")
765                         nodedef.tiledef[5].name = splitted[2];
766                 else if (splitted[1] == "all" || splitted[1] == "*")
767                         for (int i = 0; i < 6; i++)
768                                 nodedef.tiledef[i].name = splitted[2];
769                 else if (splitted[1] == "sides")
770                         for (int i = 2; i < 6; i++)
771                                 nodedef.tiledef[i].name = splitted[2];
772                 else {
773                         errorstream << override_filepath
774                                 << ":" << line_c << " Could not apply texture override \""
775                                 << line << "\": Unknown node side \""
776                                 << splitted[1] << "\"" << std::endl;
777                         continue;
778                 }
779         }
780 }
781
782 void CNodeDefManager::updateTextures(IGameDef *gamedef,
783         void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress),
784         void *progress_callback_args)
785 {
786 #ifndef SERVER
787         infostream << "CNodeDefManager::updateTextures(): Updating "
788                 "textures in node definitions" << std::endl;
789         ITextureSource *tsrc = gamedef->tsrc();
790         IShaderSource *shdsrc = gamedef->getShaderSource();
791         scene::ISceneManager* smgr = gamedef->getSceneManager();
792         scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator();
793
794         bool new_style_water           = g_settings->getBool("new_style_water");
795         bool connected_glass           = g_settings->getBool("connected_glass");
796         bool opaque_water              = g_settings->getBool("opaque_water");
797         bool enable_shaders            = g_settings->getBool("enable_shaders");
798         bool enable_bumpmapping        = g_settings->getBool("enable_bumpmapping");
799         bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion");
800         bool enable_mesh_cache         = g_settings->getBool("enable_mesh_cache");
801         bool enable_minimap            = g_settings->getBool("enable_minimap");
802         std::string leaves_style       = g_settings->get("leaves_style");
803
804         bool use_normal_texture = enable_shaders &&
805                 (enable_bumpmapping || enable_parallax_occlusion);
806
807         u32 size = m_content_features.size();
808
809         for (u32 i = 0; i < size; i++) {
810                 ContentFeatures *f = &m_content_features[i];
811
812                 // minimap pixel color - the average color of a texture
813                 if (enable_minimap && f->tiledef[0].name != "")
814                         f->minimap_color = tsrc->getTextureAverageColor(f->tiledef[0].name);
815
816                 // Figure out the actual tiles to use
817                 TileDef tiledef[6];
818                 for (u32 j = 0; j < 6; j++) {
819                         tiledef[j] = f->tiledef[j];
820                         if (tiledef[j].name == "")
821                                 tiledef[j].name = "unknown_node.png";
822                 }
823
824                 bool is_liquid = false;
825                 bool is_water_surface = false;
826
827                 u8 material_type = (f->alpha == 255) ?
828                         TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA;
829
830                 switch (f->drawtype) {
831                 default:
832                 case NDT_NORMAL:
833                         f->solidness = 2;
834                         break;
835                 case NDT_AIRLIKE:
836                         f->solidness = 0;
837                         break;
838                 case NDT_LIQUID:
839                         assert(f->liquid_type == LIQUID_SOURCE);
840                         if (opaque_water)
841                                 f->alpha = 255;
842                         if (new_style_water){
843                                 f->solidness = 0;
844                         } else {
845                                 f->solidness = 1;
846                                 f->backface_culling = false;
847                         }
848                         is_liquid = true;
849                         break;
850                 case NDT_FLOWINGLIQUID:
851                         assert(f->liquid_type == LIQUID_FLOWING);
852                         f->solidness = 0;
853                         if (opaque_water)
854                                 f->alpha = 255;
855                         is_liquid = true;
856                         break;
857                 case NDT_GLASSLIKE:
858                         f->solidness = 0;
859                         f->visual_solidness = 1;
860                         break;
861                 case NDT_GLASSLIKE_FRAMED:
862                         f->solidness = 0;
863                         f->visual_solidness = 1;
864                         break;
865                 case NDT_GLASSLIKE_FRAMED_OPTIONAL:
866                         f->solidness = 0;
867                         f->visual_solidness = 1;
868                         f->drawtype = connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE;
869                         break;
870                 case NDT_ALLFACES:
871                         f->solidness = 0;
872                         f->visual_solidness = 1;
873                         break;
874                 case NDT_ALLFACES_OPTIONAL:
875                         if (leaves_style == "fancy") {
876                                 f->drawtype = NDT_ALLFACES;
877                                 f->solidness = 0;
878                                 f->visual_solidness = 1;
879                         } else if (leaves_style == "simple") {
880                                 for (u32 j = 0; j < 6; j++) {
881                                         if (f->tiledef_special[j].name != "")
882                                                 tiledef[j].name = f->tiledef_special[j].name;
883                                 }
884                                 f->drawtype = NDT_GLASSLIKE;
885                                 f->solidness = 0;
886                                 f->visual_solidness = 1;
887                         } else {
888                                 f->drawtype = NDT_NORMAL;
889                                 f->solidness = 2;
890                                 for (u32 i = 0; i < 6; i++)
891                                         tiledef[i].name += std::string("^[noalpha");
892                         }
893                         if (f->waving == 1)
894                                 material_type = TILE_MATERIAL_WAVING_LEAVES;
895                         break;
896                 case NDT_PLANTLIKE:
897                         f->solidness = 0;
898                         f->backface_culling = false;
899                         if (f->waving == 1)
900                                 material_type = TILE_MATERIAL_WAVING_PLANTS;
901                         break;
902                 case NDT_FIRELIKE:
903                         f->backface_culling = false;
904                         f->solidness = 0;
905                         break;
906                 case NDT_MESH:
907                         f->solidness = 0;
908                         f->backface_culling = false;
909                         break;
910                 case NDT_TORCHLIKE:
911                 case NDT_SIGNLIKE:
912                 case NDT_FENCELIKE:
913                 case NDT_RAILLIKE:
914                 case NDT_NODEBOX:
915                         f->solidness = 0;
916                         break;
917                 }
918
919                 if (is_liquid) {
920                         material_type = (f->alpha == 255) ?
921                                 TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT;
922                         if (f->name == "default:water_source")
923                                 is_water_surface = true;
924                 }
925
926                 u32 tile_shader[6];
927                 for (u16 j = 0; j < 6; j++) {
928                         tile_shader[j] = shdsrc->getShader("nodes_shader",
929                                 material_type, f->drawtype);
930                 }
931
932                 if (is_water_surface) {
933                         tile_shader[0] = shdsrc->getShader("water_surface_shader",
934                                 material_type, f->drawtype);
935                 }
936
937                 // Tiles (fill in f->tiles[])
938                 for (u16 j = 0; j < 6; j++) {
939                         fillTileAttribs(tsrc, &f->tiles[j], &tiledef[j], tile_shader[j],
940                                 use_normal_texture, f->backface_culling, f->alpha, material_type);
941                 }
942
943                 // Special tiles (fill in f->special_tiles[])
944                 for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) {
945                         fillTileAttribs(tsrc, &f->special_tiles[j], &f->tiledef_special[j],
946                                 tile_shader[j], use_normal_texture,
947                                 f->tiledef_special[j].backface_culling, f->alpha, material_type);
948                 }
949
950                 if ((f->drawtype == NDT_MESH) && (f->mesh != "")) {
951                         // Meshnode drawtype
952                         // Read the mesh and apply scale
953                         f->mesh_ptr[0] = gamedef->getMesh(f->mesh);
954                         if (f->mesh_ptr[0]){
955                                 v3f scale = v3f(1.0, 1.0, 1.0) * BS * f->visual_scale;
956                                 scaleMesh(f->mesh_ptr[0], scale);
957                                 recalculateBoundingBox(f->mesh_ptr[0]);
958                                 meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
959                         }
960                 } else if ((f->drawtype == NDT_NODEBOX) &&
961                                 ((f->node_box.type == NODEBOX_REGULAR) ||
962                                 (f->node_box.type == NODEBOX_FIXED)) &&
963                                 (!f->node_box.fixed.empty())) {
964                         //Convert regular nodebox nodes to meshnodes
965                         //Change the drawtype and apply scale
966                         f->drawtype = NDT_MESH;
967                         f->mesh_ptr[0] = convertNodeboxNodeToMesh(f);
968                         v3f scale = v3f(1.0, 1.0, 1.0) * f->visual_scale;
969                         scaleMesh(f->mesh_ptr[0], scale);
970                         recalculateBoundingBox(f->mesh_ptr[0]);
971                         meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
972                 }
973
974                 //Cache 6dfacedir and wallmounted rotated clones of meshes
975                 if (enable_mesh_cache && f->mesh_ptr[0] && (f->param_type_2 == CPT2_FACEDIR)) {
976                         for (u16 j = 1; j < 24; j++) {
977                                 f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
978                                 rotateMeshBy6dFacedir(f->mesh_ptr[j], j);
979                                 recalculateBoundingBox(f->mesh_ptr[j]);
980                                 meshmanip->recalculateNormals(f->mesh_ptr[j], true, false);
981                         }
982                 } else if (enable_mesh_cache && f->mesh_ptr[0] && (f->param_type_2 == CPT2_WALLMOUNTED)) {
983                         static const u8 wm_to_6d[6] = {20, 0, 16+1, 12+3, 8, 4+2};
984                         for (u16 j = 1; j < 6; j++) {
985                                 f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
986                                 rotateMeshBy6dFacedir(f->mesh_ptr[j], wm_to_6d[j]);
987                                 recalculateBoundingBox(f->mesh_ptr[j]);
988                                 meshmanip->recalculateNormals(f->mesh_ptr[j], true, false);
989                         }
990                         rotateMeshBy6dFacedir(f->mesh_ptr[0], wm_to_6d[0]);
991                         recalculateBoundingBox(f->mesh_ptr[0]);
992                         meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
993                 }
994
995                 progress_callback(progress_callback_args, i, size);
996         }
997 #endif
998 }
999
1000
1001 #ifndef SERVER
1002 void CNodeDefManager::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile,
1003                 TileDef *tiledef, u32 shader_id, bool use_normal_texture,
1004                 bool backface_culling, u8 alpha, u8 material_type)
1005 {
1006         tile->shader_id     = shader_id;
1007         tile->texture       = tsrc->getTextureForMesh(tiledef->name, &tile->texture_id);
1008         tile->alpha         = alpha;
1009         tile->material_type = material_type;
1010
1011         // Normal texture and shader flags texture
1012         if (use_normal_texture) {
1013                 tile->normal_texture = tsrc->getNormalTexture(tiledef->name);
1014         }
1015         tile->flags_texture = tsrc->getShaderFlagsTexture(tile->normal_texture ? true : false);
1016
1017         // Material flags
1018         tile->material_flags = 0;
1019         if (backface_culling)
1020                 tile->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
1021         if (tiledef->animation.type == TAT_VERTICAL_FRAMES)
1022                 tile->material_flags |= MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
1023         if (tiledef->tileable_horizontal)
1024                 tile->material_flags |= MATERIAL_FLAG_TILEABLE_HORIZONTAL;
1025         if (tiledef->tileable_vertical)
1026                 tile->material_flags |= MATERIAL_FLAG_TILEABLE_VERTICAL;
1027
1028         // Animation parameters
1029         int frame_count = 1;
1030         if (tile->material_flags & MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES) {
1031                 // Get texture size to determine frame count by aspect ratio
1032                 v2u32 size = tile->texture->getOriginalSize();
1033                 int frame_height = (float)size.X /
1034                                 (float)tiledef->animation.aspect_w *
1035                                 (float)tiledef->animation.aspect_h;
1036                 frame_count = size.Y / frame_height;
1037                 int frame_length_ms = 1000.0 * tiledef->animation.length / frame_count;
1038                 tile->animation_frame_count = frame_count;
1039                 tile->animation_frame_length_ms = frame_length_ms;
1040         }
1041
1042         if (frame_count == 1) {
1043                 tile->material_flags &= ~MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
1044         } else {
1045                 std::ostringstream os(std::ios::binary);
1046                 tile->frames.resize(frame_count);
1047
1048                 for (int i = 0; i < frame_count; i++) {
1049
1050                         FrameSpec frame;
1051
1052                         os.str("");
1053                         os << tiledef->name << "^[verticalframe:"
1054                                 << frame_count << ":" << i;
1055
1056                         frame.texture = tsrc->getTextureForMesh(os.str(), &frame.texture_id);
1057                         if (tile->normal_texture)
1058                                 frame.normal_texture = tsrc->getNormalTexture(os.str());
1059                         frame.flags_texture = tile->flags_texture;
1060                         tile->frames[i] = frame;
1061                 }
1062         }
1063 }
1064 #endif
1065
1066
1067 void CNodeDefManager::serialize(std::ostream &os, u16 protocol_version) const
1068 {
1069         writeU8(os, 1); // version
1070         u16 count = 0;
1071         std::ostringstream os2(std::ios::binary);
1072         for (u32 i = 0; i < m_content_features.size(); i++) {
1073                 if (i == CONTENT_IGNORE || i == CONTENT_AIR
1074                                 || i == CONTENT_UNKNOWN)
1075                         continue;
1076                 const ContentFeatures *f = &m_content_features[i];
1077                 if (f->name == "")
1078                         continue;
1079                 writeU16(os2, i);
1080                 // Wrap it in a string to allow different lengths without
1081                 // strict version incompatibilities
1082                 std::ostringstream wrapper_os(std::ios::binary);
1083                 f->serialize(wrapper_os, protocol_version);
1084                 os2<<serializeString(wrapper_os.str());
1085
1086                 // must not overflow
1087                 u16 next = count + 1;
1088                 FATAL_ERROR_IF(next < count, "Overflow");
1089                 count++;
1090         }
1091         writeU16(os, count);
1092         os << serializeLongString(os2.str());
1093 }
1094
1095
1096 void CNodeDefManager::deSerialize(std::istream &is)
1097 {
1098         clear();
1099         int version = readU8(is);
1100         if (version != 1)
1101                 throw SerializationError("unsupported NodeDefinitionManager version");
1102         u16 count = readU16(is);
1103         std::istringstream is2(deSerializeLongString(is), std::ios::binary);
1104         ContentFeatures f;
1105         for (u16 n = 0; n < count; n++) {
1106                 u16 i = readU16(is2);
1107
1108                 // Read it from the string wrapper
1109                 std::string wrapper = deSerializeString(is2);
1110                 std::istringstream wrapper_is(wrapper, std::ios::binary);
1111                 f.deSerialize(wrapper_is);
1112
1113                 // Check error conditions
1114                 if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) {
1115                         warningstream << "NodeDefManager::deSerialize(): "
1116                                 "not changing builtin node " << i << std::endl;
1117                         continue;
1118                 }
1119                 if (f.name == "") {
1120                         warningstream << "NodeDefManager::deSerialize(): "
1121                                 "received empty name" << std::endl;
1122                         continue;
1123                 }
1124
1125                 // Ignore aliases
1126                 u16 existing_id;
1127                 if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) {
1128                         warningstream << "NodeDefManager::deSerialize(): "
1129                                 "already defined with different ID: " << f.name << std::endl;
1130                         continue;
1131                 }
1132
1133                 // All is ok, add node definition with the requested ID
1134                 if (i >= m_content_features.size())
1135                         m_content_features.resize((u32)(i) + 1);
1136                 m_content_features[i] = f;
1137                 addNameIdMapping(i, f.name);
1138                 verbosestream << "deserialized " << f.name << std::endl;
1139         }
1140 }
1141
1142
1143 void CNodeDefManager::addNameIdMapping(content_t i, std::string name)
1144 {
1145         m_name_id_mapping.set(i, name);
1146         m_name_id_mapping_with_aliases.insert(std::make_pair(name, i));
1147 }
1148
1149
1150 IWritableNodeDefManager *createNodeDefManager()
1151 {
1152         return new CNodeDefManager();
1153 }
1154
1155
1156 //// Serialization of old ContentFeatures formats
1157 void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const
1158 {
1159         if (protocol_version == 13)
1160         {
1161                 writeU8(os, 5); // version
1162                 os<<serializeString(name);
1163                 writeU16(os, groups.size());
1164                 for (ItemGroupList::const_iterator
1165                                 i = groups.begin(); i != groups.end(); ++i) {
1166                         os<<serializeString(i->first);
1167                         writeS16(os, i->second);
1168                 }
1169                 writeU8(os, drawtype);
1170                 writeF1000(os, visual_scale);
1171                 writeU8(os, 6);
1172                 for (u32 i = 0; i < 6; i++)
1173                         tiledef[i].serialize(os, protocol_version);
1174                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1175                 writeU8(os, 2);
1176                 for (u32 i = 0; i < 2; i++)
1177                         tiledef_special[i].serialize(os, protocol_version);
1178                 writeU8(os, alpha);
1179                 writeU8(os, post_effect_color.getAlpha());
1180                 writeU8(os, post_effect_color.getRed());
1181                 writeU8(os, post_effect_color.getGreen());
1182                 writeU8(os, post_effect_color.getBlue());
1183                 writeU8(os, param_type);
1184                 writeU8(os, param_type_2);
1185                 writeU8(os, is_ground_content);
1186                 writeU8(os, light_propagates);
1187                 writeU8(os, sunlight_propagates);
1188                 writeU8(os, walkable);
1189                 writeU8(os, pointable);
1190                 writeU8(os, diggable);
1191                 writeU8(os, climbable);
1192                 writeU8(os, buildable_to);
1193                 os<<serializeString(""); // legacy: used to be metadata_name
1194                 writeU8(os, liquid_type);
1195                 os<<serializeString(liquid_alternative_flowing);
1196                 os<<serializeString(liquid_alternative_source);
1197                 writeU8(os, liquid_viscosity);
1198                 writeU8(os, light_source);
1199                 writeU32(os, damage_per_second);
1200                 node_box.serialize(os, protocol_version);
1201                 selection_box.serialize(os, protocol_version);
1202                 writeU8(os, legacy_facedir_simple);
1203                 writeU8(os, legacy_wallmounted);
1204                 serializeSimpleSoundSpec(sound_footstep, os);
1205                 serializeSimpleSoundSpec(sound_dig, os);
1206                 serializeSimpleSoundSpec(sound_dug, os);
1207         }
1208         else if (protocol_version > 13 && protocol_version < 24) {
1209                 writeU8(os, 6); // version
1210                 os<<serializeString(name);
1211                 writeU16(os, groups.size());
1212                 for (ItemGroupList::const_iterator
1213                         i = groups.begin(); i != groups.end(); ++i) {
1214                                 os<<serializeString(i->first);
1215                                 writeS16(os, i->second);
1216                 }
1217                 writeU8(os, drawtype);
1218                 writeF1000(os, visual_scale);
1219                 writeU8(os, 6);
1220                 for (u32 i = 0; i < 6; i++)
1221                         tiledef[i].serialize(os, protocol_version);
1222                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1223                 writeU8(os, 2);
1224                 for (u32 i = 0; i < 2; i++)
1225                         tiledef_special[i].serialize(os, protocol_version);
1226                 writeU8(os, alpha);
1227                 writeU8(os, post_effect_color.getAlpha());
1228                 writeU8(os, post_effect_color.getRed());
1229                 writeU8(os, post_effect_color.getGreen());
1230                 writeU8(os, post_effect_color.getBlue());
1231                 writeU8(os, param_type);
1232                 writeU8(os, param_type_2);
1233                 writeU8(os, is_ground_content);
1234                 writeU8(os, light_propagates);
1235                 writeU8(os, sunlight_propagates);
1236                 writeU8(os, walkable);
1237                 writeU8(os, pointable);
1238                 writeU8(os, diggable);
1239                 writeU8(os, climbable);
1240                 writeU8(os, buildable_to);
1241                 os<<serializeString(""); // legacy: used to be metadata_name
1242                 writeU8(os, liquid_type);
1243                 os<<serializeString(liquid_alternative_flowing);
1244                 os<<serializeString(liquid_alternative_source);
1245                 writeU8(os, liquid_viscosity);
1246                 writeU8(os, liquid_renewable);
1247                 writeU8(os, light_source);
1248                 writeU32(os, damage_per_second);
1249                 node_box.serialize(os, protocol_version);
1250                 selection_box.serialize(os, protocol_version);
1251                 writeU8(os, legacy_facedir_simple);
1252                 writeU8(os, legacy_wallmounted);
1253                 serializeSimpleSoundSpec(sound_footstep, os);
1254                 serializeSimpleSoundSpec(sound_dig, os);
1255                 serializeSimpleSoundSpec(sound_dug, os);
1256                 writeU8(os, rightclickable);
1257                 writeU8(os, drowning);
1258                 writeU8(os, leveled);
1259                 writeU8(os, liquid_range);
1260         } else
1261                 throw SerializationError("ContentFeatures::serialize(): "
1262                         "Unsupported version requested");
1263 }
1264
1265
1266 void ContentFeatures::deSerializeOld(std::istream &is, int version)
1267 {
1268         if (version == 5) // In PROTOCOL_VERSION 13
1269         {
1270                 name = deSerializeString(is);
1271                 groups.clear();
1272                 u32 groups_size = readU16(is);
1273                 for(u32 i=0; i<groups_size; i++){
1274                         std::string name = deSerializeString(is);
1275                         int value = readS16(is);
1276                         groups[name] = value;
1277                 }
1278                 drawtype = (enum NodeDrawType)readU8(is);
1279                 visual_scale = readF1000(is);
1280                 if (readU8(is) != 6)
1281                         throw SerializationError("unsupported tile count");
1282                 for (u32 i = 0; i < 6; i++)
1283                         tiledef[i].deSerialize(is);
1284                 if (readU8(is) != CF_SPECIAL_COUNT)
1285                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1286                 for (u32 i = 0; i < CF_SPECIAL_COUNT; i++)
1287                         tiledef_special[i].deSerialize(is);
1288                 alpha = readU8(is);
1289                 post_effect_color.setAlpha(readU8(is));
1290                 post_effect_color.setRed(readU8(is));
1291                 post_effect_color.setGreen(readU8(is));
1292                 post_effect_color.setBlue(readU8(is));
1293                 param_type = (enum ContentParamType)readU8(is);
1294                 param_type_2 = (enum ContentParamType2)readU8(is);
1295                 is_ground_content = readU8(is);
1296                 light_propagates = readU8(is);
1297                 sunlight_propagates = readU8(is);
1298                 walkable = readU8(is);
1299                 pointable = readU8(is);
1300                 diggable = readU8(is);
1301                 climbable = readU8(is);
1302                 buildable_to = readU8(is);
1303                 deSerializeString(is); // legacy: used to be metadata_name
1304                 liquid_type = (enum LiquidType)readU8(is);
1305                 liquid_alternative_flowing = deSerializeString(is);
1306                 liquid_alternative_source = deSerializeString(is);
1307                 liquid_viscosity = readU8(is);
1308                 light_source = readU8(is);
1309                 damage_per_second = readU32(is);
1310                 node_box.deSerialize(is);
1311                 selection_box.deSerialize(is);
1312                 legacy_facedir_simple = readU8(is);
1313                 legacy_wallmounted = readU8(is);
1314                 deSerializeSimpleSoundSpec(sound_footstep, is);
1315                 deSerializeSimpleSoundSpec(sound_dig, is);
1316                 deSerializeSimpleSoundSpec(sound_dug, is);
1317         } else if (version == 6) {
1318                 name = deSerializeString(is);
1319                 groups.clear();
1320                 u32 groups_size = readU16(is);
1321                 for (u32 i = 0; i < groups_size; i++) {
1322                         std::string name = deSerializeString(is);
1323                         int     value = readS16(is);
1324                         groups[name] = value;
1325                 }
1326                 drawtype = (enum NodeDrawType)readU8(is);
1327                 visual_scale = readF1000(is);
1328                 if (readU8(is) != 6)
1329                         throw SerializationError("unsupported tile count");
1330                 for (u32 i = 0; i < 6; i++)
1331                         tiledef[i].deSerialize(is);
1332                 // CF_SPECIAL_COUNT in version 6 = 2
1333                 if (readU8(is) != 2)
1334                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1335                 for (u32 i = 0; i < 2; i++)
1336                         tiledef_special[i].deSerialize(is);
1337                 alpha = readU8(is);
1338                 post_effect_color.setAlpha(readU8(is));
1339                 post_effect_color.setRed(readU8(is));
1340                 post_effect_color.setGreen(readU8(is));
1341                 post_effect_color.setBlue(readU8(is));
1342                 param_type = (enum ContentParamType)readU8(is);
1343                 param_type_2 = (enum ContentParamType2)readU8(is);
1344                 is_ground_content = readU8(is);
1345                 light_propagates = readU8(is);
1346                 sunlight_propagates = readU8(is);
1347                 walkable = readU8(is);
1348                 pointable = readU8(is);
1349                 diggable = readU8(is);
1350                 climbable = readU8(is);
1351                 buildable_to = readU8(is);
1352                 deSerializeString(is); // legacy: used to be metadata_name
1353                 liquid_type = (enum LiquidType)readU8(is);
1354                 liquid_alternative_flowing = deSerializeString(is);
1355                 liquid_alternative_source = deSerializeString(is);
1356                 liquid_viscosity = readU8(is);
1357                 liquid_renewable = readU8(is);
1358                 light_source = readU8(is);
1359                 damage_per_second = readU32(is);
1360                 node_box.deSerialize(is);
1361                 selection_box.deSerialize(is);
1362                 legacy_facedir_simple = readU8(is);
1363                 legacy_wallmounted = readU8(is);
1364                 deSerializeSimpleSoundSpec(sound_footstep, is);
1365                 deSerializeSimpleSoundSpec(sound_dig, is);
1366                 deSerializeSimpleSoundSpec(sound_dug, is);
1367                 rightclickable = readU8(is);
1368                 drowning = readU8(is);
1369                 leveled = readU8(is);
1370                 liquid_range = readU8(is);
1371         } else {
1372                 throw SerializationError("unsupported ContentFeatures version");
1373         }
1374 }
1375
1376
1377 inline bool CNodeDefManager::getNodeRegistrationStatus() const
1378 {
1379         return m_node_registration_complete;
1380 }
1381
1382
1383 inline void CNodeDefManager::setNodeRegistrationStatus(bool completed)
1384 {
1385         m_node_registration_complete = completed;
1386 }
1387
1388
1389 void CNodeDefManager::pendNodeResolve(NodeResolver *nr)
1390 {
1391         nr->m_ndef = this;
1392         if (m_node_registration_complete)
1393                 nr->nodeResolveInternal();
1394         else
1395                 m_pending_resolve_callbacks.push_back(nr);
1396 }
1397
1398
1399 bool CNodeDefManager::cancelNodeResolveCallback(NodeResolver *nr)
1400 {
1401         size_t len = m_pending_resolve_callbacks.size();
1402         for (size_t i = 0; i != len; i++) {
1403                 if (nr != m_pending_resolve_callbacks[i])
1404                         continue;
1405
1406                 len--;
1407                 m_pending_resolve_callbacks[i] = m_pending_resolve_callbacks[len];
1408                 m_pending_resolve_callbacks.resize(len);
1409                 return true;
1410         }
1411
1412         return false;
1413 }
1414
1415
1416 void CNodeDefManager::runNodeResolveCallbacks()
1417 {
1418         for (size_t i = 0; i != m_pending_resolve_callbacks.size(); i++) {
1419                 NodeResolver *nr = m_pending_resolve_callbacks[i];
1420                 nr->nodeResolveInternal();
1421         }
1422
1423         m_pending_resolve_callbacks.clear();
1424 }
1425
1426
1427 void CNodeDefManager::resetNodeResolveState()
1428 {
1429         m_node_registration_complete = false;
1430         m_pending_resolve_callbacks.clear();
1431 }
1432
1433
1434 ////
1435 //// NodeResolver
1436 ////
1437
1438 NodeResolver::NodeResolver()
1439 {
1440         m_ndef            = NULL;
1441         m_nodenames_idx   = 0;
1442         m_nnlistsizes_idx = 0;
1443         m_resolve_done    = false;
1444
1445         m_nodenames.reserve(16);
1446         m_nnlistsizes.reserve(4);
1447 }
1448
1449
1450 NodeResolver::~NodeResolver()
1451 {
1452         if (!m_resolve_done && m_ndef)
1453                 m_ndef->cancelNodeResolveCallback(this);
1454 }
1455
1456
1457 void NodeResolver::nodeResolveInternal()
1458 {
1459         m_nodenames_idx   = 0;
1460         m_nnlistsizes_idx = 0;
1461
1462         resolveNodeNames();
1463         m_resolve_done = true;
1464
1465         m_nodenames.clear();
1466         m_nnlistsizes.clear();
1467 }
1468
1469
1470 bool NodeResolver::getIdFromNrBacklog(content_t *result_out,
1471         const std::string &node_alt, content_t c_fallback)
1472 {
1473         if (m_nodenames_idx == m_nodenames.size()) {
1474                 *result_out = c_fallback;
1475                 errorstream << "NodeResolver: no more nodes in list" << std::endl;
1476                 return false;
1477         }
1478
1479         content_t c;
1480         std::string name = m_nodenames[m_nodenames_idx++];
1481
1482         bool success = m_ndef->getId(name, c);
1483         if (!success && node_alt != "") {
1484                 name = node_alt;
1485                 success = m_ndef->getId(name, c);
1486         }
1487
1488         if (!success) {
1489                 errorstream << "NodeResolver: failed to resolve node name '" << name
1490                         << "'." << std::endl;
1491                 c = c_fallback;
1492         }
1493
1494         *result_out = c;
1495         return success;
1496 }
1497
1498
1499 bool NodeResolver::getIdsFromNrBacklog(std::vector<content_t> *result_out,
1500         bool all_required, content_t c_fallback)
1501 {
1502         bool success = true;
1503
1504         if (m_nnlistsizes_idx == m_nnlistsizes.size()) {
1505                 errorstream << "NodeResolver: no more node lists" << std::endl;
1506                 return false;
1507         }
1508
1509         size_t length = m_nnlistsizes[m_nnlistsizes_idx++];
1510
1511         while (length--) {
1512                 if (m_nodenames_idx == m_nodenames.size()) {
1513                         errorstream << "NodeResolver: no more nodes in list" << std::endl;
1514                         return false;
1515                 }
1516
1517                 content_t c;
1518                 std::string &name = m_nodenames[m_nodenames_idx++];
1519
1520                 if (name.substr(0,6) != "group:") {
1521                         if (m_ndef->getId(name, c)) {
1522                                 result_out->push_back(c);
1523                         } else if (all_required) {
1524                                 errorstream << "NodeResolver: failed to resolve node name '"
1525                                         << name << "'." << std::endl;
1526                                 result_out->push_back(c_fallback);
1527                                 success = false;
1528                         }
1529                 } else {
1530                         std::set<content_t> cids;
1531                         std::set<content_t>::iterator it;
1532                         m_ndef->getIds(name, cids);
1533                         for (it = cids.begin(); it != cids.end(); ++it)
1534                                 result_out->push_back(*it);
1535                 }
1536         }
1537
1538         return success;
1539 }