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