Fix memory leak caused by mesh nodes (and nodeboxes)
[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 "main.h" // For g_settings
23 #include "itemdef.h"
24 #ifndef SERVER
25 #include "tile.h"
26 #include "mesh.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
37 /*
38         NodeBox
39 */
40
41 void NodeBox::reset()
42 {
43         type = NODEBOX_REGULAR;
44         // default is empty
45         fixed.clear();
46         // default is sign/ladder-like
47         wall_top = aabb3f(-BS/2, BS/2-BS/16., -BS/2, BS/2, BS/2, BS/2);
48         wall_bottom = aabb3f(-BS/2, -BS/2, -BS/2, BS/2, -BS/2+BS/16., BS/2);
49         wall_side = aabb3f(-BS/2, -BS/2, -BS/2, -BS/2+BS/16., BS/2, BS/2);
50 }
51
52 void NodeBox::serialize(std::ostream &os, u16 protocol_version) const
53 {
54         int version = protocol_version >= 21 ? 2 : 1;
55         writeU8(os, version);
56
57         if (version == 1 && type == NODEBOX_LEVELED)
58                 writeU8(os, NODEBOX_FIXED);
59         else
60                 writeU8(os, type);
61
62         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
63         {
64                 writeU16(os, fixed.size());
65                 for(std::vector<aabb3f>::const_iterator
66                                 i = fixed.begin();
67                                 i != fixed.end(); i++)
68                 {
69                         writeV3F1000(os, i->MinEdge);
70                         writeV3F1000(os, i->MaxEdge);
71                 }
72         }
73         else if(type == NODEBOX_WALLMOUNTED)
74         {
75                 writeV3F1000(os, wall_top.MinEdge);
76                 writeV3F1000(os, wall_top.MaxEdge);
77                 writeV3F1000(os, wall_bottom.MinEdge);
78                 writeV3F1000(os, wall_bottom.MaxEdge);
79                 writeV3F1000(os, wall_side.MinEdge);
80                 writeV3F1000(os, wall_side.MaxEdge);
81         }
82 }
83
84 void NodeBox::deSerialize(std::istream &is)
85 {
86         int version = readU8(is);
87         if(version < 1 || version > 2)
88                 throw SerializationError("unsupported NodeBox version");
89
90         reset();
91
92         type = (enum NodeBoxType)readU8(is);
93
94         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
95         {
96                 u16 fixed_count = readU16(is);
97                 while(fixed_count--)
98                 {
99                         aabb3f box;
100                         box.MinEdge = readV3F1000(is);
101                         box.MaxEdge = readV3F1000(is);
102                         fixed.push_back(box);
103                 }
104         }
105         else if(type == NODEBOX_WALLMOUNTED)
106         {
107                 wall_top.MinEdge = readV3F1000(is);
108                 wall_top.MaxEdge = readV3F1000(is);
109                 wall_bottom.MinEdge = readV3F1000(is);
110                 wall_bottom.MaxEdge = readV3F1000(is);
111                 wall_side.MinEdge = readV3F1000(is);
112                 wall_side.MaxEdge = readV3F1000(is);
113         }
114 }
115
116 /*
117         TileDef
118 */
119
120 void TileDef::serialize(std::ostream &os, u16 protocol_version) const
121 {
122         if(protocol_version >= 17)
123                 writeU8(os, 1);
124         else
125                 writeU8(os, 0);
126         os<<serializeString(name);
127         writeU8(os, animation.type);
128         writeU16(os, animation.aspect_w);
129         writeU16(os, animation.aspect_h);
130         writeF1000(os, animation.length);
131         if(protocol_version >= 17)
132                 writeU8(os, backface_culling);
133 }
134
135 void TileDef::deSerialize(std::istream &is)
136 {
137         int version = readU8(is);
138         name = deSerializeString(is);
139         animation.type = (TileAnimationType)readU8(is);
140         animation.aspect_w = readU16(is);
141         animation.aspect_h = readU16(is);
142         animation.length = readF1000(is);
143         if(version >= 1)
144                 backface_culling = readU8(is);
145 }
146
147 /*
148         SimpleSoundSpec serialization
149 */
150
151 static void serializeSimpleSoundSpec(const SimpleSoundSpec &ss,
152                 std::ostream &os)
153 {
154         os<<serializeString(ss.name);
155         writeF1000(os, ss.gain);
156 }
157 static void deSerializeSimpleSoundSpec(SimpleSoundSpec &ss, std::istream &is)
158 {
159         ss.name = deSerializeString(is);
160         ss.gain = readF1000(is);
161 }
162
163 /*
164         ContentFeatures
165 */
166
167 ContentFeatures::ContentFeatures()
168 {
169         reset();
170 }
171
172 ContentFeatures::~ContentFeatures()
173 {
174 #ifndef SERVER
175         for (u32 i = 0; i < 24; i++) {
176                 if (mesh_ptr[i])
177                         mesh_ptr[i]->drop();
178         }
179 #endif
180 }
181
182 void ContentFeatures::reset()
183 {
184         /*
185                 Cached stuff
186         */
187 #ifndef SERVER
188         solidness = 2;
189         visual_solidness = 0;
190         backface_culling = true;
191 #endif
192         has_on_construct = false;
193         has_on_destruct = false;
194         has_after_destruct = false;
195         /*
196                 Actual data
197
198                 NOTE: Most of this is always overridden by the default values given
199                       in builtin.lua
200         */
201         name = "";
202         groups.clear();
203         // Unknown nodes can be dug
204         groups["dig_immediate"] = 2;
205         drawtype = NDT_NORMAL;
206         mesh = "";
207 #ifndef SERVER
208         for(u32 i = 0; i < 24; i++)
209                 mesh_ptr[i] = NULL;
210 #endif
211         visual_scale = 1.0;
212         for(u32 i = 0; i < 6; i++)
213                 tiledef[i] = TileDef();
214         for(u16 j = 0; j < CF_SPECIAL_COUNT; j++)
215                 tiledef_special[j] = TileDef();
216         alpha = 255;
217         post_effect_color = video::SColor(0, 0, 0, 0);
218         param_type = CPT_NONE;
219         param_type_2 = CPT2_NONE;
220         is_ground_content = false;
221         light_propagates = false;
222         sunlight_propagates = false;
223         walkable = true;
224         pointable = true;
225         diggable = true;
226         climbable = false;
227         buildable_to = false;
228         rightclickable = true;
229         leveled = 0;
230         liquid_type = LIQUID_NONE;
231         liquid_alternative_flowing = "";
232         liquid_alternative_source = "";
233         liquid_viscosity = 0;
234         liquid_renewable = true;
235         freezemelt = "";
236         liquid_range = LIQUID_LEVEL_MAX+1;
237         drowning = 0;
238         light_source = 0;
239         damage_per_second = 0;
240         node_box = NodeBox();
241         selection_box = NodeBox();
242         collision_box = NodeBox();
243         waving = 0;
244         legacy_facedir_simple = false;
245         legacy_wallmounted = false;
246         sound_footstep = SimpleSoundSpec();
247         sound_dig = SimpleSoundSpec("__group");
248         sound_dug = SimpleSoundSpec();
249 }
250
251 void ContentFeatures::serialize(std::ostream &os, u16 protocol_version)
252 {
253         if(protocol_version < 24){
254                 serializeOld(os, protocol_version);
255                 return;
256         }
257
258         writeU8(os, 7); // version
259         os<<serializeString(name);
260         writeU16(os, groups.size());
261         for(ItemGroupList::const_iterator
262                         i = groups.begin(); i != groups.end(); i++){
263                 os<<serializeString(i->first);
264                 writeS16(os, i->second);
265         }
266         writeU8(os, drawtype);
267         writeF1000(os, visual_scale);
268         writeU8(os, 6);
269         for(u32 i = 0; i < 6; i++)
270                 tiledef[i].serialize(os, protocol_version);
271         writeU8(os, CF_SPECIAL_COUNT);
272         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++){
273                 tiledef_special[i].serialize(os, protocol_version);
274         }
275         writeU8(os, alpha);
276         writeU8(os, post_effect_color.getAlpha());
277         writeU8(os, post_effect_color.getRed());
278         writeU8(os, post_effect_color.getGreen());
279         writeU8(os, post_effect_color.getBlue());
280         writeU8(os, param_type);
281         writeU8(os, param_type_2);
282         writeU8(os, is_ground_content);
283         writeU8(os, light_propagates);
284         writeU8(os, sunlight_propagates);
285         writeU8(os, walkable);
286         writeU8(os, pointable);
287         writeU8(os, diggable);
288         writeU8(os, climbable);
289         writeU8(os, buildable_to);
290         os<<serializeString(""); // legacy: used to be metadata_name
291         writeU8(os, liquid_type);
292         os<<serializeString(liquid_alternative_flowing);
293         os<<serializeString(liquid_alternative_source);
294         writeU8(os, liquid_viscosity);
295         writeU8(os, liquid_renewable);
296         writeU8(os, light_source);
297         writeU32(os, damage_per_second);
298         node_box.serialize(os, protocol_version);
299         selection_box.serialize(os, protocol_version);
300         writeU8(os, legacy_facedir_simple);
301         writeU8(os, legacy_wallmounted);
302         serializeSimpleSoundSpec(sound_footstep, os);
303         serializeSimpleSoundSpec(sound_dig, os);
304         serializeSimpleSoundSpec(sound_dug, os);
305         writeU8(os, rightclickable);
306         writeU8(os, drowning);
307         writeU8(os, leveled);
308         writeU8(os, liquid_range);
309         writeU8(os, waving);
310         // Stuff below should be moved to correct place in a version that otherwise changes
311         // the protocol version
312         os<<serializeString(mesh);
313         collision_box.serialize(os, protocol_version);
314 }
315
316 void ContentFeatures::deSerialize(std::istream &is)
317 {
318         int version = readU8(is);
319         if(version != 7){
320                 deSerializeOld(is, version);
321                 return;
322         }
323
324         name = deSerializeString(is);
325         groups.clear();
326         u32 groups_size = readU16(is);
327         for(u32 i = 0; i < groups_size; i++){
328                 std::string name = deSerializeString(is);
329                 int value = readS16(is);
330                 groups[name] = value;
331         }
332         drawtype = (enum NodeDrawType)readU8(is);
333         visual_scale = readF1000(is);
334         if(readU8(is) != 6)
335                 throw SerializationError("unsupported tile count");
336         for(u32 i = 0; i < 6; i++)
337                 tiledef[i].deSerialize(is);
338         if(readU8(is) != CF_SPECIAL_COUNT)
339                 throw SerializationError("unsupported CF_SPECIAL_COUNT");
340         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++)
341                 tiledef_special[i].deSerialize(is);
342         alpha = readU8(is);
343         post_effect_color.setAlpha(readU8(is));
344         post_effect_color.setRed(readU8(is));
345         post_effect_color.setGreen(readU8(is));
346         post_effect_color.setBlue(readU8(is));
347         param_type = (enum ContentParamType)readU8(is);
348         param_type_2 = (enum ContentParamType2)readU8(is);
349         is_ground_content = readU8(is);
350         light_propagates = readU8(is);
351         sunlight_propagates = readU8(is);
352         walkable = readU8(is);
353         pointable = readU8(is);
354         diggable = readU8(is);
355         climbable = readU8(is);
356         buildable_to = readU8(is);
357         deSerializeString(is); // legacy: used to be metadata_name
358         liquid_type = (enum LiquidType)readU8(is);
359         liquid_alternative_flowing = deSerializeString(is);
360         liquid_alternative_source = deSerializeString(is);
361         liquid_viscosity = readU8(is);
362         liquid_renewable = readU8(is);
363         light_source = readU8(is);
364         damage_per_second = readU32(is);
365         node_box.deSerialize(is);
366         selection_box.deSerialize(is);
367         legacy_facedir_simple = readU8(is);
368         legacy_wallmounted = readU8(is);
369         deSerializeSimpleSoundSpec(sound_footstep, is);
370         deSerializeSimpleSoundSpec(sound_dig, is);
371         deSerializeSimpleSoundSpec(sound_dug, is);
372         rightclickable = readU8(is);
373         drowning = readU8(is);
374         leveled = readU8(is);
375         liquid_range = readU8(is);
376         waving = readU8(is);
377         // If you add anything here, insert it primarily inside the try-catch
378         // block to not need to increase the version.
379         try{
380                 // Stuff below should be moved to correct place in a version that
381                 // otherwise changes the protocol version
382         mesh = deSerializeString(is);
383         collision_box.deSerialize(is);
384         }catch(SerializationError &e) {};
385 }
386
387 /*
388         CNodeDefManager
389 */
390
391 class CNodeDefManager: public IWritableNodeDefManager {
392 public:
393         CNodeDefManager();
394         virtual ~CNodeDefManager();
395         void clear();
396         virtual IWritableNodeDefManager *clone();
397         virtual const ContentFeatures& get(content_t c) const;
398         virtual const ContentFeatures& get(const MapNode &n) const;
399         virtual bool getId(const std::string &name, content_t &result) const;
400         virtual content_t getId(const std::string &name) const;
401         virtual void getIds(const std::string &name, std::set<content_t> &result) const;
402         virtual const ContentFeatures& get(const std::string &name) const;
403         content_t allocateId();
404         virtual content_t set(const std::string &name, const ContentFeatures &def);
405         virtual content_t allocateDummy(const std::string &name);
406         virtual void updateAliases(IItemDefManager *idef);
407         virtual void updateTextures(IGameDef *gamedef);
408         void serialize(std::ostream &os, u16 protocol_version);
409         void deSerialize(std::istream &is);
410
411 private:
412         void addNameIdMapping(content_t i, std::string name);
413 #ifndef SERVER
414         void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef,
415                 u32 shader_id, bool use_normal_texture, bool backface_culling,
416                 u8 alpha, u8 material_type);
417 #endif
418
419         // Features indexed by id
420         std::vector<ContentFeatures> m_content_features;
421
422         // A mapping for fast converting back and forth between names and ids
423         NameIdMapping m_name_id_mapping;
424
425         // Like m_name_id_mapping, but only from names to ids, and includes
426         // item aliases too. Updated by updateAliases()
427         // Note: Not serialized.
428
429         std::map<std::string, content_t> m_name_id_mapping_with_aliases;
430
431         // A mapping from groups to a list of content_ts (and their levels)
432         // that belong to it.  Necessary for a direct lookup in getIds().
433         // Note: Not serialized.
434         std::map<std::string, GroupItems> m_group_to_items;
435
436         // Next possibly free id
437         content_t m_next_id;
438 };
439
440
441 CNodeDefManager::CNodeDefManager()
442 {
443         clear();
444 }
445
446
447 CNodeDefManager::~CNodeDefManager()
448 {
449 }
450
451
452 void CNodeDefManager::clear()
453 {
454         m_content_features.clear();
455         m_name_id_mapping.clear();
456         m_name_id_mapping_with_aliases.clear();
457         m_group_to_items.clear();
458         m_next_id = 0;
459
460         u32 initial_length = 0;
461         initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1);
462         initial_length = MYMAX(initial_length, CONTENT_AIR + 1);
463         initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1);
464         m_content_features.resize(initial_length);
465
466         // Set CONTENT_UNKNOWN
467         {
468                 ContentFeatures f;
469                 f.name = "unknown";
470                 // Insert directly into containers
471                 content_t c = CONTENT_UNKNOWN;
472                 m_content_features[c] = f;
473                 addNameIdMapping(c, f.name);
474         }
475
476         // Set CONTENT_AIR
477         {
478                 ContentFeatures f;
479                 f.name                = "air";
480                 f.drawtype            = NDT_AIRLIKE;
481                 f.param_type          = CPT_LIGHT;
482                 f.light_propagates    = true;
483                 f.sunlight_propagates = true;
484                 f.walkable            = false;
485                 f.pointable           = false;
486                 f.diggable            = false;
487                 f.buildable_to        = true;
488                 f.is_ground_content   = true;
489                 // Insert directly into containers
490                 content_t c = CONTENT_AIR;
491                 m_content_features[c] = f;
492                 addNameIdMapping(c, f.name);
493         }
494
495         // Set CONTENT_IGNORE
496         {
497                 ContentFeatures f;
498                 f.name                = "ignore";
499                 f.drawtype            = NDT_AIRLIKE;
500                 f.param_type          = CPT_NONE;
501                 f.light_propagates    = false;
502                 f.sunlight_propagates = false;
503                 f.walkable            = false;
504                 f.pointable           = false;
505                 f.diggable            = false;
506                 f.buildable_to        = true; // A way to remove accidental CONTENT_IGNOREs
507                 f.is_ground_content   = true;
508                 // Insert directly into containers
509                 content_t c = CONTENT_IGNORE;
510                 m_content_features[c] = f;
511                 addNameIdMapping(c, f.name);
512         }
513 }
514
515
516 IWritableNodeDefManager *CNodeDefManager::clone()
517 {
518         CNodeDefManager *mgr = new CNodeDefManager();
519         *mgr = *this;
520         return mgr;
521 }
522
523
524 const ContentFeatures& CNodeDefManager::get(content_t c) const
525 {
526         if (c < m_content_features.size())
527                 return m_content_features[c];
528         else
529                 return m_content_features[CONTENT_UNKNOWN];
530 }
531
532
533 const ContentFeatures& CNodeDefManager::get(const MapNode &n) const
534 {
535         return get(n.getContent());
536 }
537
538
539 bool CNodeDefManager::getId(const std::string &name, content_t &result) const
540 {
541         std::map<std::string, content_t>::const_iterator
542                 i = m_name_id_mapping_with_aliases.find(name);
543         if(i == m_name_id_mapping_with_aliases.end())
544                 return false;
545         result = i->second;
546         return true;
547 }
548
549
550 content_t CNodeDefManager::getId(const std::string &name) const
551 {
552         content_t id = CONTENT_IGNORE;
553         getId(name, id);
554         return id;
555 }
556
557
558 void CNodeDefManager::getIds(const std::string &name,
559                 std::set<content_t> &result) const
560 {
561         //TimeTaker t("getIds", NULL, PRECISION_MICRO);
562         if (name.substr(0,6) != "group:") {
563                 content_t id = CONTENT_IGNORE;
564                 if(getId(name, id))
565                         result.insert(id);
566                 return;
567         }
568         std::string group = name.substr(6);
569
570         std::map<std::string, GroupItems>::const_iterator
571                 i = m_group_to_items.find(group);
572         if (i == m_group_to_items.end())
573                 return;
574
575         const GroupItems &items = i->second;
576         for (GroupItems::const_iterator j = items.begin();
577                 j != items.end(); ++j) {
578                 if ((*j).second != 0)
579                         result.insert((*j).first);
580         }
581         //printf("getIds: %dus\n", t.stop());
582 }
583
584
585 const ContentFeatures& CNodeDefManager::get(const std::string &name) const
586 {
587         content_t id = CONTENT_UNKNOWN;
588         getId(name, id);
589         return get(id);
590 }
591
592
593 // returns CONTENT_IGNORE if no free ID found
594 content_t CNodeDefManager::allocateId()
595 {
596         for (content_t id = m_next_id;
597                         id >= m_next_id; // overflow?
598                         ++id) {
599                 while (id >= m_content_features.size()) {
600                         m_content_features.push_back(ContentFeatures());
601                 }
602                 const ContentFeatures &f = m_content_features[id];
603                 if (f.name == "") {
604                         m_next_id = id + 1;
605                         return id;
606                 }
607         }
608         // If we arrive here, an overflow occurred in id.
609         // That means no ID was found
610         return CONTENT_IGNORE;
611 }
612
613
614 // IWritableNodeDefManager
615 content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
616 {
617         assert(name != "");
618         assert(name == def.name);
619
620         // Don't allow redefining ignore (but allow air and unknown)
621         if (name == "ignore") {
622                 infostream << "NodeDefManager: WARNING: Ignoring "
623                         "CONTENT_IGNORE redefinition"<<std::endl;
624                 return CONTENT_IGNORE;
625         }
626
627         content_t id = CONTENT_IGNORE;
628         if (!m_name_id_mapping.getId(name, id)) { // ignore aliases
629                 // Get new id
630                 id = allocateId();
631                 if (id == CONTENT_IGNORE) {
632                         infostream << "NodeDefManager: WARNING: Absolute "
633                                 "limit reached" << std::endl;
634                         return CONTENT_IGNORE;
635                 }
636                 assert(id != CONTENT_IGNORE);
637                 addNameIdMapping(id, name);
638         }
639         m_content_features[id] = def;
640         verbosestream << "NodeDefManager: registering content id \"" << id
641                 << "\": name=\"" << def.name << "\""<<std::endl;
642
643         // Add this content to the list of all groups it belongs to
644         // FIXME: This should remove a node from groups it no longer
645         // belongs to when a node is re-registered
646         for (ItemGroupList::const_iterator i = def.groups.begin();
647                 i != def.groups.end(); ++i) {
648                 std::string group_name = i->first;
649
650                 std::map<std::string, GroupItems>::iterator
651                         j = m_group_to_items.find(group_name);
652                 if (j == m_group_to_items.end()) {
653                         m_group_to_items[group_name].push_back(
654                                         std::make_pair(id, i->second));
655                 } else {
656                         GroupItems &items = j->second;
657                         items.push_back(std::make_pair(id, i->second));
658                 }
659         }
660         return id;
661 }
662
663
664 content_t CNodeDefManager::allocateDummy(const std::string &name)
665 {
666         assert(name != "");
667         ContentFeatures f;
668         f.name = name;
669         return set(name, f);
670 }
671
672
673 void CNodeDefManager::updateAliases(IItemDefManager *idef)
674 {
675         std::set<std::string> all = idef->getAll();
676         m_name_id_mapping_with_aliases.clear();
677         for (std::set<std::string>::iterator
678                         i = all.begin(); i != all.end(); i++) {
679                 std::string name = *i;
680                 std::string convert_to = idef->getAlias(name);
681                 content_t id;
682                 if (m_name_id_mapping.getId(convert_to, id)) {
683                         m_name_id_mapping_with_aliases.insert(
684                                         std::make_pair(name, id));
685                 }
686         }
687 }
688
689
690 void CNodeDefManager::updateTextures(IGameDef *gamedef)
691 {
692 #ifndef SERVER
693         infostream << "CNodeDefManager::updateTextures(): Updating "
694                 "textures in node definitions" << std::endl;
695         
696         ITextureSource *tsrc = gamedef->tsrc();
697         IShaderSource *shdsrc = gamedef->getShaderSource();
698
699         bool new_style_water           = g_settings->getBool("new_style_water");
700         bool new_style_leaves          = g_settings->getBool("new_style_leaves");
701         bool connected_glass           = g_settings->getBool("connected_glass");
702         bool opaque_water              = g_settings->getBool("opaque_water");
703         bool enable_shaders            = g_settings->getBool("enable_shaders");
704         bool enable_bumpmapping        = g_settings->getBool("enable_bumpmapping");
705         bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion");
706
707         bool use_normal_texture = enable_shaders &&
708                 (enable_bumpmapping || enable_parallax_occlusion);
709
710         for (u32 i = 0; i < m_content_features.size(); i++) {
711                 ContentFeatures *f = &m_content_features[i];
712
713                 // Figure out the actual tiles to use
714                 TileDef tiledef[6];
715                 for (u32 j = 0; j < 6; j++) {
716                         tiledef[j] = f->tiledef[j];
717                         if (tiledef[j].name == "")
718                                 tiledef[j].name = "unknown_node.png";
719                 }
720
721                 bool is_liquid = false;
722                 bool is_water_surface = false;
723
724                 u8 material_type = (f->alpha == 255) ?
725                         TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA;
726
727                 switch (f->drawtype) {
728                 default:
729                 case NDT_NORMAL:
730                         f->solidness = 2;
731                         break;
732                 case NDT_AIRLIKE:
733                         f->solidness = 0;
734                         break;
735                 case NDT_LIQUID:
736                         assert(f->liquid_type == LIQUID_SOURCE);
737                         if (opaque_water)
738                                 f->alpha = 255;
739                         if (new_style_water){
740                                 f->solidness = 0;
741                         } else {
742                                 f->solidness = 1;
743                                 f->backface_culling = false;
744                         }
745                         is_liquid = true;
746                         break;
747                 case NDT_FLOWINGLIQUID:
748                         assert(f->liquid_type == LIQUID_FLOWING);
749                         f->solidness = 0;
750                         if (opaque_water)
751                                 f->alpha = 255;
752                         is_liquid = true;
753                         break;
754                 case NDT_GLASSLIKE:
755                         f->solidness = 0;
756                         f->visual_solidness = 1;
757                         break;
758                 case NDT_GLASSLIKE_FRAMED:
759                         f->solidness = 0;
760                         f->visual_solidness = 1;
761                         break;
762                 case NDT_GLASSLIKE_FRAMED_OPTIONAL:
763                         f->solidness = 0;
764                         f->visual_solidness = 1;
765                         f->drawtype = connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE;
766                         break;
767                 case NDT_ALLFACES:
768                         f->solidness = 0;
769                         f->visual_solidness = 1;
770                         break;
771                 case NDT_ALLFACES_OPTIONAL:
772                         if (new_style_leaves) {
773                                 f->drawtype = NDT_ALLFACES;
774                                 f->solidness = 0;
775                                 f->visual_solidness = 1;
776                         } else {
777                                 f->drawtype = NDT_NORMAL;
778                                 f->solidness = 2;
779                                 for (u32 i = 0; i < 6; i++)
780                                         tiledef[i].name += std::string("^[noalpha");
781                         }
782                         if (f->waving == 1)
783                                 material_type = TILE_MATERIAL_WAVING_LEAVES;
784                         break;
785                 case NDT_PLANTLIKE:
786                         f->solidness = 0;
787                         f->backface_culling = false;
788                         if (f->waving == 1)
789                                 material_type = TILE_MATERIAL_WAVING_PLANTS;
790                         break;
791                 case NDT_FIRELIKE:
792                         f->backface_culling = false;
793                         f->solidness = 0;
794                         break;
795                 case NDT_MESH:
796                         f->solidness = 0;
797                         f->backface_culling = false;
798                         break;
799                 case NDT_TORCHLIKE:
800                 case NDT_SIGNLIKE:
801                 case NDT_FENCELIKE:
802                 case NDT_RAILLIKE:
803                 case NDT_NODEBOX:
804                         f->solidness = 0;
805                         break;
806                 }
807
808                 if (is_liquid) {
809                         material_type = (f->alpha == 255) ?
810                                 TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT;
811                         if (f->name == "default:water_source")
812                                 is_water_surface = true;
813                 }
814
815                 u32 tile_shader[6];
816                 for (u16 j = 0; j < 6; j++) {
817                         tile_shader[j] = shdsrc->getShader("nodes_shader",
818                                 material_type, f->drawtype);
819                 }
820
821                 if (is_water_surface) {
822                         tile_shader[0] = shdsrc->getShader("water_surface_shader",
823                                 material_type, f->drawtype);
824                 }
825
826                 // Tiles (fill in f->tiles[])
827                 for (u16 j = 0; j < 6; j++) {
828                         fillTileAttribs(tsrc, &f->tiles[j], &tiledef[j], tile_shader[j],
829                                 use_normal_texture, f->backface_culling, f->alpha, material_type);
830                 }
831
832                 // Special tiles (fill in f->special_tiles[])
833                 for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) {
834                         fillTileAttribs(tsrc, &f->special_tiles[j], &f->tiledef_special[j],
835                                 tile_shader[j], use_normal_texture,
836                                 f->tiledef_special[j].backface_culling, f->alpha, material_type);
837                 }
838
839                 // Meshnode drawtype
840                 // Read the mesh and apply scale
841                 if ((f->drawtype == NDT_MESH) && (f->mesh != "")) {
842                         f->mesh_ptr[0] = gamedef->getMesh(f->mesh);
843                         scaleMesh(f->mesh_ptr[0], v3f(f->visual_scale,f->visual_scale,f->visual_scale));
844                         recalculateBoundingBox(f->mesh_ptr[0]);
845                 }
846
847                 //Convert regular nodebox nodes to meshnodes
848                 //Change the drawtype and apply scale
849                 if ((f->drawtype == NDT_NODEBOX) && 
850                                 ((f->node_box.type == NODEBOX_REGULAR) || (f->node_box.type == NODEBOX_FIXED)) &&
851                                 (!f->node_box.fixed.empty())) {
852                         f->drawtype = NDT_MESH;
853                         f->mesh_ptr[0] = convertNodeboxNodeToMesh(f);
854                         scaleMesh(f->mesh_ptr[0], v3f(f->visual_scale,f->visual_scale,f->visual_scale));
855                         recalculateBoundingBox(f->mesh_ptr[0]);
856                 }
857
858                 //Cache 6dfacedir rotated clones of meshes
859                 if (f->mesh_ptr[0] && (f->param_type_2 == CPT2_FACEDIR)) {
860                                 for (u16 j = 1; j < 24; j++) {
861                                         f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
862                                         rotateMeshBy6dFacedir(f->mesh_ptr[j], j);
863                                         recalculateBoundingBox(f->mesh_ptr[j]);
864                                 }
865                         }
866         }
867 #endif
868 }
869
870
871 #ifndef SERVER
872 void CNodeDefManager::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile,
873                 TileDef *tiledef, u32 shader_id, bool use_normal_texture,
874                 bool backface_culling, u8 alpha, u8 material_type)
875 {
876         tile->shader_id     = shader_id;
877         tile->texture       = tsrc->getTexture(tiledef->name, &tile->texture_id);
878         tile->alpha         = alpha;
879         tile->material_type = material_type;
880
881         // Normal texture
882         if (use_normal_texture)
883                 tile->normal_texture = tsrc->getNormalTexture(tiledef->name);
884
885         // Material flags
886         tile->material_flags = 0;
887         if (backface_culling)
888                 tile->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
889         if (tiledef->animation.type == TAT_VERTICAL_FRAMES)
890                 tile->material_flags |= MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
891
892         // Animation parameters
893         int frame_count = 1;
894         if (tile->material_flags & MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES) {
895                 // Get texture size to determine frame count by aspect ratio
896                 v2u32 size = tile->texture->getOriginalSize();
897                 int frame_height = (float)size.X /
898                                 (float)tiledef->animation.aspect_w *
899                                 (float)tiledef->animation.aspect_h;
900                 frame_count = size.Y / frame_height;
901                 int frame_length_ms = 1000.0 * tiledef->animation.length / frame_count;
902                 tile->animation_frame_count = frame_count;
903                 tile->animation_frame_length_ms = frame_length_ms;
904         }
905
906         if (frame_count == 1) {
907                 tile->material_flags &= ~MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
908         } else {
909                 std::ostringstream os(std::ios::binary);
910                 for (int i = 0; i < frame_count; i++) {
911                         FrameSpec frame;
912
913                         os.str("");
914                         os << tiledef->name << "^[verticalframe:"
915                                 << frame_count << ":" << i;
916
917                         frame.texture = tsrc->getTexture(os.str(), &frame.texture_id);
918                         if (tile->normal_texture)
919                                 frame.normal_texture = tsrc->getNormalTexture(os.str());
920                         tile->frames[i] = frame;
921                 }
922         }
923 }
924 #endif
925
926
927 void CNodeDefManager::serialize(std::ostream &os, u16 protocol_version)
928 {
929         writeU8(os, 1); // version
930         u16 count = 0;
931         std::ostringstream os2(std::ios::binary);
932         for (u32 i = 0; i < m_content_features.size(); i++) {
933                 if (i == CONTENT_IGNORE || i == CONTENT_AIR
934                                 || i == CONTENT_UNKNOWN)
935                         continue;
936                 ContentFeatures *f = &m_content_features[i];
937                 if (f->name == "")
938                         continue;
939                 writeU16(os2, i);
940                 // Wrap it in a string to allow different lengths without
941                 // strict version incompatibilities
942                 std::ostringstream wrapper_os(std::ios::binary);
943                 f->serialize(wrapper_os, protocol_version);
944                 os2<<serializeString(wrapper_os.str());
945
946                 assert(count + 1 > count); // must not overflow
947                 count++;
948         }
949         writeU16(os, count);
950         os << serializeLongString(os2.str());
951 }
952
953
954 void CNodeDefManager::deSerialize(std::istream &is)
955 {
956         clear();
957         int version = readU8(is);
958         if (version != 1)
959                 throw SerializationError("unsupported NodeDefinitionManager version");
960         u16 count = readU16(is);
961         std::istringstream is2(deSerializeLongString(is), std::ios::binary);
962         ContentFeatures f;
963         for (u16 n = 0; n < count; n++) {
964                 u16 i = readU16(is2);
965
966                 // Read it from the string wrapper
967                 std::string wrapper = deSerializeString(is2);
968                 std::istringstream wrapper_is(wrapper, std::ios::binary);
969                 f.deSerialize(wrapper_is);
970
971                 // Check error conditions
972                 if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) {
973                         infostream << "NodeDefManager::deSerialize(): WARNING: "
974                                 "not changing builtin node " << i << std::endl;
975                         continue;
976                 }
977                 if (f.name == "") {
978                         infostream << "NodeDefManager::deSerialize(): WARNING: "
979                                 "received empty name" << std::endl;
980                         continue;
981                 }
982
983                 // Ignore aliases
984                 u16 existing_id;
985                 if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) {
986                         infostream << "NodeDefManager::deSerialize(): WARNING: "
987                                 "already defined with different ID: " << f.name << std::endl;
988                         continue;
989                 }
990
991                 // All is ok, add node definition with the requested ID
992                 if (i >= m_content_features.size())
993                         m_content_features.resize((u32)(i) + 1);
994                 m_content_features[i] = f;
995                 addNameIdMapping(i, f.name);
996                 verbosestream << "deserialized " << f.name << std::endl;
997         }
998 }
999
1000
1001 void CNodeDefManager::addNameIdMapping(content_t i, std::string name)
1002 {
1003         m_name_id_mapping.set(i, name);
1004         m_name_id_mapping_with_aliases.insert(std::make_pair(name, i));
1005 }
1006
1007
1008 IWritableNodeDefManager *createNodeDefManager()
1009 {
1010         return new CNodeDefManager();
1011 }
1012
1013
1014 //// Serialization of old ContentFeatures formats
1015 void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version)
1016 {
1017         if (protocol_version == 13)
1018         {
1019                 writeU8(os, 5); // version
1020                 os<<serializeString(name);
1021                 writeU16(os, groups.size());
1022                 for (ItemGroupList::const_iterator
1023                                 i = groups.begin(); i != groups.end(); i++) {
1024                         os<<serializeString(i->first);
1025                         writeS16(os, i->second);
1026                 }
1027                 writeU8(os, drawtype);
1028                 writeF1000(os, visual_scale);
1029                 writeU8(os, 6);
1030                 for (u32 i = 0; i < 6; i++)
1031                         tiledef[i].serialize(os, protocol_version);
1032                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1033                 writeU8(os, 2);
1034                 for (u32 i = 0; i < 2; i++)
1035                         tiledef_special[i].serialize(os, protocol_version);
1036                 writeU8(os, alpha);
1037                 writeU8(os, post_effect_color.getAlpha());
1038                 writeU8(os, post_effect_color.getRed());
1039                 writeU8(os, post_effect_color.getGreen());
1040                 writeU8(os, post_effect_color.getBlue());
1041                 writeU8(os, param_type);
1042                 writeU8(os, param_type_2);
1043                 writeU8(os, is_ground_content);
1044                 writeU8(os, light_propagates);
1045                 writeU8(os, sunlight_propagates);
1046                 writeU8(os, walkable);
1047                 writeU8(os, pointable);
1048                 writeU8(os, diggable);
1049                 writeU8(os, climbable);
1050                 writeU8(os, buildable_to);
1051                 os<<serializeString(""); // legacy: used to be metadata_name
1052                 writeU8(os, liquid_type);
1053                 os<<serializeString(liquid_alternative_flowing);
1054                 os<<serializeString(liquid_alternative_source);
1055                 writeU8(os, liquid_viscosity);
1056                 writeU8(os, light_source);
1057                 writeU32(os, damage_per_second);
1058                 node_box.serialize(os, protocol_version);
1059                 selection_box.serialize(os, protocol_version);
1060                 writeU8(os, legacy_facedir_simple);
1061                 writeU8(os, legacy_wallmounted);
1062                 serializeSimpleSoundSpec(sound_footstep, os);
1063                 serializeSimpleSoundSpec(sound_dig, os);
1064                 serializeSimpleSoundSpec(sound_dug, os);
1065         }
1066         else if (protocol_version > 13 && protocol_version < 24) {
1067                 writeU8(os, 6); // version
1068                 os<<serializeString(name);
1069                 writeU16(os, groups.size());
1070                 for (ItemGroupList::const_iterator
1071                         i = groups.begin(); i != groups.end(); i++) {
1072                                 os<<serializeString(i->first);
1073                                 writeS16(os, i->second);
1074                 }
1075                 writeU8(os, drawtype);
1076                 writeF1000(os, visual_scale);
1077                 writeU8(os, 6);
1078                 for (u32 i = 0; i < 6; i++)
1079                         tiledef[i].serialize(os, protocol_version);
1080                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1081                 writeU8(os, 2);
1082                 for (u32 i = 0; i < 2; i++)
1083                         tiledef_special[i].serialize(os, protocol_version);
1084                 writeU8(os, alpha);
1085                 writeU8(os, post_effect_color.getAlpha());
1086                 writeU8(os, post_effect_color.getRed());
1087                 writeU8(os, post_effect_color.getGreen());
1088                 writeU8(os, post_effect_color.getBlue());
1089                 writeU8(os, param_type);
1090                 writeU8(os, param_type_2);
1091                 writeU8(os, is_ground_content);
1092                 writeU8(os, light_propagates);
1093                 writeU8(os, sunlight_propagates);
1094                 writeU8(os, walkable);
1095                 writeU8(os, pointable);
1096                 writeU8(os, diggable);
1097                 writeU8(os, climbable);
1098                 writeU8(os, buildable_to);
1099                 os<<serializeString(""); // legacy: used to be metadata_name
1100                 writeU8(os, liquid_type);
1101                 os<<serializeString(liquid_alternative_flowing);
1102                 os<<serializeString(liquid_alternative_source);
1103                 writeU8(os, liquid_viscosity);
1104                 writeU8(os, liquid_renewable);
1105                 writeU8(os, light_source);
1106                 writeU32(os, damage_per_second);
1107                 node_box.serialize(os, protocol_version);
1108                 selection_box.serialize(os, protocol_version);
1109                 writeU8(os, legacy_facedir_simple);
1110                 writeU8(os, legacy_wallmounted);
1111                 serializeSimpleSoundSpec(sound_footstep, os);
1112                 serializeSimpleSoundSpec(sound_dig, os);
1113                 serializeSimpleSoundSpec(sound_dug, os);
1114                 writeU8(os, rightclickable);
1115                 writeU8(os, drowning);
1116                 writeU8(os, leveled);
1117                 writeU8(os, liquid_range);
1118         } else 
1119                 throw SerializationError("ContentFeatures::serialize(): "
1120                         "Unsupported version requested");
1121 }
1122
1123
1124 void ContentFeatures::deSerializeOld(std::istream &is, int version)
1125 {
1126         if (version == 5) // In PROTOCOL_VERSION 13
1127         {
1128                 name = deSerializeString(is);
1129                 groups.clear();
1130                 u32 groups_size = readU16(is);
1131                 for(u32 i=0; i<groups_size; i++){
1132                         std::string name = deSerializeString(is);
1133                         int value = readS16(is);
1134                         groups[name] = value;
1135                 }
1136                 drawtype = (enum NodeDrawType)readU8(is);
1137                 visual_scale = readF1000(is);
1138                 if (readU8(is) != 6)
1139                         throw SerializationError("unsupported tile count");
1140                 for (u32 i = 0; i < 6; i++)
1141                         tiledef[i].deSerialize(is);
1142                 if (readU8(is) != CF_SPECIAL_COUNT)
1143                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1144                 for (u32 i = 0; i < CF_SPECIAL_COUNT; i++)
1145                         tiledef_special[i].deSerialize(is);
1146                 alpha = readU8(is);
1147                 post_effect_color.setAlpha(readU8(is));
1148                 post_effect_color.setRed(readU8(is));
1149                 post_effect_color.setGreen(readU8(is));
1150                 post_effect_color.setBlue(readU8(is));
1151                 param_type = (enum ContentParamType)readU8(is);
1152                 param_type_2 = (enum ContentParamType2)readU8(is);
1153                 is_ground_content = readU8(is);
1154                 light_propagates = readU8(is);
1155                 sunlight_propagates = readU8(is);
1156                 walkable = readU8(is);
1157                 pointable = readU8(is);
1158                 diggable = readU8(is);
1159                 climbable = readU8(is);
1160                 buildable_to = readU8(is);
1161                 deSerializeString(is); // legacy: used to be metadata_name
1162                 liquid_type = (enum LiquidType)readU8(is);
1163                 liquid_alternative_flowing = deSerializeString(is);
1164                 liquid_alternative_source = deSerializeString(is);
1165                 liquid_viscosity = readU8(is);
1166                 light_source = readU8(is);
1167                 damage_per_second = readU32(is);
1168                 node_box.deSerialize(is);
1169                 selection_box.deSerialize(is);
1170                 legacy_facedir_simple = readU8(is);
1171                 legacy_wallmounted = readU8(is);
1172                 deSerializeSimpleSoundSpec(sound_footstep, is);
1173                 deSerializeSimpleSoundSpec(sound_dig, is);
1174                 deSerializeSimpleSoundSpec(sound_dug, is);
1175         } else if (version == 6) {
1176                 name = deSerializeString(is);
1177                 groups.clear();
1178                 u32 groups_size = readU16(is);
1179                 for (u32 i = 0; i < groups_size; i++) {
1180                         std::string name = deSerializeString(is);
1181                         int     value = readS16(is);
1182                         groups[name] = value;
1183                 }
1184                 drawtype = (enum NodeDrawType)readU8(is);
1185                 visual_scale = readF1000(is);
1186                 if (readU8(is) != 6)
1187                         throw SerializationError("unsupported tile count");
1188                 for (u32 i = 0; i < 6; i++)
1189                         tiledef[i].deSerialize(is);
1190                 // CF_SPECIAL_COUNT in version 6 = 2
1191                 if (readU8(is) != 2)
1192                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1193                 for (u32 i = 0; i < 2; i++)
1194                         tiledef_special[i].deSerialize(is);
1195                 alpha = readU8(is);
1196                 post_effect_color.setAlpha(readU8(is));
1197                 post_effect_color.setRed(readU8(is));
1198                 post_effect_color.setGreen(readU8(is));
1199                 post_effect_color.setBlue(readU8(is));
1200                 param_type = (enum ContentParamType)readU8(is);
1201                 param_type_2 = (enum ContentParamType2)readU8(is);
1202                 is_ground_content = readU8(is);
1203                 light_propagates = readU8(is);
1204                 sunlight_propagates = readU8(is);
1205                 walkable = readU8(is);
1206                 pointable = readU8(is);
1207                 diggable = readU8(is);
1208                 climbable = readU8(is);
1209                 buildable_to = readU8(is);
1210                 deSerializeString(is); // legacy: used to be metadata_name
1211                 liquid_type = (enum LiquidType)readU8(is);
1212                 liquid_alternative_flowing = deSerializeString(is);
1213                 liquid_alternative_source = deSerializeString(is);
1214                 liquid_viscosity = readU8(is);
1215                 liquid_renewable = readU8(is);
1216                 light_source = readU8(is);
1217                 damage_per_second = readU32(is);
1218                 node_box.deSerialize(is);
1219                 selection_box.deSerialize(is);
1220                 legacy_facedir_simple = readU8(is);
1221                 legacy_wallmounted = readU8(is);
1222                 deSerializeSimpleSoundSpec(sound_footstep, is);
1223                 deSerializeSimpleSoundSpec(sound_dig, is);
1224                 deSerializeSimpleSoundSpec(sound_dug, is);
1225                 rightclickable = readU8(is);
1226                 drowning = readU8(is);
1227                 leveled = readU8(is);
1228                 liquid_range = readU8(is);
1229         } else {
1230                 throw SerializationError("unsupported ContentFeatures version");
1231         }
1232 }