]> git.lizzy.rs Git - dragonfireclient.git/blob - src/map.h
93ab591a3c0184428a29a80c614d226ae1db7b75
[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 #pragma once
21
22 #include <iostream>
23 #include <sstream>
24 #include <set>
25 #include <map>
26 #include <list>
27
28 #include "irrlichttypes_bloated.h"
29 #include "mapnode.h"
30 #include "constants.h"
31 #include "voxel.h"
32 #include "modifiedstate.h"
33 #include "util/container.h"
34 #include "nodetimer.h"
35 #include "map_settings_manager.h"
36 #include "debug.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 = MEET_OTHER;
76         v3s16 p;
77         MapNode n = CONTENT_AIR;
78         std::set<v3s16> modified_blocks;
79         u16 already_known_by_peer = 0;
80
81         MapEditEvent() = default;
82
83         MapEditEvent * clone()
84         {
85                 MapEditEvent *event = new MapEditEvent();
86                 event->type = type;
87                 event->p = p;
88                 event->n = n;
89                 event->modified_blocks = modified_blocks;
90                 return event;
91         }
92
93         VoxelArea getArea()
94         {
95                 switch(type){
96                 case MEET_ADDNODE:
97                         return VoxelArea(p);
98                 case MEET_REMOVENODE:
99                         return VoxelArea(p);
100                 case MEET_SWAPNODE:
101                         return VoxelArea(p);
102                 case MEET_BLOCK_NODE_METADATA_CHANGED:
103                 {
104                         v3s16 np1 = p*MAP_BLOCKSIZE;
105                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
106                         return VoxelArea(np1, np2);
107                 }
108                 case MEET_OTHER:
109                 {
110                         VoxelArea a;
111                         for (v3s16 p : modified_blocks) {
112                                 v3s16 np1 = p*MAP_BLOCKSIZE;
113                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
114                                 a.addPoint(np1);
115                                 a.addPoint(np2);
116                         }
117                         return a;
118                 }
119                 }
120                 return VoxelArea();
121         }
122 };
123
124 class MapEventReceiver
125 {
126 public:
127         // event shall be deleted by caller after the call.
128         virtual void onMapEditEvent(MapEditEvent *event) = 0;
129 };
130
131 class Map /*: public NodeContainer*/
132 {
133 public:
134
135         Map(std::ostream &dout, IGameDef *gamedef);
136         virtual ~Map();
137         DISABLE_CLASS_COPY(Map);
138
139         virtual s32 mapType() const
140         {
141                 return MAPTYPE_BASE;
142         }
143
144         /*
145                 Drop (client) or delete (server) the map.
146         */
147         virtual void drop()
148         {
149                 delete this;
150         }
151
152         void addEventReceiver(MapEventReceiver *event_receiver);
153         void removeEventReceiver(MapEventReceiver *event_receiver);
154         // event shall be deleted by caller after the call.
155         void dispatchEvent(MapEditEvent *event);
156
157         // On failure returns NULL
158         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
159         // Same as the above (there exists no lock anymore)
160         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
161         // On failure throws InvalidPositionException
162         MapSector * getSectorNoGenerate(v2s16 p2d);
163         // Gets an existing sector or creates an empty one
164         //MapSector * getSectorCreate(v2s16 p2d);
165
166         /*
167                 This is overloaded by ClientMap and ServerMap to allow
168                 their differing fetch methods.
169         */
170         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
171         virtual MapSector * emergeSector(v2s16 p,
172                         std::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
173
174         // Returns InvalidPositionException if not found
175         MapBlock * getBlockNoCreate(v3s16 p);
176         // Returns NULL if not found
177         MapBlock * getBlockNoCreateNoEx(v3s16 p);
178
179         /* Server overrides */
180         virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
181         { return getBlockNoCreateNoEx(p); }
182
183         inline INodeDefManager * getNodeDefManager() { return m_nodedef; }
184
185         // Returns InvalidPositionException if not found
186         bool isNodeUnderground(v3s16 p);
187
188         bool isValidPosition(v3s16 p);
189
190         // throws InvalidPositionException if not found
191         void setNode(v3s16 p, MapNode & n);
192
193         // Returns a CONTENT_IGNORE node if not found
194         // If is_valid_position is not NULL then this will be set to true if the
195         // position is valid, otherwise false
196         MapNode getNodeNoEx(v3s16 p, bool *is_valid_position = NULL);
197
198         /*
199                 These handle lighting but not faces.
200         */
201         void addNodeAndUpdate(v3s16 p, MapNode n,
202                         std::map<v3s16, MapBlock*> &modified_blocks,
203                         bool remove_metadata = true);
204         void removeNodeAndUpdate(v3s16 p,
205                         std::map<v3s16, MapBlock*> &modified_blocks);
206
207         /*
208                 Wrappers for the latter ones.
209                 These emit events.
210                 Return true if succeeded, false if not.
211         */
212         bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
213         bool removeNodeWithEvent(v3s16 p);
214
215         // Call these before and after saving of many blocks
216         virtual void beginSave() {}
217         virtual void endSave() {}
218
219         virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
220
221         // Server implements these.
222         // Client leaves them as no-op.
223         virtual bool saveBlock(MapBlock *block) { return false; }
224         virtual bool deleteBlock(v3s16 blockpos) { return false; }
225
226         /*
227                 Updates usage timers and unloads unused blocks and sectors.
228                 Saves modified blocks before unloading on MAPTYPE_SERVER.
229         */
230         void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
231                         std::vector<v3s16> *unloaded_blocks=NULL);
232
233         /*
234                 Unloads all blocks with a zero refCount().
235                 Saves modified blocks before unloading on MAPTYPE_SERVER.
236         */
237         void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
238
239         // Deletes sectors and their blocks from memory
240         // Takes cache into account
241         // If deleted sector is in sector cache, clears cache
242         void deleteSectors(std::vector<v2s16> &list);
243
244         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
245         virtual void PrintInfo(std::ostream &out);
246
247         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
248                         ServerEnvironment *env);
249
250         /*
251                 Node metadata
252                 These are basically coordinate wrappers to MapBlock
253         */
254
255         std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
256         NodeMetadata *getNodeMetadata(v3s16 p);
257
258         /**
259          * Sets metadata for a node.
260          * This method sets the metadata for a given node.
261          * On success, it returns @c true and the object pointed to
262          * by @p meta is then managed by the system and should
263          * not be deleted by the caller.
264          *
265          * In case of failure, the method returns @c false and the
266          * caller is still responsible for deleting the object!
267          *
268          * @param p node coordinates
269          * @param meta pointer to @c NodeMetadata object
270          * @return @c true on success, false on failure
271          */
272         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
273         void removeNodeMetadata(v3s16 p);
274
275         /*
276                 Node Timers
277                 These are basically coordinate wrappers to MapBlock
278         */
279
280         NodeTimer getNodeTimer(v3s16 p);
281         void setNodeTimer(const NodeTimer &t);
282         void removeNodeTimer(v3s16 p);
283
284         /*
285                 Misc.
286         */
287         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
288
289         /*
290                 Variables
291         */
292
293         void transforming_liquid_add(v3s16 p);
294         s32 transforming_liquid_size();
295
296         bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
297 protected:
298         friend class LuaVoxelManip;
299
300         std::ostream &m_dout; // A bit deprecated, could be removed
301
302         IGameDef *m_gamedef;
303
304         std::set<MapEventReceiver*> m_event_receivers;
305
306         std::map<v2s16, MapSector*> m_sectors;
307
308         // Be sure to set this to NULL when the cached sector is deleted
309         MapSector *m_sector_cache = nullptr;
310         v2s16 m_sector_cache_p;
311
312         // Queued transforming water nodes
313         UniqueQueue<v3s16> m_transforming_liquid;
314
315         // This stores the properties of the nodes on the map.
316         INodeDefManager *m_nodedef;
317
318         bool isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac,
319                         float start_off, float end_off, u32 needed_count);
320
321 private:
322         f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
323         u32 m_unprocessed_count = 0;
324         u64 m_inc_trending_up_start_time = 0; // milliseconds
325         bool m_queue_size_timer_started = false;
326 };
327
328 /*
329         ServerMap
330
331         This is the only map class that is able to generate map.
332 */
333
334 class ServerMap : public Map
335 {
336 public:
337         /*
338                 savedir: directory to which map data should be saved
339         */
340         ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge);
341         ~ServerMap();
342
343         s32 mapType() const
344         {
345                 return MAPTYPE_SERVER;
346         }
347
348         /*
349                 Get a sector from somewhere.
350                 - Check memory
351                 - Check disk (doesn't load blocks)
352                 - Create blank one
353         */
354         ServerMapSector *createSector(v2s16 p);
355
356         bool saoPositionOverLimit(const v3f &p);
357
358         /*
359                 Blocks are generated by using these and makeBlock().
360         */
361         bool blockpos_over_mapgen_limit(v3s16 p);
362         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
363         void finishBlockMake(BlockMakeData *data,
364                 std::map<v3s16, MapBlock*> *changed_blocks);
365
366         /*
367                 Get a block from somewhere.
368                 - Memory
369                 - Create blank
370         */
371         MapBlock *createBlock(v3s16 p);
372
373         /*
374                 Forcefully get a block from somewhere.
375                 - Memory
376                 - Load from disk
377                 - Create blank filled with CONTENT_IGNORE
378
379         */
380         MapBlock *emergeBlock(v3s16 p, bool create_blank=true);
381
382         /*
383                 Try to get a block.
384                 If it does not exist in memory, add it to the emerge queue.
385                 - Memory
386                 - Emerge Queue (deferred disk or generate)
387         */
388         MapBlock *getBlockOrEmerge(v3s16 p3d);
389
390         // Helper for placing objects on ground level
391         s16 findGroundLevel(v2s16 p2d);
392
393         /*
394                 Misc. helper functions for fiddling with directory and file
395                 names when saving
396         */
397         void createDirs(std::string path);
398         // returns something like "map/sectors/xxxxxxxx"
399         std::string getSectorDir(v2s16 pos, int layout = 2);
400         // dirname: final directory name
401         v2s16 getSectorPos(const std::string &dirname);
402         v3s16 getBlockPos(const std::string &sectordir, const std::string &blockfile);
403         static std::string getBlockFilename(v3s16 p);
404
405         /*
406                 Database functions
407         */
408         static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
409
410         // Returns true if the database file does not exist
411         bool loadFromFolders();
412
413         // Call these before and after saving of blocks
414         void beginSave();
415         void endSave();
416
417         void save(ModifiedState save_level);
418         void listAllLoadableBlocks(std::vector<v3s16> &dst);
419         void listAllLoadedBlocks(std::vector<v3s16> &dst);
420
421         MapgenParams *getMapgenParams();
422
423         /*void saveChunkMeta();
424         void loadChunkMeta();*/
425
426         // The sector mutex should be locked when calling most of these
427
428         // This only saves sector-specific data such as the heightmap
429         // (no MapBlocks)
430         // DEPRECATED? Sectors have no metadata anymore.
431         void saveSectorMeta(ServerMapSector *sector);
432         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
433         bool loadSectorMeta(v2s16 p2d);
434
435         bool saveBlock(MapBlock *block);
436         static bool saveBlock(MapBlock *block, MapDatabase *db);
437         // This will generate a sector with getSector if not found.
438         void loadBlock(const std::string &sectordir, const std::string &blockfile,
439                         MapSector *sector, bool save_after_load=false);
440         MapBlock* loadBlock(v3s16 p);
441         // Database version
442         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
443
444         bool deleteBlock(v3s16 blockpos);
445
446         void updateVManip(v3s16 pos);
447
448         // For debug printing
449         virtual void PrintInfo(std::ostream &out);
450
451         bool isSavingEnabled(){ return m_map_saving_enabled; }
452
453         u64 getSeed();
454         s16 getWaterLevel();
455
456         /*!
457          * Fixes lighting in one map block.
458          * May modify other blocks as well, as light can spread
459          * out of the specified block.
460          * Returns false if the block is not generated (so nothing
461          * changed), true otherwise.
462          */
463         bool repairBlockLight(v3s16 blockpos,
464                 std::map<v3s16, MapBlock *> *modified_blocks);
465
466         MapSettingsManager settings_mgr;
467
468 private:
469         // Emerge manager
470         EmergeManager *m_emerge;
471
472         std::string m_savedir;
473         bool m_map_saving_enabled;
474
475 #if 0
476         // Chunk size in MapSectors
477         // If 0, chunks are disabled.
478         s16 m_chunksize;
479         // Chunks
480         core::map<v2s16, MapChunk*> m_chunks;
481 #endif
482
483         /*
484                 Metadata is re-written on disk only if this is true.
485                 This is reset to false when written on disk.
486         */
487         bool m_map_metadata_changed = true;
488         MapDatabase *dbase = nullptr;
489 };
490
491
492 #define VMANIP_BLOCK_DATA_INEXIST     1
493 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
494
495 class MMVManip : public VoxelManipulator
496 {
497 public:
498         MMVManip(Map *map);
499         virtual ~MMVManip();
500
501         virtual void clear()
502         {
503                 VoxelManipulator::clear();
504                 m_loaded_blocks.clear();
505         }
506
507         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
508                 bool load_if_inexistent = true);
509
510         // This is much faster with big chunks of generated data
511         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
512                 bool overwrite_generated = true);
513
514         bool m_is_dirty = false;
515
516 protected:
517         Map *m_map;
518         /*
519                 key = blockpos
520                 value = flags describing the block
521         */
522         std::map<v3s16, u8> m_loaded_blocks;
523 };