Merge remote branch 'origin/master'
[oweals/minetest.git] / src / map.h
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 #ifndef MAP_HEADER
21 #define MAP_HEADER
22
23 #include <jmutex.h>
24 #include <jmutexautolock.h>
25 #include <jthread.h>
26 #include <iostream>
27 #include <sstream>
28
29 #include "irrlichttypes_bloated.h"
30 #include "mapnode.h"
31 #include "constants.h"
32 #include "voxel.h"
33 #include "mapgen.h" //for BlockMakeData and EmergeManager
34 #include "modifiedstate.h"
35 #include "util/container.h"
36 #include "nodetimer.h"
37
38 extern "C" {
39         #include "sqlite3.h"
40 }
41
42 class ClientMap;
43 class MapSector;
44 class ServerMapSector;
45 class MapBlock;
46 class NodeMetadata;
47 class IGameDef;
48 class IRollbackReportSink;
49 class EmergeManager;
50 class BlockMakeData;
51
52
53 /*
54         MapEditEvent
55 */
56
57 #define MAPTYPE_BASE 0
58 #define MAPTYPE_SERVER 1
59 #define MAPTYPE_CLIENT 2
60
61 enum MapEditEventType{
62         // Node added (changed from air or something else to something)
63         MEET_ADDNODE,
64         // Node removed (changed to air)
65         MEET_REMOVENODE,
66         // Node metadata of block changed (not knowing which node exactly)
67         // p stores block coordinate
68         MEET_BLOCK_NODE_METADATA_CHANGED,
69         // Anything else (modified_blocks are set unsent)
70         MEET_OTHER
71 };
72
73 struct MapEditEvent
74 {
75         MapEditEventType type;
76         v3s16 p;
77         MapNode n;
78         core::map<v3s16, bool> modified_blocks;
79         u16 already_known_by_peer;
80
81         MapEditEvent():
82                 type(MEET_OTHER),
83                 already_known_by_peer(0)
84         {
85         }
86
87         MapEditEvent * clone()
88         {
89                 MapEditEvent *event = new MapEditEvent();
90                 event->type = type;
91                 event->p = p;
92                 event->n = n;
93                 for(core::map<v3s16, bool>::Iterator
94                                 i = modified_blocks.getIterator();
95                                 i.atEnd()==false; i++)
96                 {
97                         v3s16 p = i.getNode()->getKey();
98                         bool v = i.getNode()->getValue();
99                         event->modified_blocks.insert(p, v);
100                 }
101                 return event;
102         }
103
104         VoxelArea getArea()
105         {
106                 switch(type){
107                 case MEET_ADDNODE:
108                         return VoxelArea(p);
109                 case MEET_REMOVENODE:
110                         return VoxelArea(p);
111                 case MEET_BLOCK_NODE_METADATA_CHANGED:
112                 {
113                         v3s16 np1 = p*MAP_BLOCKSIZE;
114                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
115                         return VoxelArea(np1, np2);
116                 }
117                 case MEET_OTHER:
118                 {
119                         VoxelArea a;
120                         for(core::map<v3s16, bool>::Iterator
121                                         i = modified_blocks.getIterator();
122                                         i.atEnd()==false; i++)
123                         {
124                                 v3s16 p = i.getNode()->getKey();
125                                 v3s16 np1 = p*MAP_BLOCKSIZE;
126                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
127                                 a.addPoint(np1);
128                                 a.addPoint(np2);
129                         }
130                         return a;
131                 }
132                 }
133                 return VoxelArea();
134         }
135 };
136
137 class MapEventReceiver
138 {
139 public:
140         // event shall be deleted by caller after the call.
141         virtual void onMapEditEvent(MapEditEvent *event) = 0;
142 };
143
144 class Map /*: public NodeContainer*/
145 {
146 public:
147
148         Map(std::ostream &dout, IGameDef *gamedef);
149         virtual ~Map();
150
151         /*virtual u16 nodeContainerId() const
152         {
153                 return NODECONTAINER_ID_MAP;
154         }*/
155
156         virtual s32 mapType() const
157         {
158                 return MAPTYPE_BASE;
159         }
160
161         /*
162                 Drop (client) or delete (server) the map.
163         */
164         virtual void drop()
165         {
166                 delete this;
167         }
168
169         void addEventReceiver(MapEventReceiver *event_receiver);
170         void removeEventReceiver(MapEventReceiver *event_receiver);
171         // event shall be deleted by caller after the call.
172         void dispatchEvent(MapEditEvent *event);
173
174         // On failure returns NULL
175         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
176         // Same as the above (there exists no lock anymore)
177         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
178         // On failure throws InvalidPositionException
179         MapSector * getSectorNoGenerate(v2s16 p2d);
180         // Gets an existing sector or creates an empty one
181         //MapSector * getSectorCreate(v2s16 p2d);
182
183         /*
184                 This is overloaded by ClientMap and ServerMap to allow
185                 their differing fetch methods.
186         */
187         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
188         virtual MapSector * emergeSector(v2s16 p,
189                         core::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
190
191         // Returns InvalidPositionException if not found
192         MapBlock * getBlockNoCreate(v3s16 p);
193         // Returns NULL if not found
194         MapBlock * getBlockNoCreateNoEx(v3s16 p);
195
196         /* Server overrides */
197         virtual MapBlock * emergeBlock(v3s16 p, bool allow_generate=true)
198         { return getBlockNoCreateNoEx(p); }
199
200         // Returns InvalidPositionException if not found
201         bool isNodeUnderground(v3s16 p);
202
203         bool isValidPosition(v3s16 p);
204
205         // throws InvalidPositionException if not found
206         MapNode getNode(v3s16 p);
207
208         // throws InvalidPositionException if not found
209         void setNode(v3s16 p, MapNode & n);
210
211         // Returns a CONTENT_IGNORE node if not found
212         MapNode getNodeNoEx(v3s16 p);
213
214         void unspreadLight(enum LightBank bank,
215                         core::map<v3s16, u8> & from_nodes,
216                         core::map<v3s16, bool> & light_sources,
217                         core::map<v3s16, MapBlock*> & modified_blocks);
218
219         void unLightNeighbors(enum LightBank bank,
220                         v3s16 pos, u8 lightwas,
221                         core::map<v3s16, bool> & light_sources,
222                         core::map<v3s16, MapBlock*> & modified_blocks);
223
224         void spreadLight(enum LightBank bank,
225                         core::map<v3s16, bool> & from_nodes,
226                         core::map<v3s16, MapBlock*> & modified_blocks);
227
228         void lightNeighbors(enum LightBank bank,
229                         v3s16 pos,
230                         core::map<v3s16, MapBlock*> & modified_blocks);
231
232         v3s16 getBrightestNeighbour(enum LightBank bank, v3s16 p);
233
234         s16 propagateSunlight(v3s16 start,
235                         core::map<v3s16, MapBlock*> & modified_blocks);
236
237         void updateLighting(enum LightBank bank,
238                         core::map<v3s16, MapBlock*>  & a_blocks,
239                         core::map<v3s16, MapBlock*> & modified_blocks);
240
241         void updateLighting(core::map<v3s16, MapBlock*>  & a_blocks,
242                         core::map<v3s16, MapBlock*> & modified_blocks);
243
244         /*
245                 These handle lighting but not faces.
246         */
247         void addNodeAndUpdate(v3s16 p, MapNode n,
248                         core::map<v3s16, MapBlock*> &modified_blocks);
249         void removeNodeAndUpdate(v3s16 p,
250                         core::map<v3s16, MapBlock*> &modified_blocks);
251
252         /*
253                 Wrappers for the latter ones.
254                 These emit events.
255                 Return true if succeeded, false if not.
256         */
257         bool addNodeWithEvent(v3s16 p, MapNode n);
258         bool removeNodeWithEvent(v3s16 p);
259
260         /*
261                 Takes the blocks at the edges into account
262         */
263         bool getDayNightDiff(v3s16 blockpos);
264
265         //core::aabbox3d<s16> getDisplayedBlockArea();
266
267         //bool updateChangedVisibleArea();
268
269         // Call these before and after saving of many blocks
270         virtual void beginSave() {return;};
271         virtual void endSave() {return;};
272
273         virtual void save(ModifiedState save_level){assert(0);};
274
275         // Server implements this.
276         // Client leaves it as no-op.
277         virtual void saveBlock(MapBlock *block){};
278
279         /*
280                 Updates usage timers and unloads unused blocks and sectors.
281                 Saves modified blocks before unloading on MAPTYPE_SERVER.
282         */
283         void timerUpdate(float dtime, float unload_timeout,
284                         core::list<v3s16> *unloaded_blocks=NULL);
285
286         // Deletes sectors and their blocks from memory
287         // Takes cache into account
288         // If deleted sector is in sector cache, clears cache
289         void deleteSectors(core::list<v2s16> &list);
290
291 #if 0
292         /*
293                 Unload unused data
294                 = flush changed to disk and delete from memory, if usage timer of
295                   block is more than timeout
296         */
297         void unloadUnusedData(float timeout,
298                         core::list<v3s16> *deleted_blocks=NULL);
299 #endif
300
301         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
302         virtual void PrintInfo(std::ostream &out);
303
304         void transformLiquids(core::map<v3s16, MapBlock*> & modified_blocks);
305         void transformLiquidsFinite(core::map<v3s16, MapBlock*> & modified_blocks);
306
307         /*
308                 Node metadata
309                 These are basically coordinate wrappers to MapBlock
310         */
311
312         NodeMetadata* getNodeMetadata(v3s16 p);
313         void setNodeMetadata(v3s16 p, NodeMetadata *meta);
314         void removeNodeMetadata(v3s16 p);
315
316         /*
317                 Node Timers
318                 These are basically coordinate wrappers to MapBlock
319         */
320
321         NodeTimer getNodeTimer(v3s16 p);
322         void setNodeTimer(v3s16 p, NodeTimer t);
323         void removeNodeTimer(v3s16 p);
324
325         /*
326                 Misc.
327         */
328         core::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
329
330         /*
331                 Variables
332         */
333
334         void transforming_liquid_add(v3s16 p);
335         s32 transforming_liquid_size();
336
337 protected:
338
339         std::ostream &m_dout; // A bit deprecated, could be removed
340
341         IGameDef *m_gamedef;
342
343         core::map<MapEventReceiver*, bool> m_event_receivers;
344
345         core::map<v2s16, MapSector*> m_sectors;
346
347         // Be sure to set this to NULL when the cached sector is deleted
348         MapSector *m_sector_cache;
349         v2s16 m_sector_cache_p;
350
351         // Queued transforming water nodes
352         UniqueQueue<v3s16> m_transforming_liquid;
353 };
354
355 /*
356         ServerMap
357
358         This is the only map class that is able to generate map.
359 */
360
361 class ServerMap : public Map
362 {
363 public:
364         /*
365                 savedir: directory to which map data should be saved
366         */
367         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
368         ~ServerMap();
369
370         s32 mapType() const
371         {
372                 return MAPTYPE_SERVER;
373         }
374
375         /*
376                 Get a sector from somewhere.
377                 - Check memory
378                 - Check disk (doesn't load blocks)
379                 - Create blank one
380         */
381         ServerMapSector * createSector(v2s16 p);
382
383         /*
384                 Blocks are generated by using these and makeBlock().
385         */
386         bool initBlockMake(BlockMakeData *data, v3s16 blockpos);
387         MapBlock *finishBlockMake(BlockMakeData *data,
388                         core::map<v3s16, MapBlock*> &changed_blocks);
389
390         // A non-threaded wrapper to the above  - DEFUNCT
391 /*      MapBlock * generateBlock(
392                         v3s16 p,
393                         core::map<v3s16, MapBlock*> &modified_blocks
394         );*/
395
396         /*
397                 Get a block from somewhere.
398                 - Memory
399                 - Create blank
400         */
401         MapBlock * createBlock(v3s16 p);
402
403         /*
404                 Forcefully get a block from somewhere.
405                 - Memory
406                 - Load from disk
407                 - Create blank filled with CONTENT_IGNORE
408
409         */
410         MapBlock * emergeBlock(v3s16 p, bool create_blank=true);
411
412         // Helper for placing objects on ground level
413         s16 findGroundLevel(v2s16 p2d);
414
415         /*
416                 Misc. helper functions for fiddling with directory and file
417                 names when saving
418         */
419         void createDirs(std::string path);
420         // returns something like "map/sectors/xxxxxxxx"
421         std::string getSectorDir(v2s16 pos, int layout = 2);
422         // dirname: final directory name
423         v2s16 getSectorPos(std::string dirname);
424         v3s16 getBlockPos(std::string sectordir, std::string blockfile);
425         static std::string getBlockFilename(v3s16 p);
426
427         /*
428                 Database functions
429         */
430         // Create the database structure
431         void createDatabase();
432         // Verify we can read/write to the database
433         void verifyDatabase();
434         // Get an integer suitable for a block
435         static sqlite3_int64 getBlockAsInteger(const v3s16 pos);
436         static v3s16 getIntegerAsBlock(sqlite3_int64 i);
437
438         // Returns true if the database file does not exist
439         bool loadFromFolders();
440
441         // Call these before and after saving of blocks
442         void beginSave();
443         void endSave();
444
445         void save(ModifiedState save_level);
446         //void loadAll();
447
448         void listAllLoadableBlocks(core::list<v3s16> &dst);
449
450         // Saves map seed and possibly other stuff
451         void saveMapMeta();
452         void loadMapMeta();
453
454         /*void saveChunkMeta();
455         void loadChunkMeta();*/
456
457         // The sector mutex should be locked when calling most of these
458
459         // This only saves sector-specific data such as the heightmap
460         // (no MapBlocks)
461         // DEPRECATED? Sectors have no metadata anymore.
462         void saveSectorMeta(ServerMapSector *sector);
463         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
464         bool loadSectorMeta(v2s16 p2d);
465
466         // Full load of a sector including all blocks.
467         // returns true on success, false on failure.
468         bool loadSectorFull(v2s16 p2d);
469         // If sector is not found in memory, try to load it from disk.
470         // Returns true if sector now resides in memory
471         //bool deFlushSector(v2s16 p2d);
472
473         void saveBlock(MapBlock *block);
474         // This will generate a sector with getSector if not found.
475         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
476         MapBlock* loadBlock(v3s16 p);
477         // Database version
478         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
479
480         // For debug printing
481         virtual void PrintInfo(std::ostream &out);
482
483         bool isSavingEnabled(){ return m_map_saving_enabled; }
484
485         u64 getSeed(){ return m_seed; }
486
487         MapgenParams *getMapgenParams(){ return m_mgparams; }
488
489         // Parameters fed to the Mapgen
490         MapgenParams *m_mgparams;
491 private:
492         // Seed used for all kinds of randomness in generation
493         u64 m_seed;
494         
495         // Emerge manager
496         EmergeManager *m_emerge;
497
498         std::string m_savedir;
499         bool m_map_saving_enabled;
500
501 #if 0
502         // Chunk size in MapSectors
503         // If 0, chunks are disabled.
504         s16 m_chunksize;
505         // Chunks
506         core::map<v2s16, MapChunk*> m_chunks;
507 #endif
508
509         /*
510                 Metadata is re-written on disk only if this is true.
511                 This is reset to false when written on disk.
512         */
513         bool m_map_metadata_changed;
514
515         /*
516                 SQLite database and statements
517         */
518         sqlite3 *m_database;
519         sqlite3_stmt *m_database_read;
520         sqlite3_stmt *m_database_write;
521         sqlite3_stmt *m_database_list;
522 };
523
524 #define VMANIP_BLOCK_DATA_INEXIST     1
525 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
526
527 class MapVoxelManipulator : public VoxelManipulator
528 {
529 public:
530         MapVoxelManipulator(Map *map);
531         virtual ~MapVoxelManipulator();
532
533         virtual void clear()
534         {
535                 VoxelManipulator::clear();
536                 m_loaded_blocks.clear();
537         }
538
539         virtual void emerge(VoxelArea a, s32 caller_id=-1);
540
541         void blitBack(core::map<v3s16, MapBlock*> & modified_blocks);
542         
543         /*
544                 key = blockpos
545                 value = flags describing the block
546         */
547         core::map<v3s16, u8> m_loaded_blocks;
548 protected:
549         Map *m_map;
550 };
551
552 class ManualMapVoxelManipulator : public MapVoxelManipulator
553 {
554 public:
555         ManualMapVoxelManipulator(Map *map);
556         virtual ~ManualMapVoxelManipulator();
557
558         void setMap(Map *map)
559         {m_map = map;}
560
561         virtual void emerge(VoxelArea a, s32 caller_id=-1);
562
563         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max);
564
565         // This is much faster with big chunks of generated data
566         void blitBackAll(core::map<v3s16, MapBlock*> * modified_blocks);
567
568 protected:
569         bool m_create_area;
570 };
571
572 #endif
573