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