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