Omnicleanup: header cleanup, add ModApiUtil shared between game and mainmenu
[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 <iostream>
24 #include <sstream>
25 #include <set>
26 #include <map>
27 #include <list>
28
29 #include "irrlichttypes_bloated.h"
30 #include "mapnode.h"
31 #include "constants.h"
32 #include "voxel.h"
33 #include "modifiedstate.h"
34 #include "util/container.h"
35 #include "nodetimer.h"
36
37 extern "C" {
38         #include "sqlite3.h"
39 }
40
41 class ClientMap;
42 class MapSector;
43 class ServerMapSector;
44 class MapBlock;
45 class NodeMetadata;
46 class IGameDef;
47 class IRollbackReportSink;
48 class EmergeManager;
49 class ServerEnvironment;
50 struct BlockMakeData;
51 struct MapgenParams;
52
53
54 /*
55         MapEditEvent
56 */
57
58 #define MAPTYPE_BASE 0
59 #define MAPTYPE_SERVER 1
60 #define MAPTYPE_CLIENT 2
61
62 enum MapEditEventType{
63         // Node added (changed from air or something else to something)
64         MEET_ADDNODE,
65         // Node removed (changed to air)
66         MEET_REMOVENODE,
67         // Node metadata of block changed (not knowing which node exactly)
68         // p stores block coordinate
69         MEET_BLOCK_NODE_METADATA_CHANGED,
70         // Anything else (modified_blocks are set unsent)
71         MEET_OTHER
72 };
73
74 struct MapEditEvent
75 {
76         MapEditEventType type;
77         v3s16 p;
78         MapNode n;
79         std::set<v3s16> modified_blocks;
80         u16 already_known_by_peer;
81
82         MapEditEvent():
83                 type(MEET_OTHER),
84                 already_known_by_peer(0)
85         {
86         }
87
88         MapEditEvent * clone()
89         {
90                 MapEditEvent *event = new MapEditEvent();
91                 event->type = type;
92                 event->p = p;
93                 event->n = n;
94                 event->modified_blocks = modified_blocks;
95                 return event;
96         }
97
98         VoxelArea getArea()
99         {
100                 switch(type){
101                 case MEET_ADDNODE:
102                         return VoxelArea(p);
103                 case MEET_REMOVENODE:
104                         return VoxelArea(p);
105                 case MEET_BLOCK_NODE_METADATA_CHANGED:
106                 {
107                         v3s16 np1 = p*MAP_BLOCKSIZE;
108                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
109                         return VoxelArea(np1, np2);
110                 }
111                 case MEET_OTHER:
112                 {
113                         VoxelArea a;
114                         for(std::set<v3s16>::iterator
115                                         i = modified_blocks.begin();
116                                         i != modified_blocks.end(); ++i)
117                         {
118                                 v3s16 p = *i;
119                                 v3s16 np1 = p*MAP_BLOCKSIZE;
120                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
121                                 a.addPoint(np1);
122                                 a.addPoint(np2);
123                         }
124                         return a;
125                 }
126                 }
127                 return VoxelArea();
128         }
129 };
130
131 class MapEventReceiver
132 {
133 public:
134         // event shall be deleted by caller after the call.
135         virtual void onMapEditEvent(MapEditEvent *event) = 0;
136 };
137
138 class Map /*: public NodeContainer*/
139 {
140 public:
141
142         Map(std::ostream &dout, IGameDef *gamedef);
143         virtual ~Map();
144
145         /*virtual u16 nodeContainerId() const
146         {
147                 return NODECONTAINER_ID_MAP;
148         }*/
149
150         virtual s32 mapType() const
151         {
152                 return MAPTYPE_BASE;
153         }
154
155         /*
156                 Drop (client) or delete (server) the map.
157         */
158         virtual void drop()
159         {
160                 delete this;
161         }
162
163         void addEventReceiver(MapEventReceiver *event_receiver);
164         void removeEventReceiver(MapEventReceiver *event_receiver);
165         // event shall be deleted by caller after the call.
166         void dispatchEvent(MapEditEvent *event);
167
168         // On failure returns NULL
169         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
170         // Same as the above (there exists no lock anymore)
171         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
172         // On failure throws InvalidPositionException
173         MapSector * getSectorNoGenerate(v2s16 p2d);
174         // Gets an existing sector or creates an empty one
175         //MapSector * getSectorCreate(v2s16 p2d);
176
177         /*
178                 This is overloaded by ClientMap and ServerMap to allow
179                 their differing fetch methods.
180         */
181         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
182         virtual MapSector * emergeSector(v2s16 p,
183                         std::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
184
185         // Returns InvalidPositionException if not found
186         MapBlock * getBlockNoCreate(v3s16 p);
187         // Returns NULL if not found
188         MapBlock * getBlockNoCreateNoEx(v3s16 p);
189
190         /* Server overrides */
191         virtual MapBlock * emergeBlock(v3s16 p, bool allow_generate=true)
192         { return getBlockNoCreateNoEx(p); }
193
194         // Returns InvalidPositionException if not found
195         bool isNodeUnderground(v3s16 p);
196
197         bool isValidPosition(v3s16 p);
198
199         // throws InvalidPositionException if not found
200         MapNode getNode(v3s16 p);
201
202         // throws InvalidPositionException if not found
203         void setNode(v3s16 p, MapNode & n);
204
205         // Returns a CONTENT_IGNORE node if not found
206         MapNode getNodeNoEx(v3s16 p);
207
208         void unspreadLight(enum LightBank bank,
209                         std::map<v3s16, u8> & from_nodes,
210                         std::set<v3s16> & light_sources,
211                         std::map<v3s16, MapBlock*> & modified_blocks);
212
213         void unLightNeighbors(enum LightBank bank,
214                         v3s16 pos, u8 lightwas,
215                         std::set<v3s16> & light_sources,
216                         std::map<v3s16, MapBlock*> & modified_blocks);
217
218         void spreadLight(enum LightBank bank,
219                         std::set<v3s16> & from_nodes,
220                         std::map<v3s16, MapBlock*> & modified_blocks);
221
222         void lightNeighbors(enum LightBank bank,
223                         v3s16 pos,
224                         std::map<v3s16, MapBlock*> & modified_blocks);
225
226         v3s16 getBrightestNeighbour(enum LightBank bank, v3s16 p);
227
228         s16 propagateSunlight(v3s16 start,
229                         std::map<v3s16, MapBlock*> & modified_blocks);
230
231         void updateLighting(enum LightBank bank,
232                         std::map<v3s16, MapBlock*>  & a_blocks,
233                         std::map<v3s16, MapBlock*> & modified_blocks);
234
235         void updateLighting(std::map<v3s16, MapBlock*>  & a_blocks,
236                         std::map<v3s16, MapBlock*> & modified_blocks);
237
238         /*
239                 These handle lighting but not faces.
240         */
241         void addNodeAndUpdate(v3s16 p, MapNode n,
242                         std::map<v3s16, MapBlock*> &modified_blocks);
243         void removeNodeAndUpdate(v3s16 p,
244                         std::map<v3s16, MapBlock*> &modified_blocks);
245
246         /*
247                 Wrappers for the latter ones.
248                 These emit events.
249                 Return true if succeeded, false if not.
250         */
251         bool addNodeWithEvent(v3s16 p, MapNode n);
252         bool removeNodeWithEvent(v3s16 p);
253
254         /*
255                 Takes the blocks at the edges into account
256         */
257         bool getDayNightDiff(v3s16 blockpos);
258
259         //core::aabbox3d<s16> getDisplayedBlockArea();
260
261         //bool updateChangedVisibleArea();
262
263         // Call these before and after saving of many blocks
264         virtual void beginSave() {return;};
265         virtual void endSave() {return;};
266
267         virtual void save(ModifiedState save_level){assert(0);};
268
269         // Server implements this.
270         // Client leaves it as no-op.
271         virtual void saveBlock(MapBlock *block){};
272
273         /*
274                 Updates usage timers and unloads unused blocks and sectors.
275                 Saves modified blocks before unloading on MAPTYPE_SERVER.
276         */
277         void timerUpdate(float dtime, float unload_timeout,
278                         std::list<v3s16> *unloaded_blocks=NULL);
279
280         /*
281                 Unloads all blocks with a zero refCount().
282                 Saves modified blocks before unloading on MAPTYPE_SERVER.
283         */
284         void unloadUnreferencedBlocks(std::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(std::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(std::map<v3s16, MapBlock*> & modified_blocks);
305         void transformLiquidsFinite(std::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         std::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         virtual s16 getHeat(v3s16 p);
338         virtual s16 getHumidity(v3s16 p);
339
340 protected:
341         friend class LuaVoxelManip;
342
343         std::ostream &m_dout; // A bit deprecated, could be removed
344
345         IGameDef *m_gamedef;
346
347         std::set<MapEventReceiver*> m_event_receivers;
348
349         std::map<v2s16, MapSector*> m_sectors;
350
351         // Be sure to set this to NULL when the cached sector is deleted
352         MapSector *m_sector_cache;
353         v2s16 m_sector_cache_p;
354
355         // Queued transforming water nodes
356         UniqueQueue<v3s16> m_transforming_liquid;
357 };
358
359 /*
360         ServerMap
361
362         This is the only map class that is able to generate map.
363 */
364
365 class ServerMap : public Map
366 {
367 public:
368         /*
369                 savedir: directory to which map data should be saved
370         */
371         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
372         ~ServerMap();
373
374         s32 mapType() const
375         {
376                 return MAPTYPE_SERVER;
377         }
378
379         /*
380                 Get a sector from somewhere.
381                 - Check memory
382                 - Check disk (doesn't load blocks)
383                 - Create blank one
384         */
385         ServerMapSector * createSector(v2s16 p);
386
387         /*
388                 Blocks are generated by using these and makeBlock().
389         */
390         bool initBlockMake(BlockMakeData *data, v3s16 blockpos);
391         MapBlock *finishBlockMake(BlockMakeData *data,
392                         std::map<v3s16, MapBlock*> &changed_blocks);
393
394         /*
395                 Get a block from somewhere.
396                 - Memory
397                 - Create blank
398         */
399         MapBlock * createBlock(v3s16 p);
400
401         /*
402                 Forcefully get a block from somewhere.
403                 - Memory
404                 - Load from disk
405                 - Create blank filled with CONTENT_IGNORE
406
407         */
408         MapBlock * emergeBlock(v3s16 p, bool create_blank=true);
409
410         // Helper for placing objects on ground level
411         s16 findGroundLevel(v2s16 p2d);
412
413         /*
414                 Misc. helper functions for fiddling with directory and file
415                 names when saving
416         */
417         void createDirs(std::string path);
418         // returns something like "map/sectors/xxxxxxxx"
419         std::string getSectorDir(v2s16 pos, int layout = 2);
420         // dirname: final directory name
421         v2s16 getSectorPos(std::string dirname);
422         v3s16 getBlockPos(std::string sectordir, std::string blockfile);
423         static std::string getBlockFilename(v3s16 p);
424
425         /*
426                 Database functions
427         */
428         // Create the database structure
429         void createDatabase();
430         // Verify we can read/write to the database
431         void verifyDatabase();
432         // Get an integer suitable for a block
433         static sqlite3_int64 getBlockAsInteger(const v3s16 pos);
434         static v3s16 getIntegerAsBlock(sqlite3_int64 i);
435
436         // Returns true if the database file does not exist
437         bool loadFromFolders();
438
439         // Call these before and after saving of blocks
440         void beginSave();
441         void endSave();
442
443         void save(ModifiedState save_level);
444         void listAllLoadableBlocks(std::list<v3s16> &dst);
445         void listAllLoadedBlocks(std::list<v3s16> &dst);
446         // Saves map seed and possibly other stuff
447         void saveMapMeta();
448         void loadMapMeta();
449
450         /*void saveChunkMeta();
451         void loadChunkMeta();*/
452
453         // The sector mutex should be locked when calling most of these
454
455         // This only saves sector-specific data such as the heightmap
456         // (no MapBlocks)
457         // DEPRECATED? Sectors have no metadata anymore.
458         void saveSectorMeta(ServerMapSector *sector);
459         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
460         bool loadSectorMeta(v2s16 p2d);
461
462         // Full load of a sector including all blocks.
463         // returns true on success, false on failure.
464         bool loadSectorFull(v2s16 p2d);
465         // If sector is not found in memory, try to load it from disk.
466         // Returns true if sector now resides in memory
467         //bool deFlushSector(v2s16 p2d);
468
469         void saveBlock(MapBlock *block);
470         // This will generate a sector with getSector if not found.
471         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
472         MapBlock* loadBlock(v3s16 p);
473         // Database version
474         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
475
476         // For debug printing
477         virtual void PrintInfo(std::ostream &out);
478
479         bool isSavingEnabled(){ return m_map_saving_enabled; }
480
481         u64 getSeed(){ return m_seed; }
482
483         MapgenParams *getMapgenParams(){ return m_mgparams; }
484
485         // Parameters fed to the Mapgen
486         MapgenParams *m_mgparams;
487
488         virtual s16 getHeat(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
489         virtual s16 getHumidity(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
490
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(std::map<v3s16, MapBlock*> & modified_blocks);
542
543 protected:
544         Map *m_map;
545         /*
546                 key = blockpos
547                 value = flags describing the block
548         */
549         std::map<v3s16, u8> m_loaded_blocks;
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                                                 bool load_if_inexistent = true);
565
566         // This is much faster with big chunks of generated data
567         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks);
568
569 protected:
570         bool m_create_area;
571 };
572
573 #endif
574