Player collisionbox: Make settable
[oweals/minetest.git] / src / map.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-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 "map.h"
21 #include "mapsector.h"
22 #include "mapblock.h"
23 #include "filesys.h"
24 #include "voxel.h"
25 #include "voxelalgorithms.h"
26 #include "porting.h"
27 #include "serialization.h"
28 #include "nodemetadata.h"
29 #include "settings.h"
30 #include "log.h"
31 #include "profiler.h"
32 #include "nodedef.h"
33 #include "gamedef.h"
34 #include "util/directiontables.h"
35 #include "util/basic_macros.h"
36 #include "rollback_interface.h"
37 #include "environment.h"
38 #include "reflowscan.h"
39 #include "emerge.h"
40 #include "mapgen_v6.h"
41 #include "mg_biome.h"
42 #include "config.h"
43 #include "server.h"
44 #include "database.h"
45 #include "database-dummy.h"
46 #include "database-sqlite3.h"
47 #include "script/scripting_server.h"
48 #include <deque>
49 #include <queue>
50 #if USE_LEVELDB
51 #include "database-leveldb.h"
52 #endif
53 #if USE_REDIS
54 #include "database-redis.h"
55 #endif
56 #if USE_POSTGRESQL
57 #include "database-postgresql.h"
58 #endif
59
60
61 /*
62         Map
63 */
64
65 Map::Map(std::ostream &dout, IGameDef *gamedef):
66         m_dout(dout),
67         m_gamedef(gamedef),
68         m_nodedef(gamedef->ndef())
69 {
70 }
71
72 Map::~Map()
73 {
74         /*
75                 Free all MapSectors
76         */
77         for(std::map<v2s16, MapSector*>::iterator i = m_sectors.begin();
78                 i != m_sectors.end(); ++i)
79         {
80                 delete i->second;
81         }
82 }
83
84 void Map::addEventReceiver(MapEventReceiver *event_receiver)
85 {
86         m_event_receivers.insert(event_receiver);
87 }
88
89 void Map::removeEventReceiver(MapEventReceiver *event_receiver)
90 {
91         m_event_receivers.erase(event_receiver);
92 }
93
94 void Map::dispatchEvent(MapEditEvent *event)
95 {
96         for(std::set<MapEventReceiver*>::iterator
97                         i = m_event_receivers.begin();
98                         i != m_event_receivers.end(); ++i)
99         {
100                 (*i)->onMapEditEvent(event);
101         }
102 }
103
104 MapSector * Map::getSectorNoGenerateNoExNoLock(v2s16 p)
105 {
106         if(m_sector_cache != NULL && p == m_sector_cache_p){
107                 MapSector * sector = m_sector_cache;
108                 return sector;
109         }
110
111         std::map<v2s16, MapSector*>::iterator n = m_sectors.find(p);
112
113         if(n == m_sectors.end())
114                 return NULL;
115
116         MapSector *sector = n->second;
117
118         // Cache the last result
119         m_sector_cache_p = p;
120         m_sector_cache = sector;
121
122         return sector;
123 }
124
125 MapSector * Map::getSectorNoGenerateNoEx(v2s16 p)
126 {
127         return getSectorNoGenerateNoExNoLock(p);
128 }
129
130 MapSector * Map::getSectorNoGenerate(v2s16 p)
131 {
132         MapSector *sector = getSectorNoGenerateNoEx(p);
133         if(sector == NULL)
134                 throw InvalidPositionException();
135
136         return sector;
137 }
138
139 MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d)
140 {
141         v2s16 p2d(p3d.X, p3d.Z);
142         MapSector * sector = getSectorNoGenerateNoEx(p2d);
143         if(sector == NULL)
144                 return NULL;
145         MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y);
146         return block;
147 }
148
149 MapBlock * Map::getBlockNoCreate(v3s16 p3d)
150 {
151         MapBlock *block = getBlockNoCreateNoEx(p3d);
152         if(block == NULL)
153                 throw InvalidPositionException();
154         return block;
155 }
156
157 bool Map::isNodeUnderground(v3s16 p)
158 {
159         v3s16 blockpos = getNodeBlockPos(p);
160         try{
161                 MapBlock * block = getBlockNoCreate(blockpos);
162                 return block->getIsUnderground();
163         }
164         catch(InvalidPositionException &e)
165         {
166                 return false;
167         }
168 }
169
170 bool Map::isValidPosition(v3s16 p)
171 {
172         v3s16 blockpos = getNodeBlockPos(p);
173         MapBlock *block = getBlockNoCreateNoEx(blockpos);
174         return (block != NULL);
175 }
176
177 // Returns a CONTENT_IGNORE node if not found
178 MapNode Map::getNodeNoEx(v3s16 p, bool *is_valid_position)
179 {
180         v3s16 blockpos = getNodeBlockPos(p);
181         MapBlock *block = getBlockNoCreateNoEx(blockpos);
182         if (block == NULL) {
183                 if (is_valid_position != NULL)
184                         *is_valid_position = false;
185                 return MapNode(CONTENT_IGNORE);
186         }
187
188         v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
189         bool is_valid_p;
190         MapNode node = block->getNodeNoCheck(relpos, &is_valid_p);
191         if (is_valid_position != NULL)
192                 *is_valid_position = is_valid_p;
193         return node;
194 }
195
196 #if 0
197 // Deprecated
198 // throws InvalidPositionException if not found
199 // TODO: Now this is deprecated, getNodeNoEx should be renamed
200 MapNode Map::getNode(v3s16 p)
201 {
202         v3s16 blockpos = getNodeBlockPos(p);
203         MapBlock *block = getBlockNoCreateNoEx(blockpos);
204         if (block == NULL)
205                 throw InvalidPositionException();
206         v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
207         bool is_valid_position;
208         MapNode node = block->getNodeNoCheck(relpos, &is_valid_position);
209         if (!is_valid_position)
210                 throw InvalidPositionException();
211         return node;
212 }
213 #endif
214
215 // throws InvalidPositionException if not found
216 void Map::setNode(v3s16 p, MapNode & n)
217 {
218         v3s16 blockpos = getNodeBlockPos(p);
219         MapBlock *block = getBlockNoCreate(blockpos);
220         v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
221         // Never allow placing CONTENT_IGNORE, it fucks up stuff
222         if(n.getContent() == CONTENT_IGNORE){
223                 bool temp_bool;
224                 errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE"
225                                 <<" while trying to replace \""
226                                 <<m_nodedef->get(block->getNodeNoCheck(relpos, &temp_bool)).name
227                                 <<"\" at "<<PP(p)<<" (block "<<PP(blockpos)<<")"<<std::endl;
228                 debug_stacks_print_to(infostream);
229                 return;
230         }
231         block->setNodeNoCheck(relpos, n);
232 }
233
234 void Map::addNodeAndUpdate(v3s16 p, MapNode n,
235                 std::map<v3s16, MapBlock*> &modified_blocks,
236                 bool remove_metadata)
237 {
238         // Collect old node for rollback
239         RollbackNode rollback_oldnode(this, p, m_gamedef);
240
241         // This is needed for updating the lighting
242         MapNode oldnode = getNodeNoEx(p);
243
244         // Remove node metadata
245         if (remove_metadata) {
246                 removeNodeMetadata(p);
247         }
248
249         // Set the node on the map
250         // Ignore light (because calling voxalgo::update_lighting_nodes)
251         n.setLight(LIGHTBANK_DAY, 0, m_nodedef);
252         n.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
253         setNode(p, n);
254
255         // Update lighting
256         std::vector<std::pair<v3s16, MapNode> > oldnodes;
257         oldnodes.push_back(std::pair<v3s16, MapNode>(p, oldnode));
258         voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks);
259
260         for(std::map<v3s16, MapBlock*>::iterator
261                         i = modified_blocks.begin();
262                         i != modified_blocks.end(); ++i)
263         {
264                 i->second->expireDayNightDiff();
265         }
266
267         // Report for rollback
268         if(m_gamedef->rollback())
269         {
270                 RollbackNode rollback_newnode(this, p, m_gamedef);
271                 RollbackAction action;
272                 action.setSetNode(p, rollback_oldnode, rollback_newnode);
273                 m_gamedef->rollback()->reportAction(action);
274         }
275
276         /*
277                 Add neighboring liquid nodes and this node to transform queue.
278                 (it's vital for the node itself to get updated last, if it was removed.)
279          */
280         v3s16 dirs[7] = {
281                 v3s16(0,0,1), // back
282                 v3s16(0,1,0), // top
283                 v3s16(1,0,0), // right
284                 v3s16(0,0,-1), // front
285                 v3s16(0,-1,0), // bottom
286                 v3s16(-1,0,0), // left
287                 v3s16(0,0,0), // self
288         };
289         for(u16 i=0; i<7; i++)
290         {
291                 v3s16 p2 = p + dirs[i];
292
293                 bool is_valid_position;
294                 MapNode n2 = getNodeNoEx(p2, &is_valid_position);
295                 if(is_valid_position &&
296                                 (m_nodedef->get(n2).isLiquid() ||
297                                 n2.getContent() == CONTENT_AIR))
298                         m_transforming_liquid.push_back(p2);
299         }
300 }
301
302 void Map::removeNodeAndUpdate(v3s16 p,
303                 std::map<v3s16, MapBlock*> &modified_blocks)
304 {
305         addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true);
306 }
307
308 bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata)
309 {
310         MapEditEvent event;
311         event.type = remove_metadata ? MEET_ADDNODE : MEET_SWAPNODE;
312         event.p = p;
313         event.n = n;
314
315         bool succeeded = true;
316         try{
317                 std::map<v3s16, MapBlock*> modified_blocks;
318                 addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
319
320                 // Copy modified_blocks to event
321                 for(std::map<v3s16, MapBlock*>::iterator
322                                 i = modified_blocks.begin();
323                                 i != modified_blocks.end(); ++i)
324                 {
325                         event.modified_blocks.insert(i->first);
326                 }
327         }
328         catch(InvalidPositionException &e){
329                 succeeded = false;
330         }
331
332         dispatchEvent(&event);
333
334         return succeeded;
335 }
336
337 bool Map::removeNodeWithEvent(v3s16 p)
338 {
339         MapEditEvent event;
340         event.type = MEET_REMOVENODE;
341         event.p = p;
342
343         bool succeeded = true;
344         try{
345                 std::map<v3s16, MapBlock*> modified_blocks;
346                 removeNodeAndUpdate(p, modified_blocks);
347
348                 // Copy modified_blocks to event
349                 for(std::map<v3s16, MapBlock*>::iterator
350                                 i = modified_blocks.begin();
351                                 i != modified_blocks.end(); ++i)
352                 {
353                         event.modified_blocks.insert(i->first);
354                 }
355         }
356         catch(InvalidPositionException &e){
357                 succeeded = false;
358         }
359
360         dispatchEvent(&event);
361
362         return succeeded;
363 }
364
365 bool Map::getDayNightDiff(v3s16 blockpos)
366 {
367         try{
368                 v3s16 p = blockpos + v3s16(0,0,0);
369                 MapBlock *b = getBlockNoCreate(p);
370                 if(b->getDayNightDiff())
371                         return true;
372         }
373         catch(InvalidPositionException &e){}
374         // Leading edges
375         try{
376                 v3s16 p = blockpos + v3s16(-1,0,0);
377                 MapBlock *b = getBlockNoCreate(p);
378                 if(b->getDayNightDiff())
379                         return true;
380         }
381         catch(InvalidPositionException &e){}
382         try{
383                 v3s16 p = blockpos + v3s16(0,-1,0);
384                 MapBlock *b = getBlockNoCreate(p);
385                 if(b->getDayNightDiff())
386                         return true;
387         }
388         catch(InvalidPositionException &e){}
389         try{
390                 v3s16 p = blockpos + v3s16(0,0,-1);
391                 MapBlock *b = getBlockNoCreate(p);
392                 if(b->getDayNightDiff())
393                         return true;
394         }
395         catch(InvalidPositionException &e){}
396         // Trailing edges
397         try{
398                 v3s16 p = blockpos + v3s16(1,0,0);
399                 MapBlock *b = getBlockNoCreate(p);
400                 if(b->getDayNightDiff())
401                         return true;
402         }
403         catch(InvalidPositionException &e){}
404         try{
405                 v3s16 p = blockpos + v3s16(0,1,0);
406                 MapBlock *b = getBlockNoCreate(p);
407                 if(b->getDayNightDiff())
408                         return true;
409         }
410         catch(InvalidPositionException &e){}
411         try{
412                 v3s16 p = blockpos + v3s16(0,0,1);
413                 MapBlock *b = getBlockNoCreate(p);
414                 if(b->getDayNightDiff())
415                         return true;
416         }
417         catch(InvalidPositionException &e){}
418
419         return false;
420 }
421
422 struct TimeOrderedMapBlock {
423         MapSector *sect;
424         MapBlock *block;
425
426         TimeOrderedMapBlock(MapSector *sect, MapBlock *block) :
427                 sect(sect),
428                 block(block)
429         {}
430
431         bool operator<(const TimeOrderedMapBlock &b) const
432         {
433                 return block->getUsageTimer() < b.block->getUsageTimer();
434         };
435 };
436
437 /*
438         Updates usage timers
439 */
440 void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
441                 std::vector<v3s16> *unloaded_blocks)
442 {
443         bool save_before_unloading = (mapType() == MAPTYPE_SERVER);
444
445         // Profile modified reasons
446         Profiler modprofiler;
447
448         std::vector<v2s16> sector_deletion_queue;
449         u32 deleted_blocks_count = 0;
450         u32 saved_blocks_count = 0;
451         u32 block_count_all = 0;
452
453         beginSave();
454
455         // If there is no practical limit, we spare creation of mapblock_queue
456         if (max_loaded_blocks == U32_MAX) {
457                 for (std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
458                                 si != m_sectors.end(); ++si) {
459                         MapSector *sector = si->second;
460
461                         bool all_blocks_deleted = true;
462
463                         MapBlockVect blocks;
464                         sector->getBlocks(blocks);
465
466                         for (MapBlockVect::iterator i = blocks.begin();
467                                         i != blocks.end(); ++i) {
468                                 MapBlock *block = (*i);
469
470                                 block->incrementUsageTimer(dtime);
471
472                                 if (block->refGet() == 0
473                                                 && block->getUsageTimer() > unload_timeout) {
474                                         v3s16 p = block->getPos();
475
476                                         // Save if modified
477                                         if (block->getModified() != MOD_STATE_CLEAN
478                                                         && save_before_unloading) {
479                                                 modprofiler.add(block->getModifiedReasonString(), 1);
480                                                 if (!saveBlock(block))
481                                                         continue;
482                                                 saved_blocks_count++;
483                                         }
484
485                                         // Delete from memory
486                                         sector->deleteBlock(block);
487
488                                         if (unloaded_blocks)
489                                                 unloaded_blocks->push_back(p);
490
491                                         deleted_blocks_count++;
492                                 } else {
493                                         all_blocks_deleted = false;
494                                         block_count_all++;
495                                 }
496                         }
497
498                         if (all_blocks_deleted) {
499                                 sector_deletion_queue.push_back(si->first);
500                         }
501                 }
502         } else {
503                 std::priority_queue<TimeOrderedMapBlock> mapblock_queue;
504                 for (std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
505                                 si != m_sectors.end(); ++si) {
506                         MapSector *sector = si->second;
507
508                         MapBlockVect blocks;
509                         sector->getBlocks(blocks);
510
511                         for(MapBlockVect::iterator i = blocks.begin();
512                                         i != blocks.end(); ++i) {
513                                 MapBlock *block = (*i);
514
515                                 block->incrementUsageTimer(dtime);
516                                 mapblock_queue.push(TimeOrderedMapBlock(sector, block));
517                         }
518                 }
519                 block_count_all = mapblock_queue.size();
520                 // Delete old blocks, and blocks over the limit from the memory
521                 while (!mapblock_queue.empty() && (mapblock_queue.size() > max_loaded_blocks
522                                 || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) {
523                         TimeOrderedMapBlock b = mapblock_queue.top();
524                         mapblock_queue.pop();
525
526                         MapBlock *block = b.block;
527
528                         if (block->refGet() != 0)
529                                 continue;
530
531                         v3s16 p = block->getPos();
532
533                         // Save if modified
534                         if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) {
535                                 modprofiler.add(block->getModifiedReasonString(), 1);
536                                 if (!saveBlock(block))
537                                         continue;
538                                 saved_blocks_count++;
539                         }
540
541                         // Delete from memory
542                         b.sect->deleteBlock(block);
543
544                         if (unloaded_blocks)
545                                 unloaded_blocks->push_back(p);
546
547                         deleted_blocks_count++;
548                         block_count_all--;
549                 }
550                 // Delete empty sectors
551                 for (std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
552                         si != m_sectors.end(); ++si) {
553                         if (si->second->empty()) {
554                                 sector_deletion_queue.push_back(si->first);
555                         }
556                 }
557         }
558         endSave();
559
560         // Finally delete the empty sectors
561         deleteSectors(sector_deletion_queue);
562
563         if(deleted_blocks_count != 0)
564         {
565                 PrintInfo(infostream); // ServerMap/ClientMap:
566                 infostream<<"Unloaded "<<deleted_blocks_count
567                                 <<" blocks from memory";
568                 if(save_before_unloading)
569                         infostream<<", of which "<<saved_blocks_count<<" were written";
570                 infostream<<", "<<block_count_all<<" blocks in memory";
571                 infostream<<"."<<std::endl;
572                 if(saved_blocks_count != 0){
573                         PrintInfo(infostream); // ServerMap/ClientMap:
574                         infostream<<"Blocks modified by: "<<std::endl;
575                         modprofiler.print(infostream);
576                 }
577         }
578 }
579
580 void Map::unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks)
581 {
582         timerUpdate(0.0, -1.0, 0, unloaded_blocks);
583 }
584
585 void Map::deleteSectors(std::vector<v2s16> &sectorList)
586 {
587         for(std::vector<v2s16>::iterator j = sectorList.begin();
588                 j != sectorList.end(); ++j) {
589                 MapSector *sector = m_sectors[*j];
590                 // If sector is in sector cache, remove it from there
591                 if(m_sector_cache == sector)
592                         m_sector_cache = NULL;
593                 // Remove from map and delete
594                 m_sectors.erase(*j);
595                 delete sector;
596         }
597 }
598
599 void Map::PrintInfo(std::ostream &out)
600 {
601         out<<"Map: ";
602 }
603
604 #define WATER_DROP_BOOST 4
605
606 enum NeighborType {
607         NEIGHBOR_UPPER,
608         NEIGHBOR_SAME_LEVEL,
609         NEIGHBOR_LOWER
610 };
611 struct NodeNeighbor {
612         MapNode n;
613         NeighborType t;
614         v3s16 p;
615         bool l; //can liquid
616
617         NodeNeighbor()
618                 : n(CONTENT_AIR)
619         { }
620
621         NodeNeighbor(const MapNode &node, NeighborType n_type, v3s16 pos)
622                 : n(node),
623                   t(n_type),
624                   p(pos)
625         { }
626 };
627
628 void Map::transforming_liquid_add(v3s16 p) {
629         m_transforming_liquid.push_back(p);
630 }
631
632 s32 Map::transforming_liquid_size() {
633         return m_transforming_liquid.size();
634 }
635
636 void Map::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks,
637                 ServerEnvironment *env)
638 {
639         DSTACK(FUNCTION_NAME);
640         //TimeTaker timer("transformLiquids()");
641
642         u32 loopcount = 0;
643         u32 initial_size = m_transforming_liquid.size();
644
645         /*if(initial_size != 0)
646                 infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/
647
648         // list of nodes that due to viscosity have not reached their max level height
649         std::deque<v3s16> must_reflow;
650
651         std::vector<std::pair<v3s16, MapNode> > changed_nodes;
652
653         u32 liquid_loop_max = g_settings->getS32("liquid_loop_max");
654         u32 loop_max = liquid_loop_max;
655
656 #if 0
657
658         /* If liquid_loop_max is not keeping up with the queue size increase
659          * loop_max up to a maximum of liquid_loop_max * dedicated_server_step.
660          */
661         if (m_transforming_liquid.size() > loop_max * 2) {
662                 // "Burst" mode
663                 float server_step = g_settings->getFloat("dedicated_server_step");
664                 if (m_transforming_liquid_loop_count_multiplier - 1.0 < server_step)
665                         m_transforming_liquid_loop_count_multiplier *= 1.0 + server_step / 10;
666         } else {
667                 m_transforming_liquid_loop_count_multiplier = 1.0;
668         }
669
670         loop_max *= m_transforming_liquid_loop_count_multiplier;
671 #endif
672
673         while (m_transforming_liquid.size() != 0)
674         {
675                 // This should be done here so that it is done when continue is used
676                 if (loopcount >= initial_size || loopcount >= loop_max)
677                         break;
678                 loopcount++;
679
680                 /*
681                         Get a queued transforming liquid node
682                 */
683                 v3s16 p0 = m_transforming_liquid.front();
684                 m_transforming_liquid.pop_front();
685
686                 MapNode n0 = getNodeNoEx(p0);
687
688                 /*
689                         Collect information about current node
690                  */
691                 s8 liquid_level = -1;
692                 // The liquid node which will be placed there if
693                 // the liquid flows into this node.
694                 content_t liquid_kind = CONTENT_IGNORE;
695                 // The node which will be placed there if liquid
696                 // can't flow into this node.
697                 content_t floodable_node = CONTENT_AIR;
698                 const ContentFeatures &cf = m_nodedef->get(n0);
699                 LiquidType liquid_type = cf.liquid_type;
700                 switch (liquid_type) {
701                         case LIQUID_SOURCE:
702                                 liquid_level = LIQUID_LEVEL_SOURCE;
703                                 liquid_kind = m_nodedef->getId(cf.liquid_alternative_flowing);
704                                 break;
705                         case LIQUID_FLOWING:
706                                 liquid_level = (n0.param2 & LIQUID_LEVEL_MASK);
707                                 liquid_kind = n0.getContent();
708                                 break;
709                         case LIQUID_NONE:
710                                 // if this node is 'floodable', it *could* be transformed
711                                 // into a liquid, otherwise, continue with the next node.
712                                 if (!cf.floodable)
713                                         continue;
714                                 floodable_node = n0.getContent();
715                                 liquid_kind = CONTENT_AIR;
716                                 break;
717                 }
718
719                 /*
720                         Collect information about the environment
721                  */
722                 const v3s16 *dirs = g_6dirs;
723                 NodeNeighbor sources[6]; // surrounding sources
724                 int num_sources = 0;
725                 NodeNeighbor flows[6]; // surrounding flowing liquid nodes
726                 int num_flows = 0;
727                 NodeNeighbor airs[6]; // surrounding air
728                 int num_airs = 0;
729                 NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid
730                 int num_neutrals = 0;
731                 bool flowing_down = false;
732                 bool ignored_sources = false;
733                 for (u16 i = 0; i < 6; i++) {
734                         NeighborType nt = NEIGHBOR_SAME_LEVEL;
735                         switch (i) {
736                                 case 1:
737                                         nt = NEIGHBOR_UPPER;
738                                         break;
739                                 case 4:
740                                         nt = NEIGHBOR_LOWER;
741                                         break;
742                         }
743                         v3s16 npos = p0 + dirs[i];
744                         NodeNeighbor nb(getNodeNoEx(npos), nt, npos);
745                         const ContentFeatures &cfnb = m_nodedef->get(nb.n);
746                         switch (m_nodedef->get(nb.n.getContent()).liquid_type) {
747                                 case LIQUID_NONE:
748                                         if (cfnb.floodable) {
749                                                 airs[num_airs++] = nb;
750                                                 // if the current node is a water source the neighbor
751                                                 // should be enqueded for transformation regardless of whether the
752                                                 // current node changes or not.
753                                                 if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE)
754                                                         m_transforming_liquid.push_back(npos);
755                                                 // if the current node happens to be a flowing node, it will start to flow down here.
756                                                 if (nb.t == NEIGHBOR_LOWER)
757                                                         flowing_down = true;
758                                         } else {
759                                                 neutrals[num_neutrals++] = nb;
760                                                 if (nb.n.getContent() == CONTENT_IGNORE) {
761                                                         // If node below is ignore prevent water from
762                                                         // spreading outwards and otherwise prevent from
763                                                         // flowing away as ignore node might be the source
764                                                         if (nb.t == NEIGHBOR_LOWER)
765                                                                 flowing_down = true;
766                                                         else
767                                                                 ignored_sources = true;
768                                                 }
769                                         }
770                                         break;
771                                 case LIQUID_SOURCE:
772                                         // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
773                                         if (liquid_kind == CONTENT_AIR)
774                                                 liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing);
775                                         if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) {
776                                                 neutrals[num_neutrals++] = nb;
777                                         } else {
778                                                 // Do not count bottom source, it will screw things up
779                                                 if(dirs[i].Y != -1)
780                                                         sources[num_sources++] = nb;
781                                         }
782                                         break;
783                                 case LIQUID_FLOWING:
784                                         // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
785                                         if (liquid_kind == CONTENT_AIR)
786                                                 liquid_kind = m_nodedef->getId(cfnb.liquid_alternative_flowing);
787                                         if (m_nodedef->getId(cfnb.liquid_alternative_flowing) != liquid_kind) {
788                                                 neutrals[num_neutrals++] = nb;
789                                         } else {
790                                                 flows[num_flows++] = nb;
791                                                 if (nb.t == NEIGHBOR_LOWER)
792                                                         flowing_down = true;
793                                         }
794                                         break;
795                         }
796                 }
797
798                 /*
799                         decide on the type (and possibly level) of the current node
800                  */
801                 content_t new_node_content;
802                 s8 new_node_level = -1;
803                 s8 max_node_level = -1;
804
805                 u8 range = m_nodedef->get(liquid_kind).liquid_range;
806                 if (range > LIQUID_LEVEL_MAX + 1)
807                         range = LIQUID_LEVEL_MAX + 1;
808
809                 if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) {
810                         // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid)
811                         // or the flowing alternative of the first of the surrounding sources (if it's air), so
812                         // it's perfectly safe to use liquid_kind here to determine the new node content.
813                         new_node_content = m_nodedef->getId(m_nodedef->get(liquid_kind).liquid_alternative_source);
814                 } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) {
815                         // liquid_kind is set properly, see above
816                         max_node_level = new_node_level = LIQUID_LEVEL_MAX;
817                         if (new_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
818                                 new_node_content = liquid_kind;
819                         else
820                                 new_node_content = floodable_node;
821                 } else if (ignored_sources && liquid_level >= 0) {
822                         // Maybe there are neighbouring sources that aren't loaded yet
823                         // so prevent flowing away.
824                         new_node_level = liquid_level;
825                         new_node_content = liquid_kind;
826                 } else {
827                         // no surrounding sources, so get the maximum level that can flow into this node
828                         for (u16 i = 0; i < num_flows; i++) {
829                                 u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK);
830                                 switch (flows[i].t) {
831                                         case NEIGHBOR_UPPER:
832                                                 if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) {
833                                                         max_node_level = LIQUID_LEVEL_MAX;
834                                                         if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX)
835                                                                 max_node_level = nb_liquid_level + WATER_DROP_BOOST;
836                                                 } else if (nb_liquid_level > max_node_level) {
837                                                         max_node_level = nb_liquid_level;
838                                                 }
839                                                 break;
840                                         case NEIGHBOR_LOWER:
841                                                 break;
842                                         case NEIGHBOR_SAME_LEVEL:
843                                                 if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK &&
844                                                                 nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level)
845                                                         max_node_level = nb_liquid_level - 1;
846                                                 break;
847                                 }
848                         }
849
850                         u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity;
851                         if (viscosity > 1 && max_node_level != liquid_level) {
852                                 // amount to gain, limited by viscosity
853                                 // must be at least 1 in absolute value
854                                 s8 level_inc = max_node_level - liquid_level;
855                                 if (level_inc < -viscosity || level_inc > viscosity)
856                                         new_node_level = liquid_level + level_inc/viscosity;
857                                 else if (level_inc < 0)
858                                         new_node_level = liquid_level - 1;
859                                 else if (level_inc > 0)
860                                         new_node_level = liquid_level + 1;
861                                 if (new_node_level != max_node_level)
862                                         must_reflow.push_back(p0);
863                         } else {
864                                 new_node_level = max_node_level;
865                         }
866
867                         if (max_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
868                                 new_node_content = liquid_kind;
869                         else
870                                 new_node_content = floodable_node;
871
872                 }
873
874                 /*
875                         check if anything has changed. if not, just continue with the next node.
876                  */
877                 if (new_node_content == n0.getContent() &&
878                                 (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING ||
879                                 ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level &&
880                                 ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK)
881                                 == flowing_down)))
882                         continue;
883
884
885                 /*
886                         update the current node
887                  */
888                 MapNode n00 = n0;
889                 //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK));
890                 if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) {
891                         // set level to last 3 bits, flowing down bit to 4th bit
892                         n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK);
893                 } else {
894                         // set the liquid level and flow bit to 0
895                         n0.param2 = ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK);
896                 }
897
898                 // change the node.
899                 n0.setContent(new_node_content);
900
901                 // on_flood() the node
902                 if (floodable_node != CONTENT_AIR) {
903                         if (env->getScriptIface()->node_on_flood(p0, n00, n0))
904                                 continue;
905                 }
906
907                 // Ignore light (because calling voxalgo::update_lighting_nodes)
908                 n0.setLight(LIGHTBANK_DAY, 0, m_nodedef);
909                 n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
910
911                 // Find out whether there is a suspect for this action
912                 std::string suspect;
913                 if (m_gamedef->rollback())
914                         suspect = m_gamedef->rollback()->getSuspect(p0, 83, 1);
915
916                 if (m_gamedef->rollback() && !suspect.empty()) {
917                         // Blame suspect
918                         RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true);
919                         // Get old node for rollback
920                         RollbackNode rollback_oldnode(this, p0, m_gamedef);
921                         // Set node
922                         setNode(p0, n0);
923                         // Report
924                         RollbackNode rollback_newnode(this, p0, m_gamedef);
925                         RollbackAction action;
926                         action.setSetNode(p0, rollback_oldnode, rollback_newnode);
927                         m_gamedef->rollback()->reportAction(action);
928                 } else {
929                         // Set node
930                         setNode(p0, n0);
931                 }
932
933                 v3s16 blockpos = getNodeBlockPos(p0);
934                 MapBlock *block = getBlockNoCreateNoEx(blockpos);
935                 if (block != NULL) {
936                         modified_blocks[blockpos] =  block;
937                         changed_nodes.push_back(std::pair<v3s16, MapNode>(p0, n00));
938                 }
939
940                 /*
941                         enqueue neighbors for update if neccessary
942                  */
943                 switch (m_nodedef->get(n0.getContent()).liquid_type) {
944                         case LIQUID_SOURCE:
945                         case LIQUID_FLOWING:
946                                 // make sure source flows into all neighboring nodes
947                                 for (u16 i = 0; i < num_flows; i++)
948                                         if (flows[i].t != NEIGHBOR_UPPER)
949                                                 m_transforming_liquid.push_back(flows[i].p);
950                                 for (u16 i = 0; i < num_airs; i++)
951                                         if (airs[i].t != NEIGHBOR_UPPER)
952                                                 m_transforming_liquid.push_back(airs[i].p);
953                                 break;
954                         case LIQUID_NONE:
955                                 // this flow has turned to air; neighboring flows might need to do the same
956                                 for (u16 i = 0; i < num_flows; i++)
957                                         m_transforming_liquid.push_back(flows[i].p);
958                                 break;
959                 }
960         }
961         //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl;
962
963         for (std::deque<v3s16>::iterator iter = must_reflow.begin(); iter != must_reflow.end(); ++iter)
964                 m_transforming_liquid.push_back(*iter);
965
966         voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks);
967
968
969         /* ----------------------------------------------------------------------
970          * Manage the queue so that it does not grow indefinately
971          */
972         u16 time_until_purge = g_settings->getU16("liquid_queue_purge_time");
973
974         if (time_until_purge == 0)
975                 return; // Feature disabled
976
977         time_until_purge *= 1000;       // seconds -> milliseconds
978
979         u64 curr_time = porting::getTimeMs();
980         u32 prev_unprocessed = m_unprocessed_count;
981         m_unprocessed_count = m_transforming_liquid.size();
982
983         // if unprocessed block count is decreasing or stable
984         if (m_unprocessed_count <= prev_unprocessed) {
985                 m_queue_size_timer_started = false;
986         } else {
987                 if (!m_queue_size_timer_started)
988                         m_inc_trending_up_start_time = curr_time;
989                 m_queue_size_timer_started = true;
990         }
991
992         // Account for curr_time overflowing
993         if (m_queue_size_timer_started && m_inc_trending_up_start_time > curr_time)
994                 m_queue_size_timer_started = false;
995
996         /* If the queue has been growing for more than liquid_queue_purge_time seconds
997          * and the number of unprocessed blocks is still > liquid_loop_max then we
998          * cannot keep up; dump the oldest blocks from the queue so that the queue
999          * has liquid_loop_max items in it
1000          */
1001         if (m_queue_size_timer_started
1002                         && curr_time - m_inc_trending_up_start_time > time_until_purge
1003                         && m_unprocessed_count > liquid_loop_max) {
1004
1005                 size_t dump_qty = m_unprocessed_count - liquid_loop_max;
1006
1007                 infostream << "transformLiquids(): DUMPING " << dump_qty
1008                            << " blocks from the queue" << std::endl;
1009
1010                 while (dump_qty--)
1011                         m_transforming_liquid.pop_front();
1012
1013                 m_queue_size_timer_started = false; // optimistically assume we can keep up now
1014                 m_unprocessed_count = m_transforming_liquid.size();
1015         }
1016 }
1017
1018 std::vector<v3s16> Map::findNodesWithMetadata(v3s16 p1, v3s16 p2)
1019 {
1020         std::vector<v3s16> positions_with_meta;
1021
1022         sortBoxVerticies(p1, p2);
1023         v3s16 bpmin = getNodeBlockPos(p1);
1024         v3s16 bpmax = getNodeBlockPos(p2);
1025
1026         VoxelArea area(p1, p2);
1027
1028         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1029         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1030         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1031                 v3s16 blockpos(x, y, z);
1032
1033                 MapBlock *block = getBlockNoCreateNoEx(blockpos);
1034                 if (!block) {
1035                         verbosestream << "Map::getNodeMetadata(): Need to emerge "
1036                                 << PP(blockpos) << std::endl;
1037                         block = emergeBlock(blockpos, false);
1038                 }
1039                 if (!block) {
1040                         infostream << "WARNING: Map::getNodeMetadata(): Block not found"
1041                                 << std::endl;
1042                         continue;
1043                 }
1044
1045                 v3s16 p_base = blockpos * MAP_BLOCKSIZE;
1046                 std::vector<v3s16> keys = block->m_node_metadata.getAllKeys();
1047                 for (size_t i = 0; i != keys.size(); i++) {
1048                         v3s16 p(keys[i] + p_base);
1049                         if (!area.contains(p))
1050                                 continue;
1051
1052                         positions_with_meta.push_back(p);
1053                 }
1054         }
1055
1056         return positions_with_meta;
1057 }
1058
1059 NodeMetadata *Map::getNodeMetadata(v3s16 p)
1060 {
1061         v3s16 blockpos = getNodeBlockPos(p);
1062         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1063         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1064         if(!block){
1065                 infostream<<"Map::getNodeMetadata(): Need to emerge "
1066                                 <<PP(blockpos)<<std::endl;
1067                 block = emergeBlock(blockpos, false);
1068         }
1069         if(!block){
1070                 warningstream<<"Map::getNodeMetadata(): Block not found"
1071                                 <<std::endl;
1072                 return NULL;
1073         }
1074         NodeMetadata *meta = block->m_node_metadata.get(p_rel);
1075         return meta;
1076 }
1077
1078 bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta)
1079 {
1080         v3s16 blockpos = getNodeBlockPos(p);
1081         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1082         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1083         if(!block){
1084                 infostream<<"Map::setNodeMetadata(): Need to emerge "
1085                                 <<PP(blockpos)<<std::endl;
1086                 block = emergeBlock(blockpos, false);
1087         }
1088         if(!block){
1089                 warningstream<<"Map::setNodeMetadata(): Block not found"
1090                                 <<std::endl;
1091                 return false;
1092         }
1093         block->m_node_metadata.set(p_rel, meta);
1094         return true;
1095 }
1096
1097 void Map::removeNodeMetadata(v3s16 p)
1098 {
1099         v3s16 blockpos = getNodeBlockPos(p);
1100         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1101         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1102         if(block == NULL)
1103         {
1104                 warningstream<<"Map::removeNodeMetadata(): Block not found"
1105                                 <<std::endl;
1106                 return;
1107         }
1108         block->m_node_metadata.remove(p_rel);
1109 }
1110
1111 NodeTimer Map::getNodeTimer(v3s16 p)
1112 {
1113         v3s16 blockpos = getNodeBlockPos(p);
1114         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1115         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1116         if(!block){
1117                 infostream<<"Map::getNodeTimer(): Need to emerge "
1118                                 <<PP(blockpos)<<std::endl;
1119                 block = emergeBlock(blockpos, false);
1120         }
1121         if(!block){
1122                 warningstream<<"Map::getNodeTimer(): Block not found"
1123                                 <<std::endl;
1124                 return NodeTimer();
1125         }
1126         NodeTimer t = block->m_node_timers.get(p_rel);
1127         NodeTimer nt(t.timeout, t.elapsed, p);
1128         return nt;
1129 }
1130
1131 void Map::setNodeTimer(const NodeTimer &t)
1132 {
1133         v3s16 p = t.position;
1134         v3s16 blockpos = getNodeBlockPos(p);
1135         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1136         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1137         if(!block){
1138                 infostream<<"Map::setNodeTimer(): Need to emerge "
1139                                 <<PP(blockpos)<<std::endl;
1140                 block = emergeBlock(blockpos, false);
1141         }
1142         if(!block){
1143                 warningstream<<"Map::setNodeTimer(): Block not found"
1144                                 <<std::endl;
1145                 return;
1146         }
1147         NodeTimer nt(t.timeout, t.elapsed, p_rel);
1148         block->m_node_timers.set(nt);
1149 }
1150
1151 void Map::removeNodeTimer(v3s16 p)
1152 {
1153         v3s16 blockpos = getNodeBlockPos(p);
1154         v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
1155         MapBlock *block = getBlockNoCreateNoEx(blockpos);
1156         if(block == NULL)
1157         {
1158                 warningstream<<"Map::removeNodeTimer(): Block not found"
1159                                 <<std::endl;
1160                 return;
1161         }
1162         block->m_node_timers.remove(p_rel);
1163 }
1164
1165 bool Map::isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac,
1166                 float start_off, float end_off, u32 needed_count)
1167 {
1168         float d0 = (float)BS * p0.getDistanceFrom(p1);
1169         v3s16 u0 = p1 - p0;
1170         v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
1171         uf.normalize();
1172         v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
1173         u32 count = 0;
1174         for(float s=start_off; s<d0+end_off; s+=step){
1175                 v3f pf = p0f + uf * s;
1176                 v3s16 p = floatToInt(pf, BS);
1177                 MapNode n = getNodeNoEx(p);
1178                 const ContentFeatures &f = m_nodedef->get(n);
1179                 if(f.drawtype == NDT_NORMAL){
1180                         // not transparent, see ContentFeature::updateTextures
1181                         count++;
1182                         if(count >= needed_count)
1183                                 return true;
1184                 }
1185                 step *= stepfac;
1186         }
1187         return false;
1188 }
1189
1190 bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) {
1191         v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
1192         cpn += v3s16(MAP_BLOCKSIZE / 2, MAP_BLOCKSIZE / 2, MAP_BLOCKSIZE / 2);
1193         float step = BS * 1;
1194         float stepfac = 1.1;
1195         float startoff = BS * 1;
1196         // The occlusion search of 'isOccluded()' must stop short of the target
1197         // point by distance 'endoff' (end offset) to not enter the target mapblock.
1198         // For the 8 mapblock corners 'endoff' must therefore be the maximum diagonal
1199         // of a mapblock, because we must consider all view angles.
1200         // sqrt(1^2 + 1^2 + 1^2) = 1.732
1201         float endoff = -BS * MAP_BLOCKSIZE * 1.732050807569;
1202         v3s16 spn = cam_pos_nodes;
1203         s16 bs2 = MAP_BLOCKSIZE / 2 + 1;
1204         // to reduce the likelihood of falsely occluded blocks
1205         // require at least two solid blocks
1206         // this is a HACK, we should think of a more precise algorithm
1207         u32 needed_count = 2;
1208
1209         return (
1210                 // For the central point of the mapblock 'endoff' can be halved
1211                 isOccluded(spn, cpn,
1212                         step, stepfac, startoff, endoff / 2.0f, needed_count) &&
1213                 isOccluded(spn, cpn + v3s16(bs2,bs2,bs2),
1214                         step, stepfac, startoff, endoff, needed_count) &&
1215                 isOccluded(spn, cpn + v3s16(bs2,bs2,-bs2),
1216                         step, stepfac, startoff, endoff, needed_count) &&
1217                 isOccluded(spn, cpn + v3s16(bs2,-bs2,bs2),
1218                         step, stepfac, startoff, endoff, needed_count) &&
1219                 isOccluded(spn, cpn + v3s16(bs2,-bs2,-bs2),
1220                         step, stepfac, startoff, endoff, needed_count) &&
1221                 isOccluded(spn, cpn + v3s16(-bs2,bs2,bs2),
1222                         step, stepfac, startoff, endoff, needed_count) &&
1223                 isOccluded(spn, cpn + v3s16(-bs2,bs2,-bs2),
1224                         step, stepfac, startoff, endoff, needed_count) &&
1225                 isOccluded(spn, cpn + v3s16(-bs2,-bs2,bs2),
1226                         step, stepfac, startoff, endoff, needed_count) &&
1227                 isOccluded(spn, cpn + v3s16(-bs2,-bs2,-bs2),
1228                         step, stepfac, startoff, endoff, needed_count));
1229 }
1230
1231 /*
1232         ServerMap
1233 */
1234 ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef,
1235                 EmergeManager *emerge):
1236         Map(dout_server, gamedef),
1237         settings_mgr(g_settings, savedir + DIR_DELIM + "map_meta.txt"),
1238         m_emerge(emerge)
1239 {
1240         verbosestream<<FUNCTION_NAME<<std::endl;
1241
1242         // Tell the EmergeManager about our MapSettingsManager
1243         emerge->map_settings_mgr = &settings_mgr;
1244
1245         /*
1246                 Try to load map; if not found, create a new one.
1247         */
1248
1249         // Determine which database backend to use
1250         std::string conf_path = savedir + DIR_DELIM + "world.mt";
1251         Settings conf;
1252         bool succeeded = conf.readConfigFile(conf_path.c_str());
1253         if (!succeeded || !conf.exists("backend")) {
1254                 // fall back to sqlite3
1255                 conf.set("backend", "sqlite3");
1256         }
1257         std::string backend = conf.get("backend");
1258         dbase = createDatabase(backend, savedir, conf);
1259
1260         if (!conf.updateConfigFile(conf_path.c_str()))
1261                 errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" << std::endl;
1262
1263         m_savedir = savedir;
1264         m_map_saving_enabled = false;
1265
1266         try
1267         {
1268                 // If directory exists, check contents and load if possible
1269                 if(fs::PathExists(m_savedir))
1270                 {
1271                         // If directory is empty, it is safe to save into it.
1272                         if(fs::GetDirListing(m_savedir).size() == 0)
1273                         {
1274                                 infostream<<"ServerMap: Empty save directory is valid."
1275                                                 <<std::endl;
1276                                 m_map_saving_enabled = true;
1277                         }
1278                         else
1279                         {
1280
1281                                 if (settings_mgr.loadMapMeta()) {
1282                                         infostream << "ServerMap: Metadata loaded from "
1283                                                 << savedir << std::endl;
1284                                 } else {
1285                                         infostream << "ServerMap: Metadata could not be loaded "
1286                                                 "from " << savedir << ", assuming valid save "
1287                                                 "directory." << std::endl;
1288                                 }
1289
1290                                 m_map_saving_enabled = true;
1291                                 // Map loaded, not creating new one
1292                                 return;
1293                         }
1294                 }
1295                 // If directory doesn't exist, it is safe to save to it
1296                 else{
1297                         m_map_saving_enabled = true;
1298                 }
1299         }
1300         catch(std::exception &e)
1301         {
1302                 warningstream<<"ServerMap: Failed to load map from "<<savedir
1303                                 <<", exception: "<<e.what()<<std::endl;
1304                 infostream<<"Please remove the map or fix it."<<std::endl;
1305                 warningstream<<"Map saving will be disabled."<<std::endl;
1306         }
1307
1308         infostream<<"Initializing new map."<<std::endl;
1309
1310         // Create zero sector
1311         emergeSector(v2s16(0,0));
1312
1313         // Initially write whole map
1314         save(MOD_STATE_CLEAN);
1315 }
1316
1317 ServerMap::~ServerMap()
1318 {
1319         verbosestream<<FUNCTION_NAME<<std::endl;
1320
1321         try
1322         {
1323                 if(m_map_saving_enabled)
1324                 {
1325                         // Save only changed parts
1326                         save(MOD_STATE_WRITE_AT_UNLOAD);
1327                         infostream<<"ServerMap: Saved map to "<<m_savedir<<std::endl;
1328                 }
1329                 else
1330                 {
1331                         infostream<<"ServerMap: Map not saved"<<std::endl;
1332                 }
1333         }
1334         catch(std::exception &e)
1335         {
1336                 infostream<<"ServerMap: Failed to save map to "<<m_savedir
1337                                 <<", exception: "<<e.what()<<std::endl;
1338         }
1339
1340         /*
1341                 Close database if it was opened
1342         */
1343         delete dbase;
1344
1345 #if 0
1346         /*
1347                 Free all MapChunks
1348         */
1349         core::map<v2s16, MapChunk*>::Iterator i = m_chunks.getIterator();
1350         for(; i.atEnd() == false; i++)
1351         {
1352                 MapChunk *chunk = i.getNode()->getValue();
1353                 delete chunk;
1354         }
1355 #endif
1356 }
1357
1358 MapgenParams *ServerMap::getMapgenParams()
1359 {
1360         // getMapgenParams() should only ever be called after Server is initialized
1361         assert(settings_mgr.mapgen_params != NULL);
1362         return settings_mgr.mapgen_params;
1363 }
1364
1365 u64 ServerMap::getSeed()
1366 {
1367         return getMapgenParams()->seed;
1368 }
1369
1370 s16 ServerMap::getWaterLevel()
1371 {
1372         return getMapgenParams()->water_level;
1373 }
1374
1375 bool ServerMap::saoPositionOverLimit(const v3f &p)
1376 {
1377         return getMapgenParams()->saoPosOverLimit(p);
1378 }
1379
1380 bool ServerMap::blockpos_over_mapgen_limit(v3s16 p)
1381 {
1382         const s16 mapgen_limit_bp = rangelim(
1383                 getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) /
1384                 MAP_BLOCKSIZE;
1385         return p.X < -mapgen_limit_bp ||
1386                 p.X >  mapgen_limit_bp ||
1387                 p.Y < -mapgen_limit_bp ||
1388                 p.Y >  mapgen_limit_bp ||
1389                 p.Z < -mapgen_limit_bp ||
1390                 p.Z >  mapgen_limit_bp;
1391 }
1392
1393 bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data)
1394 {
1395         s16 csize = getMapgenParams()->chunksize;
1396         v3s16 bpmin = EmergeManager::getContainingChunk(blockpos, csize);
1397         v3s16 bpmax = bpmin + v3s16(1, 1, 1) * (csize - 1);
1398
1399         bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
1400         EMERGE_DBG_OUT("initBlockMake(): " PP(bpmin) " - " PP(bpmax));
1401
1402         v3s16 extra_borders(1, 1, 1);
1403         v3s16 full_bpmin = bpmin - extra_borders;
1404         v3s16 full_bpmax = bpmax + extra_borders;
1405
1406         // Do nothing if not inside mapgen limits (+-1 because of neighbors)
1407         if (blockpos_over_mapgen_limit(full_bpmin) ||
1408                         blockpos_over_mapgen_limit(full_bpmax))
1409                 return false;
1410
1411         data->seed = getSeed();
1412         data->blockpos_min = bpmin;
1413         data->blockpos_max = bpmax;
1414         data->blockpos_requested = blockpos;
1415         data->nodedef = m_nodedef;
1416
1417         /*
1418                 Create the whole area of this and the neighboring blocks
1419         */
1420         for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++)
1421         for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) {
1422                 v2s16 sectorpos(x, z);
1423                 // Sector metadata is loaded from disk if not already loaded.
1424                 ServerMapSector *sector = createSector(sectorpos);
1425                 FATAL_ERROR_IF(sector == NULL, "createSector() failed");
1426
1427                 for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) {
1428                         v3s16 p(x, y, z);
1429
1430                         MapBlock *block = emergeBlock(p, false);
1431                         if (block == NULL) {
1432                                 block = createBlock(p);
1433
1434                                 // Block gets sunlight if this is true.
1435                                 // Refer to the map generator heuristics.
1436                                 bool ug = m_emerge->isBlockUnderground(p);
1437                                 block->setIsUnderground(ug);
1438                         }
1439                 }
1440         }
1441
1442         /*
1443                 Now we have a big empty area.
1444
1445                 Make a ManualMapVoxelManipulator that contains this and the
1446                 neighboring blocks
1447         */
1448
1449         data->vmanip = new MMVManip(this);
1450         data->vmanip->initialEmerge(full_bpmin, full_bpmax);
1451
1452         // Note: we may need this again at some point.
1453 #if 0
1454         // Ensure none of the blocks to be generated were marked as
1455         // containing CONTENT_IGNORE
1456         for (s16 z = blockpos_min.Z; z <= blockpos_max.Z; z++) {
1457                 for (s16 y = blockpos_min.Y; y <= blockpos_max.Y; y++) {
1458                         for (s16 x = blockpos_min.X; x <= blockpos_max.X; x++) {
1459                                 core::map<v3s16, u8>::Node *n;
1460                                 n = data->vmanip->m_loaded_blocks.find(v3s16(x, y, z));
1461                                 if (n == NULL)
1462                                         continue;
1463                                 u8 flags = n->getValue();
1464                                 flags &= ~VMANIP_BLOCK_CONTAINS_CIGNORE;
1465                                 n->setValue(flags);
1466                         }
1467                 }
1468         }
1469 #endif
1470
1471         // Data is ready now.
1472         return true;
1473 }
1474
1475 void ServerMap::finishBlockMake(BlockMakeData *data,
1476         std::map<v3s16, MapBlock*> *changed_blocks)
1477 {
1478         v3s16 bpmin = data->blockpos_min;
1479         v3s16 bpmax = data->blockpos_max;
1480
1481         v3s16 extra_borders(1, 1, 1);
1482
1483         bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
1484         EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax));
1485
1486         /*
1487                 Blit generated stuff to map
1488                 NOTE: blitBackAll adds nearly everything to changed_blocks
1489         */
1490         data->vmanip->blitBackAll(changed_blocks);
1491
1492         EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()="
1493                 << changed_blocks->size());
1494
1495         /*
1496                 Copy transforming liquid information
1497         */
1498         while (data->transforming_liquid.size()) {
1499                 m_transforming_liquid.push_back(data->transforming_liquid.front());
1500                 data->transforming_liquid.pop_front();
1501         }
1502
1503         for (std::map<v3s16, MapBlock *>::iterator
1504                         it = changed_blocks->begin();
1505                         it != changed_blocks->end(); ++it) {
1506                 MapBlock *block = it->second;
1507                 if (!block)
1508                         continue;
1509                 /*
1510                         Update day/night difference cache of the MapBlocks
1511                 */
1512                 block->expireDayNightDiff();
1513                 /*
1514                         Set block as modified
1515                 */
1516                 block->raiseModified(MOD_STATE_WRITE_NEEDED,
1517                         MOD_REASON_EXPIRE_DAYNIGHTDIFF);
1518         }
1519
1520         /*
1521                 Set central blocks as generated
1522         */
1523         for (s16 x = bpmin.X; x <= bpmax.X; x++)
1524         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1525         for (s16 y = bpmin.Y; y <= bpmax.Y; y++) {
1526                 MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z));
1527                 if (!block)
1528                         continue;
1529
1530                 block->setGenerated(true);
1531         }
1532
1533         /*
1534                 Save changed parts of map
1535                 NOTE: Will be saved later.
1536         */
1537         //save(MOD_STATE_WRITE_AT_UNLOAD);
1538 }
1539
1540 ServerMapSector *ServerMap::createSector(v2s16 p2d)
1541 {
1542         DSTACKF("%s: p2d=(%d,%d)",
1543                         FUNCTION_NAME,
1544                         p2d.X, p2d.Y);
1545
1546         /*
1547                 Check if it exists already in memory
1548         */
1549         ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d);
1550         if(sector != NULL)
1551                 return sector;
1552
1553         /*
1554                 Try to load it from disk (with blocks)
1555         */
1556         //if(loadSectorFull(p2d) == true)
1557
1558         /*
1559                 Try to load metadata from disk
1560         */
1561 #if 0
1562         if(loadSectorMeta(p2d) == true)
1563         {
1564                 ServerMapSector *sector = (ServerMapSector*)getSectorNoGenerateNoEx(p2d);
1565                 if(sector == NULL)
1566                 {
1567                         infostream<<"ServerMap::createSector(): loadSectorFull didn't make a sector"<<std::endl;
1568                         throw InvalidPositionException("");
1569                 }
1570                 return sector;
1571         }
1572 #endif
1573
1574         /*
1575                 Do not create over max mapgen limit
1576         */
1577         const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE;
1578         if (p2d.X < -max_limit_bp ||
1579                         p2d.X >  max_limit_bp ||
1580                         p2d.Y < -max_limit_bp ||
1581                         p2d.Y >  max_limit_bp)
1582                 throw InvalidPositionException("createSector(): pos. over max mapgen limit");
1583
1584         /*
1585                 Generate blank sector
1586         */
1587
1588         sector = new ServerMapSector(this, p2d, m_gamedef);
1589
1590         // Sector position on map in nodes
1591         //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
1592
1593         /*
1594                 Insert to container
1595         */
1596         m_sectors[p2d] = sector;
1597
1598         return sector;
1599 }
1600
1601 #if 0
1602 /*
1603         This is a quick-hand function for calling makeBlock().
1604 */
1605 MapBlock * ServerMap::generateBlock(
1606                 v3s16 p,
1607                 std::map<v3s16, MapBlock*> &modified_blocks
1608 )
1609 {
1610         DSTACKF("%s: p=(%d,%d,%d)", FUNCTION_NAME, p.X, p.Y, p.Z);
1611
1612         /*infostream<<"generateBlock(): "
1613                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1614                         <<std::endl;*/
1615
1616         bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
1617
1618         TimeTaker timer("generateBlock");
1619
1620         //MapBlock *block = original_dummy;
1621
1622         v2s16 p2d(p.X, p.Z);
1623         v2s16 p2d_nodes = p2d * MAP_BLOCKSIZE;
1624
1625         /*
1626                 Do not generate over-limit
1627         */
1628         if(blockpos_over_limit(p))
1629         {
1630                 infostream<<FUNCTION_NAME<<": Block position over limit"<<std::endl;
1631                 throw InvalidPositionException("generateBlock(): pos. over limit");
1632         }
1633
1634         /*
1635                 Create block make data
1636         */
1637         BlockMakeData data;
1638         initBlockMake(&data, p);
1639
1640         /*
1641                 Generate block
1642         */
1643         {
1644                 TimeTaker t("mapgen::make_block()");
1645                 mapgen->makeChunk(&data);
1646                 //mapgen::make_block(&data);
1647
1648                 if(enable_mapgen_debug_info == false)
1649                         t.stop(true); // Hide output
1650         }
1651
1652         /*
1653                 Blit data back on map, update lighting, add mobs and whatever this does
1654         */
1655         finishBlockMake(&data, modified_blocks);
1656
1657         /*
1658                 Get central block
1659         */
1660         MapBlock *block = getBlockNoCreateNoEx(p);
1661
1662 #if 0
1663         /*
1664                 Check result
1665         */
1666         if(block)
1667         {
1668                 bool erroneus_content = false;
1669                 for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
1670                 for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
1671                 for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
1672                 {
1673                         v3s16 p(x0,y0,z0);
1674                         MapNode n = block->getNode(p);
1675                         if(n.getContent() == CONTENT_IGNORE)
1676                         {
1677                                 infostream<<"CONTENT_IGNORE at "
1678                                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1679                                                 <<std::endl;
1680                                 erroneus_content = true;
1681                                 assert(0);
1682                         }
1683                 }
1684                 if(erroneus_content)
1685                 {
1686                         assert(0);
1687                 }
1688         }
1689 #endif
1690
1691 #if 0
1692         /*
1693                 Generate a completely empty block
1694         */
1695         if(block)
1696         {
1697                 for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
1698                 for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
1699                 {
1700                         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
1701                         {
1702                                 MapNode n;
1703                                 n.setContent(CONTENT_AIR);
1704                                 block->setNode(v3s16(x0,y0,z0), n);
1705                         }
1706                 }
1707         }
1708 #endif
1709
1710         if(enable_mapgen_debug_info == false)
1711                 timer.stop(true); // Hide output
1712
1713         return block;
1714 }
1715 #endif
1716
1717 MapBlock * ServerMap::createBlock(v3s16 p)
1718 {
1719         DSTACKF("%s: p=(%d,%d,%d)",
1720                         FUNCTION_NAME, p.X, p.Y, p.Z);
1721
1722         /*
1723                 Do not create over max mapgen limit
1724         */
1725         if (blockpos_over_max_limit(p))
1726                 throw InvalidPositionException("createBlock(): pos. over max mapgen limit");
1727
1728         v2s16 p2d(p.X, p.Z);
1729         s16 block_y = p.Y;
1730         /*
1731                 This will create or load a sector if not found in memory.
1732                 If block exists on disk, it will be loaded.
1733
1734                 NOTE: On old save formats, this will be slow, as it generates
1735                       lighting on blocks for them.
1736         */
1737         ServerMapSector *sector;
1738         try {
1739                 sector = (ServerMapSector*)createSector(p2d);
1740                 assert(sector->getId() == MAPSECTOR_SERVER);
1741         }
1742         catch(InvalidPositionException &e)
1743         {
1744                 infostream<<"createBlock: createSector() failed"<<std::endl;
1745                 throw e;
1746         }
1747         /*
1748                 NOTE: This should not be done, or at least the exception
1749                 should not be passed on as std::exception, because it
1750                 won't be catched at all.
1751         */
1752         /*catch(std::exception &e)
1753         {
1754                 infostream<<"createBlock: createSector() failed: "
1755                                 <<e.what()<<std::endl;
1756                 throw e;
1757         }*/
1758
1759         /*
1760                 Try to get a block from the sector
1761         */
1762
1763         MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
1764         if(block)
1765         {
1766                 if(block->isDummy())
1767                         block->unDummify();
1768                 return block;
1769         }
1770         // Create blank
1771         block = sector->createBlankBlock(block_y);
1772
1773         return block;
1774 }
1775
1776 MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank)
1777 {
1778         DSTACKF("%s: p=(%d,%d,%d), create_blank=%d",
1779                         FUNCTION_NAME,
1780                         p.X, p.Y, p.Z, create_blank);
1781
1782         {
1783                 MapBlock *block = getBlockNoCreateNoEx(p);
1784                 if(block && block->isDummy() == false)
1785                         return block;
1786         }
1787
1788         {
1789                 MapBlock *block = loadBlock(p);
1790                 if(block)
1791                         return block;
1792         }
1793
1794         if (create_blank) {
1795                 ServerMapSector *sector = createSector(v2s16(p.X, p.Z));
1796                 MapBlock *block = sector->createBlankBlock(p.Y);
1797
1798                 return block;
1799         }
1800
1801 #if 0
1802         if(allow_generate)
1803         {
1804                 std::map<v3s16, MapBlock*> modified_blocks;
1805                 MapBlock *block = generateBlock(p, modified_blocks);
1806                 if(block)
1807                 {
1808                         MapEditEvent event;
1809                         event.type = MEET_OTHER;
1810                         event.p = p;
1811
1812                         // Copy modified_blocks to event
1813                         for(std::map<v3s16, MapBlock*>::iterator
1814                                         i = modified_blocks.begin();
1815                                         i != modified_blocks.end(); ++i)
1816                         {
1817                                 event.modified_blocks.insert(i->first);
1818                         }
1819
1820                         // Queue event
1821                         dispatchEvent(&event);
1822
1823                         return block;
1824                 }
1825         }
1826 #endif
1827
1828         return NULL;
1829 }
1830
1831 MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d)
1832 {
1833         MapBlock *block = getBlockNoCreateNoEx(p3d);
1834         if (block == NULL)
1835                 m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false);
1836
1837         return block;
1838 }
1839
1840 // N.B.  This requires no synchronization, since data will not be modified unless
1841 // the VoxelManipulator being updated belongs to the same thread.
1842 void ServerMap::updateVManip(v3s16 pos)
1843 {
1844         Mapgen *mg = m_emerge->getCurrentMapgen();
1845         if (!mg)
1846                 return;
1847
1848         MMVManip *vm = mg->vm;
1849         if (!vm)
1850                 return;
1851
1852         if (!vm->m_area.contains(pos))
1853                 return;
1854
1855         s32 idx = vm->m_area.index(pos);
1856         vm->m_data[idx] = getNodeNoEx(pos);
1857         vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA;
1858
1859         vm->m_is_dirty = true;
1860 }
1861
1862 s16 ServerMap::findGroundLevel(v2s16 p2d)
1863 {
1864 #if 0
1865         /*
1866                 Uh, just do something random...
1867         */
1868         // Find existing map from top to down
1869         s16 max=63;
1870         s16 min=-64;
1871         v3s16 p(p2d.X, max, p2d.Y);
1872         for(; p.Y>min; p.Y--)
1873         {
1874                 MapNode n = getNodeNoEx(p);
1875                 if(n.getContent() != CONTENT_IGNORE)
1876                         break;
1877         }
1878         if(p.Y == min)
1879                 goto plan_b;
1880         // If this node is not air, go to plan b
1881         if(getNodeNoEx(p).getContent() != CONTENT_AIR)
1882                 goto plan_b;
1883         // Search existing walkable and return it
1884         for(; p.Y>min; p.Y--)
1885         {
1886                 MapNode n = getNodeNoEx(p);
1887                 if(content_walkable(n.d) && n.getContent() != CONTENT_IGNORE)
1888                         return p.Y;
1889         }
1890
1891         // Move to plan b
1892 plan_b:
1893 #endif
1894
1895         /*
1896                 Determine from map generator noise functions
1897         */
1898
1899         s16 level = m_emerge->getGroundLevelAtPoint(p2d);
1900         return level;
1901
1902         //double level = base_rock_level_2d(m_seed, p2d) + AVERAGE_MUD_AMOUNT;
1903         //return (s16)level;
1904 }
1905
1906 bool ServerMap::loadFromFolders() {
1907         if (!dbase->initialized() &&
1908                         !fs::PathExists(m_savedir + DIR_DELIM + "map.sqlite"))
1909                 return true;
1910         return false;
1911 }
1912
1913 void ServerMap::createDirs(std::string path)
1914 {
1915         if(fs::CreateAllDirs(path) == false)
1916         {
1917                 m_dout<<"ServerMap: Failed to create directory "
1918                                 <<"\""<<path<<"\""<<std::endl;
1919                 throw BaseException("ServerMap failed to create directory");
1920         }
1921 }
1922
1923 std::string ServerMap::getSectorDir(v2s16 pos, int layout)
1924 {
1925         char cc[9];
1926         switch(layout)
1927         {
1928                 case 1:
1929                         snprintf(cc, 9, "%.4x%.4x",
1930                                 (unsigned int) pos.X & 0xffff,
1931                                 (unsigned int) pos.Y & 0xffff);
1932
1933                         return m_savedir + DIR_DELIM + "sectors" + DIR_DELIM + cc;
1934                 case 2:
1935                         snprintf(cc, 9, (std::string("%.3x") + DIR_DELIM + "%.3x").c_str(),
1936                                 (unsigned int) pos.X & 0xfff,
1937                                 (unsigned int) pos.Y & 0xfff);
1938
1939                         return m_savedir + DIR_DELIM + "sectors2" + DIR_DELIM + cc;
1940                 default:
1941                         assert(false);
1942                         return "";
1943         }
1944 }
1945
1946 v2s16 ServerMap::getSectorPos(const std::string &dirname)
1947 {
1948         unsigned int x = 0, y = 0;
1949         int r;
1950         std::string component;
1951         fs::RemoveLastPathComponent(dirname, &component, 1);
1952         if(component.size() == 8)
1953         {
1954                 // Old layout
1955                 r = sscanf(component.c_str(), "%4x%4x", &x, &y);
1956         }
1957         else if(component.size() == 3)
1958         {
1959                 // New layout
1960                 fs::RemoveLastPathComponent(dirname, &component, 2);
1961                 r = sscanf(component.c_str(), (std::string("%3x") + DIR_DELIM + "%3x").c_str(), &x, &y);
1962                 // Sign-extend the 12 bit values up to 16 bits...
1963                 if(x & 0x800) x |= 0xF000;
1964                 if(y & 0x800) y |= 0xF000;
1965         }
1966         else
1967         {
1968                 r = -1;
1969         }
1970
1971         FATAL_ERROR_IF(r != 2, "getSectorPos()");
1972         v2s16 pos((s16)x, (s16)y);
1973         return pos;
1974 }
1975
1976 v3s16 ServerMap::getBlockPos(const std::string &sectordir, const std::string &blockfile)
1977 {
1978         v2s16 p2d = getSectorPos(sectordir);
1979
1980         if(blockfile.size() != 4){
1981                 throw InvalidFilenameException("Invalid block filename");
1982         }
1983         unsigned int y;
1984         int r = sscanf(blockfile.c_str(), "%4x", &y);
1985         if(r != 1)
1986                 throw InvalidFilenameException("Invalid block filename");
1987         return v3s16(p2d.X, y, p2d.Y);
1988 }
1989
1990 std::string ServerMap::getBlockFilename(v3s16 p)
1991 {
1992         char cc[5];
1993         snprintf(cc, 5, "%.4x", (unsigned int)p.Y&0xffff);
1994         return cc;
1995 }
1996
1997 void ServerMap::save(ModifiedState save_level)
1998 {
1999         DSTACK(FUNCTION_NAME);
2000         if(m_map_saving_enabled == false) {
2001                 warningstream<<"Not saving map, saving disabled."<<std::endl;
2002                 return;
2003         }
2004
2005         if(save_level == MOD_STATE_CLEAN)
2006                 infostream<<"ServerMap: Saving whole map, this can take time."
2007                                 <<std::endl;
2008
2009         if (m_map_metadata_changed || save_level == MOD_STATE_CLEAN) {
2010                 if (settings_mgr.saveMapMeta())
2011                         m_map_metadata_changed = false;
2012         }
2013
2014         // Profile modified reasons
2015         Profiler modprofiler;
2016
2017         u32 sector_meta_count = 0;
2018         u32 block_count = 0;
2019         u32 block_count_all = 0; // Number of blocks in memory
2020
2021         // Don't do anything with sqlite unless something is really saved
2022         bool save_started = false;
2023
2024         for(std::map<v2s16, MapSector*>::iterator i = m_sectors.begin();
2025                 i != m_sectors.end(); ++i) {
2026                 ServerMapSector *sector = (ServerMapSector*)i->second;
2027                 assert(sector->getId() == MAPSECTOR_SERVER);
2028
2029                 if(sector->differs_from_disk || save_level == MOD_STATE_CLEAN) {
2030                         saveSectorMeta(sector);
2031                         sector_meta_count++;
2032                 }
2033
2034                 MapBlockVect blocks;
2035                 sector->getBlocks(blocks);
2036
2037                 for(MapBlockVect::iterator j = blocks.begin();
2038                         j != blocks.end(); ++j) {
2039                         MapBlock *block = *j;
2040
2041                         block_count_all++;
2042
2043                         if(block->getModified() >= (u32)save_level) {
2044                                 // Lazy beginSave()
2045                                 if(!save_started) {
2046                                         beginSave();
2047                                         save_started = true;
2048                                 }
2049
2050                                 modprofiler.add(block->getModifiedReasonString(), 1);
2051
2052                                 saveBlock(block);
2053                                 block_count++;
2054
2055                                 /*infostream<<"ServerMap: Written block ("
2056                                                 <<block->getPos().X<<","
2057                                                 <<block->getPos().Y<<","
2058                                                 <<block->getPos().Z<<")"
2059                                                 <<std::endl;*/
2060                         }
2061                 }
2062         }
2063
2064         if(save_started)
2065                 endSave();
2066
2067         /*
2068                 Only print if something happened or saved whole map
2069         */
2070         if(save_level == MOD_STATE_CLEAN || sector_meta_count != 0
2071                         || block_count != 0) {
2072                 infostream<<"ServerMap: Written: "
2073                                 <<sector_meta_count<<" sector metadata files, "
2074                                 <<block_count<<" block files"
2075                                 <<", "<<block_count_all<<" blocks in memory."
2076                                 <<std::endl;
2077                 PrintInfo(infostream); // ServerMap/ClientMap:
2078                 infostream<<"Blocks modified by: "<<std::endl;
2079                 modprofiler.print(infostream);
2080         }
2081 }
2082
2083 void ServerMap::listAllLoadableBlocks(std::vector<v3s16> &dst)
2084 {
2085         if (loadFromFolders()) {
2086                 errorstream << "Map::listAllLoadableBlocks(): Result will be missing "
2087                                 << "all blocks that are stored in flat files." << std::endl;
2088         }
2089         dbase->listAllLoadableBlocks(dst);
2090 }
2091
2092 void ServerMap::listAllLoadedBlocks(std::vector<v3s16> &dst)
2093 {
2094         for(std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
2095                 si != m_sectors.end(); ++si)
2096         {
2097                 MapSector *sector = si->second;
2098
2099                 MapBlockVect blocks;
2100                 sector->getBlocks(blocks);
2101
2102                 for(MapBlockVect::iterator i = blocks.begin();
2103                                 i != blocks.end(); ++i) {
2104                         v3s16 p = (*i)->getPos();
2105                         dst.push_back(p);
2106                 }
2107         }
2108 }
2109
2110 void ServerMap::saveSectorMeta(ServerMapSector *sector)
2111 {
2112         DSTACK(FUNCTION_NAME);
2113         // Format used for writing
2114         u8 version = SER_FMT_VER_HIGHEST_WRITE;
2115         // Get destination
2116         v2s16 pos = sector->getPos();
2117         std::string dir = getSectorDir(pos);
2118         createDirs(dir);
2119
2120         std::string fullpath = dir + DIR_DELIM + "meta";
2121         std::ostringstream ss(std::ios_base::binary);
2122
2123         sector->serialize(ss, version);
2124
2125         if(!fs::safeWriteToFile(fullpath, ss.str()))
2126                 throw FileNotGoodException("Cannot write sector metafile");
2127
2128         sector->differs_from_disk = false;
2129 }
2130
2131 MapSector* ServerMap::loadSectorMeta(std::string sectordir, bool save_after_load)
2132 {
2133         DSTACK(FUNCTION_NAME);
2134         // Get destination
2135         v2s16 p2d = getSectorPos(sectordir);
2136
2137         ServerMapSector *sector = NULL;
2138
2139         std::string fullpath = sectordir + DIR_DELIM + "meta";
2140         std::ifstream is(fullpath.c_str(), std::ios_base::binary);
2141         if(is.good() == false)
2142         {
2143                 // If the directory exists anyway, it probably is in some old
2144                 // format. Just go ahead and create the sector.
2145                 if(fs::PathExists(sectordir))
2146                 {
2147                         /*infostream<<"ServerMap::loadSectorMeta(): Sector metafile "
2148                                         <<fullpath<<" doesn't exist but directory does."
2149                                         <<" Continuing with a sector with no metadata."
2150                                         <<std::endl;*/
2151                         sector = new ServerMapSector(this, p2d, m_gamedef);
2152                         m_sectors[p2d] = sector;
2153                 }
2154                 else
2155                 {
2156                         throw FileNotGoodException("Cannot open sector metafile");
2157                 }
2158         }
2159         else
2160         {
2161                 sector = ServerMapSector::deSerialize
2162                                 (is, this, p2d, m_sectors, m_gamedef);
2163                 if(save_after_load)
2164                         saveSectorMeta(sector);
2165         }
2166
2167         sector->differs_from_disk = false;
2168
2169         return sector;
2170 }
2171
2172 bool ServerMap::loadSectorMeta(v2s16 p2d)
2173 {
2174         DSTACK(FUNCTION_NAME);
2175
2176         // The directory layout we're going to load from.
2177         //  1 - original sectors/xxxxzzzz/
2178         //  2 - new sectors2/xxx/zzz/
2179         //  If we load from anything but the latest structure, we will
2180         //  immediately save to the new one, and remove the old.
2181         int loadlayout = 1;
2182         std::string sectordir1 = getSectorDir(p2d, 1);
2183         std::string sectordir;
2184         if(fs::PathExists(sectordir1))
2185         {
2186                 sectordir = sectordir1;
2187         }
2188         else
2189         {
2190                 loadlayout = 2;
2191                 sectordir = getSectorDir(p2d, 2);
2192         }
2193
2194         try{
2195                 loadSectorMeta(sectordir, loadlayout != 2);
2196         }
2197         catch(InvalidFilenameException &e)
2198         {
2199                 return false;
2200         }
2201         catch(FileNotGoodException &e)
2202         {
2203                 return false;
2204         }
2205         catch(std::exception &e)
2206         {
2207                 return false;
2208         }
2209
2210         return true;
2211 }
2212
2213 #if 0
2214 bool ServerMap::loadSectorFull(v2s16 p2d)
2215 {
2216         DSTACK(FUNCTION_NAME);
2217
2218         MapSector *sector = NULL;
2219
2220         // The directory layout we're going to load from.
2221         //  1 - original sectors/xxxxzzzz/
2222         //  2 - new sectors2/xxx/zzz/
2223         //  If we load from anything but the latest structure, we will
2224         //  immediately save to the new one, and remove the old.
2225         int loadlayout = 1;
2226         std::string sectordir1 = getSectorDir(p2d, 1);
2227         std::string sectordir;
2228         if(fs::PathExists(sectordir1))
2229         {
2230                 sectordir = sectordir1;
2231         }
2232         else
2233         {
2234                 loadlayout = 2;
2235                 sectordir = getSectorDir(p2d, 2);
2236         }
2237
2238         try{
2239                 sector = loadSectorMeta(sectordir, loadlayout != 2);
2240         }
2241         catch(InvalidFilenameException &e)
2242         {
2243                 return false;
2244         }
2245         catch(FileNotGoodException &e)
2246         {
2247                 return false;
2248         }
2249         catch(std::exception &e)
2250         {
2251                 return false;
2252         }
2253
2254         /*
2255                 Load blocks
2256         */
2257         std::vector<fs::DirListNode> list2 = fs::GetDirListing
2258                         (sectordir);
2259         std::vector<fs::DirListNode>::iterator i2;
2260         for(i2=list2.begin(); i2!=list2.end(); i2++)
2261         {
2262                 // We want files
2263                 if(i2->dir)
2264                         continue;
2265                 try{
2266                         loadBlock(sectordir, i2->name, sector, loadlayout != 2);
2267                 }
2268                 catch(InvalidFilenameException &e)
2269                 {
2270                         // This catches unknown crap in directory
2271                 }
2272         }
2273
2274         if(loadlayout != 2)
2275         {
2276                 infostream<<"Sector converted to new layout - deleting "<<
2277                         sectordir1<<std::endl;
2278                 fs::RecursiveDelete(sectordir1);
2279         }
2280
2281         return true;
2282 }
2283 #endif
2284
2285 MapDatabase *ServerMap::createDatabase(
2286         const std::string &name,
2287         const std::string &savedir,
2288         Settings &conf)
2289 {
2290         if (name == "sqlite3")
2291                 return new MapDatabaseSQLite3(savedir);
2292         if (name == "dummy")
2293                 return new Database_Dummy();
2294         #if USE_LEVELDB
2295         else if (name == "leveldb")
2296                 return new Database_LevelDB(savedir);
2297         #endif
2298         #if USE_REDIS
2299         else if (name == "redis")
2300                 return new Database_Redis(conf);
2301         #endif
2302         #if USE_POSTGRESQL
2303         else if (name == "postgresql") {
2304                 std::string connect_string = "";
2305                 conf.getNoEx("pgsql_connection", connect_string);
2306                 return new MapDatabasePostgreSQL(connect_string);
2307         }
2308         #endif
2309         else
2310                 throw BaseException(std::string("Database backend ") + name + " not supported.");
2311 }
2312
2313 void ServerMap::beginSave()
2314 {
2315         dbase->beginSave();
2316 }
2317
2318 void ServerMap::endSave()
2319 {
2320         dbase->endSave();
2321 }
2322
2323 bool ServerMap::saveBlock(MapBlock *block)
2324 {
2325         return saveBlock(block, dbase);
2326 }
2327
2328 bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db)
2329 {
2330         v3s16 p3d = block->getPos();
2331
2332         // Dummy blocks are not written
2333         if (block->isDummy()) {
2334                 warningstream << "saveBlock: Not writing dummy block "
2335                         << PP(p3d) << std::endl;
2336                 return true;
2337         }
2338
2339         // Format used for writing
2340         u8 version = SER_FMT_VER_HIGHEST_WRITE;
2341
2342         /*
2343                 [0] u8 serialization version
2344                 [1] data
2345         */
2346         std::ostringstream o(std::ios_base::binary);
2347         o.write((char*) &version, 1);
2348         block->serialize(o, version, true);
2349
2350         std::string data = o.str();
2351         bool ret = db->saveBlock(p3d, data);
2352         if (ret) {
2353                 // We just wrote it to the disk so clear modified flag
2354                 block->resetModified();
2355         }
2356         return ret;
2357 }
2358
2359 void ServerMap::loadBlock(const std::string &sectordir, const std::string &blockfile,
2360                 MapSector *sector, bool save_after_load)
2361 {
2362         DSTACK(FUNCTION_NAME);
2363
2364         std::string fullpath = sectordir + DIR_DELIM + blockfile;
2365         try {
2366                 std::ifstream is(fullpath.c_str(), std::ios_base::binary);
2367                 if (!is.good())
2368                         throw FileNotGoodException("Cannot open block file");
2369
2370                 v3s16 p3d = getBlockPos(sectordir, blockfile);
2371                 v2s16 p2d(p3d.X, p3d.Z);
2372
2373                 assert(sector->getPos() == p2d);
2374
2375                 u8 version = SER_FMT_VER_INVALID;
2376                 is.read((char*)&version, 1);
2377
2378                 if(is.fail())
2379                         throw SerializationError("ServerMap::loadBlock(): Failed"
2380                                         " to read MapBlock version");
2381
2382                 /*u32 block_size = MapBlock::serializedLength(version);
2383                 SharedBuffer<u8> data(block_size);
2384                 is.read((char*)*data, block_size);*/
2385
2386                 // This will always return a sector because we're the server
2387                 //MapSector *sector = emergeSector(p2d);
2388
2389                 MapBlock *block = NULL;
2390                 bool created_new = false;
2391                 block = sector->getBlockNoCreateNoEx(p3d.Y);
2392                 if(block == NULL)
2393                 {
2394                         block = sector->createBlankBlockNoInsert(p3d.Y);
2395                         created_new = true;
2396                 }
2397
2398                 // Read basic data
2399                 block->deSerialize(is, version, true);
2400
2401                 // If it's a new block, insert it to the map
2402                 if (created_new) {
2403                         sector->insertBlock(block);
2404                         ReflowScan scanner(this, m_emerge->ndef);
2405                         scanner.scan(block, &m_transforming_liquid);
2406                 }
2407
2408                 /*
2409                         Save blocks loaded in old format in new format
2410                 */
2411
2412                 if(version < SER_FMT_VER_HIGHEST_WRITE || save_after_load)
2413                 {
2414                         saveBlock(block);
2415
2416                         // Should be in database now, so delete the old file
2417                         fs::RecursiveDelete(fullpath);
2418                 }
2419
2420                 // We just loaded it from the disk, so it's up-to-date.
2421                 block->resetModified();
2422
2423         }
2424         catch(SerializationError &e)
2425         {
2426                 warningstream<<"Invalid block data on disk "
2427                                 <<"fullpath="<<fullpath
2428                                 <<" (SerializationError). "
2429                                 <<"what()="<<e.what()
2430                                 <<std::endl;
2431                                 // Ignoring. A new one will be generated.
2432                 abort();
2433
2434                 // TODO: Backup file; name is in fullpath.
2435         }
2436 }
2437
2438 void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load)
2439 {
2440         DSTACK(FUNCTION_NAME);
2441
2442         try {
2443                 std::istringstream is(*blob, std::ios_base::binary);
2444
2445                 u8 version = SER_FMT_VER_INVALID;
2446                 is.read((char*)&version, 1);
2447
2448                 if(is.fail())
2449                         throw SerializationError("ServerMap::loadBlock(): Failed"
2450                                         " to read MapBlock version");
2451
2452                 MapBlock *block = NULL;
2453                 bool created_new = false;
2454                 block = sector->getBlockNoCreateNoEx(p3d.Y);
2455                 if(block == NULL)
2456                 {
2457                         block = sector->createBlankBlockNoInsert(p3d.Y);
2458                         created_new = true;
2459                 }
2460
2461                 // Read basic data
2462                 block->deSerialize(is, version, true);
2463
2464                 // If it's a new block, insert it to the map
2465                 if (created_new) {
2466                         sector->insertBlock(block);
2467                         ReflowScan scanner(this, m_emerge->ndef);
2468                         scanner.scan(block, &m_transforming_liquid);
2469                 }
2470
2471                 /*
2472                         Save blocks loaded in old format in new format
2473                 */
2474
2475                 //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load)
2476                 // Only save if asked to; no need to update version
2477                 if(save_after_load)
2478                         saveBlock(block);
2479
2480                 // We just loaded it from, so it's up-to-date.
2481                 block->resetModified();
2482         }
2483         catch(SerializationError &e)
2484         {
2485                 errorstream<<"Invalid block data in database"
2486                                 <<" ("<<p3d.X<<","<<p3d.Y<<","<<p3d.Z<<")"
2487                                 <<" (SerializationError): "<<e.what()<<std::endl;
2488
2489                 // TODO: Block should be marked as invalid in memory so that it is
2490                 // not touched but the game can run
2491
2492                 if(g_settings->getBool("ignore_world_load_errors")){
2493                         errorstream<<"Ignoring block load error. Duck and cover! "
2494                                         <<"(ignore_world_load_errors)"<<std::endl;
2495                 } else {
2496                         throw SerializationError("Invalid block data in database");
2497                 }
2498         }
2499 }
2500
2501 MapBlock* ServerMap::loadBlock(v3s16 blockpos)
2502 {
2503         DSTACK(FUNCTION_NAME);
2504
2505         bool created_new = (getBlockNoCreateNoEx(blockpos) == NULL);
2506
2507         v2s16 p2d(blockpos.X, blockpos.Z);
2508
2509         std::string ret;
2510         dbase->loadBlock(blockpos, &ret);
2511         if (ret != "") {
2512                 loadBlock(&ret, blockpos, createSector(p2d), false);
2513         } else {
2514                 // Not found in database, try the files
2515
2516                 // The directory layout we're going to load from.
2517                 //  1 - original sectors/xxxxzzzz/
2518                 //  2 - new sectors2/xxx/zzz/
2519                 //  If we load from anything but the latest structure, we will
2520                 //  immediately save to the new one, and remove the old.
2521                 int loadlayout = 1;
2522                 std::string sectordir1 = getSectorDir(p2d, 1);
2523                 std::string sectordir;
2524                 if (fs::PathExists(sectordir1)) {
2525                         sectordir = sectordir1;
2526                 } else {
2527                         loadlayout = 2;
2528                         sectordir = getSectorDir(p2d, 2);
2529                 }
2530
2531                 /*
2532                 Make sure sector is loaded
2533                  */
2534
2535                 MapSector *sector = getSectorNoGenerateNoEx(p2d);
2536                 if (sector == NULL) {
2537                         try {
2538                                 sector = loadSectorMeta(sectordir, loadlayout != 2);
2539                         } catch(InvalidFilenameException &e) {
2540                                 return NULL;
2541                         } catch(FileNotGoodException &e) {
2542                                 return NULL;
2543                         } catch(std::exception &e) {
2544                                 return NULL;
2545                         }
2546                 }
2547
2548
2549                 /*
2550                 Make sure file exists
2551                  */
2552
2553                 std::string blockfilename = getBlockFilename(blockpos);
2554                 if (fs::PathExists(sectordir + DIR_DELIM + blockfilename) == false)
2555                         return NULL;
2556
2557                 /*
2558                 Load block and save it to the database
2559                  */
2560                 loadBlock(sectordir, blockfilename, sector, true);
2561         }
2562         MapBlock *block = getBlockNoCreateNoEx(blockpos);
2563         if (created_new && (block != NULL)) {
2564                 std::map<v3s16, MapBlock*> modified_blocks;
2565                 // Fix lighting if necessary
2566                 voxalgo::update_block_border_lighting(this, block, modified_blocks);
2567                 if (!modified_blocks.empty()) {
2568                         //Modified lighting, send event
2569                         MapEditEvent event;
2570                         event.type = MEET_OTHER;
2571                         std::map<v3s16, MapBlock *>::iterator it;
2572                         for (it = modified_blocks.begin();
2573                                         it != modified_blocks.end(); ++it)
2574                                 event.modified_blocks.insert(it->first);
2575                         dispatchEvent(&event);
2576                 }
2577         }
2578         return block;
2579 }
2580
2581 bool ServerMap::deleteBlock(v3s16 blockpos)
2582 {
2583         if (!dbase->deleteBlock(blockpos))
2584                 return false;
2585
2586         MapBlock *block = getBlockNoCreateNoEx(blockpos);
2587         if (block) {
2588                 v2s16 p2d(blockpos.X, blockpos.Z);
2589                 MapSector *sector = getSectorNoGenerateNoEx(p2d);
2590                 if (!sector)
2591                         return false;
2592                 sector->deleteBlock(block);
2593         }
2594
2595         return true;
2596 }
2597
2598 void ServerMap::PrintInfo(std::ostream &out)
2599 {
2600         out<<"ServerMap: ";
2601 }
2602
2603 bool ServerMap::repairBlockLight(v3s16 blockpos,
2604         std::map<v3s16, MapBlock *> *modified_blocks)
2605 {
2606         MapBlock *block = emergeBlock(blockpos, false);
2607         if (!block || !block->isGenerated())
2608                 return false;
2609         voxalgo::repair_block_light(this, block, modified_blocks);
2610         return true;
2611 }
2612
2613 MMVManip::MMVManip(Map *map):
2614                 VoxelManipulator(),
2615                 m_map(map)
2616 {
2617 }
2618
2619 MMVManip::~MMVManip()
2620 {
2621 }
2622
2623 void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
2624         bool load_if_inexistent)
2625 {
2626         TimeTaker timer1("initialEmerge", &emerge_time);
2627
2628         // Units of these are MapBlocks
2629         v3s16 p_min = blockpos_min;
2630         v3s16 p_max = blockpos_max;
2631
2632         VoxelArea block_area_nodes
2633                         (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
2634
2635         u32 size_MB = block_area_nodes.getVolume()*4/1000000;
2636         if(size_MB >= 1)
2637         {
2638                 infostream<<"initialEmerge: area: ";
2639                 block_area_nodes.print(infostream);
2640                 infostream<<" ("<<size_MB<<"MB)";
2641                 infostream<<std::endl;
2642         }
2643
2644         addArea(block_area_nodes);
2645
2646         for(s32 z=p_min.Z; z<=p_max.Z; z++)
2647         for(s32 y=p_min.Y; y<=p_max.Y; y++)
2648         for(s32 x=p_min.X; x<=p_max.X; x++)
2649         {
2650                 u8 flags = 0;
2651                 MapBlock *block;
2652                 v3s16 p(x,y,z);
2653                 std::map<v3s16, u8>::iterator n;
2654                 n = m_loaded_blocks.find(p);
2655                 if(n != m_loaded_blocks.end())
2656                         continue;
2657
2658                 bool block_data_inexistent = false;
2659                 try
2660                 {
2661                         TimeTaker timer1("emerge load", &emerge_load_time);
2662
2663                         block = m_map->getBlockNoCreate(p);
2664                         if(block->isDummy())
2665                                 block_data_inexistent = true;
2666                         else
2667                                 block->copyTo(*this);
2668                 }
2669                 catch(InvalidPositionException &e)
2670                 {
2671                         block_data_inexistent = true;
2672                 }
2673
2674                 if(block_data_inexistent)
2675                 {
2676
2677                         if (load_if_inexistent && !blockpos_over_max_limit(p)) {
2678                                 ServerMap *svrmap = (ServerMap *)m_map;
2679                                 block = svrmap->emergeBlock(p, false);
2680                                 if (block == NULL)
2681                                         block = svrmap->createBlock(p);
2682                                 block->copyTo(*this);
2683                         } else {
2684                                 flags |= VMANIP_BLOCK_DATA_INEXIST;
2685
2686                                 /*
2687                                         Mark area inexistent
2688                                 */
2689                                 VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
2690                                 // Fill with VOXELFLAG_NO_DATA
2691                                 for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
2692                                 for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++)
2693                                 {
2694                                         s32 i = m_area.index(a.MinEdge.X,y,z);
2695                                         memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE);
2696                                 }
2697                         }
2698                 }
2699                 /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE)
2700                 {
2701                         // Mark that block was loaded as blank
2702                         flags |= VMANIP_BLOCK_CONTAINS_CIGNORE;
2703                 }*/
2704
2705                 m_loaded_blocks[p] = flags;
2706         }
2707
2708         m_is_dirty = false;
2709 }
2710
2711 void MMVManip::blitBackAll(std::map<v3s16, MapBlock*> *modified_blocks,
2712         bool overwrite_generated)
2713 {
2714         if(m_area.getExtent() == v3s16(0,0,0))
2715                 return;
2716
2717         /*
2718                 Copy data of all blocks
2719         */
2720         for(std::map<v3s16, u8>::iterator
2721                         i = m_loaded_blocks.begin();
2722                         i != m_loaded_blocks.end(); ++i)
2723         {
2724                 v3s16 p = i->first;
2725                 MapBlock *block = m_map->getBlockNoCreateNoEx(p);
2726                 bool existed = !(i->second & VMANIP_BLOCK_DATA_INEXIST);
2727                 if ((existed == false) || (block == NULL) ||
2728                         (overwrite_generated == false && block->isGenerated() == true))
2729                         continue;
2730
2731                 block->copyFrom(*this);
2732
2733                 if(modified_blocks)
2734                         (*modified_blocks)[p] = block;
2735         }
2736 }
2737
2738 //END