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