]> git.lizzy.rs Git - dragonfireclient.git/blob - src/map.h
C++11 patchset 2: remove util/cpp11.h and util/cpp11_container.h (#5821)
[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 #include "map_settings_manager.h"
37
38 class Settings;
39 class MapDatabase;
40 class ClientMap;
41 class MapSector;
42 class ServerMapSector;
43 class MapBlock;
44 class NodeMetadata;
45 class IGameDef;
46 class IRollbackManager;
47 class EmergeManager;
48 class ServerEnvironment;
49 struct BlockMakeData;
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                 n(CONTENT_AIR),
84                 already_known_by_peer(0)
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 create_blank=true)
193         { return getBlockNoCreateNoEx(p); }
194
195         inline INodeDefManager * getNodeDefManager() { return m_nodedef; }
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         void setNode(v3s16 p, MapNode & n);
204
205         // Returns a CONTENT_IGNORE node if not found
206         // If is_valid_position is not NULL then this will be set to true if the
207         // position is valid, otherwise false
208         MapNode getNodeNoEx(v3s16 p, bool *is_valid_position = NULL);
209
210         /*
211                 These handle lighting but not faces.
212         */
213         void addNodeAndUpdate(v3s16 p, MapNode n,
214                         std::map<v3s16, MapBlock*> &modified_blocks,
215                         bool remove_metadata = true);
216         void removeNodeAndUpdate(v3s16 p,
217                         std::map<v3s16, MapBlock*> &modified_blocks);
218
219         /*
220                 Wrappers for the latter ones.
221                 These emit events.
222                 Return true if succeeded, false if not.
223         */
224         bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
225         bool removeNodeWithEvent(v3s16 p);
226
227         /*
228                 Takes the blocks at the edges into account
229         */
230         bool getDayNightDiff(v3s16 blockpos);
231
232         //core::aabbox3d<s16> getDisplayedBlockArea();
233
234         //bool updateChangedVisibleArea();
235
236         // Call these before and after saving of many blocks
237         virtual void beginSave() { return; }
238         virtual void endSave() { return; }
239
240         virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
241
242         // Server implements these.
243         // Client leaves them as no-op.
244         virtual bool saveBlock(MapBlock *block) { return false; }
245         virtual bool deleteBlock(v3s16 blockpos) { return false; }
246
247         /*
248                 Updates usage timers and unloads unused blocks and sectors.
249                 Saves modified blocks before unloading on MAPTYPE_SERVER.
250         */
251         void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
252                         std::vector<v3s16> *unloaded_blocks=NULL);
253
254         /*
255                 Unloads all blocks with a zero refCount().
256                 Saves modified blocks before unloading on MAPTYPE_SERVER.
257         */
258         void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
259
260         // Deletes sectors and their blocks from memory
261         // Takes cache into account
262         // If deleted sector is in sector cache, clears cache
263         void deleteSectors(std::vector<v2s16> &list);
264
265         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
266         virtual void PrintInfo(std::ostream &out);
267
268         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
269                         ServerEnvironment *env);
270
271         /*
272                 Node metadata
273                 These are basically coordinate wrappers to MapBlock
274         */
275
276         std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
277         NodeMetadata *getNodeMetadata(v3s16 p);
278
279         /**
280          * Sets metadata for a node.
281          * This method sets the metadata for a given node.
282          * On success, it returns @c true and the object pointed to
283          * by @p meta is then managed by the system and should
284          * not be deleted by the caller.
285          *
286          * In case of failure, the method returns @c false and the
287          * caller is still responsible for deleting the object!
288          *
289          * @param p node coordinates
290          * @param meta pointer to @c NodeMetadata object
291          * @return @c true on success, false on failure
292          */
293         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
294         void removeNodeMetadata(v3s16 p);
295
296         /*
297                 Node Timers
298                 These are basically coordinate wrappers to MapBlock
299         */
300
301         NodeTimer getNodeTimer(v3s16 p);
302         void setNodeTimer(const NodeTimer &t);
303         void removeNodeTimer(v3s16 p);
304
305         /*
306                 Misc.
307         */
308         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
309
310         /*
311                 Variables
312         */
313
314         void transforming_liquid_add(v3s16 p);
315         s32 transforming_liquid_size();
316
317         bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
318 protected:
319         friend class LuaVoxelManip;
320
321         std::ostream &m_dout; // A bit deprecated, could be removed
322
323         IGameDef *m_gamedef;
324
325         std::set<MapEventReceiver*> m_event_receivers;
326
327         std::map<v2s16, MapSector*> m_sectors;
328
329         // Be sure to set this to NULL when the cached sector is deleted
330         MapSector *m_sector_cache;
331         v2s16 m_sector_cache_p;
332
333         // Queued transforming water nodes
334         UniqueQueue<v3s16> m_transforming_liquid;
335
336         // This stores the properties of the nodes on the map.
337         INodeDefManager *m_nodedef;
338
339         bool isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac,
340                         float start_off, float end_off, u32 needed_count);
341
342 private:
343         f32 m_transforming_liquid_loop_count_multiplier;
344         u32 m_unprocessed_count;
345         u64 m_inc_trending_up_start_time; // milliseconds
346         bool m_queue_size_timer_started;
347
348         DISABLE_CLASS_COPY(Map);
349 };
350
351 /*
352         ServerMap
353
354         This is the only map class that is able to generate map.
355 */
356
357 class ServerMap : public Map
358 {
359 public:
360         /*
361                 savedir: directory to which map data should be saved
362         */
363         ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge);
364         ~ServerMap();
365
366         s32 mapType() const
367         {
368                 return MAPTYPE_SERVER;
369         }
370
371         /*
372                 Get a sector from somewhere.
373                 - Check memory
374                 - Check disk (doesn't load blocks)
375                 - Create blank one
376         */
377         ServerMapSector *createSector(v2s16 p);
378
379         bool saoPositionOverLimit(const v3f &p);
380
381         /*
382                 Blocks are generated by using these and makeBlock().
383         */
384         bool blockpos_over_mapgen_limit(v3s16 p);
385         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
386         void finishBlockMake(BlockMakeData *data,
387                 std::map<v3s16, MapBlock*> *changed_blocks);
388
389         /*
390                 Get a block from somewhere.
391                 - Memory
392                 - Create blank
393         */
394         MapBlock *createBlock(v3s16 p);
395
396         /*
397                 Forcefully get a block from somewhere.
398                 - Memory
399                 - Load from disk
400                 - Create blank filled with CONTENT_IGNORE
401
402         */
403         MapBlock *emergeBlock(v3s16 p, bool create_blank=true);
404
405         /*
406                 Try to get a block.
407                 If it does not exist in memory, add it to the emerge queue.
408                 - Memory
409                 - Emerge Queue (deferred disk or generate)
410         */
411         MapBlock *getBlockOrEmerge(v3s16 p3d);
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(const std::string &dirname);
425         v3s16 getBlockPos(const std::string &sectordir, const std::string &blockfile);
426         static std::string getBlockFilename(v3s16 p);
427
428         /*
429                 Database functions
430         */
431         static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
432
433         // Returns true if the database file does not exist
434         bool loadFromFolders();
435
436         // Call these before and after saving of blocks
437         void beginSave();
438         void endSave();
439
440         void save(ModifiedState save_level);
441         void listAllLoadableBlocks(std::vector<v3s16> &dst);
442         void listAllLoadedBlocks(std::vector<v3s16> &dst);
443
444         MapgenParams *getMapgenParams();
445
446         /*void saveChunkMeta();
447         void loadChunkMeta();*/
448
449         // The sector mutex should be locked when calling most of these
450
451         // This only saves sector-specific data such as the heightmap
452         // (no MapBlocks)
453         // DEPRECATED? Sectors have no metadata anymore.
454         void saveSectorMeta(ServerMapSector *sector);
455         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
456         bool loadSectorMeta(v2s16 p2d);
457
458         bool saveBlock(MapBlock *block);
459         static bool saveBlock(MapBlock *block, MapDatabase *db);
460         // This will generate a sector with getSector if not found.
461         void loadBlock(const std::string &sectordir, const std::string &blockfile,
462                         MapSector *sector, bool save_after_load=false);
463         MapBlock* loadBlock(v3s16 p);
464         // Database version
465         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
466
467         bool deleteBlock(v3s16 blockpos);
468
469         void updateVManip(v3s16 pos);
470
471         // For debug printing
472         virtual void PrintInfo(std::ostream &out);
473
474         bool isSavingEnabled(){ return m_map_saving_enabled; }
475
476         u64 getSeed();
477         s16 getWaterLevel();
478
479         /*!
480          * Fixes lighting in one map block.
481          * May modify other blocks as well, as light can spread
482          * out of the specified block.
483          * Returns false if the block is not generated (so nothing
484          * changed), true otherwise.
485          */
486         bool repairBlockLight(v3s16 blockpos,
487                 std::map<v3s16, MapBlock *> *modified_blocks);
488
489         MapSettingsManager settings_mgr;
490
491 private:
492         // Emerge manager
493         EmergeManager *m_emerge;
494
495         std::string m_savedir;
496         bool m_map_saving_enabled;
497
498 #if 0
499         // Chunk size in MapSectors
500         // If 0, chunks are disabled.
501         s16 m_chunksize;
502         // Chunks
503         core::map<v2s16, MapChunk*> m_chunks;
504 #endif
505
506         /*
507                 Metadata is re-written on disk only if this is true.
508                 This is reset to false when written on disk.
509         */
510         bool m_map_metadata_changed;
511         MapDatabase *dbase;
512 };
513
514
515 #define VMANIP_BLOCK_DATA_INEXIST     1
516 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
517
518 class MMVManip : public VoxelManipulator
519 {
520 public:
521         MMVManip(Map *map);
522         virtual ~MMVManip();
523
524         virtual void clear()
525         {
526                 VoxelManipulator::clear();
527                 m_loaded_blocks.clear();
528         }
529
530         void setMap(Map *map)
531         {m_map = map;}
532
533         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
534                 bool load_if_inexistent = true);
535
536         // This is much faster with big chunks of generated data
537         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
538                 bool overwrite_generated = true);
539
540         bool m_is_dirty;
541
542 protected:
543         bool m_create_area;
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 #endif